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