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