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