1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
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 // This coordinates the debug information generation while generating code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGDebugInfo.h"
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/RecordLayout.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/FileManager.h"
23 #include "clang/Basic/Version.h"
24 #include "clang/CodeGen/CodeGenOptions.h"
25 #include "llvm/Constants.h"
26 #include "llvm/DerivedTypes.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Module.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/Support/Dwarf.h"
33 #include "llvm/System/Path.h"
34 #include "llvm/Target/TargetMachine.h"
35 using namespace clang;
36 using namespace clang::CodeGen;
37 
38 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
39   : CGM(CGM), isMainCompileUnitCreated(false), DebugFactory(CGM.getModule()),
40     BlockLiteralGenericSet(false) {
41 }
42 
43 CGDebugInfo::~CGDebugInfo() {
44   assert(RegionStack.empty() && "Region stack mismatch, stack not empty!");
45 }
46 
47 void CGDebugInfo::setLocation(SourceLocation Loc) {
48   if (Loc.isValid())
49     CurLoc = CGM.getContext().getSourceManager().getInstantiationLoc(Loc);
50 }
51 
52 /// getContext - Get context info for the decl.
53 llvm::DIDescriptor CGDebugInfo::getContext(const VarDecl *Decl,
54                                            llvm::DIDescriptor &CompileUnit) {
55   if (Decl->isFileVarDecl())
56     return CompileUnit;
57   if (Decl->getDeclContext()->isFunctionOrMethod()) {
58     // Find the last subprogram in region stack.
59     for (unsigned RI = RegionStack.size(), RE = 0; RI != RE; --RI) {
60       llvm::DIDescriptor R(RegionStack[RI - 1]);
61       if (R.isSubprogram())
62         return R;
63     }
64   }
65   return CompileUnit;
66 }
67 
68 /// getOrCreateCompileUnit - Get the compile unit from the cache or create a new
69 /// one if necessary. This returns null for invalid source locations.
70 llvm::DICompileUnit CGDebugInfo::getOrCreateCompileUnit(SourceLocation Loc) {
71   // Get source file information.
72   const char *FileName =  "<unknown>";
73   SourceManager &SM = CGM.getContext().getSourceManager();
74   unsigned FID = 0;
75   if (Loc.isValid()) {
76     PresumedLoc PLoc = SM.getPresumedLoc(Loc);
77     FileName = PLoc.getFilename();
78     FID = PLoc.getIncludeLoc().getRawEncoding();
79   }
80 
81   // See if this compile unit has been used before.
82   llvm::DICompileUnit &Unit = CompileUnitCache[FID];
83   if (!Unit.isNull()) return Unit;
84 
85   // Get absolute path name.
86   llvm::sys::Path AbsFileName(FileName);
87   AbsFileName.makeAbsolute();
88 
89   // See if thie compile unit is representing main source file. Each source
90   // file has corresponding compile unit. There is only one main source
91   // file at a time.
92   bool isMain = false;
93   const LangOptions &LO = CGM.getLangOptions();
94   const CodeGenOptions &CGO = CGM.getCodeGenOpts();
95   if (isMainCompileUnitCreated == false) {
96     if (!CGO.MainFileName.empty()) {
97       if (AbsFileName.getLast() == CGO.MainFileName)
98         isMain = true;
99     } else {
100       if (Loc.isValid() && SM.isFromMainFile(Loc))
101         isMain = true;
102     }
103     if (isMain)
104       isMainCompileUnitCreated = true;
105   }
106 
107   unsigned LangTag;
108   if (LO.CPlusPlus) {
109     if (LO.ObjC1)
110       LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
111     else
112       LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
113   } else if (LO.ObjC1) {
114     LangTag = llvm::dwarf::DW_LANG_ObjC;
115   } else if (LO.C99) {
116     LangTag = llvm::dwarf::DW_LANG_C99;
117   } else {
118     LangTag = llvm::dwarf::DW_LANG_C89;
119   }
120 
121   const char *Producer =
122 #ifdef CLANG_VENDOR
123     CLANG_VENDOR
124 #endif
125     "clang " CLANG_VERSION_STRING;
126   bool isOptimized = LO.Optimize;
127   const char *Flags = "";   // FIXME: Encode command line options.
128 
129   // Figure out which version of the ObjC runtime we have.
130   unsigned RuntimeVers = 0;
131   if (LO.ObjC1)
132     RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
133 
134   // Create new compile unit.
135   return Unit = DebugFactory.CreateCompileUnit(LangTag,
136                                                AbsFileName.getLast(),
137                                                AbsFileName.getDirname(),
138                                                Producer, isMain,
139                                                isOptimized, Flags, RuntimeVers);
140 }
141 
142 /// CreateType - Get the Basic type from the cache or create a new
143 /// one if necessary.
144 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT,
145                                      llvm::DICompileUnit Unit) {
146   unsigned Encoding = 0;
147   switch (BT->getKind()) {
148   default:
149   case BuiltinType::Void:
150     return llvm::DIType();
151   case BuiltinType::UChar:
152   case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
153   case BuiltinType::Char_S:
154   case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
155   case BuiltinType::UShort:
156   case BuiltinType::UInt:
157   case BuiltinType::ULong:
158   case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
159   case BuiltinType::Short:
160   case BuiltinType::Int:
161   case BuiltinType::Long:
162   case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
163   case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
164   case BuiltinType::Float:
165   case BuiltinType::LongDouble:
166   case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
167   }
168   // Bit size, align and offset of the type.
169   uint64_t Size = CGM.getContext().getTypeSize(BT);
170   uint64_t Align = CGM.getContext().getTypeAlign(BT);
171   uint64_t Offset = 0;
172 
173   llvm::DIType DbgTy =
174     DebugFactory.CreateBasicType(Unit,
175                                  BT->getName(CGM.getContext().getLangOptions()),
176                                  Unit, 0, Size, Align,
177                                  Offset, /*flags*/ 0, Encoding);
178   return DbgTy;
179 }
180 
181 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty,
182                                      llvm::DICompileUnit Unit) {
183   // Bit size, align and offset of the type.
184   unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
185   if (Ty->isComplexIntegerType())
186     Encoding = llvm::dwarf::DW_ATE_lo_user;
187 
188   uint64_t Size = CGM.getContext().getTypeSize(Ty);
189   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
190   uint64_t Offset = 0;
191 
192   llvm::DIType DbgTy =
193     DebugFactory.CreateBasicType(Unit, "complex",
194                                  Unit, 0, Size, Align,
195                                  Offset, /*flags*/ 0, Encoding);
196   return DbgTy;
197 }
198 
199 /// CreateCVRType - Get the qualified type from the cache or create
200 /// a new one if necessary.
201 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DICompileUnit Unit) {
202   QualifierCollector Qc;
203   const Type *T = Qc.strip(Ty);
204 
205   // Ignore these qualifiers for now.
206   Qc.removeObjCGCAttr();
207   Qc.removeAddressSpace();
208 
209   // We will create one Derived type for one qualifier and recurse to handle any
210   // additional ones.
211   unsigned Tag;
212   if (Qc.hasConst()) {
213     Tag = llvm::dwarf::DW_TAG_const_type;
214     Qc.removeConst();
215   } else if (Qc.hasVolatile()) {
216     Tag = llvm::dwarf::DW_TAG_volatile_type;
217     Qc.removeVolatile();
218   } else if (Qc.hasRestrict()) {
219     Tag = llvm::dwarf::DW_TAG_restrict_type;
220     Qc.removeRestrict();
221   } else {
222     assert(Qc.empty() && "Unknown type qualifier for debug info");
223     return getOrCreateType(QualType(T, 0), Unit);
224   }
225 
226   llvm::DIType FromTy = getOrCreateType(Qc.apply(T), Unit);
227 
228   // No need to fill in the Name, Line, Size, Alignment, Offset in case of
229   // CVR derived types.
230   llvm::DIType DbgTy =
231     DebugFactory.CreateDerivedType(Tag, Unit, "", llvm::DICompileUnit(),
232                                    0, 0, 0, 0, 0, FromTy);
233   return DbgTy;
234 }
235 
236 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
237                                      llvm::DICompileUnit Unit) {
238   llvm::DIType DbgTy =
239     CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
240                           Ty->getPointeeType(), Unit);
241   return DbgTy;
242 }
243 
244 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
245                                      llvm::DICompileUnit Unit) {
246   return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
247                                Ty->getPointeeType(), Unit);
248 }
249 
250 llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
251                                                 const Type *Ty,
252                                                 QualType PointeeTy,
253                                                 llvm::DICompileUnit Unit) {
254   llvm::DIType EltTy = getOrCreateType(PointeeTy, Unit);
255 
256   // Bit size, align and offset of the type.
257 
258   // Size is always the size of a pointer. We can't use getTypeSize here
259   // because that does not return the correct value for references.
260   uint64_t Size =
261     CGM.getContext().Target.getPointerWidth(PointeeTy.getAddressSpace());
262   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
263 
264   return
265     DebugFactory.CreateDerivedType(Tag, Unit, "", llvm::DICompileUnit(),
266                                    0, Size, Align, 0, 0, EltTy);
267 
268 }
269 
270 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
271                                      llvm::DICompileUnit Unit) {
272   if (BlockLiteralGenericSet)
273     return BlockLiteralGeneric;
274 
275   llvm::DICompileUnit DefUnit;
276   unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
277 
278   llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
279 
280   llvm::DIType FieldTy;
281 
282   QualType FType;
283   uint64_t FieldSize, FieldOffset;
284   unsigned FieldAlign;
285 
286   llvm::DIArray Elements;
287   llvm::DIType EltTy, DescTy;
288 
289   FieldOffset = 0;
290   FType = CGM.getContext().UnsignedLongTy;
291   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
292   FieldSize = CGM.getContext().getTypeSize(FType);
293   FieldAlign = CGM.getContext().getTypeAlign(FType);
294   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
295                                            "reserved", DefUnit,
296                                            0, FieldSize, FieldAlign,
297                                            FieldOffset, 0, FieldTy);
298   EltTys.push_back(FieldTy);
299 
300   FieldOffset += FieldSize;
301   FType = CGM.getContext().UnsignedLongTy;
302   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
303   FieldSize = CGM.getContext().getTypeSize(FType);
304   FieldAlign = CGM.getContext().getTypeAlign(FType);
305   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
306                                            "Size", DefUnit,
307                                            0, FieldSize, FieldAlign,
308                                            FieldOffset, 0, FieldTy);
309   EltTys.push_back(FieldTy);
310 
311   FieldOffset += FieldSize;
312   Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
313   EltTys.clear();
314 
315   unsigned Flags = llvm::DIType::FlagAppleBlock;
316 
317   EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_descriptor",
318                                            DefUnit, 0, FieldOffset, 0, 0, Flags,
319                                            llvm::DIType(), Elements);
320 
321   // Bit size, align and offset of the type.
322   uint64_t Size = CGM.getContext().getTypeSize(Ty);
323   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
324 
325   DescTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
326                                           Unit, "", llvm::DICompileUnit(),
327                                           0, Size, Align, 0, 0, EltTy);
328 
329   FieldOffset = 0;
330   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
331   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
332   FieldSize = CGM.getContext().getTypeSize(FType);
333   FieldAlign = CGM.getContext().getTypeAlign(FType);
334   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
335                                            "__isa", DefUnit,
336                                            0, FieldSize, FieldAlign,
337                                            FieldOffset, 0, FieldTy);
338   EltTys.push_back(FieldTy);
339 
340   FieldOffset += FieldSize;
341   FType = CGM.getContext().IntTy;
342   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
343   FieldSize = CGM.getContext().getTypeSize(FType);
344   FieldAlign = CGM.getContext().getTypeAlign(FType);
345   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
346                                            "__flags", DefUnit,
347                                            0, FieldSize, FieldAlign,
348                                            FieldOffset, 0, FieldTy);
349   EltTys.push_back(FieldTy);
350 
351   FieldOffset += FieldSize;
352   FType = CGM.getContext().IntTy;
353   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
354   FieldSize = CGM.getContext().getTypeSize(FType);
355   FieldAlign = CGM.getContext().getTypeAlign(FType);
356   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
357                                            "__reserved", DefUnit,
358                                            0, FieldSize, FieldAlign,
359                                            FieldOffset, 0, FieldTy);
360   EltTys.push_back(FieldTy);
361 
362   FieldOffset += FieldSize;
363   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
364   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
365   FieldSize = CGM.getContext().getTypeSize(FType);
366   FieldAlign = CGM.getContext().getTypeAlign(FType);
367   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
368                                            "__FuncPtr", DefUnit,
369                                            0, FieldSize, FieldAlign,
370                                            FieldOffset, 0, FieldTy);
371   EltTys.push_back(FieldTy);
372 
373   FieldOffset += FieldSize;
374   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
375   FieldTy = DescTy;
376   FieldSize = CGM.getContext().getTypeSize(Ty);
377   FieldAlign = CGM.getContext().getTypeAlign(Ty);
378   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
379                                            "__descriptor", DefUnit,
380                                            0, FieldSize, FieldAlign,
381                                            FieldOffset, 0, FieldTy);
382   EltTys.push_back(FieldTy);
383 
384   FieldOffset += FieldSize;
385   Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
386 
387   EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_literal_generic",
388                                            DefUnit, 0, FieldOffset, 0, 0, Flags,
389                                            llvm::DIType(), Elements);
390 
391   BlockLiteralGenericSet = true;
392   BlockLiteralGeneric
393     = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
394                                      "", llvm::DICompileUnit(),
395                                      0, Size, Align, 0, 0, EltTy);
396   return BlockLiteralGeneric;
397 }
398 
399 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
400                                      llvm::DICompileUnit Unit) {
401   // Typedefs are derived from some other type.  If we have a typedef of a
402   // typedef, make sure to emit the whole chain.
403   llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
404 
405   // We don't set size information, but do specify where the typedef was
406   // declared.
407   SourceLocation DefLoc = Ty->getDecl()->getLocation();
408   llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(DefLoc);
409 
410   SourceManager &SM = CGM.getContext().getSourceManager();
411   PresumedLoc PLoc = SM.getPresumedLoc(DefLoc);
412   unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
413 
414   llvm::DIType DbgTy =
415     DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_typedef, Unit,
416                                    Ty->getDecl()->getName(),
417                                    DefUnit, Line, 0, 0, 0, 0, Src);
418   return DbgTy;
419 }
420 
421 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
422                                      llvm::DICompileUnit Unit) {
423   llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
424 
425   // Add the result type at least.
426   EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
427 
428   // Set up remainder of arguments if there is a prototype.
429   // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
430   if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
431     for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
432       EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
433   } else {
434     // FIXME: Handle () case in C.  llvm-gcc doesn't do it either.
435   }
436 
437   llvm::DIArray EltTypeArray =
438     DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
439 
440   llvm::DIType DbgTy =
441     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
442                                      Unit, "", llvm::DICompileUnit(),
443                                      0, 0, 0, 0, 0,
444                                      llvm::DIType(), EltTypeArray);
445   return DbgTy;
446 }
447 
448 /// CreateType - get structure or union type.
449 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty,
450                                      llvm::DICompileUnit Unit) {
451   RecordDecl *Decl = Ty->getDecl();
452 
453   unsigned Tag;
454   if (Decl->isStruct())
455     Tag = llvm::dwarf::DW_TAG_structure_type;
456   else if (Decl->isUnion())
457     Tag = llvm::dwarf::DW_TAG_union_type;
458   else {
459     assert(Decl->isClass() && "Unknown RecordType!");
460     Tag = llvm::dwarf::DW_TAG_class_type;
461   }
462 
463   SourceManager &SM = CGM.getContext().getSourceManager();
464 
465   // Get overall information about the record type for the debug info.
466   PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
467   llvm::DICompileUnit DefUnit;
468   unsigned Line = 0;
469   if (!PLoc.isInvalid()) {
470     DefUnit = getOrCreateCompileUnit(Decl->getLocation());
471     Line = PLoc.getLine();
472   }
473 
474   // Records and classes and unions can all be recursive.  To handle them, we
475   // first generate a debug descriptor for the struct as a forward declaration.
476   // Then (if it is a definition) we go through and get debug info for all of
477   // its members.  Finally, we create a descriptor for the complete type (which
478   // may refer to the forward decl if the struct is recursive) and replace all
479   // uses of the forward declaration with the final definition.
480   llvm::DICompositeType FwdDecl =
481     DebugFactory.CreateCompositeType(Tag, Unit, Decl->getName(),
482                                      DefUnit, Line, 0, 0, 0, 0,
483                                      llvm::DIType(), llvm::DIArray());
484 
485   // If this is just a forward declaration, return it.
486   if (!Decl->getDefinition(CGM.getContext()))
487     return FwdDecl;
488 
489   llvm::TrackingVH<llvm::MDNode> FwdDeclNode = FwdDecl.getNode();
490   // Otherwise, insert it into the TypeCache so that recursive uses will find
491   // it.
492   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl.getNode();
493 
494   // Convert all the elements.
495   llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
496 
497   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(Decl);
498 
499   unsigned FieldNo = 0;
500   for (RecordDecl::field_iterator I = Decl->field_begin(),
501                                   E = Decl->field_end();
502        I != E; ++I, ++FieldNo) {
503     FieldDecl *Field = *I;
504     llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
505 
506     llvm::StringRef FieldName = Field->getName();
507 
508     // Ignore unnamed fields.
509     if (FieldName.empty())
510       continue;
511 
512     // Get the location for the field.
513     SourceLocation FieldDefLoc = Field->getLocation();
514     PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
515     llvm::DICompileUnit FieldDefUnit;
516     unsigned FieldLine = 0;
517 
518     if (!PLoc.isInvalid()) {
519       FieldDefUnit = getOrCreateCompileUnit(FieldDefLoc);
520       FieldLine = PLoc.getLine();
521     }
522 
523     QualType FType = Field->getType();
524     uint64_t FieldSize = 0;
525     unsigned FieldAlign = 0;
526     if (!FType->isIncompleteArrayType()) {
527 
528       // Bit size, align and offset of the type.
529       FieldSize = CGM.getContext().getTypeSize(FType);
530       Expr *BitWidth = Field->getBitWidth();
531       if (BitWidth)
532         FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
533 
534       FieldAlign =  CGM.getContext().getTypeAlign(FType);
535     }
536 
537     uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
538 
539     // Create a DW_TAG_member node to remember the offset of this field in the
540     // struct.  FIXME: This is an absolutely insane way to capture this
541     // information.  When we gut debug info, this should be fixed.
542     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
543                                              FieldName, FieldDefUnit,
544                                              FieldLine, FieldSize, FieldAlign,
545                                              FieldOffset, 0, FieldTy);
546     EltTys.push_back(FieldTy);
547   }
548 
549   llvm::DIArray Elements =
550     DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
551 
552   // Bit size, align and offset of the type.
553   uint64_t Size = CGM.getContext().getTypeSize(Ty);
554   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
555 
556   llvm::DICompositeType RealDecl =
557     DebugFactory.CreateCompositeType(Tag, Unit, Decl->getName(),
558                                      DefUnit, Line, Size, Align, 0, 0,
559                                      llvm::DIType(), Elements);
560 
561   // Now that we have a real decl for the struct, replace anything using the
562   // old decl with the new one.  This will recursively update the debug info.
563   llvm::DIDerivedType(FwdDeclNode).replaceAllUsesWith(RealDecl);
564 
565   return RealDecl;
566 }
567 
568 /// CreateType - get objective-c interface type.
569 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
570                                      llvm::DICompileUnit Unit) {
571   ObjCInterfaceDecl *Decl = Ty->getDecl();
572 
573   unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
574   SourceManager &SM = CGM.getContext().getSourceManager();
575 
576   // Get overall information about the record type for the debug info.
577   llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(Decl->getLocation());
578   PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
579   unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
580 
581 
582   unsigned RuntimeLang = DefUnit.getLanguage();
583 
584   // To handle recursive interface, we
585   // first generate a debug descriptor for the struct as a forward declaration.
586   // Then (if it is a definition) we go through and get debug info for all of
587   // its members.  Finally, we create a descriptor for the complete type (which
588   // may refer to the forward decl if the struct is recursive) and replace all
589   // uses of the forward declaration with the final definition.
590   llvm::DICompositeType FwdDecl =
591     DebugFactory.CreateCompositeType(Tag, Unit, Decl->getName(),
592                                      DefUnit, Line, 0, 0, 0, 0,
593                                      llvm::DIType(), llvm::DIArray(),
594                                      RuntimeLang);
595 
596   // If this is just a forward declaration, return it.
597   if (Decl->isForwardDecl())
598     return FwdDecl;
599 
600   llvm::TrackingVH<llvm::MDNode> FwdDeclNode = FwdDecl.getNode();
601   // Otherwise, insert it into the TypeCache so that recursive uses will find
602   // it.
603   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl.getNode();
604 
605   // Convert all the elements.
606   llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
607 
608   ObjCInterfaceDecl *SClass = Decl->getSuperClass();
609   if (SClass) {
610     llvm::DIType SClassTy =
611       getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
612     llvm::DIType InhTag =
613       DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
614                                      Unit, "", llvm::DICompileUnit(), 0, 0, 0,
615                                      0 /* offset */, 0, SClassTy);
616     EltTys.push_back(InhTag);
617   }
618 
619   const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(Decl);
620 
621   unsigned FieldNo = 0;
622   for (ObjCInterfaceDecl::ivar_iterator I = Decl->ivar_begin(),
623          E = Decl->ivar_end();  I != E; ++I, ++FieldNo) {
624     ObjCIvarDecl *Field = *I;
625     llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
626 
627     llvm::StringRef FieldName = Field->getName();
628 
629     // Ignore unnamed fields.
630     if (FieldName.empty())
631       continue;
632 
633     // Get the location for the field.
634     SourceLocation FieldDefLoc = Field->getLocation();
635     llvm::DICompileUnit FieldDefUnit = getOrCreateCompileUnit(FieldDefLoc);
636     PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
637     unsigned FieldLine = PLoc.isInvalid() ? 0 : PLoc.getLine();
638 
639 
640     QualType FType = Field->getType();
641     uint64_t FieldSize = 0;
642     unsigned FieldAlign = 0;
643 
644     if (!FType->isIncompleteArrayType()) {
645 
646       // Bit size, align and offset of the type.
647       FieldSize = CGM.getContext().getTypeSize(FType);
648       Expr *BitWidth = Field->getBitWidth();
649       if (BitWidth)
650         FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
651 
652       FieldAlign =  CGM.getContext().getTypeAlign(FType);
653     }
654 
655     uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
656 
657     unsigned Flags = 0;
658     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
659       Flags = llvm::DIType::FlagProtected;
660     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
661       Flags = llvm::DIType::FlagPrivate;
662 
663     // Create a DW_TAG_member node to remember the offset of this field in the
664     // struct.  FIXME: This is an absolutely insane way to capture this
665     // information.  When we gut debug info, this should be fixed.
666     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
667                                              FieldName, FieldDefUnit,
668                                              FieldLine, FieldSize, FieldAlign,
669                                              FieldOffset, Flags, FieldTy);
670     EltTys.push_back(FieldTy);
671   }
672 
673   llvm::DIArray Elements =
674     DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
675 
676   // Bit size, align and offset of the type.
677   uint64_t Size = CGM.getContext().getTypeSize(Ty);
678   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
679 
680   llvm::DICompositeType RealDecl =
681     DebugFactory.CreateCompositeType(Tag, Unit, Decl->getName(), DefUnit,
682                                      Line, Size, Align, 0, 0, llvm::DIType(),
683                                      Elements, RuntimeLang);
684 
685   // Now that we have a real decl for the struct, replace anything using the
686   // old decl with the new one.  This will recursively update the debug info.
687   llvm::DIDerivedType(FwdDeclNode).replaceAllUsesWith(RealDecl);
688 
689   return RealDecl;
690 }
691 
692 llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty,
693                                      llvm::DICompileUnit Unit) {
694   EnumDecl *Decl = Ty->getDecl();
695 
696   llvm::SmallVector<llvm::DIDescriptor, 32> Enumerators;
697 
698   // Create DIEnumerator elements for each enumerator.
699   for (EnumDecl::enumerator_iterator
700          Enum = Decl->enumerator_begin(), EnumEnd = Decl->enumerator_end();
701        Enum != EnumEnd; ++Enum) {
702     Enumerators.push_back(DebugFactory.CreateEnumerator(Enum->getName(),
703                                             Enum->getInitVal().getZExtValue()));
704   }
705 
706   // Return a CompositeType for the enum itself.
707   llvm::DIArray EltArray =
708     DebugFactory.GetOrCreateArray(Enumerators.data(), Enumerators.size());
709 
710   SourceLocation DefLoc = Decl->getLocation();
711   llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(DefLoc);
712   SourceManager &SM = CGM.getContext().getSourceManager();
713   PresumedLoc PLoc = SM.getPresumedLoc(DefLoc);
714   unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
715 
716 
717   // Size and align of the type.
718   uint64_t Size = 0;
719   unsigned Align = 0;
720   if (!Ty->isIncompleteType()) {
721     Size = CGM.getContext().getTypeSize(Ty);
722     Align = CGM.getContext().getTypeAlign(Ty);
723   }
724 
725   llvm::DIType DbgTy =
726     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type,
727                                      Unit, Decl->getName(), DefUnit, Line,
728                                      Size, Align, 0, 0,
729                                      llvm::DIType(), EltArray);
730   return DbgTy;
731 }
732 
733 llvm::DIType CGDebugInfo::CreateType(const TagType *Ty,
734                                      llvm::DICompileUnit Unit) {
735   if (const RecordType *RT = dyn_cast<RecordType>(Ty))
736     return CreateType(RT, Unit);
737   else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
738     return CreateType(ET, Unit);
739 
740   return llvm::DIType();
741 }
742 
743 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
744                                      llvm::DICompileUnit Unit) {
745   uint64_t Size;
746   uint64_t Align;
747 
748 
749   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
750   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
751     Size = 0;
752     Align =
753       CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
754   } else if (Ty->isIncompleteArrayType()) {
755     Size = 0;
756     Align = CGM.getContext().getTypeAlign(Ty->getElementType());
757   } else {
758     // Size and align of the whole array, not the element type.
759     Size = CGM.getContext().getTypeSize(Ty);
760     Align = CGM.getContext().getTypeAlign(Ty);
761   }
762 
763   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
764   // interior arrays, do we care?  Why aren't nested arrays represented the
765   // obvious/recursive way?
766   llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
767   QualType EltTy(Ty, 0);
768   while ((Ty = dyn_cast<ArrayType>(EltTy))) {
769     uint64_t Upper = 0;
770     if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
771       if (CAT->getSize().getZExtValue())
772         Upper = CAT->getSize().getZExtValue() - 1;
773     // FIXME: Verify this is right for VLAs.
774     Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper));
775     EltTy = Ty->getElementType();
776   }
777 
778   llvm::DIArray SubscriptArray =
779     DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size());
780 
781   llvm::DIType DbgTy =
782     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_array_type,
783                                      Unit, "", llvm::DICompileUnit(),
784                                      0, Size, Align, 0, 0,
785                                      getOrCreateType(EltTy, Unit),
786                                      SubscriptArray);
787   return DbgTy;
788 }
789 
790 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
791                                      llvm::DICompileUnit Unit) {
792   return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
793                                Ty, Ty->getPointeeType(), Unit);
794 }
795 
796 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
797                                      llvm::DICompileUnit U) {
798   QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
799   llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
800 
801   if (!Ty->getPointeeType()->isFunctionType()) {
802     // We have a data member pointer type.
803     return PointerDiffDITy;
804   }
805 
806   // We have a member function pointer type. Treat it as a struct with two
807   // ptrdiff_t members.
808   std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
809 
810   uint64_t FieldOffset = 0;
811   llvm::DIDescriptor ElementTypes[2];
812 
813   // FIXME: This should probably be a function type instead.
814   ElementTypes[0] =
815     DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
816                                    "ptr", llvm::DICompileUnit(), 0,
817                                    Info.first, Info.second, FieldOffset, 0,
818                                    PointerDiffDITy);
819   FieldOffset += Info.first;
820 
821   ElementTypes[1] =
822     DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
823                                    "ptr", llvm::DICompileUnit(), 0,
824                                    Info.first, Info.second, FieldOffset, 0,
825                                    PointerDiffDITy);
826 
827   llvm::DIArray Elements =
828     DebugFactory.GetOrCreateArray(&ElementTypes[0],
829                                   llvm::array_lengthof(ElementTypes));
830 
831   return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
832                                           U, llvm::StringRef("test"),
833                                           llvm::DICompileUnit(), 0, FieldOffset,
834                                           0, 0, 0, llvm::DIType(), Elements);
835 }
836 
837 static QualType CanonicalizeTypeForDebugInfo(QualType T) {
838   switch (T->getTypeClass()) {
839   default:
840     return T;
841   case Type::TemplateSpecialization:
842     return cast<TemplateSpecializationType>(T)->desugar();
843   case Type::TypeOfExpr: {
844     TypeOfExprType *Ty = cast<TypeOfExprType>(T);
845     return CanonicalizeTypeForDebugInfo(Ty->getUnderlyingExpr()->getType());
846   }
847   case Type::TypeOf:
848     return cast<TypeOfType>(T)->getUnderlyingType();
849   case Type::Decltype:
850     return cast<DecltypeType>(T)->getUnderlyingType();
851   case Type::QualifiedName:
852     return cast<QualifiedNameType>(T)->getNamedType();
853   case Type::SubstTemplateTypeParm:
854     return cast<SubstTemplateTypeParmType>(T)->getReplacementType();
855   case Type::Elaborated:
856     return cast<ElaboratedType>(T)->getUnderlyingType();
857   }
858 }
859 
860 /// getOrCreateType - Get the type from the cache or create a new
861 /// one if necessary.
862 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
863                                           llvm::DICompileUnit Unit) {
864   if (Ty.isNull())
865     return llvm::DIType();
866 
867   // Canonicalize the type.
868   Ty = CanonicalizeTypeForDebugInfo(Ty);
869 
870   // Check for existing entry.
871   std::map<void *, llvm::WeakVH>::iterator it =
872     TypeCache.find(Ty.getAsOpaquePtr());
873   if (it != TypeCache.end()) {
874     // Verify that the debug info still exists.
875     if (&*it->second)
876       return llvm::DIType(cast<llvm::MDNode>(it->second));
877   }
878 
879   // Otherwise create the type.
880   llvm::DIType Res = CreateTypeNode(Ty, Unit);
881 
882   // And update the type cache.
883   TypeCache[Ty.getAsOpaquePtr()] = Res.getNode();
884   return Res;
885 }
886 
887 /// CreateTypeNode - Create a new debug type node.
888 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
889                                          llvm::DICompileUnit Unit) {
890   // Handle qualifiers, which recursively handles what they refer to.
891   if (Ty.hasLocalQualifiers())
892     return CreateQualifiedType(Ty, Unit);
893 
894   // Work out details of type.
895   switch (Ty->getTypeClass()) {
896 #define TYPE(Class, Base)
897 #define ABSTRACT_TYPE(Class, Base)
898 #define NON_CANONICAL_TYPE(Class, Base)
899 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
900 #include "clang/AST/TypeNodes.def"
901     assert(false && "Dependent types cannot show up in debug information");
902 
903   // FIXME: Handle these.
904   case Type::ExtVector:
905   case Type::Vector:
906   case Type::FixedWidthInt:
907     return llvm::DIType();
908   default:
909     assert(false && "Unhandled type class!");
910     return llvm::DIType();
911   case Type::ObjCObjectPointer:
912     return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
913   case Type::ObjCInterface:
914     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
915   case Type::Builtin: return CreateType(cast<BuiltinType>(Ty), Unit);
916   case Type::Complex: return CreateType(cast<ComplexType>(Ty), Unit);
917   case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
918   case Type::BlockPointer:
919     return CreateType(cast<BlockPointerType>(Ty), Unit);
920   case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
921   case Type::Record:
922   case Type::Enum:
923     return CreateType(cast<TagType>(Ty), Unit);
924   case Type::FunctionProto:
925   case Type::FunctionNoProto:
926     return CreateType(cast<FunctionType>(Ty), Unit);
927   case Type::ConstantArray:
928   case Type::VariableArray:
929   case Type::IncompleteArray:
930     return CreateType(cast<ArrayType>(Ty), Unit);
931 
932   case Type::LValueReference:
933     return CreateType(cast<LValueReferenceType>(Ty), Unit);
934 
935   case Type::MemberPointer:
936     return CreateType(cast<MemberPointerType>(Ty), Unit);
937   }
938 }
939 
940 /// EmitFunctionStart - Constructs the debug code for entering a function -
941 /// "llvm.dbg.func.start.".
942 void CGDebugInfo::EmitFunctionStart(llvm::StringRef Name, QualType FnType,
943                                     llvm::Function *Fn,
944                                     CGBuilderTy &Builder) {
945   llvm::StringRef LinkageName(Name);
946 
947   // Skip the asm prefix if it exists.
948   //
949   // FIXME: This should probably be the unmangled name?
950   if (Name[0] == '\01')
951     Name = Name.substr(1);
952 
953   // FIXME: Why is this using CurLoc???
954   llvm::DICompileUnit Unit = getOrCreateCompileUnit(CurLoc);
955   SourceManager &SM = CGM.getContext().getSourceManager();
956   unsigned LineNo = SM.getPresumedLoc(CurLoc).getLine();
957 
958   llvm::DISubprogram SP =
959     DebugFactory.CreateSubprogram(Unit, Name, Name, LinkageName, Unit, LineNo,
960                                   getOrCreateType(FnType, Unit),
961                                   Fn->hasInternalLinkage(), true/*definition*/);
962 
963   // Push function on region stack.
964   RegionStack.push_back(SP.getNode());
965 }
966 
967 
968 void CGDebugInfo::EmitStopPoint(llvm::Function *Fn, CGBuilderTy &Builder) {
969   if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
970 
971   // Don't bother if things are the same as last time.
972   SourceManager &SM = CGM.getContext().getSourceManager();
973   if (CurLoc == PrevLoc
974        || (SM.getInstantiationLineNumber(CurLoc) ==
975            SM.getInstantiationLineNumber(PrevLoc)
976            && SM.isFromSameFile(CurLoc, PrevLoc)))
977     return;
978 
979   // Update last state.
980   PrevLoc = CurLoc;
981 
982   // Get the appropriate compile unit.
983   llvm::DICompileUnit Unit = getOrCreateCompileUnit(CurLoc);
984   PresumedLoc PLoc = SM.getPresumedLoc(CurLoc);
985 
986   llvm::DIDescriptor DR(RegionStack.back());
987   llvm::DIScope DS = llvm::DIScope(DR.getNode());
988   llvm::DILocation DO(NULL);
989   llvm::DILocation DL =
990     DebugFactory.CreateLocation(PLoc.getLine(), PLoc.getColumn(),
991                                 DS, DO);
992   Builder.SetCurrentDebugLocation(DL.getNode());
993 }
994 
995 /// EmitRegionStart- Constructs the debug code for entering a declarative
996 /// region - "llvm.dbg.region.start.".
997 void CGDebugInfo::EmitRegionStart(llvm::Function *Fn, CGBuilderTy &Builder) {
998   llvm::DIDescriptor D =
999     DebugFactory.CreateLexicalBlock(RegionStack.empty() ?
1000                                     llvm::DIDescriptor() :
1001                                     llvm::DIDescriptor(RegionStack.back()));
1002   RegionStack.push_back(D.getNode());
1003 }
1004 
1005 /// EmitRegionEnd - Constructs the debug code for exiting a declarative
1006 /// region - "llvm.dbg.region.end."
1007 void CGDebugInfo::EmitRegionEnd(llvm::Function *Fn, CGBuilderTy &Builder) {
1008   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1009 
1010   // Provide an region stop point.
1011   EmitStopPoint(Fn, Builder);
1012 
1013   RegionStack.pop_back();
1014 }
1015 
1016 /// EmitDeclare - Emit local variable declaration debug info.
1017 void CGDebugInfo::EmitDeclare(const VarDecl *Decl, unsigned Tag,
1018                               llvm::Value *Storage, CGBuilderTy &Builder) {
1019   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1020 
1021   // Do not emit variable debug information while generating optimized code.
1022   // The llvm optimizer and code generator are not yet ready to support
1023   // optimized code debugging.
1024   const CodeGenOptions &CGO = CGM.getCodeGenOpts();
1025   if (CGO.OptimizationLevel)
1026     return;
1027 
1028   llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
1029   QualType Type = Decl->getType();
1030   llvm::DIType Ty = getOrCreateType(Type, Unit);
1031   if (Decl->hasAttr<BlocksAttr>()) {
1032     llvm::DICompileUnit DefUnit;
1033     unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
1034 
1035     llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
1036 
1037     llvm::DIType FieldTy;
1038 
1039     QualType FType;
1040     uint64_t FieldSize, FieldOffset;
1041     unsigned FieldAlign;
1042 
1043     llvm::DIArray Elements;
1044     llvm::DIType EltTy;
1045 
1046     // Build up structure for the byref.  See BuildByRefType.
1047     FieldOffset = 0;
1048     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1049     FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1050     FieldSize = CGM.getContext().getTypeSize(FType);
1051     FieldAlign = CGM.getContext().getTypeAlign(FType);
1052     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1053                                              "__isa", DefUnit,
1054                                              0, FieldSize, FieldAlign,
1055                                              FieldOffset, 0, FieldTy);
1056     EltTys.push_back(FieldTy);
1057     FieldOffset += FieldSize;
1058 
1059     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1060     FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1061     FieldSize = CGM.getContext().getTypeSize(FType);
1062     FieldAlign = CGM.getContext().getTypeAlign(FType);
1063     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1064                                              "__forwarding", DefUnit,
1065                                              0, FieldSize, FieldAlign,
1066                                              FieldOffset, 0, FieldTy);
1067     EltTys.push_back(FieldTy);
1068     FieldOffset += FieldSize;
1069 
1070     FType = CGM.getContext().getFixedWidthIntType(32, true); // Int32Ty;
1071     FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1072     FieldSize = CGM.getContext().getTypeSize(FType);
1073     FieldAlign = CGM.getContext().getTypeAlign(FType);
1074     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1075                                              "__flags", DefUnit,
1076                                              0, FieldSize, FieldAlign,
1077                                              FieldOffset, 0, FieldTy);
1078     EltTys.push_back(FieldTy);
1079     FieldOffset += FieldSize;
1080 
1081     FType = CGM.getContext().getFixedWidthIntType(32, true); // Int32Ty;
1082     FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1083     FieldSize = CGM.getContext().getTypeSize(FType);
1084     FieldAlign = CGM.getContext().getTypeAlign(FType);
1085     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1086                                              "__size", DefUnit,
1087                                              0, FieldSize, FieldAlign,
1088                                              FieldOffset, 0, FieldTy);
1089     EltTys.push_back(FieldTy);
1090     FieldOffset += FieldSize;
1091 
1092     bool HasCopyAndDispose = CGM.BlockRequiresCopying(Type);
1093     if (HasCopyAndDispose) {
1094       FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1095       FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1096       FieldSize = CGM.getContext().getTypeSize(FType);
1097       FieldAlign = CGM.getContext().getTypeAlign(FType);
1098       FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1099                                                "__copy_helper", DefUnit,
1100                                                0, FieldSize, FieldAlign,
1101                                                FieldOffset, 0, FieldTy);
1102       EltTys.push_back(FieldTy);
1103       FieldOffset += FieldSize;
1104 
1105       FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1106       FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1107       FieldSize = CGM.getContext().getTypeSize(FType);
1108       FieldAlign = CGM.getContext().getTypeAlign(FType);
1109       FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1110                                                "__destroy_helper", DefUnit,
1111                                                0, FieldSize, FieldAlign,
1112                                                FieldOffset, 0, FieldTy);
1113       EltTys.push_back(FieldTy);
1114       FieldOffset += FieldSize;
1115     }
1116 
1117     unsigned Align = CGM.getContext().getDeclAlignInBytes(Decl);
1118     if (Align > CGM.getContext().Target.getPointerAlign(0) / 8) {
1119       unsigned AlignedOffsetInBytes
1120         = llvm::RoundUpToAlignment(FieldOffset/8, Align);
1121       unsigned NumPaddingBytes
1122         = AlignedOffsetInBytes - FieldOffset/8;
1123 
1124       if (NumPaddingBytes > 0) {
1125         llvm::APInt pad(32, NumPaddingBytes);
1126         FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1127                                                      pad, ArrayType::Normal, 0);
1128         FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1129         FieldSize = CGM.getContext().getTypeSize(FType);
1130         FieldAlign = CGM.getContext().getTypeAlign(FType);
1131         FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member,
1132                                                  Unit, "", DefUnit,
1133                                                  0, FieldSize, FieldAlign,
1134                                                  FieldOffset, 0, FieldTy);
1135         EltTys.push_back(FieldTy);
1136         FieldOffset += FieldSize;
1137       }
1138     }
1139 
1140     FType = Type;
1141     FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1142     FieldSize = CGM.getContext().getTypeSize(FType);
1143     FieldAlign = Align*8;
1144 
1145     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1146                                              Decl->getName(), DefUnit,
1147                                              0, FieldSize, FieldAlign,
1148                                              FieldOffset, 0, FieldTy);
1149     EltTys.push_back(FieldTy);
1150     FieldOffset += FieldSize;
1151 
1152     Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
1153 
1154     unsigned Flags = llvm::DIType::FlagBlockByrefStruct;
1155 
1156     Ty = DebugFactory.CreateCompositeType(Tag, Unit, "",
1157                                           llvm::DICompileUnit(),
1158                                           0, FieldOffset, 0, 0, Flags,
1159                                           llvm::DIType(), Elements);
1160   }
1161 
1162   // Get location information.
1163   SourceManager &SM = CGM.getContext().getSourceManager();
1164   PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
1165   unsigned Line = 0;
1166   unsigned Column = 0;
1167   if (!PLoc.isInvalid()) {
1168     Line = PLoc.getLine();
1169     Column = PLoc.getColumn();
1170   } else {
1171     Unit = llvm::DICompileUnit();
1172   }
1173 
1174   // Create the descriptor for the variable.
1175   llvm::DIVariable D =
1176     DebugFactory.CreateVariable(Tag, llvm::DIDescriptor(RegionStack.back()),
1177                                 Decl->getName(),
1178                                 Unit, Line, Ty);
1179   // Insert an llvm.dbg.declare into the current block.
1180   llvm::Instruction *Call =
1181     DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1182 
1183   llvm::DIScope DS(RegionStack.back());
1184   llvm::DILocation DO(NULL);
1185   llvm::DILocation DL =
1186     DebugFactory.CreateLocation(Line, Column, DS, DO);
1187   Builder.SetDebugLocation(Call, DL.getNode());
1188 }
1189 
1190 /// EmitDeclare - Emit local variable declaration debug info.
1191 void CGDebugInfo::EmitDeclare(const BlockDeclRefExpr *BDRE, unsigned Tag,
1192                               llvm::Value *Storage, CGBuilderTy &Builder,
1193                               CodeGenFunction *CGF) {
1194   const ValueDecl *Decl = BDRE->getDecl();
1195   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1196 
1197   // Do not emit variable debug information while generating optimized code.
1198   // The llvm optimizer and code generator are not yet ready to support
1199   // optimized code debugging.
1200   const CodeGenOptions &CGO = CGM.getCodeGenOpts();
1201   if (CGO.OptimizationLevel || Builder.GetInsertBlock() == 0)
1202     return;
1203 
1204   uint64_t XOffset = 0;
1205   llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
1206   QualType Type = Decl->getType();
1207   llvm::DIType Ty = getOrCreateType(Type, Unit);
1208   if (Decl->hasAttr<BlocksAttr>()) {
1209     llvm::DICompileUnit DefUnit;
1210     unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
1211 
1212     llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
1213 
1214     llvm::DIType FieldTy;
1215 
1216     QualType FType;
1217     uint64_t FieldSize, FieldOffset;
1218     unsigned FieldAlign;
1219 
1220     llvm::DIArray Elements;
1221     llvm::DIType EltTy;
1222 
1223     // Build up structure for the byref.  See BuildByRefType.
1224     FieldOffset = 0;
1225     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1226     FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1227     FieldSize = CGM.getContext().getTypeSize(FType);
1228     FieldAlign = CGM.getContext().getTypeAlign(FType);
1229     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1230                                              "__isa", DefUnit,
1231                                              0, FieldSize, FieldAlign,
1232                                              FieldOffset, 0, FieldTy);
1233     EltTys.push_back(FieldTy);
1234     FieldOffset += FieldSize;
1235 
1236     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1237     FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1238     FieldSize = CGM.getContext().getTypeSize(FType);
1239     FieldAlign = CGM.getContext().getTypeAlign(FType);
1240     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1241                                              "__forwarding", DefUnit,
1242                                              0, FieldSize, FieldAlign,
1243                                              FieldOffset, 0, FieldTy);
1244     EltTys.push_back(FieldTy);
1245     FieldOffset += FieldSize;
1246 
1247     FType = CGM.getContext().getFixedWidthIntType(32, true); // Int32Ty;
1248     FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1249     FieldSize = CGM.getContext().getTypeSize(FType);
1250     FieldAlign = CGM.getContext().getTypeAlign(FType);
1251     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1252                                              "__flags", DefUnit,
1253                                              0, FieldSize, FieldAlign,
1254                                              FieldOffset, 0, FieldTy);
1255     EltTys.push_back(FieldTy);
1256     FieldOffset += FieldSize;
1257 
1258     FType = CGM.getContext().getFixedWidthIntType(32, true); // Int32Ty;
1259     FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1260     FieldSize = CGM.getContext().getTypeSize(FType);
1261     FieldAlign = CGM.getContext().getTypeAlign(FType);
1262     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1263                                              "__size", DefUnit,
1264                                              0, FieldSize, FieldAlign,
1265                                              FieldOffset, 0, FieldTy);
1266     EltTys.push_back(FieldTy);
1267     FieldOffset += FieldSize;
1268 
1269     bool HasCopyAndDispose = CGM.BlockRequiresCopying(Type);
1270     if (HasCopyAndDispose) {
1271       FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1272       FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1273       FieldSize = CGM.getContext().getTypeSize(FType);
1274       FieldAlign = CGM.getContext().getTypeAlign(FType);
1275       FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1276                                                "__copy_helper", DefUnit,
1277                                                0, FieldSize, FieldAlign,
1278                                                FieldOffset, 0, FieldTy);
1279       EltTys.push_back(FieldTy);
1280       FieldOffset += FieldSize;
1281 
1282       FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1283       FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1284       FieldSize = CGM.getContext().getTypeSize(FType);
1285       FieldAlign = CGM.getContext().getTypeAlign(FType);
1286       FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1287                                                "__destroy_helper", DefUnit,
1288                                                0, FieldSize, FieldAlign,
1289                                                FieldOffset, 0, FieldTy);
1290       EltTys.push_back(FieldTy);
1291       FieldOffset += FieldSize;
1292     }
1293 
1294     unsigned Align = CGM.getContext().getDeclAlignInBytes(Decl);
1295     if (Align > CGM.getContext().Target.getPointerAlign(0) / 8) {
1296       unsigned AlignedOffsetInBytes
1297         = llvm::RoundUpToAlignment(FieldOffset/8, Align);
1298       unsigned NumPaddingBytes
1299         = AlignedOffsetInBytes - FieldOffset/8;
1300 
1301       if (NumPaddingBytes > 0) {
1302         llvm::APInt pad(32, NumPaddingBytes);
1303         FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1304                                                      pad, ArrayType::Normal, 0);
1305         FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1306         FieldSize = CGM.getContext().getTypeSize(FType);
1307         FieldAlign = CGM.getContext().getTypeAlign(FType);
1308         FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member,
1309                                                  Unit, "", DefUnit,
1310                                                  0, FieldSize, FieldAlign,
1311                                                  FieldOffset, 0, FieldTy);
1312         EltTys.push_back(FieldTy);
1313         FieldOffset += FieldSize;
1314       }
1315     }
1316 
1317     FType = Type;
1318     FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1319     FieldSize = CGM.getContext().getTypeSize(FType);
1320     FieldAlign = Align*8;
1321 
1322     XOffset = FieldOffset;
1323     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1324                                              Decl->getName(), DefUnit,
1325                                              0, FieldSize, FieldAlign,
1326                                              FieldOffset, 0, FieldTy);
1327     EltTys.push_back(FieldTy);
1328     FieldOffset += FieldSize;
1329 
1330     Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
1331 
1332     unsigned Flags = llvm::DIType::FlagBlockByrefStruct;
1333 
1334     Ty = DebugFactory.CreateCompositeType(Tag, Unit, "",
1335                                           llvm::DICompileUnit(),
1336                                           0, FieldOffset, 0, 0, Flags,
1337                                           llvm::DIType(), Elements);
1338   }
1339 
1340   // Get location information.
1341   SourceManager &SM = CGM.getContext().getSourceManager();
1342   PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
1343   unsigned Line = 0;
1344   if (!PLoc.isInvalid())
1345     Line = PLoc.getLine();
1346   else
1347     Unit = llvm::DICompileUnit();
1348 
1349   uint64_t offset = CGF->BlockDecls[Decl];
1350   llvm::SmallVector<llvm::Value *, 9> addr;
1351   llvm::LLVMContext &VMContext = CGM.getLLVMContext();
1352   addr.push_back(llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1353                                         llvm::DIFactory::OpDeref));
1354   addr.push_back(llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1355                                         llvm::DIFactory::OpPlus));
1356   addr.push_back(llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1357                                         offset));
1358   if (BDRE->isByRef()) {
1359     addr.push_back(llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1360                                           llvm::DIFactory::OpDeref));
1361     addr.push_back(llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1362                                           llvm::DIFactory::OpPlus));
1363     offset = CGF->LLVMPointerWidth/8; // offset of __forwarding field
1364     addr.push_back(llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1365                                           offset));
1366     addr.push_back(llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1367                                           llvm::DIFactory::OpDeref));
1368     addr.push_back(llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1369                                           llvm::DIFactory::OpPlus));
1370     offset = XOffset/8;               // offset of x field
1371     addr.push_back(llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1372                                           offset));
1373   }
1374 
1375   // Create the descriptor for the variable.
1376   llvm::DIVariable D =
1377     DebugFactory.CreateComplexVariable(Tag, llvm::DIDescriptor(RegionStack.back()),
1378                                        Decl->getName(), Unit, Line, Ty,
1379                                        addr);
1380   // Insert an llvm.dbg.declare into the current block.
1381   llvm::Instruction *Call =
1382     DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertPoint());
1383 
1384   llvm::DIScope DS(RegionStack.back());
1385   llvm::DILocation DO(NULL);
1386   llvm::DILocation DL =
1387     DebugFactory.CreateLocation(Line, PLoc.getColumn(), DS, DO);
1388   Builder.SetDebugLocation(Call, DL.getNode());
1389 }
1390 
1391 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *Decl,
1392                                             llvm::Value *Storage,
1393                                             CGBuilderTy &Builder) {
1394   EmitDeclare(Decl, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder);
1395 }
1396 
1397 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
1398   const BlockDeclRefExpr *BDRE, llvm::Value *Storage, CGBuilderTy &Builder,
1399   CodeGenFunction *CGF) {
1400   EmitDeclare(BDRE, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder, CGF);
1401 }
1402 
1403 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
1404 /// variable declaration.
1405 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI,
1406                                            CGBuilderTy &Builder) {
1407   EmitDeclare(Decl, llvm::dwarf::DW_TAG_arg_variable, AI, Builder);
1408 }
1409 
1410 
1411 
1412 /// EmitGlobalVariable - Emit information about a global variable.
1413 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1414                                      const VarDecl *Decl) {
1415 
1416   // Create global variable debug descriptor.
1417   llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
1418   SourceManager &SM = CGM.getContext().getSourceManager();
1419   PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
1420   unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1421 
1422   QualType T = Decl->getType();
1423   if (T->isIncompleteArrayType()) {
1424 
1425     // CodeGen turns int[] into int[1] so we'll do the same here.
1426     llvm::APSInt ConstVal(32);
1427 
1428     ConstVal = 1;
1429     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1430 
1431     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1432                                            ArrayType::Normal, 0);
1433   }
1434   llvm::StringRef DeclName = Decl->getName();
1435   DebugFactory.CreateGlobalVariable(getContext(Decl, Unit), DeclName, DeclName,
1436                                     llvm::StringRef(), Unit, LineNo,
1437                                     getOrCreateType(T, Unit),
1438                                     Var->hasInternalLinkage(),
1439                                     true/*definition*/, Var);
1440 }
1441 
1442 /// EmitGlobalVariable - Emit information about an objective-c interface.
1443 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1444                                      ObjCInterfaceDecl *Decl) {
1445   // Create global variable debug descriptor.
1446   llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
1447   SourceManager &SM = CGM.getContext().getSourceManager();
1448   PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
1449   unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1450 
1451   llvm::StringRef Name = Decl->getName();
1452 
1453   QualType T = CGM.getContext().getObjCInterfaceType(Decl);
1454   if (T->isIncompleteArrayType()) {
1455 
1456     // CodeGen turns int[] into int[1] so we'll do the same here.
1457     llvm::APSInt ConstVal(32);
1458 
1459     ConstVal = 1;
1460     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1461 
1462     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1463                                            ArrayType::Normal, 0);
1464   }
1465 
1466   DebugFactory.CreateGlobalVariable(Unit, Name, Name, Name, Unit, LineNo,
1467                                     getOrCreateType(T, Unit),
1468                                     Var->hasInternalLinkage(),
1469                                     true/*definition*/, Var);
1470 }
1471