LLVM  8.0.1
Legalizer.cpp
Go to the documentation of this file.
1 //===-- llvm/CodeGen/GlobalISel/Legalizer.cpp -----------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file This file implements the LegalizerHelper class to legalize individual
11 /// instructions and the LegalizePass wrapper pass for the primary
12 /// legalization.
13 //
14 //===----------------------------------------------------------------------===//
15 
18 #include "llvm/ADT/SetVector.h"
30 #include "llvm/Support/Debug.h"
31 
32 #include <iterator>
33 
34 #define DEBUG_TYPE "legalizer"
35 
36 using namespace llvm;
37 
38 static cl::opt<bool>
39  EnableCSEInLegalizer("enable-cse-in-legalizer",
40  cl::desc("Should enable CSE in Legalizer"),
41  cl::Optional, cl::init(false));
42 
43 char Legalizer::ID = 0;
45  "Legalize the Machine IR a function's Machine IR", false,
46  false)
50  "Legalize the Machine IR a function's Machine IR", false,
51  false)
52 
53 Legalizer::Legalizer() : MachineFunctionPass(ID) {
55 }
56 
63 }
64 
65 void Legalizer::init(MachineFunction &MF) {
66 }
67 
68 static bool isArtifact(const MachineInstr &MI) {
69  switch (MI.getOpcode()) {
70  default:
71  return false;
72  case TargetOpcode::G_TRUNC:
73  case TargetOpcode::G_ZEXT:
74  case TargetOpcode::G_ANYEXT:
75  case TargetOpcode::G_SEXT:
76  case TargetOpcode::G_MERGE_VALUES:
77  case TargetOpcode::G_UNMERGE_VALUES:
78  case TargetOpcode::G_CONCAT_VECTORS:
79  case TargetOpcode::G_BUILD_VECTOR:
80  return true;
81  }
82 }
85 
86 namespace {
87 class LegalizerWorkListManager : public GISelChangeObserver {
88  InstListTy &InstList;
89  ArtifactListTy &ArtifactList;
90 
91 public:
92  LegalizerWorkListManager(InstListTy &Insts, ArtifactListTy &Arts)
93  : InstList(Insts), ArtifactList(Arts) {}
94 
95  void createdInstr(MachineInstr &MI) override {
96  // Only legalize pre-isel generic instructions.
97  // Legalization process could generate Target specific pseudo
98  // instructions with generic types. Don't record them
100  if (isArtifact(MI))
101  ArtifactList.insert(&MI);
102  else
103  InstList.insert(&MI);
104  }
105  LLVM_DEBUG(dbgs() << ".. .. New MI: " << MI);
106  }
107 
108  void erasingInstr(MachineInstr &MI) override {
109  LLVM_DEBUG(dbgs() << ".. .. Erasing: " << MI);
110  InstList.remove(&MI);
111  ArtifactList.remove(&MI);
112  }
113 
114  void changingInstr(MachineInstr &MI) override {
115  LLVM_DEBUG(dbgs() << ".. .. Changing MI: " << MI);
116  }
117 
118  void changedInstr(MachineInstr &MI) override {
119  // When insts change, we want to revisit them to legalize them again.
120  // We'll consider them the same as created.
121  LLVM_DEBUG(dbgs() << ".. .. Changed MI: " << MI);
122  createdInstr(MI);
123  }
124 };
125 } // namespace
126 
128  // If the ISel pipeline failed, do not bother running that pass.
129  if (MF.getProperties().hasProperty(
131  return false;
132  LLVM_DEBUG(dbgs() << "Legalize Machine IR for: " << MF.getName() << '\n');
133  init(MF);
134  const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>();
136  getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper();
137  MachineOptimizationRemarkEmitter MORE(MF, /*MBFI=*/nullptr);
138 
139  const size_t NumBlocks = MF.size();
141 
142  // Populate Insts
143  InstListTy InstList;
144  ArtifactListTy ArtifactList;
146  // Perform legalization bottom up so we can DCE as we legalize.
147  // Traverse BB in RPOT and within each basic block, add insts top down,
148  // so when we pop_back_val in the legalization process, we traverse bottom-up.
149  for (auto *MBB : RPOT) {
150  if (MBB->empty())
151  continue;
152  for (MachineInstr &MI : *MBB) {
153  // Only legalize pre-isel generic instructions: others don't have types
154  // and are assumed to be legal.
155  if (!isPreISelGenericOpcode(MI.getOpcode()))
156  continue;
157  if (isArtifact(MI))
158  ArtifactList.insert(&MI);
159  else
160  InstList.insert(&MI);
161  }
162  }
163  std::unique_ptr<MachineIRBuilder> MIRBuilder;
164  GISelCSEInfo *CSEInfo = nullptr;
165  bool IsO0 = TPC.getOptLevel() == CodeGenOpt::Level::None;
166  // Disable CSE for O0.
167  bool EnableCSE = !IsO0 && EnableCSEInLegalizer;
168  if (EnableCSE) {
169  MIRBuilder = make_unique<CSEMIRBuilder>();
170  std::unique_ptr<CSEConfig> Config = make_unique<CSEConfig>();
171  CSEInfo = &Wrapper.get(std::move(Config));
172  MIRBuilder->setCSEInfo(CSEInfo);
173  } else
174  MIRBuilder = make_unique<MachineIRBuilder>();
175  // This observer keeps the worklist updated.
176  LegalizerWorkListManager WorkListObserver(InstList, ArtifactList);
177  // We want both WorkListObserver as well as CSEInfo to observe all changes.
178  // Use the wrapper observer.
179  GISelObserverWrapper WrapperObserver(&WorkListObserver);
180  if (EnableCSE && CSEInfo)
181  WrapperObserver.addObserver(CSEInfo);
182  // Now install the observer as the delegate to MF.
183  // This will keep all the observers notified about new insertions/deletions.
184  RAIIDelegateInstaller DelInstall(MF, &WrapperObserver);
185  LegalizerHelper Helper(MF, WrapperObserver, *MIRBuilder.get());
186  const LegalizerInfo &LInfo(Helper.getLegalizerInfo());
187  LegalizationArtifactCombiner ArtCombiner(*MIRBuilder.get(), MF.getRegInfo(),
188  LInfo);
189  auto RemoveDeadInstFromLists = [&WrapperObserver](MachineInstr *DeadMI) {
190  WrapperObserver.erasingInstr(*DeadMI);
191  };
192  bool Changed = false;
193  do {
194  while (!InstList.empty()) {
195  MachineInstr &MI = *InstList.pop_back_val();
196  assert(isPreISelGenericOpcode(MI.getOpcode()) && "Expecting generic opcode");
197  if (isTriviallyDead(MI, MRI)) {
198  LLVM_DEBUG(dbgs() << MI << "Is dead; erasing.\n");
200  continue;
201  }
202 
203  // Do the legalization for this instruction.
204  auto Res = Helper.legalizeInstrStep(MI);
205  // Error out if we couldn't legalize this instruction. We may want to
206  // fall back to DAG ISel instead in the future.
208  Helper.MIRBuilder.stopObservingChanges();
209  reportGISelFailure(MF, TPC, MORE, "gisel-legalize",
210  "unable to legalize instruction", MI);
211  return false;
212  }
213  Changed |= Res == LegalizerHelper::Legalized;
214  }
215  while (!ArtifactList.empty()) {
216  MachineInstr &MI = *ArtifactList.pop_back_val();
217  assert(isPreISelGenericOpcode(MI.getOpcode()) && "Expecting generic opcode");
218  if (isTriviallyDead(MI, MRI)) {
219  LLVM_DEBUG(dbgs() << MI << "Is dead\n");
220  RemoveDeadInstFromLists(&MI);
222  continue;
223  }
224  SmallVector<MachineInstr *, 4> DeadInstructions;
225  if (ArtCombiner.tryCombineInstruction(MI, DeadInstructions)) {
226  for (auto *DeadMI : DeadInstructions) {
227  LLVM_DEBUG(dbgs() << *DeadMI << "Is dead\n");
228  RemoveDeadInstFromLists(DeadMI);
229  DeadMI->eraseFromParentAndMarkDBGValuesForRemoval();
230  }
231  Changed = true;
232  continue;
233  }
234  // If this was not an artifact (that could be combined away), this might
235  // need special handling. Add it to InstList, so when it's processed
236  // there, it has to be legal or specially handled.
237  else
238  InstList.insert(&MI);
239  }
240  } while (!InstList.empty());
241 
242  // For now don't support if new blocks are inserted - we would need to fix the
243  // outerloop for that.
244  if (MF.size() != NumBlocks) {
245  MachineOptimizationRemarkMissed R("gisel-legalize", "GISelFailure",
246  MF.getFunction().getSubprogram(),
247  /*MBB=*/nullptr);
248  R << "inserting blocks is not supported yet";
249  reportGISelFailure(MF, TPC, MORE, R);
250  return false;
251  }
252 
253  return Changed;
254 }
const NoneType None
Definition: None.h:24
A simple RAII based CSEInfo installer.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
The CSE Analysis object.
Definition: CSEInfo.h:69
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This class represents lattice values for constants.
Definition: AllocatorList.h:24
void getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU)
Modify analysis usage so it preserves passes required for the SelectionDAG fallback.
Definition: Utils.cpp:289
const MachineFunctionProperties & getProperties() const
Get the function properties.
unsigned size() const
bool empty() const
Definition: GISelWorkList.h:39
The actual analysis pass wrapper.
Definition: CSEInfo.h:213
INITIALIZE_PASS_BEGIN(Legalizer, DEBUG_TYPE, "Legalize the Machine IR a function's Machine IR", false, false) INITIALIZE_PASS_END(Legalizer
void remove(const MachineInstr *I)
Remove I from the worklist if it exists.
Definition: GISelWorkList.h:50
CodeGenOpt::Level getOptLevel() const
void erasingInstr(MachineInstr &MI) override
An instruction is about to be erased.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
amdgpu aa AMDGPU Address space based Alias Analysis Wrapper
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:409
Target-Independent Code Generator Pass Configuration Options.
void eraseFromParentAndMarkDBGValuesForRemoval()
Unlink &#39;this&#39; from the containing basic block and delete it.
COFF::MachineTypes Machine
Definition: COFFYAML.cpp:363
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:423
Abstract class that contains various methods for clients to notify about changes. ...
unsigned const MachineRegisterInfo * MRI
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1508
This file implements a version of MachineIRBuilder which CSEs insts within a MachineBasicBlock.
Represent the analysis usage information of a pass.
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
Definition: Legalizer.cpp:127
Some kind of error has occurred and we could not legalize this instruction.
Legalize the Machine IR a function s Machine IR
Definition: Legalizer.cpp:49
Simple wrapper that does the following.
Definition: CSEInfo.h:196
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
The optimization diagnostic interface.
#define MORE()
Definition: regcomp.c:251
MachineInstr * pop_back_val()
Definition: GISelWorkList.h:65
void insert(MachineInstr *I)
Add the specified instruction to the worklist if it isn&#39;t already in it.
Definition: GISelWorkList.h:44
const Function & getFunction() const
Return the LLVM function that this machine code represents.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
static char ID
Definition: Legalizer.h:33
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
bool isTriviallyDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
Check whether an instruction MI is dead: it only defines dead virtual registers, and doesn&#39;t have oth...
Definition: Utils.cpp:135
static cl::opt< bool > EnableCSEInLegalizer("enable-cse-in-legalizer", cl::desc("Should enable CSE in Legalizer"), cl::Optional, cl::init(false))
Representation of each machine instruction.
Definition: MachineInstr.h:64
Instruction has been legalized and the MachineFunction changed.
void addObserver(GISelChangeObserver *O)
#define DEBUG_TYPE
Definition: Legalizer.cpp:34
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
static bool isArtifact(const MachineInstr &MI)
Definition: Legalizer.cpp:68
void initializeLegalizerPass(PassRegistry &)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Legalizer.cpp:57
Diagnostic information for missed-optimization remarks.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool hasProperty(Property P) const
bool isPreISelGenericOpcode(unsigned Opcode)
Check whether the given Opcode is a generic opcode that is not supposed to appear after ISel...
Definition: TargetOpcodes.h:31
print Print MemDeps of function
IRTranslator LLVM IR MI
Simple wrapper observer that takes several observers, and calls each one for each event...
#define LLVM_DEBUG(X)
Definition: Debug.h:123
void reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC, MachineOptimizationRemarkEmitter &MORE, MachineOptimizationRemarkMissed &R)
Report an ISel error as a missed optimization remark to the LLVMContext&#39;s diagnostic stream...
Definition: Utils.cpp:156