LLVM  10.0.0svn
MachineModuleInfo.cpp
Go to the documentation of this file.
1 //===-- llvm/CodeGen/MachineModuleInfo.cpp ----------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/ADT/DenseMap.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/ADT/TinyPtrVector.h"
16 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/IR/BasicBlock.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IR/Value.h"
22 #include "llvm/IR/ValueHandle.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCSymbol.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/Casting.h"
30 #include <algorithm>
31 #include <cassert>
32 #include <memory>
33 #include <utility>
34 #include <vector>
35 
36 using namespace llvm;
37 using namespace llvm::dwarf;
38 
39 // Out of line virtual method.
41 
42 namespace llvm {
43 
45  MMIAddrLabelMap *Map = nullptr;
46 
47 public:
48  MMIAddrLabelMapCallbackPtr() = default;
50 
51  void setPtr(BasicBlock *BB) {
53  }
54 
55  void setMap(MMIAddrLabelMap *map) { Map = map; }
56 
57  void deleted() override;
58  void allUsesReplacedWith(Value *V2) override;
59 };
60 
63  struct AddrLabelSymEntry {
64  /// The symbols for the label.
66 
67  Function *Fn; // The containing function of the BasicBlock.
68  unsigned Index; // The index in BBCallbacks for the BasicBlock.
69  };
70 
71  DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
72 
73  /// Callbacks for the BasicBlock's that we have entries for. We use this so
74  /// we get notified if a block is deleted or RAUWd.
75  std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks;
76 
77  /// This is a per-function list of symbols whose corresponding BasicBlock got
78  /// deleted. These symbols need to be emitted at some point in the file, so
79  /// AsmPrinter emits them after the function body.
80  DenseMap<AssertingVH<Function>, std::vector<MCSymbol*>>
81  DeletedAddrLabelsNeedingEmission;
82 
83 public:
84  MMIAddrLabelMap(MCContext &context) : Context(context) {}
85 
87  assert(DeletedAddrLabelsNeedingEmission.empty() &&
88  "Some labels for deleted blocks never got emitted");
89  }
90 
91  ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB);
92 
93  void takeDeletedSymbolsForFunction(Function *F,
94  std::vector<MCSymbol*> &Result);
95 
96  void UpdateForDeletedBlock(BasicBlock *BB);
97  void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
98 };
99 
100 } // end namespace llvm
101 
103  assert(BB->hasAddressTaken() &&
104  "Shouldn't get label for block without address taken");
105  AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
106 
107  // If we already had an entry for this block, just return it.
108  if (!Entry.Symbols.empty()) {
109  assert(BB->getParent() == Entry.Fn && "Parent changed");
110  return Entry.Symbols;
111  }
112 
113  // Otherwise, this is a new entry, create a new symbol for it and add an
114  // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
115  BBCallbacks.emplace_back(BB);
116  BBCallbacks.back().setMap(this);
117  Entry.Index = BBCallbacks.size() - 1;
118  Entry.Fn = BB->getParent();
119  Entry.Symbols.push_back(Context.createTempSymbol(!BB->hasAddressTaken()));
120  return Entry.Symbols;
121 }
122 
123 /// If we have any deleted symbols for F, return them.
125 takeDeletedSymbolsForFunction(Function *F, std::vector<MCSymbol*> &Result) {
126  DenseMap<AssertingVH<Function>, std::vector<MCSymbol*>>::iterator I =
127  DeletedAddrLabelsNeedingEmission.find(F);
128 
129  // If there are no entries for the function, just return.
130  if (I == DeletedAddrLabelsNeedingEmission.end()) return;
131 
132  // Otherwise, take the list.
133  std::swap(Result, I->second);
134  DeletedAddrLabelsNeedingEmission.erase(I);
135 }
136 
138  // If the block got deleted, there is no need for the symbol. If the symbol
139  // was already emitted, we can just forget about it, otherwise we need to
140  // queue it up for later emission when the function is output.
141  AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
142  AddrLabelSymbols.erase(BB);
143  assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
144  BBCallbacks[Entry.Index] = nullptr; // Clear the callback.
145 
146  assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
147  "Block/parent mismatch");
148 
149  for (MCSymbol *Sym : Entry.Symbols) {
150  if (Sym->isDefined())
151  return;
152 
153  // If the block is not yet defined, we need to emit it at the end of the
154  // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list
155  // for the containing Function. Since the block is being deleted, its
156  // parent may already be removed, we have to get the function from 'Entry'.
157  DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
158  }
159 }
160 
162  // Get the entry for the RAUW'd block and remove it from our map.
163  AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
164  AddrLabelSymbols.erase(Old);
165  assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
166 
167  AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
168 
169  // If New is not address taken, just move our symbol over to it.
170  if (NewEntry.Symbols.empty()) {
171  BBCallbacks[OldEntry.Index].setPtr(New); // Update the callback.
172  NewEntry = std::move(OldEntry); // Set New's entry.
173  return;
174  }
175 
176  BBCallbacks[OldEntry.Index] = nullptr; // Update the callback.
177 
178  // Otherwise, we need to add the old symbols to the new block's set.
179  NewEntry.Symbols.insert(NewEntry.Symbols.end(), OldEntry.Symbols.begin(),
180  OldEntry.Symbols.end());
181 }
182 
184  Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
185 }
186 
188  Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
189 }
190 
192  ObjFileMMI = nullptr;
193  CurCallSite = 0;
194  UsesMSVCFloatingPoint = UsesMorestackAddr = false;
195  HasSplitStack = HasNosplitStack = false;
196  AddrLabelSymbols = nullptr;
197 }
198 
200  Personalities.clear();
201 
202  delete AddrLabelSymbols;
203  AddrLabelSymbols = nullptr;
204 
205  Context.reset();
206 
207  delete ObjFileMMI;
208  ObjFileMMI = nullptr;
209 }
210 
212  : TM(std::move(MMI.TM)),
213  Context(MMI.TM.getMCAsmInfo(), MMI.TM.getMCRegisterInfo(),
214  MMI.TM.getObjFileLowering(), nullptr, nullptr, false) {
215  ObjFileMMI = MMI.ObjFileMMI;
216  CurCallSite = MMI.CurCallSite;
217  UsesMSVCFloatingPoint = MMI.UsesMSVCFloatingPoint;
218  UsesMorestackAddr = MMI.UsesMorestackAddr;
219  HasSplitStack = MMI.HasSplitStack;
220  HasNosplitStack = MMI.HasNosplitStack;
221  AddrLabelSymbols = MMI.AddrLabelSymbols;
222  TheModule = MMI.TheModule;
223 }
224 
226  : TM(*TM), Context(TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
227  TM->getObjFileLowering(), nullptr, nullptr, false) {
228  initialize();
229 }
230 
232 
233 //===- Address of Block Management ----------------------------------------===//
234 
237  // Lazily create AddrLabelSymbols.
238  if (!AddrLabelSymbols)
239  AddrLabelSymbols = new MMIAddrLabelMap(Context);
240  return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB));
241 }
242 
245  std::vector<MCSymbol*> &Result) {
246  // If no blocks have had their addresses taken, we're done.
247  if (!AddrLabelSymbols) return;
248  return AddrLabelSymbols->
249  takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result);
250 }
251 
252 /// \name Exception Handling
253 /// \{
254 
255 void MachineModuleInfo::addPersonality(const Function *Personality) {
256  for (unsigned i = 0; i < Personalities.size(); ++i)
257  if (Personalities[i] == Personality)
258  return;
259  Personalities.push_back(Personality);
260 }
261 
262 /// \}
263 
266  auto I = MachineFunctions.find(&F);
267  return I != MachineFunctions.end() ? I->second.get() : nullptr;
268 }
269 
272  // Shortcut for the common case where a sequence of MachineFunctionPasses
273  // all query for the same Function.
274  if (LastRequest == &F)
275  return *LastResult;
276 
277  auto I = MachineFunctions.insert(
278  std::make_pair(&F, std::unique_ptr<MachineFunction>()));
279  MachineFunction *MF;
280  if (I.second) {
281  // No pre-existing machine function, create a new one.
282  const TargetSubtargetInfo &STI = *TM.getSubtargetImpl(F);
283  MF = new MachineFunction(F, TM, STI, NextFnNum++, *this);
284  // Update the set entry.
285  I.first->second.reset(MF);
286  } else {
287  MF = I.first->second.get();
288  }
289 
290  LastRequest = &F;
291  LastResult = MF;
292  return *MF;
293 }
294 
296  MachineFunctions.erase(&F);
297  LastRequest = nullptr;
298  LastResult = nullptr;
299 }
300 
301 namespace {
302 
303 /// This pass frees the MachineFunction object associated with a Function.
304 class FreeMachineFunction : public FunctionPass {
305 public:
306  static char ID;
307 
308  FreeMachineFunction() : FunctionPass(ID) {}
309 
310  void getAnalysisUsage(AnalysisUsage &AU) const override {
313  }
314 
315  bool runOnFunction(Function &F) override {
316  MachineModuleInfo &MMI =
317  getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
319  return true;
320  }
321 
322  StringRef getPassName() const override {
323  return "Free MachineFunction";
324  }
325 };
326 
327 } // end anonymous namespace
328 
330 
332  return new FreeMachineFunction();
333 }
334 
336  const LLVMTargetMachine *TM)
337  : ImmutablePass(ID), MMI(TM) {
339 }
340 
341 // Handle the Pass registration stuff necessary to use DataLayout's.
342 INITIALIZE_PASS(MachineModuleInfoWrapperPass, "machinemoduleinfo",
343  "Machine Module Information", false, false)
345 
347  MMI.initialize();
348  MMI.TheModule = &M;
349  MMI.DbgInfoAvailable = !M.debug_compile_units().empty();
350  return false;
351 }
352 
354  MMI.finalize();
355  return false;
356 }
357 
358 AnalysisKey MachineModuleAnalysis::Key;
359 
362  MachineModuleInfo MMI(TM);
363  MMI.TheModule = &M;
364  MMI.DbgInfoAvailable = !M.debug_compile_units().empty();
365  return MMI;
366 }
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVMContext & Context
This class represents lattice values for constants.
Definition: AllocatorList.h:23
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:66
void deleteMachineFunctionFor(Function &F)
Delete the MachineFunction MF and reset the link in the IR Function to Machine Function map...
F(f)
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
Definition: TinyPtrVector.h:30
MachineModuleInfo(const LLVMTargetMachine *TM=nullptr)
MachineModuleInfo run(Module &M, ModuleAnalysisManager &)
Run the analysis pass and produce machine module information.
void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New)
AnalysisUsage & addRequired()
MachineModuleInfoWrapperPass(const LLVMTargetMachine *TM=nullptr)
Definition: BitVector.h:937
MMIAddrLabelMap(MCContext &context)
Context object for machine code objects.
Definition: MCContext.h:65
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
ArrayRef< MCSymbol * > getAddrLabelSymbolToEmit(const BasicBlock *BB)
Return the symbol to be used for the specified basic block when its address is taken.
static bool runOnFunction(Function &F, bool PostInlining)
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
void takeDeletedSymbolsForFunction(const Function *F, std::vector< MCSymbol *> &Result)
If the specified function has had any references to address-taken blocks generated, but the block got deleted, return the symbol now so we can emit it.
void addPersonality(const Function *Personality)
Provide the personality function for the exception information.
FunctionPass * createFreeMachineFunctionPass()
This pass frees the memory occupied by the MachineFunction.
Represent the analysis usage information of a pass.
This class describes a target machine that is implemented with the LLVM target-independent code gener...
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
MachineFunction & getOrCreateMachineFunction(const Function &F)
Returns the MachineFunction constructed for the IR function F.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:33
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
Definition: BasicBlock.h:396
ImmutablePass class - This class is used to provide information that does not need to be run...
Definition: Pass.h:255
MachineFunction * getMachineFunction(const Function &F) const
Returns the MachineFunction associated to IR function F if there is one, otherwise nullptr...
Module.h This file contains the declarations for the Module class.
void setMap(MMIAddrLabelMap *map)
void initializeMachineModuleInfoWrapperPassPass(PassRegistry &)
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target&#39;s TargetSubtargetInf...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:940
bool isDefined() const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition: MCSymbol.h:249
TargetSubtargetInfo - Generic base class for all target subtargets.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:106
#define I(x, y, z)
Definition: MD5.cpp:58
iterator_range< debug_compile_units_iterator > debug_compile_units() const
Return an iterator for all DICompileUnits listed in this Module&#39;s llvm.dbg.cu named metadata node and...
Definition: Module.h:782
void allUsesReplacedWith(Value *V2) override
Callback for Value RAUW.
Value * operator=(Value *RHS)
Definition: ValueHandle.h:69
ArrayRef< MCSymbol * > getAddrLabelSymbolToEmit(BasicBlock *BB)
void deleted() override
Callback for Value destruction.
bool doInitialization(Module &) override
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:74
bool doFinalization(Module &) override
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
void UpdateForDeletedBlock(BasicBlock *BB)
Value handle with callbacks on RAUW and destruction.
Definition: ValueHandle.h:379
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
A container for analyses that lazily runs them and caches their results.
void takeDeletedSymbolsForFunction(Function *F, std::vector< MCSymbol *> &Result)
If we have any deleted symbols for F, return them.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:71
This class contains meta information specific to a module.