Reformat.
[oota-llvm.git] / include / llvm / CodeGen / MachineModuleInfo.h
1 //===-- llvm/CodeGen/MachineModuleInfo.h ------------------------*- 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 //
10 // Collect meta information for a module.  This information should be in a
11 // neutral form that can be used by different debugging and exception handling
12 // schemes.
13 //
14 // The organization of information is primarily clustered around the source
15 // compile units.  The main exception is source line correspondence where
16 // inlining may interleave code from various compile units.
17 //
18 // The following information can be retrieved from the MachineModuleInfo.
19 //
20 //  -- Source directories - Directories are uniqued based on their canonical
21 //     string and assigned a sequential numeric ID (base 1.)
22 //  -- Source files - Files are also uniqued based on their name and directory
23 //     ID.  A file ID is sequential number (base 1.)
24 //  -- Source line correspondence - A vector of file ID, line#, column# triples.
25 //     A DEBUG_LOCATION instruction is generated  by the DAG Legalizer
26 //     corresponding to each entry in the source line list.  This allows a debug
27 //     emitter to generate labels referenced by debug information tables.
28 //
29 //===----------------------------------------------------------------------===//
30
31 #ifndef LLVM_CODEGEN_MACHINEMODULEINFO_H
32 #define LLVM_CODEGEN_MACHINEMODULEINFO_H
33
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/PointerIntPair.h"
36 #include "llvm/ADT/SmallPtrSet.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/Analysis/LibCallSemantics.h"
39 #include "llvm/IR/DebugLoc.h"
40 #include "llvm/IR/Metadata.h"
41 #include "llvm/IR/ValueHandle.h"
42 #include "llvm/MC/MCContext.h"
43 #include "llvm/MC/MachineLocation.h"
44 #include "llvm/Pass.h"
45 #include "llvm/Support/DataTypes.h"
46 #include "llvm/Support/Dwarf.h"
47
48 namespace llvm {
49
50 //===----------------------------------------------------------------------===//
51 // Forward declarations.
52 class Constant;
53 class GlobalVariable;
54 class BlockAddress;
55 class MDNode;
56 class MMIAddrLabelMap;
57 class MachineBasicBlock;
58 class MachineFunction;
59 class Module;
60 class PointerType;
61 class StructType;
62 struct WinEHFuncInfo;
63
64 struct SEHHandler {
65   // Filter or finally function. Null indicates a catch-all.
66   const Function *FilterOrFinally;
67
68   // Address of block to recover at. Null for a finally handler.
69   const BlockAddress *RecoverBA;
70 };
71
72 //===----------------------------------------------------------------------===//
73 /// LandingPadInfo - This structure is used to retain landing pad info for
74 /// the current function.
75 ///
76 struct LandingPadInfo {
77   MachineBasicBlock *LandingPadBlock;      // Landing pad block.
78   SmallVector<MCSymbol *, 1> BeginLabels;  // Labels prior to invoke.
79   SmallVector<MCSymbol *, 1> EndLabels;    // Labels after invoke.
80   SmallVector<SEHHandler, 1> SEHHandlers;  // SEH handlers active at this lpad.
81   MCSymbol *LandingPadLabel;               // Label at beginning of landing pad.
82   const Function *Personality;             // Personality function.
83   std::vector<int> TypeIds;               // List of type ids (filters negative).
84   int WinEHState;                         // WinEH specific state number.
85
86   explicit LandingPadInfo(MachineBasicBlock *MBB)
87       : LandingPadBlock(MBB), LandingPadLabel(nullptr), Personality(nullptr),
88         WinEHState(-1) {}
89 };
90
91 //===----------------------------------------------------------------------===//
92 /// MachineModuleInfoImpl - This class can be derived from and used by targets
93 /// to hold private target-specific information for each Module.  Objects of
94 /// type are accessed/created with MMI::getInfo and destroyed when the
95 /// MachineModuleInfo is destroyed.
96 /// 
97 class MachineModuleInfoImpl {
98 public:
99   typedef PointerIntPair<MCSymbol*, 1, bool> StubValueTy;
100   virtual ~MachineModuleInfoImpl();
101   typedef std::vector<std::pair<MCSymbol*, StubValueTy> > SymbolListTy;
102 protected:
103
104   /// Return the entries from a DenseMap in a deterministic sorted orer.
105   /// Clears the map.
106   static SymbolListTy getSortedStubs(DenseMap<MCSymbol*, StubValueTy>&);
107 };
108
109 //===----------------------------------------------------------------------===//
110 /// MachineModuleInfo - This class contains meta information specific to a
111 /// module.  Queries can be made by different debugging and exception handling
112 /// schemes and reformated for specific use.
113 ///
114 class MachineModuleInfo : public ImmutablePass {
115   /// Context - This is the MCContext used for the entire code generator.
116   MCContext Context;
117
118   /// TheModule - This is the LLVM Module being worked on.
119   const Module *TheModule;
120
121   /// ObjFileMMI - This is the object-file-format-specific implementation of
122   /// MachineModuleInfoImpl, which lets targets accumulate whatever info they
123   /// want.
124   MachineModuleInfoImpl *ObjFileMMI;
125
126   /// List of moves done by a function's prolog.  Used to construct frame maps
127   /// by debug and exception handling consumers.
128   std::vector<MCCFIInstruction> FrameInstructions;
129
130   /// LandingPads - List of LandingPadInfo describing the landing pad
131   /// information in the current function.
132   std::vector<LandingPadInfo> LandingPads;
133
134   /// LPadToCallSiteMap - Map a landing pad's EH symbol to the call site
135   /// indexes.
136   DenseMap<MCSymbol*, SmallVector<unsigned, 4> > LPadToCallSiteMap;
137
138   /// CallSiteMap - Map of invoke call site index values to associated begin
139   /// EH_LABEL for the current function.
140   DenseMap<MCSymbol*, unsigned> CallSiteMap;
141
142   /// CurCallSite - The current call site index being processed, if any. 0 if
143   /// none.
144   unsigned CurCallSite;
145
146   /// TypeInfos - List of C++ TypeInfo used in the current function.
147   std::vector<const GlobalValue *> TypeInfos;
148
149   /// FilterIds - List of typeids encoding filters used in the current function.
150   std::vector<unsigned> FilterIds;
151
152   /// FilterEnds - List of the indices in FilterIds corresponding to filter
153   /// terminators.
154   std::vector<unsigned> FilterEnds;
155
156   /// Personalities - Vector of all personality functions ever seen. Used to
157   /// emit common EH frames.
158   std::vector<const Function *> Personalities;
159
160   /// UsedFunctions - The functions in the @llvm.used list in a more easily
161   /// searchable format.  This does not include the functions in
162   /// llvm.compiler.used.
163   SmallPtrSet<const Function *, 32> UsedFunctions;
164
165   /// AddrLabelSymbols - This map keeps track of which symbol is being used for
166   /// the specified basic block's address of label.
167   MMIAddrLabelMap *AddrLabelSymbols;
168
169   bool CallsEHReturn;
170   bool CallsUnwindInit;
171
172   /// DbgInfoAvailable - True if debugging information is available
173   /// in this module.
174   bool DbgInfoAvailable;
175
176   /// UsesVAFloatArgument - True if this module calls VarArg function with
177   /// floating-point arguments.  This is used to emit an undefined reference
178   /// to _fltused on Windows targets.
179   bool UsesVAFloatArgument;
180
181   /// UsesMorestackAddr - True if the module calls the __morestack function
182   /// indirectly, as is required under the large code model on x86. This is used
183   /// to emit a definition of a symbol, __morestack_addr, containing the
184   /// address. See comments in lib/Target/X86/X86FrameLowering.cpp for more
185   /// details.
186   bool UsesMorestackAddr;
187
188   EHPersonality PersonalityTypeCache;
189
190   DenseMap<const Function *, std::unique_ptr<WinEHFuncInfo>> FuncInfoMap;
191
192 public:
193   static char ID; // Pass identification, replacement for typeid
194
195   struct VariableDbgInfo {
196     const DILocalVariable *Var;
197     const DIExpression *Expr;
198     unsigned Slot;
199     const DILocation *Loc;
200
201     VariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr,
202                     unsigned Slot, const DILocation *Loc)
203         : Var(Var), Expr(Expr), Slot(Slot), Loc(Loc) {}
204   };
205   typedef SmallVector<VariableDbgInfo, 4> VariableDbgInfoMapTy;
206   VariableDbgInfoMapTy VariableDbgInfos;
207
208   MachineModuleInfo();  // DUMMY CONSTRUCTOR, DO NOT CALL.
209   // Real constructor.
210   MachineModuleInfo(const MCAsmInfo &MAI, const MCRegisterInfo &MRI,
211                     const MCObjectFileInfo *MOFI);
212   ~MachineModuleInfo() override;
213
214   // Initialization and Finalization
215   bool doInitialization(Module &) override;
216   bool doFinalization(Module &) override;
217
218   /// EndFunction - Discard function meta information.
219   ///
220   void EndFunction();
221
222   const MCContext &getContext() const { return Context; }
223   MCContext &getContext() { return Context; }
224
225   void setModule(const Module *M) { TheModule = M; }
226   const Module *getModule() const { return TheModule; }
227
228   const Function *getWinEHParent(const Function *F) const;
229   WinEHFuncInfo &getWinEHFuncInfo(const Function *F);
230   bool hasWinEHFuncInfo(const Function *F) const {
231     return FuncInfoMap.count(getWinEHParent(F)) > 0;
232   }
233
234   /// getInfo - Keep track of various per-function pieces of information for
235   /// backends that would like to do so.
236   ///
237   template<typename Ty>
238   Ty &getObjFileInfo() {
239     if (ObjFileMMI == nullptr)
240       ObjFileMMI = new Ty(*this);
241     return *static_cast<Ty*>(ObjFileMMI);
242   }
243
244   template<typename Ty>
245   const Ty &getObjFileInfo() const {
246     return const_cast<MachineModuleInfo*>(this)->getObjFileInfo<Ty>();
247   }
248
249   /// AnalyzeModule - Scan the module for global debug information.
250   ///
251   void AnalyzeModule(const Module &M);
252
253   /// hasDebugInfo - Returns true if valid debug info is present.
254   ///
255   bool hasDebugInfo() const { return DbgInfoAvailable; }
256   void setDebugInfoAvailability(bool avail) { DbgInfoAvailable = avail; }
257
258   bool callsEHReturn() const { return CallsEHReturn; }
259   void setCallsEHReturn(bool b) { CallsEHReturn = b; }
260
261   bool callsUnwindInit() const { return CallsUnwindInit; }
262   void setCallsUnwindInit(bool b) { CallsUnwindInit = b; }
263
264   bool usesVAFloatArgument() const {
265     return UsesVAFloatArgument;
266   }
267
268   void setUsesVAFloatArgument(bool b) {
269     UsesVAFloatArgument = b;
270   }
271
272   bool usesMorestackAddr() const {
273     return UsesMorestackAddr;
274   }
275
276   void setUsesMorestackAddr(bool b) {
277     UsesMorestackAddr = b;
278   }
279
280   /// \brief Returns a reference to a list of cfi instructions in the current
281   /// function's prologue.  Used to construct frame maps for debug and exception
282   /// handling comsumers.
283   const std::vector<MCCFIInstruction> &getFrameInstructions() const {
284     return FrameInstructions;
285   }
286
287   unsigned LLVM_ATTRIBUTE_UNUSED_RESULT
288   addFrameInst(const MCCFIInstruction &Inst) {
289     FrameInstructions.push_back(Inst);
290     return FrameInstructions.size() - 1;
291   }
292
293   /// getAddrLabelSymbol - Return the symbol to be used for the specified basic
294   /// block when its address is taken.  This cannot be its normal LBB label
295   /// because the block may be accessed outside its containing function.
296   MCSymbol *getAddrLabelSymbol(const BasicBlock *BB);
297
298   /// getAddrLabelSymbolToEmit - Return the symbol to be used for the specified
299   /// basic block when its address is taken.  If other blocks were RAUW'd to
300   /// this one, we may have to emit them as well, return the whole set.
301   std::vector<MCSymbol*> getAddrLabelSymbolToEmit(const BasicBlock *BB);
302
303   /// takeDeletedSymbolsForFunction - If the specified function has had any
304   /// references to address-taken blocks generated, but the block got deleted,
305   /// return the symbol now so we can emit it.  This prevents emitting a
306   /// reference to a symbol that has no definition.
307   void takeDeletedSymbolsForFunction(const Function *F,
308                                      std::vector<MCSymbol*> &Result);
309
310
311   //===- EH ---------------------------------------------------------------===//
312
313   /// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the
314   /// specified MachineBasicBlock.
315   LandingPadInfo &getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad);
316
317   /// addInvoke - Provide the begin and end labels of an invoke style call and
318   /// associate it with a try landing pad block.
319   void addInvoke(MachineBasicBlock *LandingPad,
320                  MCSymbol *BeginLabel, MCSymbol *EndLabel);
321
322   /// addLandingPad - Add a new panding pad.  Returns the label ID for the
323   /// landing pad entry.
324   MCSymbol *addLandingPad(MachineBasicBlock *LandingPad);
325
326   /// addPersonality - Provide the personality function for the exception
327   /// information.
328   void addPersonality(MachineBasicBlock *LandingPad,
329                       const Function *Personality);
330
331   void addWinEHState(MachineBasicBlock *LandingPad, int State);
332
333   /// getPersonalityIndex - Get index of the current personality function inside
334   /// Personalitites array
335   unsigned getPersonalityIndex() const;
336
337   /// getPersonalities - Return array of personality functions ever seen.
338   const std::vector<const Function *>& getPersonalities() const {
339     return Personalities;
340   }
341
342   /// isUsedFunction - Return true if the functions in the llvm.used list.  This
343   /// does not return true for things in llvm.compiler.used unless they are also
344   /// in llvm.used.
345   bool isUsedFunction(const Function *F) const {
346     return UsedFunctions.count(F);
347   }
348
349   /// addCatchTypeInfo - Provide the catch typeinfo for a landing pad.
350   ///
351   void addCatchTypeInfo(MachineBasicBlock *LandingPad,
352                         ArrayRef<const GlobalValue *> TyInfo);
353
354   /// addFilterTypeInfo - Provide the filter typeinfo for a landing pad.
355   ///
356   void addFilterTypeInfo(MachineBasicBlock *LandingPad,
357                          ArrayRef<const GlobalValue *> TyInfo);
358
359   /// addCleanup - Add a cleanup action for a landing pad.
360   ///
361   void addCleanup(MachineBasicBlock *LandingPad);
362
363   void addSEHCatchHandler(MachineBasicBlock *LandingPad, const Function *Filter,
364                           const BlockAddress *RecoverLabel);
365
366   void addSEHCleanupHandler(MachineBasicBlock *LandingPad,
367                             const Function *Cleanup);
368
369   /// getTypeIDFor - Return the type id for the specified typeinfo.  This is
370   /// function wide.
371   unsigned getTypeIDFor(const GlobalValue *TI);
372
373   /// getFilterIDFor - Return the id of the filter encoded by TyIds.  This is
374   /// function wide.
375   int getFilterIDFor(std::vector<unsigned> &TyIds);
376
377   /// TidyLandingPads - Remap landing pad labels and remove any deleted landing
378   /// pads.
379   void TidyLandingPads(DenseMap<MCSymbol*, uintptr_t> *LPMap = nullptr);
380
381   /// getLandingPads - Return a reference to the landing pad info for the
382   /// current function.
383   const std::vector<LandingPadInfo> &getLandingPads() const {
384     return LandingPads;
385   }
386
387   /// setCallSiteLandingPad - Map the landing pad's EH symbol to the call
388   /// site indexes.
389   void setCallSiteLandingPad(MCSymbol *Sym, ArrayRef<unsigned> Sites);
390
391   /// getCallSiteLandingPad - Get the call site indexes for a landing pad EH
392   /// symbol.
393   SmallVectorImpl<unsigned> &getCallSiteLandingPad(MCSymbol *Sym) {
394     assert(hasCallSiteLandingPad(Sym) &&
395            "missing call site number for landing pad!");
396     return LPadToCallSiteMap[Sym];
397   }
398
399   /// hasCallSiteLandingPad - Return true if the landing pad Eh symbol has an
400   /// associated call site.
401   bool hasCallSiteLandingPad(MCSymbol *Sym) {
402     return !LPadToCallSiteMap[Sym].empty();
403   }
404
405   /// setCallSiteBeginLabel - Map the begin label for a call site.
406   void setCallSiteBeginLabel(MCSymbol *BeginLabel, unsigned Site) {
407     CallSiteMap[BeginLabel] = Site;
408   }
409
410   /// getCallSiteBeginLabel - Get the call site number for a begin label.
411   unsigned getCallSiteBeginLabel(MCSymbol *BeginLabel) {
412     assert(hasCallSiteBeginLabel(BeginLabel) &&
413            "Missing call site number for EH_LABEL!");
414     return CallSiteMap[BeginLabel];
415   }
416
417   /// hasCallSiteBeginLabel - Return true if the begin label has a call site
418   /// number associated with it.
419   bool hasCallSiteBeginLabel(MCSymbol *BeginLabel) {
420     return CallSiteMap[BeginLabel] != 0;
421   }
422
423   /// setCurrentCallSite - Set the call site currently being processed.
424   void setCurrentCallSite(unsigned Site) { CurCallSite = Site; }
425
426   /// getCurrentCallSite - Get the call site currently being processed, if any.
427   /// return zero if none.
428   unsigned getCurrentCallSite() { return CurCallSite; }
429
430   /// getTypeInfos - Return a reference to the C++ typeinfo for the current
431   /// function.
432   const std::vector<const GlobalValue *> &getTypeInfos() const {
433     return TypeInfos;
434   }
435
436   /// getFilterIds - Return a reference to the typeids encoding filters used in
437   /// the current function.
438   const std::vector<unsigned> &getFilterIds() const {
439     return FilterIds;
440   }
441
442   /// getPersonality - Return a personality function if available.  The presence
443   /// of one is required to emit exception handling info.
444   const Function *getPersonality() const;
445
446   /// Classify the personality function amongst known EH styles.
447   EHPersonality getPersonalityType();
448
449   /// setVariableDbgInfo - Collect information used to emit debugging
450   /// information of a variable.
451   void setVariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr,
452                           unsigned Slot, const DILocation *Loc) {
453     VariableDbgInfos.emplace_back(Var, Expr, Slot, Loc);
454   }
455
456   VariableDbgInfoMapTy &getVariableDbgInfo() { return VariableDbgInfos; }
457
458 }; // End class MachineModuleInfo
459
460 } // End llvm namespace
461
462 #endif