//== ----- llvm/CodeGen/GlobalISel/Combiner.h -------------------*- C++ -*-== //
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
/// \file
/// This contains the base class for all Combiners generated by TableGen.
/// Backends need to create class that inherits from "Combiner" and put all of
/// the TableGen-erated code in there, as it implements the virtual functions.
///
//===----------------------------------------------------------------------===//

#ifndef LLVM_CODEGEN_GLOBALISEL_COMBINER_H
#define LLVM_CODEGEN_GLOBALISEL_COMBINER_H

#include "llvm/CodeGen/GlobalISel/GIMatchTableExecutor.h"
#include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
#include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"

namespace llvm {
class MachineRegisterInfo;
struct CombinerInfo;
class GISelCSEInfo;
class TargetPassConfig;
class MachineFunction;
class MachineIRBuilder;

/// Combiner implementation. This is per-function, so passes need to recreate
/// one of these each time they enter a new function.
///
/// TODO: Is it worth making this module-wide?
class Combiner : public GIMatchTableExecutor {
private:
  class WorkListMaintainer;
  GISelWorkList<512> WorkList;

  // We have a little hack here where keep the owned pointers private, and only
  // expose a reference. This has two purposes:
  //  - Avoid derived classes messing with those pointers.
  //  - Keep the API consistent. CInfo, MF, MRI, etc. are all accessed as
  //  references. Accessing Observer/B as pointers unnecessarily leaks
  //  implementation details into derived classes.
  std::unique_ptr<MachineIRBuilder> Builder;
  std::unique_ptr<WorkListMaintainer> WLObserver;
  std::unique_ptr<GISelObserverWrapper> ObserverWrapper;

  bool HasSetupMF = false;

public:
  /// If CSEInfo is not null, then the Combiner will use CSEInfo as the observer
  /// and also create a CSEMIRBuilder. Pass nullptr if CSE is not needed.
  Combiner(MachineFunction &MF, CombinerInfo &CInfo,
           const TargetPassConfig *TPC, GISelKnownBits *KB,
           GISelCSEInfo *CSEInfo = nullptr);
  virtual ~Combiner();

  virtual bool tryCombineAll(MachineInstr &I) const = 0;

  bool combineMachineInstrs();

protected:
  CombinerInfo &CInfo;
  GISelChangeObserver &Observer;
  MachineIRBuilder &B;
  MachineFunction &MF;
  MachineRegisterInfo &MRI;
  GISelKnownBits *KB;

  const TargetPassConfig *TPC;
  GISelCSEInfo *CSEInfo;
};

} // End namespace llvm.

#endif // LLVM_CODEGEN_GLOBALISEL_COMBINER_H
