LLVM  10.0.0
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/InitializePasses.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCSymbolXCOFF.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/Casting.h"
32 #include <algorithm>
33 #include <cassert>
34 #include <memory>
35 #include <utility>
36 #include <vector>
37 
38 using namespace llvm;
39 using namespace llvm::dwarf;
40 
41 // Out of line virtual method.
43 
44 namespace llvm {
45 
47  MMIAddrLabelMap *Map = nullptr;
48 
49 public:
50  MMIAddrLabelMapCallbackPtr() = default;
52 
53  void setPtr(BasicBlock *BB) {
55  }
56 
57  void setMap(MMIAddrLabelMap *map) { Map = map; }
58 
59  void deleted() override;
60  void allUsesReplacedWith(Value *V2) override;
61 };
62 
65  struct AddrLabelSymEntry {
66  /// The symbols for the label.
68 
69  Function *Fn; // The containing function of the BasicBlock.
70  unsigned Index; // The index in BBCallbacks for the BasicBlock.
71  };
72 
73  DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
74 
75  /// Callbacks for the BasicBlock's that we have entries for. We use this so
76  /// we get notified if a block is deleted or RAUWd.
77  std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks;
78 
79  /// This is a per-function list of symbols whose corresponding BasicBlock got
80  /// deleted. These symbols need to be emitted at some point in the file, so
81  /// AsmPrinter emits them after the function body.
82  DenseMap<AssertingVH<Function>, std::vector<MCSymbol*>>
83  DeletedAddrLabelsNeedingEmission;
84 
85 public:
86  MMIAddrLabelMap(MCContext &context) : Context(context) {}
87 
89  assert(DeletedAddrLabelsNeedingEmission.empty() &&
90  "Some labels for deleted blocks never got emitted");
91  }
92 
93  ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB);
94 
95  void takeDeletedSymbolsForFunction(Function *F,
96  std::vector<MCSymbol*> &Result);
97 
98  void UpdateForDeletedBlock(BasicBlock *BB);
99  void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
100 };
101 
102 } // end namespace llvm
103 
105  assert(BB->hasAddressTaken() &&
106  "Shouldn't get label for block without address taken");
107  AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
108 
109  // If we already had an entry for this block, just return it.
110  if (!Entry.Symbols.empty()) {
111  assert(BB->getParent() == Entry.Fn && "Parent changed");
112  return Entry.Symbols;
113  }
114 
115  // Otherwise, this is a new entry, create a new symbol for it and add an
116  // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
117  BBCallbacks.emplace_back(BB);
118  BBCallbacks.back().setMap(this);
119  Entry.Index = BBCallbacks.size() - 1;
120  Entry.Fn = BB->getParent();
121  MCSymbol *Sym = Context.createTempSymbol(!BB->hasAddressTaken());
122  if (Context.getObjectFileInfo()->getTargetTriple().isOSBinFormatXCOFF()) {
123  MCSymbol *FnEntryPointSym =
124  Context.lookupSymbol("." + Entry.Fn->getName());
125  assert(FnEntryPointSym && "The function entry pointer symbol should have"
126  " already been initialized.");
127  MCSectionXCOFF *Csect =
128  cast<MCSymbolXCOFF>(FnEntryPointSym)->getContainingCsect();
129  cast<MCSymbolXCOFF>(Sym)->setContainingCsect(Csect);
130  }
131  Entry.Symbols.push_back(Sym);
132  return Entry.Symbols;
133 }
134 
135 /// If we have any deleted symbols for F, return them.
137 takeDeletedSymbolsForFunction(Function *F, std::vector<MCSymbol*> &Result) {
138  DenseMap<AssertingVH<Function>, std::vector<MCSymbol*>>::iterator I =
139  DeletedAddrLabelsNeedingEmission.find(F);
140 
141  // If there are no entries for the function, just return.
142  if (I == DeletedAddrLabelsNeedingEmission.end()) return;
143 
144  // Otherwise, take the list.
145  std::swap(Result, I->second);
146  DeletedAddrLabelsNeedingEmission.erase(I);
147 }
148 
150  // If the block got deleted, there is no need for the symbol. If the symbol
151  // was already emitted, we can just forget about it, otherwise we need to
152  // queue it up for later emission when the function is output.
153  AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
154  AddrLabelSymbols.erase(BB);
155  assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
156  BBCallbacks[Entry.Index] = nullptr; // Clear the callback.
157 
158  assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
159  "Block/parent mismatch");
160 
161  for (MCSymbol *Sym : Entry.Symbols) {
162  if (Sym->isDefined())
163  return;
164 
165  // If the block is not yet defined, we need to emit it at the end of the
166  // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list
167  // for the containing Function. Since the block is being deleted, its
168  // parent may already be removed, we have to get the function from 'Entry'.
169  DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
170  }
171 }
172 
174  // Get the entry for the RAUW'd block and remove it from our map.
175  AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
176  AddrLabelSymbols.erase(Old);
177  assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
178 
179  AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
180 
181  // If New is not address taken, just move our symbol over to it.
182  if (NewEntry.Symbols.empty()) {
183  BBCallbacks[OldEntry.Index].setPtr(New); // Update the callback.
184  NewEntry = std::move(OldEntry); // Set New's entry.
185  return;
186  }
187 
188  BBCallbacks[OldEntry.Index] = nullptr; // Update the callback.
189 
190  // Otherwise, we need to add the old symbols to the new block's set.
191  NewEntry.Symbols.insert(NewEntry.Symbols.end(), OldEntry.Symbols.begin(),
192  OldEntry.Symbols.end());
193 }
194 
196  Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
197 }
198 
200  Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
201 }
202 
204  ObjFileMMI = nullptr;
205  CurCallSite = 0;
206  UsesMSVCFloatingPoint = UsesMorestackAddr = false;
207  HasSplitStack = HasNosplitStack = false;
208  AddrLabelSymbols = nullptr;
209 }
210 
212  Personalities.clear();
213 
214  delete AddrLabelSymbols;
215  AddrLabelSymbols = nullptr;
216 
217  Context.reset();
218 
219  delete ObjFileMMI;
220  ObjFileMMI = nullptr;
221 }
222 
224  : TM(std::move(MMI.TM)),
225  Context(MMI.TM.getMCAsmInfo(), MMI.TM.getMCRegisterInfo(),
226  MMI.TM.getObjFileLowering(), nullptr, nullptr, false) {
227  ObjFileMMI = MMI.ObjFileMMI;
228  CurCallSite = MMI.CurCallSite;
229  UsesMSVCFloatingPoint = MMI.UsesMSVCFloatingPoint;
230  UsesMorestackAddr = MMI.UsesMorestackAddr;
231  HasSplitStack = MMI.HasSplitStack;
232  HasNosplitStack = MMI.HasNosplitStack;
233  AddrLabelSymbols = MMI.AddrLabelSymbols;
234  TheModule = MMI.TheModule;
235 }
236 
238  : TM(*TM), Context(TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
239  TM->getObjFileLowering(), nullptr, nullptr, false) {
240  initialize();
241 }
242 
244 
245 //===- Address of Block Management ----------------------------------------===//
246 
249  // Lazily create AddrLabelSymbols.
250  if (!AddrLabelSymbols)
251  AddrLabelSymbols = new MMIAddrLabelMap(Context);
252  return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB));
253 }
254 
257  std::vector<MCSymbol*> &Result) {
258  // If no blocks have had their addresses taken, we're done.
259  if (!AddrLabelSymbols) return;
260  return AddrLabelSymbols->
261  takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result);
262 }
263 
264 /// \name Exception Handling
265 /// \{
266 
267 void MachineModuleInfo::addPersonality(const Function *Personality) {
268  for (unsigned i = 0; i < Personalities.size(); ++i)
269  if (Personalities[i] == Personality)
270  return;
271  Personalities.push_back(Personality);
272 }
273 
274 /// \}
275 
278  auto I = MachineFunctions.find(&F);
279  return I != MachineFunctions.end() ? I->second.get() : nullptr;
280 }
281 
284  // Shortcut for the common case where a sequence of MachineFunctionPasses
285  // all query for the same Function.
286  if (LastRequest == &F)
287  return *LastResult;
288 
289  auto I = MachineFunctions.insert(
290  std::make_pair(&F, std::unique_ptr<MachineFunction>()));
291  MachineFunction *MF;
292  if (I.second) {
293  // No pre-existing machine function, create a new one.
294  const TargetSubtargetInfo &STI = *TM.getSubtargetImpl(F);
295  MF = new MachineFunction(F, TM, STI, NextFnNum++, *this);
296  // Update the set entry.
297  I.first->second.reset(MF);
298  } else {
299  MF = I.first->second.get();
300  }
301 
302  LastRequest = &F;
303  LastResult = MF;
304  return *MF;
305 }
306 
308  MachineFunctions.erase(&F);
309  LastRequest = nullptr;
310  LastResult = nullptr;
311 }
312 
313 namespace {
314 
315 /// This pass frees the MachineFunction object associated with a Function.
316 class FreeMachineFunction : public FunctionPass {
317 public:
318  static char ID;
319 
320  FreeMachineFunction() : FunctionPass(ID) {}
321 
322  void getAnalysisUsage(AnalysisUsage &AU) const override {
325  }
326 
327  bool runOnFunction(Function &F) override {
328  MachineModuleInfo &MMI =
329  getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
331  return true;
332  }
333 
334  StringRef getPassName() const override {
335  return "Free MachineFunction";
336  }
337 };
338 
339 } // end anonymous namespace
340 
342 
344  return new FreeMachineFunction();
345 }
346 
348  const LLVMTargetMachine *TM)
349  : ImmutablePass(ID), MMI(TM) {
351 }
352 
353 // Handle the Pass registration stuff necessary to use DataLayout's.
354 INITIALIZE_PASS(MachineModuleInfoWrapperPass, "machinemoduleinfo",
355  "Machine Module Information", false, false)
357 
359  MMI.initialize();
360  MMI.TheModule = &M;
361  MMI.DbgInfoAvailable = !M.debug_compile_units().empty();
362  return false;
363 }
364 
366  MMI.finalize();
367  return false;
368 }
369 
370 AnalysisKey MachineModuleAnalysis::Key;
371 
374  MachineModuleInfo MMI(TM);
375  MMI.TheModule = &M;
376  MMI.DbgInfoAvailable = !M.debug_compile_units().empty();
377  return MMI;
378 }
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:282
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:253
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:241
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:751
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:399
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
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.