LLVM  4.0.0
MachineModuleInfo.cpp
Go to the documentation of this file.
1 //===-- llvm/CodeGen/MachineModuleInfo.cpp ----------------------*- C++ -*-===//
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 
11 #include "llvm/ADT/PointerUnion.h"
13 #include "llvm/ADT/TinyPtrVector.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/GlobalVariable.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/Module.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/Support/Dwarf.h"
31 using namespace llvm;
32 using namespace llvm::dwarf;
33 
34 // Handle the Pass registration stuff necessary to use DataLayout's.
35 INITIALIZE_TM_PASS(MachineModuleInfo, "machinemoduleinfo",
36  "Machine Module Information", false, false)
37 char MachineModuleInfo::ID = 0;
38 
39 // Out of line virtual method.
41 
42 namespace llvm {
44  MMIAddrLabelMap *Map;
45 public:
46  MMIAddrLabelMapCallbackPtr() : Map(nullptr) {}
47  MMIAddrLabelMapCallbackPtr(Value *V) : CallbackVH(V), Map(nullptr) {}
48 
49  void setPtr(BasicBlock *BB) {
51  }
52 
53  void setMap(MMIAddrLabelMap *map) { Map = map; }
54 
55  void deleted() override;
56  void allUsesReplacedWith(Value *V2) override;
57 };
58 
61  struct AddrLabelSymEntry {
62  /// The symbols for the label.
64 
65  Function *Fn; // The containing function of the BasicBlock.
66  unsigned Index; // The index in BBCallbacks for the BasicBlock.
67  };
68 
69  DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
70 
71  /// Callbacks for the BasicBlock's that we have entries for. We use this so
72  /// we get notified if a block is deleted or RAUWd.
73  std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks;
74 
75  /// This is a per-function list of symbols whose corresponding BasicBlock got
76  /// deleted. These symbols need to be emitted at some point in the file, so
77  /// AsmPrinter emits them after the function body.
78  DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >
79  DeletedAddrLabelsNeedingEmission;
80 public:
81 
82  MMIAddrLabelMap(MCContext &context) : Context(context) {}
84  assert(DeletedAddrLabelsNeedingEmission.empty() &&
85  "Some labels for deleted blocks never got emitted");
86  }
87 
88  ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB);
89 
90  void takeDeletedSymbolsForFunction(Function *F,
91  std::vector<MCSymbol*> &Result);
92 
93  void UpdateForDeletedBlock(BasicBlock *BB);
94  void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
95 };
96 }
97 
99  assert(BB->hasAddressTaken() &&
100  "Shouldn't get label for block without address taken");
101  AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
102 
103  // If we already had an entry for this block, just return it.
104  if (!Entry.Symbols.empty()) {
105  assert(BB->getParent() == Entry.Fn && "Parent changed");
106  return Entry.Symbols;
107  }
108 
109  // Otherwise, this is a new entry, create a new symbol for it and add an
110  // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
111  BBCallbacks.emplace_back(BB);
112  BBCallbacks.back().setMap(this);
113  Entry.Index = BBCallbacks.size() - 1;
114  Entry.Fn = BB->getParent();
115  Entry.Symbols.push_back(Context.createTempSymbol());
116  return Entry.Symbols;
117 }
118 
119 /// If we have any deleted symbols for F, return them.
121 takeDeletedSymbolsForFunction(Function *F, std::vector<MCSymbol*> &Result) {
122  DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >::iterator I =
123  DeletedAddrLabelsNeedingEmission.find(F);
124 
125  // If there are no entries for the function, just return.
126  if (I == DeletedAddrLabelsNeedingEmission.end()) return;
127 
128  // Otherwise, take the list.
129  std::swap(Result, I->second);
130  DeletedAddrLabelsNeedingEmission.erase(I);
131 }
132 
133 
135  // If the block got deleted, there is no need for the symbol. If the symbol
136  // was already emitted, we can just forget about it, otherwise we need to
137  // queue it up for later emission when the function is output.
138  AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
139  AddrLabelSymbols.erase(BB);
140  assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
141  BBCallbacks[Entry.Index] = nullptr; // Clear the callback.
142 
143  assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
144  "Block/parent mismatch");
145 
146  for (MCSymbol *Sym : Entry.Symbols) {
147  if (Sym->isDefined())
148  return;
149 
150  // If the block is not yet defined, we need to emit it at the end of the
151  // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list
152  // for the containing Function. Since the block is being deleted, its
153  // parent may already be removed, we have to get the function from 'Entry'.
154  DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
155  }
156 }
157 
159  // Get the entry for the RAUW'd block and remove it from our map.
160  AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
161  AddrLabelSymbols.erase(Old);
162  assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
163 
164  AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
165 
166  // If New is not address taken, just move our symbol over to it.
167  if (NewEntry.Symbols.empty()) {
168  BBCallbacks[OldEntry.Index].setPtr(New); // Update the callback.
169  NewEntry = std::move(OldEntry); // Set New's entry.
170  return;
171  }
172 
173  BBCallbacks[OldEntry.Index] = nullptr; // Update the callback.
174 
175  // Otherwise, we need to add the old symbols to the new block's set.
176  NewEntry.Symbols.insert(NewEntry.Symbols.end(), OldEntry.Symbols.begin(),
177  OldEntry.Symbols.end());
178 }
179 
180 
182  Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
183 }
184 
186  Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
187 }
188 
189 
190 //===----------------------------------------------------------------------===//
191 
193  : ImmutablePass(ID), TM(*TM),
194  Context(TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
195  TM->getObjFileLowering(), nullptr, false) {
197 }
198 
200 }
201 
203 
204  ObjFileMMI = nullptr;
205  CurCallSite = 0;
206  DbgInfoAvailable = UsesVAFloatArgument = UsesMorestackAddr = false;
207  AddrLabelSymbols = nullptr;
208  TheModule = &M;
209 
210  return false;
211 }
212 
214 
215  Personalities.clear();
216 
217  delete AddrLabelSymbols;
218  AddrLabelSymbols = nullptr;
219 
220  Context.reset();
221 
222  delete ObjFileMMI;
223  ObjFileMMI = nullptr;
224 
225  return false;
226 }
227 
228 //===- Address of Block Management ----------------------------------------===//
229 
232  // Lazily create AddrLabelSymbols.
233  if (!AddrLabelSymbols)
234  AddrLabelSymbols = new MMIAddrLabelMap(Context);
235  return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB));
236 }
237 
240  std::vector<MCSymbol*> &Result) {
241  // If no blocks have had their addresses taken, we're done.
242  if (!AddrLabelSymbols) return;
243  return AddrLabelSymbols->
244  takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result);
245 }
246 
247 /// \name Exception Handling
248 /// \{
249 
250 void MachineModuleInfo::addPersonality(const Function *Personality) {
251  for (unsigned i = 0; i < Personalities.size(); ++i)
252  if (Personalities[i] == Personality)
253  return;
254  Personalities.push_back(Personality);
255 }
256 
257 /// \}
258 
260  // Shortcut for the common case where a sequence of MachineFunctionPasses
261  // all query for the same Function.
262  if (LastRequest == &F)
263  return *LastResult;
264 
265  auto I = MachineFunctions.insert(
266  std::make_pair(&F, std::unique_ptr<MachineFunction>()));
267  MachineFunction *MF;
268  if (I.second) {
269  // No pre-existing machine function, create a new one.
270  MF = new MachineFunction(&F, TM, NextFnNum++, *this);
271  // Update the set entry.
272  I.first->second.reset(MF);
273 
274  if (MFInitializer)
275  if (MFInitializer->initializeMachineFunction(*MF))
276  report_fatal_error("Unable to initialize machine function");
277  } else {
278  MF = I.first->second.get();
279  }
280 
281  LastRequest = &F;
282  LastResult = MF;
283  return *MF;
284 }
285 
287  MachineFunctions.erase(&F);
288  LastRequest = nullptr;
289  LastResult = nullptr;
290 }
291 
292 namespace {
293 /// This pass frees the MachineFunction object associated with a Function.
294 class FreeMachineFunction : public FunctionPass {
295 public:
296  static char ID;
297  FreeMachineFunction() : FunctionPass(ID) {}
298 
299  void getAnalysisUsage(AnalysisUsage &AU) const override {
302  }
303 
304  bool runOnFunction(Function &F) override {
305  MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
307  return true;
308  }
309 };
311 } // end anonymous namespace
312 
313 namespace llvm {
315  return new FreeMachineFunction();
316 }
317 } // end namespace llvm
318 
319 //===- MMI building helpers -----------------------------------------------===//
320 
322  MachineModuleInfo &MMI) {
323  FunctionType *FT =
324  cast<FunctionType>(I.getCalledValue()->getType()->getContainedType(0));
325  if (FT->isVarArg() && !MMI.usesVAFloatArgument()) {
326  for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
327  Type *T = I.getArgOperand(i)->getType();
328  for (auto i : post_order(T)) {
329  if (i->isFloatingPointTy()) {
330  MMI.setUsesVAFloatArgument(true);
331  return;
332  }
333  }
334  }
335  }
336 }
const Value * getCalledValue() const
Get a pointer to the function that is invoked by this instruction.
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...
bool doFinalization(Module &) override
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
LLVMContext & Context
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
size_t i
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:39
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:52
void deleteMachineFunctionFor(Function &F)
Delete the MachineFunction MF and reset the link in the IR Function to Machine Function map...
void reset()
reset - return object to right after construction state to prepare to process a new module ...
Definition: MCContext.cpp:74
This class represents a function call, abstracting a target machine's calling convention.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:100
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
Definition: TinyPtrVector.h:31
void computeUsesVAFloatArgument(const CallInst &I, MachineModuleInfo &MMI)
Determine if any floating-point values are being passed to this variadic function, and set the MachineModuleInfo's usesVAFloatArgument flag if so.
void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New)
AnalysisUsage & addRequired()
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.
unsigned getNumArgOperands() const
Return the number of call arguments.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
Definition: BasicBlock.h:308
MachineModuleInfo(const TargetMachine *TM=nullptr)
bool usesVAFloatArgument() const
MMIAddrLabelMap(MCContext &context)
Context object for machine code objects.
Definition: MCContext.h:51
Class to represent function types.
Definition: DerivedTypes.h:102
#define F(x, y, z)
Definition: MD5.cpp:51
Function Alias Analysis false
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
ArrayRef< MCSymbol * > getAddrLabelSymbolToEmit(const BasicBlock *BB)
Return the symbol to be used for the specified basic block when its address is taken.
MachineFunction & getMachineFunction(const Function &F)
Returns the MachineFunction constructed for the IR function F.
LLVM Basic Block Representation.
Definition: BasicBlock.h:51
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
Type * getContainedType(unsigned i) const
This method is used to implement the type iterator (defined at the end of the file).
Definition: Type.h:316
void addPersonality(const Function *Personality)
Provide the personality function for the exception information.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
FunctionPass * createFreeMachineFunctionPass()
This pass frees the memory occupied by the MachineFunction.
Represent the analysis usage information of a pass.
void takeDeletedSymbolsForFunction(Function *F, std::vector< MCSymbol * > &Result)
If we have any deleted symbols for F, return them.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
iterator_range< po_iterator< T > > post_order(const T &G)
void initializeMachineModuleInfoPass(PassRegistry &)
#define INITIALIZE_TM_PASS(passName, arg, name, cfg, analysis)
This initializer registers TargetMachine constructor, so the pass being initialized can use target de...
ImmutablePass class - This class is used to provide information that does not need to be run...
Definition: Pass.h:266
Module.h This file contains the declarations for the Module class.
void setMap(MMIAddrLabelMap *map)
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:230
virtual bool initializeMachineFunction(MachineFunction &MF)=0
Initialize the machine function.
bool isDefined(bool SetUsed=true) const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition: MCSymbol.h:245
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:586
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
bool doInitialization(Module &) override
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
#define I(x, y, z)
Definition: MD5.cpp:54
void setUsesVAFloatArgument(bool b)
void allUsesReplacedWith(Value *V2) override
Callback for Value RAUW.
Value * operator=(Value *RHS)
Definition: ValueHandle.h:73
ArrayRef< MCSymbol * > getAddrLabelSymbolToEmit(BasicBlock *BB)
void deleted() override
Callback for Value destruction.
bool isVarArg() const
Definition: DerivedTypes.h:122
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:71
void UpdateForDeletedBlock(BasicBlock *BB)
Primary interface to the complete machine description for the target machine.
Value handle with callbacks on RAUW and destruction.
Definition: ValueHandle.h:333
This class can be derived from and used by targets to hold private target-specific information for ea...
This class contains meta information specific to a module.