More cruft from revert...
[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/GlobalValue.h"
35 #include "llvm/Pass.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/UniqueVector.h"
40 #include "llvm/Support/DataTypes.h"
41 #include "llvm/Support/Dwarf.h"
42
43 namespace llvm {
44
45 //===----------------------------------------------------------------------===//
46 // Forward declarations.
47 class AnchoredDesc;
48 class CompileUnitDesc;
49 class Constant;
50 class DebugInfoDesc;
51 class GlobalVariable;
52 class MachineBasicBlock;
53 class MachineFunction;
54 class MachineMove;
55 class Module;
56 class PointerType;
57 class StructType;
58 class VariableDesc;
59
60 //===----------------------------------------------------------------------===//
61 /// DIVisitor - Subclasses of this class apply steps to each of the fields in
62 /// the supplied DebugInfoDesc.
63 class DIVisitor {
64 public:
65   DIVisitor() {}
66   virtual ~DIVisitor() {}
67
68   /// ApplyToFields - Target the visitor to each field of the debug information
69   /// descriptor.
70   void ApplyToFields(DebugInfoDesc *DD);
71   
72   /// Apply - Subclasses override each of these methods to perform the
73   /// appropriate action for the type of field.
74   virtual void Apply(int &Field) = 0;
75   virtual void Apply(unsigned &Field) = 0;
76   virtual void Apply(int64_t &Field) = 0;
77   virtual void Apply(uint64_t &Field) = 0;
78   virtual void Apply(bool &Field) = 0;
79   virtual void Apply(std::string &Field) = 0;
80   virtual void Apply(DebugInfoDesc *&Field) = 0;
81   virtual void Apply(GlobalVariable *&Field) = 0;
82   virtual void Apply(std::vector<DebugInfoDesc *> &Field) = 0;
83 };
84
85 //===----------------------------------------------------------------------===//
86 /// DIDeserializer - This class is responsible for casting GlobalVariables
87 /// into DebugInfoDesc objects.
88 class DIDeserializer {
89   // Previously defined gloabls.
90   std::map<GlobalVariable*, DebugInfoDesc*> GlobalDescs;
91 public:
92   const std::map<GlobalVariable *, DebugInfoDesc *> &getGlobalDescs() const {
93     return GlobalDescs;
94   }
95
96   /// Deserialize - Reconstitute a GlobalVariable into it's component
97   /// DebugInfoDesc objects.
98   DebugInfoDesc *Deserialize(Value *V);
99   DebugInfoDesc *Deserialize(GlobalVariable *GV);
100 };
101
102 //===----------------------------------------------------------------------===//
103 /// DISerializer - This class is responsible for casting DebugInfoDesc objects
104 /// into GlobalVariables.
105 class DISerializer {
106   Module *M;                            // Definition space module.
107   PointerType *StrPtrTy;                // A "i8*" type.  Created lazily.
108   PointerType *EmptyStructPtrTy;        // A "{ }*" type.  Created lazily.
109
110   // Types per Tag. Created lazily.
111   std::map<unsigned, StructType *> TagTypes;
112
113   // Previously defined descriptors.
114   DenseMap<DebugInfoDesc *, GlobalVariable *> DescGlobals;
115
116   // Previously defined strings.
117   DenseMap<const char *, Constant*> StringCache;
118 public:
119   DISerializer()
120     : M(NULL), StrPtrTy(NULL), EmptyStructPtrTy(NULL), TagTypes(),
121       DescGlobals(), StringCache()
122   {}
123   
124   // Accessors
125   Module *getModule()        const { return M; };
126   void setModule(Module *module)  { M = module; }
127
128   /// getStrPtrType - Return a "i8*" type.
129   ///
130   const PointerType *getStrPtrType();
131   
132   /// getEmptyStructPtrType - Return a "{ }*" type.
133   ///
134   const PointerType *getEmptyStructPtrType();
135   
136   /// getTagType - Return the type describing the specified descriptor (via
137   /// tag.)
138   const StructType *getTagType(DebugInfoDesc *DD);
139   
140   /// getString - Construct the string as constant string global.
141   ///
142   Constant *getString(const std::string &String);
143   
144   /// Serialize - Recursively cast the specified descriptor into a
145   /// GlobalVariable so that it can be serialized to a .bc or .ll file.
146   GlobalVariable *Serialize(DebugInfoDesc *DD);
147
148   /// addDescriptor - Directly connect DD with existing GV.
149   void addDescriptor(DebugInfoDesc *DD, GlobalVariable *GV);
150 };
151
152 //===----------------------------------------------------------------------===//
153 /// DIVerifier - This class is responsible for verifying the given network of
154 /// GlobalVariables are valid as DebugInfoDesc objects.
155 class DIVerifier {
156   enum {
157     Unknown = 0,
158     Invalid,
159     Valid
160   };
161   DenseMap<GlobalVariable *, unsigned> Validity; // Tracks prior results.
162   std::map<unsigned, unsigned> Counts; // Count of fields per Tag type.
163 public:
164   DIVerifier()
165     : Validity(), Counts()
166   {}
167   
168   /// Verify - Return true if the GlobalVariable appears to be a valid
169   /// serialization of a DebugInfoDesc.
170   bool Verify(Value *V);
171   bool Verify(GlobalVariable *GV);
172
173   /// isVerified - Return true if the specified GV has already been
174   /// verified as a debug information descriptor.
175   bool isVerified(GlobalVariable *GV);
176 };
177
178 //===----------------------------------------------------------------------===//
179 /// SourceLineInfo - This class is used to record source line correspondence.
180 ///
181 class SourceLineInfo {
182   unsigned Line;                        // Source line number.
183   unsigned Column;                      // Source column.
184   unsigned SourceID;                    // Source ID number.
185   unsigned LabelID;                     // Label in code ID number.
186 public:
187   SourceLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
188   : Line(L), Column(C), SourceID(S), LabelID(I) {}
189   
190   // Accessors
191   unsigned getLine()     const { return Line; }
192   unsigned getColumn()   const { return Column; }
193   unsigned getSourceID() const { return SourceID; }
194   unsigned getLabelID()  const { return LabelID; }
195 };
196
197 //===----------------------------------------------------------------------===//
198 /// SourceFileInfo - This class is used to track source information.
199 ///
200 class SourceFileInfo {
201   unsigned DirectoryID;                 // Directory ID number.
202   std::string Name;                     // File name (not including directory.)
203 public:
204   SourceFileInfo(unsigned D, const std::string &N) : DirectoryID(D), Name(N) {}
205             
206   // Accessors
207   unsigned getDirectoryID()    const { return DirectoryID; }
208   const std::string &getName() const { return Name; }
209
210   /// operator== - Used by UniqueVector to locate entry.
211   ///
212   bool operator==(const SourceFileInfo &SI) const {
213     return getDirectoryID() == SI.getDirectoryID() && getName() == SI.getName();
214   }
215
216   /// operator< - Used by UniqueVector to locate entry.
217   ///
218   bool operator<(const SourceFileInfo &SI) const {
219     return getDirectoryID() < SI.getDirectoryID() ||
220           (getDirectoryID() == SI.getDirectoryID() && getName() < SI.getName());
221   }
222 };
223
224 //===----------------------------------------------------------------------===//
225 /// DebugVariable - This class is used to track local variable information.
226 ///
227 class DebugVariable {
228 private:
229   VariableDesc *Desc;                   // Variable Descriptor.
230   unsigned FrameIndex;                  // Variable frame index.
231
232 public:
233   DebugVariable(VariableDesc *D, unsigned I)
234   : Desc(D)
235   , FrameIndex(I)
236   {}
237   
238   // Accessors.
239   VariableDesc *getDesc()  const { return Desc; }
240   unsigned getFrameIndex() const { return FrameIndex; }
241 };
242
243 //===----------------------------------------------------------------------===//
244 /// DebugScope - This class is used to track scope information.
245 ///
246 class DebugScope {
247 private:
248   DebugScope *Parent;                   // Parent to this scope.
249   DebugInfoDesc *Desc;                  // Debug info descriptor for scope.
250                                         // Either subprogram or block.
251   unsigned StartLabelID;                // Label ID of the beginning of scope.
252   unsigned EndLabelID;                  // Label ID of the end of scope.
253   std::vector<DebugScope *> Scopes;     // Scopes defined in scope.
254   std::vector<DebugVariable *> Variables;// Variables declared in scope.
255   
256 public:
257   DebugScope(DebugScope *P, DebugInfoDesc *D)
258   : Parent(P)
259   , Desc(D)
260   , StartLabelID(0)
261   , EndLabelID(0)
262   , Scopes()
263   , Variables()
264   {}
265   ~DebugScope();
266   
267   // Accessors.
268   DebugScope *getParent()        const { return Parent; }
269   DebugInfoDesc *getDesc()       const { return Desc; }
270   unsigned getStartLabelID()     const { return StartLabelID; }
271   unsigned getEndLabelID()       const { return EndLabelID; }
272   std::vector<DebugScope *> &getScopes() { return Scopes; }
273   std::vector<DebugVariable *> &getVariables() { return Variables; }
274   void setStartLabelID(unsigned S) { StartLabelID = S; }
275   void setEndLabelID(unsigned E)   { EndLabelID = E; }
276   
277   /// AddScope - Add a scope to the scope.
278   ///
279   void AddScope(DebugScope *S) { Scopes.push_back(S); }
280   
281   /// AddVariable - Add a variable to the scope.
282   ///
283   void AddVariable(DebugVariable *V) { Variables.push_back(V); }
284 };
285
286 //===----------------------------------------------------------------------===//
287 /// LandingPadInfo - This structure is used to retain landing pad info for
288 /// the current function.
289 ///
290 struct LandingPadInfo {
291   MachineBasicBlock *LandingPadBlock;   // Landing pad block.
292   SmallVector<unsigned, 1> BeginLabels; // Labels prior to invoke.
293   SmallVector<unsigned, 1> EndLabels;   // Labels after invoke.
294   unsigned LandingPadLabel;             // Label at beginning of landing pad.
295   Function *Personality;                // Personality function.
296   std::vector<int> TypeIds;             // List of type ids (filters negative)
297
298   explicit LandingPadInfo(MachineBasicBlock *MBB)
299   : LandingPadBlock(MBB)
300   , LandingPadLabel(0)
301   , Personality(NULL)  
302   {}
303 };
304
305 //===----------------------------------------------------------------------===//
306 /// MachineModuleInfo - This class contains meta information specific to a
307 /// module.  Queries can be made by different debugging and exception handling 
308 /// schemes and reformated for specific use.
309 ///
310 class MachineModuleInfo : public ImmutablePass {
311 private:
312   // Use the same deserializer/verifier for the module.
313   DIDeserializer DR;
314   DIVerifier VR;
315
316   // CompileUnits - Uniquing vector for compile units.
317   UniqueVector<CompileUnitDesc *> CompileUnits;
318   
319   // Directories - Uniquing vector for directories.
320   UniqueVector<std::string> Directories;
321                                          
322   // SourceFiles - Uniquing vector for source files.
323   UniqueVector<SourceFileInfo> SourceFiles;
324
325   // Lines - List of of source line correspondence.
326   std::vector<SourceLineInfo> Lines;
327   
328   // LabelIDList - One entry per assigned label.  Normally the entry is equal to
329   // the list index(+1).  If the entry is zero then the label has been deleted.
330   // Any other value indicates the label has been deleted by is mapped to
331   // another label.
332   std::vector<unsigned> LabelIDList;
333   
334   // ScopeMap - Tracks the scopes in the current function.
335   std::map<DebugInfoDesc *, DebugScope *> ScopeMap;
336   
337   // RootScope - Top level scope for the current function.
338   //
339   DebugScope *RootScope;
340   
341   // FrameMoves - List of moves done by a function's prolog.  Used to construct
342   // frame maps by debug and exception handling consumers.
343   std::vector<MachineMove> FrameMoves;
344   
345   // LandingPads - List of LandingPadInfo describing the landing pad information
346   // in the current function.
347   std::vector<LandingPadInfo> LandingPads;
348   
349   // TypeInfos - List of C++ TypeInfo used in the current function.
350   //
351   std::vector<GlobalVariable *> TypeInfos;
352
353   // FilterIds - List of typeids encoding filters used in the current function.
354   //
355   std::vector<unsigned> FilterIds;
356
357   // FilterEnds - List of the indices in FilterIds corresponding to filter
358   // terminators.
359   //
360   std::vector<unsigned> FilterEnds;
361
362   // Personalities - Vector of all personality functions ever seen. Used to emit
363   // common EH frames.
364   std::vector<Function *> Personalities;
365
366   // UsedFunctions - the functions in the llvm.used list in a more easily
367   // searchable format.
368   SmallPtrSet<const Function *, 32> UsedFunctions;
369
370   bool CallsEHReturn;
371   bool CallsUnwindInit;
372 public:
373   static char ID; // Pass identification, replacement for typeid
374
375   MachineModuleInfo();
376   ~MachineModuleInfo();
377   
378   /// doInitialization - Initialize the state for a new module.
379   ///
380   bool doInitialization();
381   
382   /// doFinalization - Tear down the state after completion of a module.
383   ///
384   bool doFinalization();
385   
386   /// BeginFunction - Begin gathering function meta information.
387   ///
388   void BeginFunction(MachineFunction *MF);
389   
390   /// EndFunction - Discard function meta information.
391   ///
392   void EndFunction();
393
394   /// getDescFor - Convert a Value to a debug information descriptor.
395   ///
396   // FIXME - use new Value type when available.
397   DebugInfoDesc *getDescFor(Value *V);
398   
399   /// Verify - Verify that a Value is debug information descriptor.
400   ///
401   bool Verify(Value *V) { return VR.Verify(V); }
402
403   /// isVerified - Return true if the specified GV has already been
404   /// verified as a debug information descriptor.
405   bool isVerified(GlobalVariable *GV) { return VR.isVerified(GV); }
406   
407   /// AnalyzeModule - Scan the module for global debug information.
408   ///
409   void AnalyzeModule(Module &M);
410   
411   /// hasDebugInfo - Returns true if valid debug info is present.
412   ///
413   bool hasDebugInfo() const { return !CompileUnits.empty(); }
414   
415   bool callsEHReturn() const { return CallsEHReturn; }
416   void setCallsEHReturn(bool b) { CallsEHReturn = b; }
417
418   bool callsUnwindInit() const { return CallsUnwindInit; }
419   void setCallsUnwindInit(bool b) { CallsUnwindInit = b; }
420   
421   /// NextLabelID - Return the next unique label id.
422   ///
423   unsigned NextLabelID() {
424     unsigned ID = (unsigned)LabelIDList.size() + 1;
425     LabelIDList.push_back(ID);
426     return ID;
427   }
428   
429   /// RecordSourceLine - Records location information and associates it with a
430   /// label.  Returns a unique label ID used to generate a label and 
431   /// provide correspondence to the source line list.
432   unsigned RecordSourceLine(unsigned Line, unsigned Column, unsigned Source);
433   
434   /// InvalidateLabel - Inhibit use of the specified label # from
435   /// MachineModuleInfo, for example because the code was deleted.
436   void InvalidateLabel(unsigned LabelID) {
437     // Remap to zero to indicate deletion.
438     RemapLabel(LabelID, 0);
439   }
440
441   /// RemapLabel - Indicate that a label has been merged into another.
442   ///
443   void RemapLabel(unsigned OldLabelID, unsigned NewLabelID) {
444     assert(0 < OldLabelID && OldLabelID <= LabelIDList.size() &&
445           "Old label ID out of range.");
446     assert(NewLabelID <= LabelIDList.size() &&
447           "New label ID out of range.");
448     LabelIDList[OldLabelID - 1] = NewLabelID;
449   }
450   
451   /// MappedLabel - Find out the label's final ID.  Zero indicates deletion.
452   /// ID != Mapped ID indicates that the label was folded into another label.
453   unsigned MappedLabel(unsigned LabelID) const {
454     assert(LabelID <= LabelIDList.size() && "Debug label ID out of range.");
455     return LabelID ? LabelIDList[LabelID - 1] : 0;
456   }
457
458   /// RecordSource - Register a source file with debug info. Returns an source
459   /// ID.
460   unsigned RecordSource(const std::string &Directory,
461                         const std::string &Source);
462   unsigned RecordSource(const CompileUnitDesc *CompileUnit);
463   
464   /// getDirectories - Return the UniqueVector of std::string representing
465   /// directories.
466   const UniqueVector<std::string> &getDirectories() const {
467     return Directories;
468   }
469   
470   /// getSourceFiles - Return the UniqueVector of source files. 
471   ///
472   const UniqueVector<SourceFileInfo> &getSourceFiles() const {
473     return SourceFiles;
474   }
475   
476   /// getSourceLines - Return a vector of source lines.
477   ///
478   const std::vector<SourceLineInfo> &getSourceLines() const {
479     return Lines;
480   }
481   
482   /// SetupCompileUnits - Set up the unique vector of compile units.
483   ///
484   void SetupCompileUnits(Module &M);
485
486   /// getCompileUnits - Return a vector of debug compile units.
487   ///
488   const UniqueVector<CompileUnitDesc *> getCompileUnits() const;
489   
490   /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
491   /// named GlobalVariable.
492   void getGlobalVariablesUsing(Module &M, const std::string &RootName,
493                                std::vector<GlobalVariable*> &Result);
494
495   /// getAnchoredDescriptors - Return a vector of anchored debug descriptors.
496   ///
497   void getAnchoredDescriptors(Module &M, const AnchoredDesc *Desc,
498                               std::vector<void*> &AnchoredDescs);
499   
500   /// RecordRegionStart - Indicate the start of a region.
501   ///
502   unsigned RecordRegionStart(Value *V);
503
504   /// RecordRegionEnd - Indicate the end of a region.
505   ///
506   unsigned RecordRegionEnd(Value *V);
507
508   /// RecordVariable - Indicate the declaration of  a local variable.
509   ///
510   void RecordVariable(GlobalValue *GV, unsigned FrameIndex);
511   
512   /// getRootScope - Return current functions root scope.
513   ///
514   DebugScope *getRootScope() { return RootScope; }
515   
516   /// getOrCreateScope - Returns the scope associated with the given descriptor.
517   ///
518   DebugScope *getOrCreateScope(DebugInfoDesc *ScopeDesc);
519   
520   /// getFrameMoves - Returns a reference to a list of moves done in the current
521   /// function's prologue.  Used to construct frame maps for debug and exception
522   /// handling comsumers.
523   std::vector<MachineMove> &getFrameMoves() { return FrameMoves; }
524   
525   //===-EH-----------------------------------------------------------------===//
526
527   /// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the
528   /// specified MachineBasicBlock.
529   LandingPadInfo &getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad);
530
531   /// addInvoke - Provide the begin and end labels of an invoke style call and
532   /// associate it with a try landing pad block.
533   void addInvoke(MachineBasicBlock *LandingPad, unsigned BeginLabel,
534                                                 unsigned EndLabel);
535   
536   /// addLandingPad - Add a new panding pad.  Returns the label ID for the 
537   /// landing pad entry.
538   unsigned addLandingPad(MachineBasicBlock *LandingPad);
539   
540   /// addPersonality - Provide the personality function for the exception
541   /// information.
542   void addPersonality(MachineBasicBlock *LandingPad, Function *Personality);
543
544   /// getPersonalityIndex - Get index of the current personality function inside
545   /// Personalitites array
546   unsigned getPersonalityIndex() const;
547
548   /// getPersonalities - Return array of personality functions ever seen.
549   const std::vector<Function *>& getPersonalities() const {
550     return Personalities;
551   }
552
553   // UsedFunctions - Return set of the functions in the llvm.used list.
554   const SmallPtrSet<const Function *, 32>& getUsedFunctions() const {
555     return UsedFunctions;
556   }
557
558   /// addCatchTypeInfo - Provide the catch typeinfo for a landing pad.
559   ///
560   void addCatchTypeInfo(MachineBasicBlock *LandingPad,
561                         std::vector<GlobalVariable *> &TyInfo);
562
563   /// addFilterTypeInfo - Provide the filter typeinfo for a landing pad.
564   ///
565   void addFilterTypeInfo(MachineBasicBlock *LandingPad,
566                          std::vector<GlobalVariable *> &TyInfo);
567
568   /// addCleanup - Add a cleanup action for a landing pad.
569   ///
570   void addCleanup(MachineBasicBlock *LandingPad);
571
572   /// getTypeIDFor - Return the type id for the specified typeinfo.  This is 
573   /// function wide.
574   unsigned getTypeIDFor(GlobalVariable *TI);
575
576   /// getFilterIDFor - Return the id of the filter encoded by TyIds.  This is
577   /// function wide.
578   int getFilterIDFor(std::vector<unsigned> &TyIds);
579
580   /// TidyLandingPads - Remap landing pad labels and remove any deleted landing
581   /// pads.
582   void TidyLandingPads();
583                         
584   /// getLandingPads - Return a reference to the landing pad info for the
585   /// current function.
586   const std::vector<LandingPadInfo> &getLandingPads() const {
587     return LandingPads;
588   }
589   
590   /// getTypeInfos - Return a reference to the C++ typeinfo for the current
591   /// function.
592   const std::vector<GlobalVariable *> &getTypeInfos() const {
593     return TypeInfos;
594   }
595
596   /// getFilterIds - Return a reference to the typeids encoding filters used in
597   /// the current function.
598   const std::vector<unsigned> &getFilterIds() const {
599     return FilterIds;
600   }
601
602   /// getPersonality - Return a personality function if available.  The presence
603   /// of one is required to emit exception handling info.
604   Function *getPersonality() const;
605
606   DIDeserializer *getDIDeserializer() { return &DR; }
607 }; // End class MachineModuleInfo
608
609 } // End llvm namespace
610
611 #endif