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 "CGBlocks.h"
16 #include "CGCXXABI.h"
17 #include "CGObjCRuntime.h"
18 #include "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclFriend.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/RecordLayout.h"
26 #include "clang/Basic/FileManager.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/Version.h"
29 #include "clang/Frontend/CodeGenOptions.h"
30 #include "clang/Lex/HeaderSearchOptions.h"
31 #include "clang/Lex/PreprocessorOptions.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/Intrinsics.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/Path.h"
43 using namespace clang;
44 using namespace clang::CodeGen;
45 
46 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
47     : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
48       DBuilder(CGM.getModule()) {
49   CreateCompileUnit();
50 }
51 
52 CGDebugInfo::~CGDebugInfo() {
53   assert(LexicalBlockStack.empty() &&
54          "Region stack mismatch, stack not empty!");
55 }
56 
57 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
58                                        SourceLocation TemporaryLocation)
59     : CGF(&CGF) {
60   init(TemporaryLocation);
61 }
62 
63 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
64                                        bool DefaultToEmpty,
65                                        SourceLocation TemporaryLocation)
66     : CGF(&CGF) {
67   init(TemporaryLocation, DefaultToEmpty);
68 }
69 
70 void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
71                               bool DefaultToEmpty) {
72   auto *DI = CGF->getDebugInfo();
73   if (!DI) {
74     CGF = nullptr;
75     return;
76   }
77 
78   OriginalLocation = CGF->Builder.getCurrentDebugLocation();
79   if (TemporaryLocation.isValid()) {
80     DI->EmitLocation(CGF->Builder, TemporaryLocation);
81     return;
82   }
83 
84   if (DefaultToEmpty) {
85     CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
86     return;
87   }
88 
89   // Construct a location that has a valid scope, but no line info.
90   assert(!DI->LexicalBlockStack.empty());
91   CGF->Builder.SetCurrentDebugLocation(
92       llvm::DebugLoc::get(0, 0, DI->LexicalBlockStack.back()));
93 }
94 
95 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
96     : CGF(&CGF) {
97   init(E->getExprLoc());
98 }
99 
100 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
101     : CGF(&CGF) {
102   if (!CGF.getDebugInfo()) {
103     this->CGF = nullptr;
104     return;
105   }
106   OriginalLocation = CGF.Builder.getCurrentDebugLocation();
107   if (Loc)
108     CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
109 }
110 
111 ApplyDebugLocation::~ApplyDebugLocation() {
112   // Query CGF so the location isn't overwritten when location updates are
113   // temporarily disabled (for C++ default function arguments)
114   if (CGF)
115     CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
116 }
117 
118 void CGDebugInfo::setLocation(SourceLocation Loc) {
119   // If the new location isn't valid return.
120   if (Loc.isInvalid())
121     return;
122 
123   CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
124 
125   // If we've changed files in the middle of a lexical scope go ahead
126   // and create a new lexical scope with file node if it's different
127   // from the one in the scope.
128   if (LexicalBlockStack.empty())
129     return;
130 
131   SourceManager &SM = CGM.getContext().getSourceManager();
132   auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
133   PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
134 
135   if (PCLoc.isInvalid() || Scope->getFilename() == PCLoc.getFilename())
136     return;
137 
138   if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
139     LexicalBlockStack.pop_back();
140     LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
141         LBF->getScope(), getOrCreateFile(CurLoc)));
142   } else if (isa<llvm::DILexicalBlock>(Scope) ||
143              isa<llvm::DISubprogram>(Scope)) {
144     LexicalBlockStack.pop_back();
145     LexicalBlockStack.emplace_back(
146         DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
147   }
148 }
149 
150 llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context) {
151   if (!Context)
152     return TheCU;
153 
154   auto I = RegionMap.find(Context);
155   if (I != RegionMap.end()) {
156     llvm::Metadata *V = I->second;
157     return dyn_cast_or_null<llvm::DIScope>(V);
158   }
159 
160   // Check namespace.
161   if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
162     return getOrCreateNameSpace(NSDecl);
163 
164   if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
165     if (!RDecl->isDependentType())
166       return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
167                              getOrCreateMainFile());
168   return TheCU;
169 }
170 
171 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
172   assert(FD && "Invalid FunctionDecl!");
173   IdentifierInfo *FII = FD->getIdentifier();
174   FunctionTemplateSpecializationInfo *Info =
175       FD->getTemplateSpecializationInfo();
176   if (!Info && FII)
177     return FII->getName();
178 
179   // Otherwise construct human readable name for debug info.
180   SmallString<128> NS;
181   llvm::raw_svector_ostream OS(NS);
182   FD->printName(OS);
183 
184   // Add any template specialization args.
185   if (Info) {
186     const TemplateArgumentList *TArgs = Info->TemplateArguments;
187     const TemplateArgument *Args = TArgs->data();
188     unsigned NumArgs = TArgs->size();
189     PrintingPolicy Policy(CGM.getLangOpts());
190     TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
191                                                           Policy);
192   }
193 
194   // Copy this name on the side and use its reference.
195   return internString(OS.str());
196 }
197 
198 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
199   SmallString<256> MethodName;
200   llvm::raw_svector_ostream OS(MethodName);
201   OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
202   const DeclContext *DC = OMD->getDeclContext();
203   if (const ObjCImplementationDecl *OID =
204           dyn_cast<const ObjCImplementationDecl>(DC)) {
205     OS << OID->getName();
206   } else if (const ObjCInterfaceDecl *OID =
207                  dyn_cast<const ObjCInterfaceDecl>(DC)) {
208     OS << OID->getName();
209   } else if (const ObjCCategoryImplDecl *OCD =
210                  dyn_cast<const ObjCCategoryImplDecl>(DC)) {
211     OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '('
212        << OCD->getIdentifier()->getNameStart() << ')';
213   } else if (isa<ObjCProtocolDecl>(DC)) {
214     // We can extract the type of the class from the self pointer.
215     if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
216       QualType ClassTy =
217           cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
218       ClassTy.print(OS, PrintingPolicy(LangOptions()));
219     }
220   }
221   OS << ' ' << OMD->getSelector().getAsString() << ']';
222 
223   return internString(OS.str());
224 }
225 
226 StringRef CGDebugInfo::getSelectorName(Selector S) {
227   return internString(S.getAsString());
228 }
229 
230 StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
231   // quick optimization to avoid having to intern strings that are already
232   // stored reliably elsewhere
233   if (!isa<ClassTemplateSpecializationDecl>(RD))
234     return RD->getName();
235 
236   SmallString<128> Name;
237   {
238     llvm::raw_svector_ostream OS(Name);
239     RD->getNameForDiagnostic(OS, CGM.getContext().getPrintingPolicy(),
240                              /*Qualified*/ false);
241   }
242 
243   // Copy this name on the side and use its reference.
244   return internString(Name);
245 }
246 
247 llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
248   if (!Loc.isValid())
249     // If Location is not valid then use main input file.
250     return DBuilder.createFile(TheCU->getFilename(), TheCU->getDirectory());
251 
252   SourceManager &SM = CGM.getContext().getSourceManager();
253   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
254 
255   if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
256     // If the location is not valid then use main input file.
257     return DBuilder.createFile(TheCU->getFilename(), TheCU->getDirectory());
258 
259   // Cache the results.
260   const char *fname = PLoc.getFilename();
261   auto it = DIFileCache.find(fname);
262 
263   if (it != DIFileCache.end()) {
264     // Verify that the information still exists.
265     if (llvm::Metadata *V = it->second)
266       return cast<llvm::DIFile>(V);
267   }
268 
269   llvm::DIFile *F =
270       DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
271 
272   DIFileCache[fname].reset(F);
273   return F;
274 }
275 
276 llvm::DIFile *CGDebugInfo::getOrCreateMainFile() {
277   return DBuilder.createFile(TheCU->getFilename(), TheCU->getDirectory());
278 }
279 
280 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
281   if (Loc.isInvalid() && CurLoc.isInvalid())
282     return 0;
283   SourceManager &SM = CGM.getContext().getSourceManager();
284   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
285   return PLoc.isValid() ? PLoc.getLine() : 0;
286 }
287 
288 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
289   // We may not want column information at all.
290   if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
291     return 0;
292 
293   // If the location is invalid then use the current column.
294   if (Loc.isInvalid() && CurLoc.isInvalid())
295     return 0;
296   SourceManager &SM = CGM.getContext().getSourceManager();
297   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
298   return PLoc.isValid() ? PLoc.getColumn() : 0;
299 }
300 
301 StringRef CGDebugInfo::getCurrentDirname() {
302   if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
303     return CGM.getCodeGenOpts().DebugCompilationDir;
304 
305   if (!CWDName.empty())
306     return CWDName;
307   SmallString<256> CWD;
308   llvm::sys::fs::current_path(CWD);
309   return CWDName = internString(CWD);
310 }
311 
312 void CGDebugInfo::CreateCompileUnit() {
313 
314   // Should we be asking the SourceManager for the main file name, instead of
315   // accepting it as an argument? This just causes the main file name to
316   // mismatch with source locations and create extra lexical scopes or
317   // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
318   // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
319   // because that's what the SourceManager says)
320 
321   // Get absolute path name.
322   SourceManager &SM = CGM.getContext().getSourceManager();
323   std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
324   if (MainFileName.empty())
325     MainFileName = "<stdin>";
326 
327   // The main file name provided via the "-main-file-name" option contains just
328   // the file name itself with no path information. This file name may have had
329   // a relative path, so we look into the actual file entry for the main
330   // file to determine the real absolute path for the file.
331   std::string MainFileDir;
332   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
333     MainFileDir = MainFile->getDir()->getName();
334     if (MainFileDir != ".") {
335       llvm::SmallString<1024> MainFileDirSS(MainFileDir);
336       llvm::sys::path::append(MainFileDirSS, MainFileName);
337       MainFileName = MainFileDirSS.str();
338     }
339   }
340 
341   // Save filename string.
342   StringRef Filename = internString(MainFileName);
343 
344   // Save split dwarf file string.
345   std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
346   StringRef SplitDwarfFilename = internString(SplitDwarfFile);
347 
348   llvm::dwarf::SourceLanguage LangTag;
349   const LangOptions &LO = CGM.getLangOpts();
350   if (LO.CPlusPlus) {
351     if (LO.ObjC1)
352       LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
353     else
354       LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
355   } else if (LO.ObjC1) {
356     LangTag = llvm::dwarf::DW_LANG_ObjC;
357   } else if (LO.C99) {
358     LangTag = llvm::dwarf::DW_LANG_C99;
359   } else {
360     LangTag = llvm::dwarf::DW_LANG_C89;
361   }
362 
363   std::string Producer = getClangFullVersion();
364 
365   // Figure out which version of the ObjC runtime we have.
366   unsigned RuntimeVers = 0;
367   if (LO.ObjC1)
368     RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
369 
370   // Create new compile unit.
371   // FIXME - Eliminate TheCU.
372   TheCU = DBuilder.createCompileUnit(
373       LangTag, Filename, getCurrentDirname(), Producer, LO.Optimize,
374       CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers, SplitDwarfFilename,
375       DebugKind <= CodeGenOptions::DebugLineTablesOnly
376           ? llvm::DIBuilder::LineTablesOnly
377           : llvm::DIBuilder::FullDebug,
378       0 /* DWOid */,
379       DebugKind != CodeGenOptions::LocTrackingOnly);
380 }
381 
382 llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
383   llvm::dwarf::TypeKind Encoding;
384   StringRef BTName;
385   switch (BT->getKind()) {
386 #define BUILTIN_TYPE(Id, SingletonId)
387 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
388 #include "clang/AST/BuiltinTypes.def"
389   case BuiltinType::Dependent:
390     llvm_unreachable("Unexpected builtin type");
391   case BuiltinType::NullPtr:
392     return DBuilder.createNullPtrType();
393   case BuiltinType::Void:
394     return nullptr;
395   case BuiltinType::ObjCClass:
396     if (!ClassTy)
397       ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
398                                            "objc_class", TheCU,
399                                            getOrCreateMainFile(), 0);
400     return ClassTy;
401   case BuiltinType::ObjCId: {
402     // typedef struct objc_class *Class;
403     // typedef struct objc_object {
404     //  Class isa;
405     // } *id;
406 
407     if (ObjTy)
408       return ObjTy;
409 
410     if (!ClassTy)
411       ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
412                                            "objc_class", TheCU,
413                                            getOrCreateMainFile(), 0);
414 
415     unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
416 
417     auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
418 
419     ObjTy =
420         DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
421                                   0, 0, 0, 0, nullptr, llvm::DINodeArray());
422 
423     DBuilder.replaceArrays(
424         ObjTy,
425         DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
426             ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
427     return ObjTy;
428   }
429   case BuiltinType::ObjCSel: {
430     if (!SelTy)
431       SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
432                                          "objc_selector", TheCU,
433                                          getOrCreateMainFile(), 0);
434     return SelTy;
435   }
436 
437   case BuiltinType::OCLImage1d:
438     return getOrCreateStructPtrType("opencl_image1d_t", OCLImage1dDITy);
439   case BuiltinType::OCLImage1dArray:
440     return getOrCreateStructPtrType("opencl_image1d_array_t",
441                                     OCLImage1dArrayDITy);
442   case BuiltinType::OCLImage1dBuffer:
443     return getOrCreateStructPtrType("opencl_image1d_buffer_t",
444                                     OCLImage1dBufferDITy);
445   case BuiltinType::OCLImage2d:
446     return getOrCreateStructPtrType("opencl_image2d_t", OCLImage2dDITy);
447   case BuiltinType::OCLImage2dArray:
448     return getOrCreateStructPtrType("opencl_image2d_array_t",
449                                     OCLImage2dArrayDITy);
450   case BuiltinType::OCLImage3d:
451     return getOrCreateStructPtrType("opencl_image3d_t", OCLImage3dDITy);
452   case BuiltinType::OCLSampler:
453     return DBuilder.createBasicType(
454         "opencl_sampler_t", CGM.getContext().getTypeSize(BT),
455         CGM.getContext().getTypeAlign(BT), llvm::dwarf::DW_ATE_unsigned);
456   case BuiltinType::OCLEvent:
457     return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
458 
459   case BuiltinType::UChar:
460   case BuiltinType::Char_U:
461     Encoding = llvm::dwarf::DW_ATE_unsigned_char;
462     break;
463   case BuiltinType::Char_S:
464   case BuiltinType::SChar:
465     Encoding = llvm::dwarf::DW_ATE_signed_char;
466     break;
467   case BuiltinType::Char16:
468   case BuiltinType::Char32:
469     Encoding = llvm::dwarf::DW_ATE_UTF;
470     break;
471   case BuiltinType::UShort:
472   case BuiltinType::UInt:
473   case BuiltinType::UInt128:
474   case BuiltinType::ULong:
475   case BuiltinType::WChar_U:
476   case BuiltinType::ULongLong:
477     Encoding = llvm::dwarf::DW_ATE_unsigned;
478     break;
479   case BuiltinType::Short:
480   case BuiltinType::Int:
481   case BuiltinType::Int128:
482   case BuiltinType::Long:
483   case BuiltinType::WChar_S:
484   case BuiltinType::LongLong:
485     Encoding = llvm::dwarf::DW_ATE_signed;
486     break;
487   case BuiltinType::Bool:
488     Encoding = llvm::dwarf::DW_ATE_boolean;
489     break;
490   case BuiltinType::Half:
491   case BuiltinType::Float:
492   case BuiltinType::LongDouble:
493   case BuiltinType::Double:
494     Encoding = llvm::dwarf::DW_ATE_float;
495     break;
496   }
497 
498   switch (BT->getKind()) {
499   case BuiltinType::Long:
500     BTName = "long int";
501     break;
502   case BuiltinType::LongLong:
503     BTName = "long long int";
504     break;
505   case BuiltinType::ULong:
506     BTName = "long unsigned int";
507     break;
508   case BuiltinType::ULongLong:
509     BTName = "long long unsigned int";
510     break;
511   default:
512     BTName = BT->getName(CGM.getLangOpts());
513     break;
514   }
515   // Bit size, align and offset of the type.
516   uint64_t Size = CGM.getContext().getTypeSize(BT);
517   uint64_t Align = CGM.getContext().getTypeAlign(BT);
518   return DBuilder.createBasicType(BTName, Size, Align, Encoding);
519 }
520 
521 llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
522   // Bit size, align and offset of the type.
523   llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
524   if (Ty->isComplexIntegerType())
525     Encoding = llvm::dwarf::DW_ATE_lo_user;
526 
527   uint64_t Size = CGM.getContext().getTypeSize(Ty);
528   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
529   return DBuilder.createBasicType("complex", Size, Align, Encoding);
530 }
531 
532 llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
533                                                llvm::DIFile *Unit) {
534   QualifierCollector Qc;
535   const Type *T = Qc.strip(Ty);
536 
537   // Ignore these qualifiers for now.
538   Qc.removeObjCGCAttr();
539   Qc.removeAddressSpace();
540   Qc.removeObjCLifetime();
541 
542   // We will create one Derived type for one qualifier and recurse to handle any
543   // additional ones.
544   llvm::dwarf::Tag Tag;
545   if (Qc.hasConst()) {
546     Tag = llvm::dwarf::DW_TAG_const_type;
547     Qc.removeConst();
548   } else if (Qc.hasVolatile()) {
549     Tag = llvm::dwarf::DW_TAG_volatile_type;
550     Qc.removeVolatile();
551   } else if (Qc.hasRestrict()) {
552     Tag = llvm::dwarf::DW_TAG_restrict_type;
553     Qc.removeRestrict();
554   } else {
555     assert(Qc.empty() && "Unknown type qualifier for debug info");
556     return getOrCreateType(QualType(T, 0), Unit);
557   }
558 
559   auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
560 
561   // No need to fill in the Name, Line, Size, Alignment, Offset in case of
562   // CVR derived types.
563   return DBuilder.createQualifiedType(Tag, FromTy);
564 }
565 
566 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
567                                       llvm::DIFile *Unit) {
568 
569   // The frontend treats 'id' as a typedef to an ObjCObjectType,
570   // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
571   // debug info, we want to emit 'id' in both cases.
572   if (Ty->isObjCQualifiedIdType())
573     return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
574 
575   return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
576                                Ty->getPointeeType(), Unit);
577 }
578 
579 llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
580                                       llvm::DIFile *Unit) {
581   return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
582                                Ty->getPointeeType(), Unit);
583 }
584 
585 /// \return whether a C++ mangling exists for the type defined by TD.
586 static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
587   switch (TheCU->getSourceLanguage()) {
588   case llvm::dwarf::DW_LANG_C_plus_plus:
589     return true;
590   case llvm::dwarf::DW_LANG_ObjC_plus_plus:
591     return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
592   default:
593     return false;
594   }
595 }
596 
597 /// In C++ mode, types have linkage, so we can rely on the ODR and
598 /// on their mangled names, if they're external.
599 static SmallString<256> getUniqueTagTypeName(const TagType *Ty,
600                                              CodeGenModule &CGM,
601                                              llvm::DICompileUnit *TheCU) {
602   SmallString<256> FullName;
603   const TagDecl *TD = Ty->getDecl();
604 
605   if (!hasCXXMangling(TD, TheCU) || !TD->isExternallyVisible())
606     return FullName;
607 
608   // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
609   if (CGM.getTarget().getCXXABI().isMicrosoft())
610     return FullName;
611 
612   // TODO: This is using the RTTI name. Is there a better way to get
613   // a unique string for a type?
614   llvm::raw_svector_ostream Out(FullName);
615   CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
616   return FullName;
617 }
618 
619 /// \return the approproate DWARF tag for a composite type.
620 static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
621    llvm::dwarf::Tag Tag;
622   if (RD->isStruct() || RD->isInterface())
623     Tag = llvm::dwarf::DW_TAG_structure_type;
624   else if (RD->isUnion())
625     Tag = llvm::dwarf::DW_TAG_union_type;
626   else {
627     // FIXME: This could be a struct type giving a default visibility different
628     // than C++ class type, but needs llvm metadata changes first.
629     assert(RD->isClass());
630     Tag = llvm::dwarf::DW_TAG_class_type;
631   }
632   return Tag;
633 }
634 
635 llvm::DICompositeType *
636 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
637                                       llvm::DIScope *Ctx) {
638   const RecordDecl *RD = Ty->getDecl();
639   if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
640     return cast<llvm::DICompositeType>(T);
641   llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
642   unsigned Line = getLineNumber(RD->getLocation());
643   StringRef RDName = getClassName(RD);
644 
645   uint64_t Size = 0;
646   uint64_t Align = 0;
647 
648   const RecordDecl *D = RD->getDefinition();
649   if (D && D->isCompleteDefinition()) {
650     Size = CGM.getContext().getTypeSize(Ty);
651     Align = CGM.getContext().getTypeAlign(Ty);
652   }
653 
654   // Create the type.
655   SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
656   llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
657       getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align,
658       llvm::DINode::FlagFwdDecl, FullName);
659   ReplaceMap.emplace_back(
660       std::piecewise_construct, std::make_tuple(Ty),
661       std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
662   return RetTy;
663 }
664 
665 llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
666                                                  const Type *Ty,
667                                                  QualType PointeeTy,
668                                                  llvm::DIFile *Unit) {
669   if (Tag == llvm::dwarf::DW_TAG_reference_type ||
670       Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
671     return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
672 
673   // Bit size, align and offset of the type.
674   // Size is always the size of a pointer. We can't use getTypeSize here
675   // because that does not return the correct value for references.
676   unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
677   uint64_t Size = CGM.getTarget().getPointerWidth(AS);
678   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
679 
680   return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
681                                     Align);
682 }
683 
684 llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
685                                                     llvm::DIType *&Cache) {
686   if (Cache)
687     return Cache;
688   Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
689                                      TheCU, getOrCreateMainFile(), 0);
690   unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
691   Cache = DBuilder.createPointerType(Cache, Size);
692   return Cache;
693 }
694 
695 llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
696                                       llvm::DIFile *Unit) {
697   SmallVector<llvm::Metadata *, 8> EltTys;
698   QualType FType;
699   uint64_t FieldSize, FieldOffset;
700   unsigned FieldAlign;
701   llvm::DINodeArray Elements;
702 
703   FieldOffset = 0;
704   FType = CGM.getContext().UnsignedLongTy;
705   EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
706   EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
707 
708   Elements = DBuilder.getOrCreateArray(EltTys);
709   EltTys.clear();
710 
711   unsigned Flags = llvm::DINode::FlagAppleBlock;
712   unsigned LineNo = 0;
713 
714   auto *EltTy =
715       DBuilder.createStructType(Unit, "__block_descriptor", nullptr, LineNo,
716                                 FieldOffset, 0, Flags, nullptr, Elements);
717 
718   // Bit size, align and offset of the type.
719   uint64_t Size = CGM.getContext().getTypeSize(Ty);
720 
721   auto *DescTy = DBuilder.createPointerType(EltTy, Size);
722 
723   FieldOffset = 0;
724   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
725   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
726   FType = CGM.getContext().IntTy;
727   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
728   EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
729   FType = CGM.getContext().getPointerType(Ty->getPointeeType());
730   EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
731 
732   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
733   FieldSize = CGM.getContext().getTypeSize(Ty);
734   FieldAlign = CGM.getContext().getTypeAlign(Ty);
735   EltTys.push_back(DBuilder.createMemberType(Unit, "__descriptor", nullptr, LineNo,
736                                              FieldSize, FieldAlign, FieldOffset,
737                                              0, DescTy));
738 
739   FieldOffset += FieldSize;
740   Elements = DBuilder.getOrCreateArray(EltTys);
741 
742   // The __block_literal_generic structs are marked with a special
743   // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
744   // the debugger needs to know about. To allow type uniquing, emit
745   // them without a name or a location.
746   EltTy =
747       DBuilder.createStructType(Unit, "", nullptr, LineNo,
748                                 FieldOffset, 0, Flags, nullptr, Elements);
749 
750   return DBuilder.createPointerType(EltTy, Size);
751 }
752 
753 llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
754                                       llvm::DIFile *Unit) {
755   assert(Ty->isTypeAlias());
756   llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
757 
758   SmallString<128> NS;
759   llvm::raw_svector_ostream OS(NS);
760   Ty->getTemplateName().print(OS, CGM.getContext().getPrintingPolicy(),
761                               /*qualified*/ false);
762 
763   TemplateSpecializationType::PrintTemplateArgumentList(
764       OS, Ty->getArgs(), Ty->getNumArgs(),
765       CGM.getContext().getPrintingPolicy());
766 
767   TypeAliasDecl *AliasDecl = cast<TypeAliasTemplateDecl>(
768       Ty->getTemplateName().getAsTemplateDecl())->getTemplatedDecl();
769 
770   SourceLocation Loc = AliasDecl->getLocation();
771   return DBuilder.createTypedef(
772       Src, internString(OS.str()), getOrCreateFile(Loc), getLineNumber(Loc),
773       getContextDescriptor(cast<Decl>(AliasDecl->getDeclContext())));
774 }
775 
776 llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
777                                       llvm::DIFile *Unit) {
778   // We don't set size information, but do specify where the typedef was
779   // declared.
780   SourceLocation Loc = Ty->getDecl()->getLocation();
781 
782   // Typedefs are derived from some other type.
783   return DBuilder.createTypedef(
784       getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
785       Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
786       getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext())));
787 }
788 
789 llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
790                                       llvm::DIFile *Unit) {
791   SmallVector<llvm::Metadata *, 16> EltTys;
792 
793   // Add the result type at least.
794   EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
795 
796   // Set up remainder of arguments if there is a prototype.
797   // otherwise emit it as a variadic function.
798   if (isa<FunctionNoProtoType>(Ty))
799     EltTys.push_back(DBuilder.createUnspecifiedParameter());
800   else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
801     for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
802       EltTys.push_back(getOrCreateType(FPT->getParamType(i), Unit));
803     if (FPT->isVariadic())
804       EltTys.push_back(DBuilder.createUnspecifiedParameter());
805   }
806 
807   llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
808   return DBuilder.createSubroutineType(Unit, EltTypeArray);
809 }
810 
811 /// Convert an AccessSpecifier into the corresponding DINode flag.
812 /// As an optimization, return 0 if the access specifier equals the
813 /// default for the containing type.
814 static unsigned getAccessFlag(AccessSpecifier Access, const RecordDecl *RD) {
815   AccessSpecifier Default = clang::AS_none;
816   if (RD && RD->isClass())
817     Default = clang::AS_private;
818   else if (RD && (RD->isStruct() || RD->isUnion()))
819     Default = clang::AS_public;
820 
821   if (Access == Default)
822     return 0;
823 
824   switch (Access) {
825   case clang::AS_private:
826     return llvm::DINode::FlagPrivate;
827   case clang::AS_protected:
828     return llvm::DINode::FlagProtected;
829   case clang::AS_public:
830     return llvm::DINode::FlagPublic;
831   case clang::AS_none:
832     return 0;
833   }
834   llvm_unreachable("unexpected access enumerator");
835 }
836 
837 llvm::DIType *CGDebugInfo::createFieldType(
838     StringRef name, QualType type, uint64_t sizeInBitsOverride,
839     SourceLocation loc, AccessSpecifier AS, uint64_t offsetInBits,
840     llvm::DIFile *tunit, llvm::DIScope *scope, const RecordDecl *RD) {
841   llvm::DIType *debugType = getOrCreateType(type, tunit);
842 
843   // Get the location for the field.
844   llvm::DIFile *file = getOrCreateFile(loc);
845   unsigned line = getLineNumber(loc);
846 
847   uint64_t SizeInBits = 0;
848   unsigned AlignInBits = 0;
849   if (!type->isIncompleteArrayType()) {
850     TypeInfo TI = CGM.getContext().getTypeInfo(type);
851     SizeInBits = TI.Width;
852     AlignInBits = TI.Align;
853 
854     if (sizeInBitsOverride)
855       SizeInBits = sizeInBitsOverride;
856   }
857 
858   unsigned flags = getAccessFlag(AS, RD);
859   return DBuilder.createMemberType(scope, name, file, line, SizeInBits,
860                                    AlignInBits, offsetInBits, flags, debugType);
861 }
862 
863 void CGDebugInfo::CollectRecordLambdaFields(
864     const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
865     llvm::DIType *RecordTy) {
866   // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
867   // has the name and the location of the variable so we should iterate over
868   // both concurrently.
869   const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
870   RecordDecl::field_iterator Field = CXXDecl->field_begin();
871   unsigned fieldno = 0;
872   for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
873                                              E = CXXDecl->captures_end();
874        I != E; ++I, ++Field, ++fieldno) {
875     const LambdaCapture &C = *I;
876     if (C.capturesVariable()) {
877       VarDecl *V = C.getCapturedVar();
878       llvm::DIFile *VUnit = getOrCreateFile(C.getLocation());
879       StringRef VName = V->getName();
880       uint64_t SizeInBitsOverride = 0;
881       if (Field->isBitField()) {
882         SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
883         assert(SizeInBitsOverride && "found named 0-width bitfield");
884       }
885       llvm::DIType *fieldType = createFieldType(
886           VName, Field->getType(), SizeInBitsOverride, C.getLocation(),
887           Field->getAccess(), layout.getFieldOffset(fieldno), VUnit, RecordTy,
888           CXXDecl);
889       elements.push_back(fieldType);
890     } else if (C.capturesThis()) {
891       // TODO: Need to handle 'this' in some way by probably renaming the
892       // this of the lambda class and having a field member of 'this' or
893       // by using AT_object_pointer for the function and having that be
894       // used as 'this' for semantic references.
895       FieldDecl *f = *Field;
896       llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
897       QualType type = f->getType();
898       llvm::DIType *fieldType = createFieldType(
899           "this", type, 0, f->getLocation(), f->getAccess(),
900           layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
901 
902       elements.push_back(fieldType);
903     }
904   }
905 }
906 
907 llvm::DIDerivedType *
908 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
909                                      const RecordDecl *RD) {
910   // Create the descriptor for the static variable, with or without
911   // constant initializers.
912   Var = Var->getCanonicalDecl();
913   llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
914   llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
915 
916   unsigned LineNumber = getLineNumber(Var->getLocation());
917   StringRef VName = Var->getName();
918   llvm::Constant *C = nullptr;
919   if (Var->getInit()) {
920     const APValue *Value = Var->evaluateValue();
921     if (Value) {
922       if (Value->isInt())
923         C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
924       if (Value->isFloat())
925         C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
926     }
927   }
928 
929   unsigned Flags = getAccessFlag(Var->getAccess(), RD);
930   llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
931       RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
932   StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
933   return GV;
934 }
935 
936 void CGDebugInfo::CollectRecordNormalField(
937     const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
938     SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
939     const RecordDecl *RD) {
940   StringRef name = field->getName();
941   QualType type = field->getType();
942 
943   // Ignore unnamed fields unless they're anonymous structs/unions.
944   if (name.empty() && !type->isRecordType())
945     return;
946 
947   uint64_t SizeInBitsOverride = 0;
948   if (field->isBitField()) {
949     SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
950     assert(SizeInBitsOverride && "found named 0-width bitfield");
951   }
952 
953   llvm::DIType *fieldType =
954       createFieldType(name, type, SizeInBitsOverride, field->getLocation(),
955                       field->getAccess(), OffsetInBits, tunit, RecordTy, RD);
956 
957   elements.push_back(fieldType);
958 }
959 
960 void CGDebugInfo::CollectRecordFields(
961     const RecordDecl *record, llvm::DIFile *tunit,
962     SmallVectorImpl<llvm::Metadata *> &elements,
963     llvm::DICompositeType *RecordTy) {
964   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
965 
966   if (CXXDecl && CXXDecl->isLambda())
967     CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
968   else {
969     const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
970 
971     // Field number for non-static fields.
972     unsigned fieldNo = 0;
973 
974     // Static and non-static members should appear in the same order as
975     // the corresponding declarations in the source program.
976     for (const auto *I : record->decls())
977       if (const auto *V = dyn_cast<VarDecl>(I)) {
978         // Reuse the existing static member declaration if one exists
979         auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
980         if (MI != StaticDataMemberCache.end()) {
981           assert(MI->second &&
982                  "Static data member declaration should still exist");
983           elements.push_back(MI->second);
984         } else {
985           auto Field = CreateRecordStaticField(V, RecordTy, record);
986           elements.push_back(Field);
987         }
988       } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
989         CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
990                                  elements, RecordTy, record);
991 
992         // Bump field number for next field.
993         ++fieldNo;
994       }
995   }
996 }
997 
998 llvm::DISubroutineType *
999 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1000                                    llvm::DIFile *Unit) {
1001   const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
1002   if (Method->isStatic())
1003     return cast_or_null<llvm::DISubroutineType>(
1004         getOrCreateType(QualType(Func, 0), Unit));
1005   return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
1006                                        Func, Unit);
1007 }
1008 
1009 llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
1010     QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
1011   // Add "this" pointer.
1012   llvm::DITypeRefArray Args(
1013       cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
1014           ->getTypeArray());
1015   assert(Args.size() && "Invalid number of arguments!");
1016 
1017   SmallVector<llvm::Metadata *, 16> Elts;
1018 
1019   // First element is always return type. For 'void' functions it is NULL.
1020   Elts.push_back(Args[0]);
1021 
1022   // "this" pointer is always first argument.
1023   const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1024   if (isa<ClassTemplateSpecializationDecl>(RD)) {
1025     // Create pointer type directly in this case.
1026     const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1027     QualType PointeeTy = ThisPtrTy->getPointeeType();
1028     unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
1029     uint64_t Size = CGM.getTarget().getPointerWidth(AS);
1030     uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
1031     llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1032     llvm::DIType *ThisPtrType =
1033         DBuilder.createPointerType(PointeeType, Size, Align);
1034     TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1035     // TODO: This and the artificial type below are misleading, the
1036     // types aren't artificial the argument is, but the current
1037     // metadata doesn't represent that.
1038     ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1039     Elts.push_back(ThisPtrType);
1040   } else {
1041     llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
1042     TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1043     ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1044     Elts.push_back(ThisPtrType);
1045   }
1046 
1047   // Copy rest of the arguments.
1048   for (unsigned i = 1, e = Args.size(); i != e; ++i)
1049     Elts.push_back(Args[i]);
1050 
1051   llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
1052 
1053   unsigned Flags = 0;
1054   if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1055     Flags |= llvm::DINode::FlagLValueReference;
1056   if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1057     Flags |= llvm::DINode::FlagRValueReference;
1058 
1059   return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags);
1060 }
1061 
1062 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1063 /// inside a function.
1064 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1065   if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1066     return isFunctionLocalClass(NRD);
1067   if (isa<FunctionDecl>(RD->getDeclContext()))
1068     return true;
1069   return false;
1070 }
1071 
1072 llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1073     const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
1074   bool IsCtorOrDtor =
1075       isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1076 
1077   StringRef MethodName = getFunctionName(Method);
1078   llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
1079 
1080   // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1081   // make sense to give a single ctor/dtor a linkage name.
1082   StringRef MethodLinkageName;
1083   if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1084     MethodLinkageName = CGM.getMangledName(Method);
1085 
1086   // Get the location for the method.
1087   llvm::DIFile *MethodDefUnit = nullptr;
1088   unsigned MethodLine = 0;
1089   if (!Method->isImplicit()) {
1090     MethodDefUnit = getOrCreateFile(Method->getLocation());
1091     MethodLine = getLineNumber(Method->getLocation());
1092   }
1093 
1094   // Collect virtual method info.
1095   llvm::DIType *ContainingType = nullptr;
1096   unsigned Virtuality = 0;
1097   unsigned VIndex = 0;
1098 
1099   if (Method->isVirtual()) {
1100     if (Method->isPure())
1101       Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1102     else
1103       Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1104 
1105     // It doesn't make sense to give a virtual destructor a vtable index,
1106     // since a single destructor has two entries in the vtable.
1107     // FIXME: Add proper support for debug info for virtual calls in
1108     // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1109     // lookup if we have multiple or virtual inheritance.
1110     if (!isa<CXXDestructorDecl>(Method) &&
1111         !CGM.getTarget().getCXXABI().isMicrosoft())
1112       VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1113     ContainingType = RecordTy;
1114   }
1115 
1116   unsigned Flags = 0;
1117   if (Method->isImplicit())
1118     Flags |= llvm::DINode::FlagArtificial;
1119   Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
1120   if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1121     if (CXXC->isExplicit())
1122       Flags |= llvm::DINode::FlagExplicit;
1123   } else if (const CXXConversionDecl *CXXC =
1124                  dyn_cast<CXXConversionDecl>(Method)) {
1125     if (CXXC->isExplicit())
1126       Flags |= llvm::DINode::FlagExplicit;
1127   }
1128   if (Method->hasPrototype())
1129     Flags |= llvm::DINode::FlagPrototyped;
1130   if (Method->getRefQualifier() == RQ_LValue)
1131     Flags |= llvm::DINode::FlagLValueReference;
1132   if (Method->getRefQualifier() == RQ_RValue)
1133     Flags |= llvm::DINode::FlagRValueReference;
1134 
1135   llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1136   llvm::DISubprogram *SP = DBuilder.createMethod(
1137       RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
1138       MethodTy, /*isLocalToUnit=*/false,
1139       /* isDefinition=*/false, Virtuality, VIndex, ContainingType, Flags,
1140       CGM.getLangOpts().Optimize, nullptr, TParamsArray.get());
1141 
1142   SPCache[Method->getCanonicalDecl()].reset(SP);
1143 
1144   return SP;
1145 }
1146 
1147 void CGDebugInfo::CollectCXXMemberFunctions(
1148     const CXXRecordDecl *RD, llvm::DIFile *Unit,
1149     SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
1150 
1151   // Since we want more than just the individual member decls if we
1152   // have templated functions iterate over every declaration to gather
1153   // the functions.
1154   for (const auto *I : RD->decls()) {
1155     const auto *Method = dyn_cast<CXXMethodDecl>(I);
1156     // If the member is implicit, don't add it to the member list. This avoids
1157     // the member being added to type units by LLVM, while still allowing it
1158     // to be emitted into the type declaration/reference inside the compile
1159     // unit.
1160     // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
1161     // FIXME: Handle Using(Shadow?)Decls here to create
1162     // DW_TAG_imported_declarations inside the class for base decls brought into
1163     // derived classes. GDB doesn't seem to notice/leverage these when I tried
1164     // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1165     // referenced)
1166     if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
1167       continue;
1168 
1169     if (Method->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
1170       continue;
1171 
1172     // Reuse the existing member function declaration if it exists.
1173     // It may be associated with the declaration of the type & should be
1174     // reused as we're building the definition.
1175     //
1176     // This situation can arise in the vtable-based debug info reduction where
1177     // implicit members are emitted in a non-vtable TU.
1178     auto MI = SPCache.find(Method->getCanonicalDecl());
1179     EltTys.push_back(MI == SPCache.end()
1180                          ? CreateCXXMemberFunction(Method, Unit, RecordTy)
1181                          : static_cast<llvm::Metadata *>(MI->second));
1182   }
1183 }
1184 
1185 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1186                                   SmallVectorImpl<llvm::Metadata *> &EltTys,
1187                                   llvm::DIType *RecordTy) {
1188   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1189   for (const auto &BI : RD->bases()) {
1190     unsigned BFlags = 0;
1191     uint64_t BaseOffset;
1192 
1193     const CXXRecordDecl *Base =
1194         cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl());
1195 
1196     if (BI.isVirtual()) {
1197       if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1198         // virtual base offset offset is -ve. The code generator emits dwarf
1199         // expression where it expects +ve number.
1200         BaseOffset = 0 - CGM.getItaniumVTableContext()
1201                              .getVirtualBaseOffsetOffset(RD, Base)
1202                              .getQuantity();
1203       } else {
1204         // In the MS ABI, store the vbtable offset, which is analogous to the
1205         // vbase offset offset in Itanium.
1206         BaseOffset =
1207             4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
1208       }
1209       BFlags = llvm::DINode::FlagVirtual;
1210     } else
1211       BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1212     // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1213     // BI->isVirtual() and bits when not.
1214 
1215     BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
1216     llvm::DIType *DTy = DBuilder.createInheritance(
1217         RecordTy, getOrCreateType(BI.getType(), Unit), BaseOffset, BFlags);
1218     EltTys.push_back(DTy);
1219   }
1220 }
1221 
1222 llvm::DINodeArray
1223 CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
1224                                    ArrayRef<TemplateArgument> TAList,
1225                                    llvm::DIFile *Unit) {
1226   SmallVector<llvm::Metadata *, 16> TemplateParams;
1227   for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1228     const TemplateArgument &TA = TAList[i];
1229     StringRef Name;
1230     if (TPList)
1231       Name = TPList->getParam(i)->getName();
1232     switch (TA.getKind()) {
1233     case TemplateArgument::Type: {
1234       llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
1235       TemplateParams.push_back(
1236           DBuilder.createTemplateTypeParameter(TheCU, Name, TTy));
1237     } break;
1238     case TemplateArgument::Integral: {
1239       llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
1240       TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1241           TheCU, Name, TTy,
1242           llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
1243     } break;
1244     case TemplateArgument::Declaration: {
1245       const ValueDecl *D = TA.getAsDecl();
1246       QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
1247       llvm::DIType *TTy = getOrCreateType(T, Unit);
1248       llvm::Constant *V = nullptr;
1249       const CXXMethodDecl *MD;
1250       // Variable pointer template parameters have a value that is the address
1251       // of the variable.
1252       if (const auto *VD = dyn_cast<VarDecl>(D))
1253         V = CGM.GetAddrOfGlobalVar(VD);
1254       // Member function pointers have special support for building them, though
1255       // this is currently unsupported in LLVM CodeGen.
1256       else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
1257         V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
1258       else if (const auto *FD = dyn_cast<FunctionDecl>(D))
1259         V = CGM.GetAddrOfFunction(FD);
1260       // Member data pointers have special handling too to compute the fixed
1261       // offset within the object.
1262       else if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr())) {
1263         // These five lines (& possibly the above member function pointer
1264         // handling) might be able to be refactored to use similar code in
1265         // CodeGenModule::getMemberPointerConstant
1266         uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1267         CharUnits chars =
1268             CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
1269         V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
1270       }
1271       TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1272           TheCU, Name, TTy,
1273           cast_or_null<llvm::Constant>(V->stripPointerCasts())));
1274     } break;
1275     case TemplateArgument::NullPtr: {
1276       QualType T = TA.getNullPtrType();
1277       llvm::DIType *TTy = getOrCreateType(T, Unit);
1278       llvm::Constant *V = nullptr;
1279       // Special case member data pointer null values since they're actually -1
1280       // instead of zero.
1281       if (const MemberPointerType *MPT =
1282               dyn_cast<MemberPointerType>(T.getTypePtr()))
1283         // But treat member function pointers as simple zero integers because
1284         // it's easier than having a special case in LLVM's CodeGen. If LLVM
1285         // CodeGen grows handling for values of non-null member function
1286         // pointers then perhaps we could remove this special case and rely on
1287         // EmitNullMemberPointer for member function pointers.
1288         if (MPT->isMemberDataPointer())
1289           V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1290       if (!V)
1291         V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1292       TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1293           TheCU, Name, TTy, cast<llvm::Constant>(V)));
1294     } break;
1295     case TemplateArgument::Template:
1296       TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
1297           TheCU, Name, nullptr,
1298           TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
1299       break;
1300     case TemplateArgument::Pack:
1301       TemplateParams.push_back(DBuilder.createTemplateParameterPack(
1302           TheCU, Name, nullptr,
1303           CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
1304       break;
1305     case TemplateArgument::Expression: {
1306       const Expr *E = TA.getAsExpr();
1307       QualType T = E->getType();
1308       if (E->isGLValue())
1309         T = CGM.getContext().getLValueReferenceType(T);
1310       llvm::Constant *V = CGM.EmitConstantExpr(E, T);
1311       assert(V && "Expression in template argument isn't constant");
1312       llvm::DIType *TTy = getOrCreateType(T, Unit);
1313       TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1314           TheCU, Name, TTy, cast<llvm::Constant>(V->stripPointerCasts())));
1315     } break;
1316     // And the following should never occur:
1317     case TemplateArgument::TemplateExpansion:
1318     case TemplateArgument::Null:
1319       llvm_unreachable(
1320           "These argument types shouldn't exist in concrete types");
1321     }
1322   }
1323   return DBuilder.getOrCreateArray(TemplateParams);
1324 }
1325 
1326 llvm::DINodeArray
1327 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
1328                                            llvm::DIFile *Unit) {
1329   if (FD->getTemplatedKind() ==
1330       FunctionDecl::TK_FunctionTemplateSpecialization) {
1331     const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
1332                                              ->getTemplate()
1333                                              ->getTemplateParameters();
1334     return CollectTemplateParams(
1335         TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
1336   }
1337   return llvm::DINodeArray();
1338 }
1339 
1340 llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
1341     const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
1342   // Always get the full list of parameters, not just the ones from
1343   // the specialization.
1344   TemplateParameterList *TPList =
1345       TSpecial->getSpecializedTemplate()->getTemplateParameters();
1346   const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
1347   return CollectTemplateParams(TPList, TAList.asArray(), Unit);
1348 }
1349 
1350 llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
1351   if (VTablePtrType)
1352     return VTablePtrType;
1353 
1354   ASTContext &Context = CGM.getContext();
1355 
1356   /* Function type */
1357   llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
1358   llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
1359   llvm::DIType *SubTy = DBuilder.createSubroutineType(Unit, SElements);
1360   unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1361   llvm::DIType *vtbl_ptr_type =
1362       DBuilder.createPointerType(SubTy, Size, 0, "__vtbl_ptr_type");
1363   VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1364   return VTablePtrType;
1365 }
1366 
1367 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1368   // Copy the gdb compatible name on the side and use its reference.
1369   return internString("_vptr$", RD->getNameAsString());
1370 }
1371 
1372 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1373                                     SmallVectorImpl<llvm::Metadata *> &EltTys) {
1374   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1375 
1376   // If there is a primary base then it will hold vtable info.
1377   if (RL.getPrimaryBase())
1378     return;
1379 
1380   // If this class is not dynamic then there is not any vtable info to collect.
1381   if (!RD->isDynamicClass())
1382     return;
1383 
1384   unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1385   llvm::DIType *VPTR = DBuilder.createMemberType(
1386       Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
1387       llvm::DINode::FlagArtificial, getOrCreateVTablePtrType(Unit));
1388   EltTys.push_back(VPTR);
1389 }
1390 
1391 llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
1392                                                  SourceLocation Loc) {
1393   assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
1394   llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
1395   return T;
1396 }
1397 
1398 llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
1399                                                     SourceLocation Loc) {
1400   assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
1401   llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
1402   RetainedTypes.push_back(D.getAsOpaquePtr());
1403   return T;
1404 }
1405 
1406 void CGDebugInfo::completeType(const EnumDecl *ED) {
1407   if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1408     return;
1409   QualType Ty = CGM.getContext().getEnumType(ED);
1410   void *TyPtr = Ty.getAsOpaquePtr();
1411   auto I = TypeCache.find(TyPtr);
1412   if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
1413     return;
1414   llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
1415   assert(!Res->isForwardDecl());
1416   TypeCache[TyPtr].reset(Res);
1417 }
1418 
1419 void CGDebugInfo::completeType(const RecordDecl *RD) {
1420   if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1421       !CGM.getLangOpts().CPlusPlus)
1422     completeRequiredType(RD);
1423 }
1424 
1425 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
1426   if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1427     return;
1428 
1429   if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1430     if (CXXDecl->isDynamicClass())
1431       return;
1432 
1433   QualType Ty = CGM.getContext().getRecordType(RD);
1434   llvm::DIType *T = getTypeOrNull(Ty);
1435   if (T && T->isForwardDecl())
1436     completeClassData(RD);
1437 }
1438 
1439 void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1440   if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1441     return;
1442   QualType Ty = CGM.getContext().getRecordType(RD);
1443   void *TyPtr = Ty.getAsOpaquePtr();
1444   auto I = TypeCache.find(TyPtr);
1445   if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
1446     return;
1447   llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1448   assert(!Res->isForwardDecl());
1449   TypeCache[TyPtr].reset(Res);
1450 }
1451 
1452 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
1453                                         CXXRecordDecl::method_iterator End) {
1454   for (; I != End; ++I)
1455     if (FunctionDecl *Tmpl = I->getInstantiatedFromMemberFunction())
1456       if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
1457           !I->getMemberSpecializationInfo()->isExplicitSpecialization())
1458         return true;
1459   return false;
1460 }
1461 
1462 static bool shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind,
1463                                  const RecordDecl *RD,
1464                                  const LangOptions &LangOpts) {
1465   if (DebugKind > CodeGenOptions::LimitedDebugInfo)
1466     return false;
1467 
1468   if (!LangOpts.CPlusPlus)
1469     return false;
1470 
1471   if (!RD->isCompleteDefinitionRequired())
1472     return true;
1473 
1474   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1475 
1476   if (!CXXDecl)
1477     return false;
1478 
1479   if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())
1480     return true;
1481 
1482   TemplateSpecializationKind Spec = TSK_Undeclared;
1483   if (const ClassTemplateSpecializationDecl *SD =
1484           dyn_cast<ClassTemplateSpecializationDecl>(RD))
1485     Spec = SD->getSpecializationKind();
1486 
1487   if (Spec == TSK_ExplicitInstantiationDeclaration &&
1488       hasExplicitMemberDefinition(CXXDecl->method_begin(),
1489                                   CXXDecl->method_end()))
1490     return true;
1491 
1492   return false;
1493 }
1494 
1495 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
1496   RecordDecl *RD = Ty->getDecl();
1497   llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
1498   if (T || shouldOmitDefinition(DebugKind, RD, CGM.getLangOpts())) {
1499     if (!T)
1500       T = getOrCreateRecordFwdDecl(
1501           Ty, getContextDescriptor(cast<Decl>(RD->getDeclContext())));
1502     return T;
1503   }
1504 
1505   return CreateTypeDefinition(Ty);
1506 }
1507 
1508 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1509   RecordDecl *RD = Ty->getDecl();
1510 
1511   // Get overall information about the record type for the debug info.
1512   llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
1513 
1514   // Records and classes and unions can all be recursive.  To handle them, we
1515   // first generate a debug descriptor for the struct as a forward declaration.
1516   // Then (if it is a definition) we go through and get debug info for all of
1517   // its members.  Finally, we create a descriptor for the complete type (which
1518   // may refer to the forward decl if the struct is recursive) and replace all
1519   // uses of the forward declaration with the final definition.
1520   llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
1521 
1522   const RecordDecl *D = RD->getDefinition();
1523   if (!D || !D->isCompleteDefinition())
1524     return FwdDecl;
1525 
1526   if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1527     CollectContainingType(CXXDecl, FwdDecl);
1528 
1529   // Push the struct on region stack.
1530   LexicalBlockStack.emplace_back(&*FwdDecl);
1531   RegionMap[Ty->getDecl()].reset(FwdDecl);
1532 
1533   // Convert all the elements.
1534   SmallVector<llvm::Metadata *, 16> EltTys;
1535   // what about nested types?
1536 
1537   // Note: The split of CXXDecl information here is intentional, the
1538   // gdb tests will depend on a certain ordering at printout. The debug
1539   // information offsets are still correct if we merge them all together
1540   // though.
1541   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1542   if (CXXDecl) {
1543     CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1544     CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1545   }
1546 
1547   // Collect data fields (including static variables and any initializers).
1548   CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1549   if (CXXDecl)
1550     CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1551 
1552   LexicalBlockStack.pop_back();
1553   RegionMap.erase(Ty->getDecl());
1554 
1555   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
1556   DBuilder.replaceArrays(FwdDecl, Elements);
1557 
1558   if (FwdDecl->isTemporary())
1559     FwdDecl =
1560         llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
1561 
1562   RegionMap[Ty->getDecl()].reset(FwdDecl);
1563   return FwdDecl;
1564 }
1565 
1566 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1567                                       llvm::DIFile *Unit) {
1568   // Ignore protocols.
1569   return getOrCreateType(Ty->getBaseType(), Unit);
1570 }
1571 
1572 /// \return true if Getter has the default name for the property PD.
1573 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1574                                  const ObjCMethodDecl *Getter) {
1575   assert(PD);
1576   if (!Getter)
1577     return true;
1578 
1579   assert(Getter->getDeclName().isObjCZeroArgSelector());
1580   return PD->getName() ==
1581          Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1582 }
1583 
1584 /// \return true if Setter has the default name for the property PD.
1585 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1586                                  const ObjCMethodDecl *Setter) {
1587   assert(PD);
1588   if (!Setter)
1589     return true;
1590 
1591   assert(Setter->getDeclName().isObjCOneArgSelector());
1592   return SelectorTable::constructSetterName(PD->getName()) ==
1593          Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1594 }
1595 
1596 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1597                                       llvm::DIFile *Unit) {
1598   ObjCInterfaceDecl *ID = Ty->getDecl();
1599   if (!ID)
1600     return nullptr;
1601 
1602   // Get overall information about the record type for the debug info.
1603   llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
1604   unsigned Line = getLineNumber(ID->getLocation());
1605   auto RuntimeLang =
1606       static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
1607 
1608   // If this is just a forward declaration return a special forward-declaration
1609   // debug type since we won't be able to lay out the entire type.
1610   ObjCInterfaceDecl *Def = ID->getDefinition();
1611   if (!Def || !Def->getImplementation()) {
1612     llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
1613         llvm::dwarf::DW_TAG_structure_type, ID->getName(), TheCU, DefUnit, Line,
1614         RuntimeLang);
1615     ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
1616     return FwdDecl;
1617   }
1618 
1619   return CreateTypeDefinition(Ty, Unit);
1620 }
1621 
1622 llvm::DIModule *
1623 CGDebugInfo::getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod) {
1624   auto it = ModuleRefCache.find(Mod.Signature);
1625   if (it != ModuleRefCache.end())
1626     return it->second;
1627 
1628   // Macro definitions that were defined with "-D" on the command line.
1629   SmallString<128> ConfigMacros;
1630   {
1631     llvm::raw_svector_ostream OS(ConfigMacros);
1632     const auto &PPOpts = CGM.getPreprocessorOpts();
1633     unsigned I = 0;
1634     // Translate the macro definitions back into a commmand line.
1635     for (auto &M : PPOpts.Macros) {
1636       if (++I > 1)
1637         OS << " ";
1638       const std::string &Macro = M.first;
1639       bool Undef = M.second;
1640       OS << "\"-" << (Undef ? 'U' : 'D');
1641       for (char c : Macro)
1642         switch (c) {
1643         case '\\' : OS << "\\\\"; break;
1644         case '"'  : OS << "\\\""; break;
1645         default: OS << c;
1646         }
1647       OS << '\"';
1648     }
1649   }
1650   llvm::DIBuilder DIB(CGM.getModule());
1651   auto *CU = DIB.createCompileUnit(
1652       TheCU->getSourceLanguage(), internString(Mod.ModuleName),
1653       internString(Mod.Path), TheCU->getProducer(), true, StringRef(), 0,
1654       internString(Mod.ASTFile), llvm::DIBuilder::FullDebug, Mod.Signature);
1655   llvm::DIModule *ModuleRef =
1656       DIB.createModule(CU, Mod.ModuleName, ConfigMacros, internString(Mod.Path),
1657                        internString(CGM.getHeaderSearchOpts().Sysroot));
1658   DIB.finalize();
1659   ModuleRefCache.insert(std::make_pair(Mod.Signature, ModuleRef));
1660   return ModuleRef;
1661 }
1662 
1663 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
1664                                                 llvm::DIFile *Unit) {
1665   ObjCInterfaceDecl *ID = Ty->getDecl();
1666   llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
1667   unsigned Line = getLineNumber(ID->getLocation());
1668   unsigned RuntimeLang = TheCU->getSourceLanguage();
1669 
1670   // Bit size, align and offset of the type.
1671   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1672   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1673 
1674   unsigned Flags = 0;
1675   if (ID->getImplementation())
1676     Flags |= llvm::DINode::FlagObjcClassComplete;
1677 
1678   llvm::DICompositeType *RealDecl = DBuilder.createStructType(
1679       Unit, ID->getName(), DefUnit, Line, Size, Align, Flags, nullptr,
1680       llvm::DINodeArray(), RuntimeLang);
1681 
1682   QualType QTy(Ty, 0);
1683   TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
1684 
1685   // Push the struct on region stack.
1686   LexicalBlockStack.emplace_back(RealDecl);
1687   RegionMap[Ty->getDecl()].reset(RealDecl);
1688 
1689   // Convert all the elements.
1690   SmallVector<llvm::Metadata *, 16> EltTys;
1691 
1692   ObjCInterfaceDecl *SClass = ID->getSuperClass();
1693   if (SClass) {
1694     llvm::DIType *SClassTy =
1695         getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1696     if (!SClassTy)
1697       return nullptr;
1698 
1699     llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1700     EltTys.push_back(InhTag);
1701   }
1702 
1703   // Create entries for all of the properties.
1704   for (const auto *PD : ID->properties()) {
1705     SourceLocation Loc = PD->getLocation();
1706     llvm::DIFile *PUnit = getOrCreateFile(Loc);
1707     unsigned PLine = getLineNumber(Loc);
1708     ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1709     ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1710     llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
1711         PD->getName(), PUnit, PLine,
1712         hasDefaultGetterName(PD, Getter) ? ""
1713                                          : getSelectorName(PD->getGetterName()),
1714         hasDefaultSetterName(PD, Setter) ? ""
1715                                          : getSelectorName(PD->getSetterName()),
1716         PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
1717     EltTys.push_back(PropertyNode);
1718   }
1719 
1720   const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1721   unsigned FieldNo = 0;
1722   for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1723        Field = Field->getNextIvar(), ++FieldNo) {
1724     llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
1725     if (!FieldTy)
1726       return nullptr;
1727 
1728     StringRef FieldName = Field->getName();
1729 
1730     // Ignore unnamed fields.
1731     if (FieldName.empty())
1732       continue;
1733 
1734     // Get the location for the field.
1735     llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
1736     unsigned FieldLine = getLineNumber(Field->getLocation());
1737     QualType FType = Field->getType();
1738     uint64_t FieldSize = 0;
1739     unsigned FieldAlign = 0;
1740 
1741     if (!FType->isIncompleteArrayType()) {
1742 
1743       // Bit size, align and offset of the type.
1744       FieldSize = Field->isBitField()
1745                       ? Field->getBitWidthValue(CGM.getContext())
1746                       : CGM.getContext().getTypeSize(FType);
1747       FieldAlign = CGM.getContext().getTypeAlign(FType);
1748     }
1749 
1750     uint64_t FieldOffset;
1751     if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1752       // We don't know the runtime offset of an ivar if we're using the
1753       // non-fragile ABI.  For bitfields, use the bit offset into the first
1754       // byte of storage of the bitfield.  For other fields, use zero.
1755       if (Field->isBitField()) {
1756         FieldOffset =
1757             CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
1758         FieldOffset %= CGM.getContext().getCharWidth();
1759       } else {
1760         FieldOffset = 0;
1761       }
1762     } else {
1763       FieldOffset = RL.getFieldOffset(FieldNo);
1764     }
1765 
1766     unsigned Flags = 0;
1767     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1768       Flags = llvm::DINode::FlagProtected;
1769     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1770       Flags = llvm::DINode::FlagPrivate;
1771     else if (Field->getAccessControl() == ObjCIvarDecl::Public)
1772       Flags = llvm::DINode::FlagPublic;
1773 
1774     llvm::MDNode *PropertyNode = nullptr;
1775     if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1776       if (ObjCPropertyImplDecl *PImpD =
1777               ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1778         if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
1779           SourceLocation Loc = PD->getLocation();
1780           llvm::DIFile *PUnit = getOrCreateFile(Loc);
1781           unsigned PLine = getLineNumber(Loc);
1782           ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1783           ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1784           PropertyNode = DBuilder.createObjCProperty(
1785               PD->getName(), PUnit, PLine,
1786               hasDefaultGetterName(PD, Getter) ? "" : getSelectorName(
1787                                                           PD->getGetterName()),
1788               hasDefaultSetterName(PD, Setter) ? "" : getSelectorName(
1789                                                           PD->getSetterName()),
1790               PD->getPropertyAttributes(),
1791               getOrCreateType(PD->getType(), PUnit));
1792         }
1793       }
1794     }
1795     FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
1796                                       FieldSize, FieldAlign, FieldOffset, Flags,
1797                                       FieldTy, PropertyNode);
1798     EltTys.push_back(FieldTy);
1799   }
1800 
1801   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
1802   DBuilder.replaceArrays(RealDecl, Elements);
1803 
1804   LexicalBlockStack.pop_back();
1805   return RealDecl;
1806 }
1807 
1808 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
1809                                       llvm::DIFile *Unit) {
1810   llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1811   int64_t Count = Ty->getNumElements();
1812   if (Count == 0)
1813     // If number of elements are not known then this is an unbounded array.
1814     // Use Count == -1 to express such arrays.
1815     Count = -1;
1816 
1817   llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1818   llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1819 
1820   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1821   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1822 
1823   return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1824 }
1825 
1826 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
1827   uint64_t Size;
1828   uint64_t Align;
1829 
1830   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1831   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1832     Size = 0;
1833     Align =
1834         CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1835   } else if (Ty->isIncompleteArrayType()) {
1836     Size = 0;
1837     if (Ty->getElementType()->isIncompleteType())
1838       Align = 0;
1839     else
1840       Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1841   } else if (Ty->isIncompleteType()) {
1842     Size = 0;
1843     Align = 0;
1844   } else {
1845     // Size and align of the whole array, not the element type.
1846     Size = CGM.getContext().getTypeSize(Ty);
1847     Align = CGM.getContext().getTypeAlign(Ty);
1848   }
1849 
1850   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1851   // interior arrays, do we care?  Why aren't nested arrays represented the
1852   // obvious/recursive way?
1853   SmallVector<llvm::Metadata *, 8> Subscripts;
1854   QualType EltTy(Ty, 0);
1855   while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1856     // If the number of elements is known, then count is that number. Otherwise,
1857     // it's -1. This allows us to represent a subrange with an array of 0
1858     // elements, like this:
1859     //
1860     //   struct foo {
1861     //     int x[0];
1862     //   };
1863     int64_t Count = -1; // Count == -1 is an unbounded array.
1864     if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1865       Count = CAT->getSize().getZExtValue();
1866 
1867     // FIXME: Verify this is right for VLAs.
1868     Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1869     EltTy = Ty->getElementType();
1870   }
1871 
1872   llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1873 
1874   return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1875                                   SubscriptArray);
1876 }
1877 
1878 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1879                                       llvm::DIFile *Unit) {
1880   return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
1881                                Ty->getPointeeType(), Unit);
1882 }
1883 
1884 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1885                                       llvm::DIFile *Unit) {
1886   return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
1887                                Ty->getPointeeType(), Unit);
1888 }
1889 
1890 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
1891                                       llvm::DIFile *U) {
1892   uint64_t Size = CGM.getCXXABI().isTypeInfoCalculable(QualType(Ty, 0))
1893                       ? CGM.getContext().getTypeSize(Ty)
1894                       : 0;
1895   llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1896   if (Ty->isMemberDataPointerType())
1897     return DBuilder.createMemberPointerType(
1898         getOrCreateType(Ty->getPointeeType(), U), ClassType, Size);
1899 
1900   const FunctionProtoType *FPT =
1901       Ty->getPointeeType()->getAs<FunctionProtoType>();
1902   return DBuilder.createMemberPointerType(
1903       getOrCreateInstanceMethodType(CGM.getContext().getPointerType(QualType(
1904                                         Ty->getClass(), FPT->getTypeQuals())),
1905                                     FPT, U),
1906       ClassType, Size);
1907 }
1908 
1909 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
1910   // Ignore the atomic wrapping
1911   // FIXME: What is the correct representation?
1912   return getOrCreateType(Ty->getValueType(), U);
1913 }
1914 
1915 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
1916   const EnumDecl *ED = Ty->getDecl();
1917   uint64_t Size = 0;
1918   uint64_t Align = 0;
1919   if (!ED->getTypeForDecl()->isIncompleteType()) {
1920     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1921     Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1922   }
1923 
1924   SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1925 
1926   // If this is just a forward declaration, construct an appropriately
1927   // marked node and just return it.
1928   if (!ED->getDefinition()) {
1929     llvm::DIScope *EDContext =
1930         getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1931     llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
1932     unsigned Line = getLineNumber(ED->getLocation());
1933     StringRef EDName = ED->getName();
1934     llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
1935         llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
1936         0, Size, Align, llvm::DINode::FlagFwdDecl, FullName);
1937     ReplaceMap.emplace_back(
1938         std::piecewise_construct, std::make_tuple(Ty),
1939         std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
1940     return RetTy;
1941   }
1942 
1943   return CreateTypeDefinition(Ty);
1944 }
1945 
1946 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
1947   const EnumDecl *ED = Ty->getDecl();
1948   uint64_t Size = 0;
1949   uint64_t Align = 0;
1950   if (!ED->getTypeForDecl()->isIncompleteType()) {
1951     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1952     Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1953   }
1954 
1955   SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1956 
1957   // Create elements for each enumerator.
1958   SmallVector<llvm::Metadata *, 16> Enumerators;
1959   ED = ED->getDefinition();
1960   for (const auto *Enum : ED->enumerators()) {
1961     Enumerators.push_back(DBuilder.createEnumerator(
1962         Enum->getName(), Enum->getInitVal().getSExtValue()));
1963   }
1964 
1965   // Return a CompositeType for the enum itself.
1966   llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1967 
1968   llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
1969   unsigned Line = getLineNumber(ED->getLocation());
1970   llvm::DIScope *EnumContext =
1971       getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1972   llvm::DIType *ClassTy =
1973       ED->isFixed() ? getOrCreateType(ED->getIntegerType(), DefUnit) : nullptr;
1974   return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
1975                                         Line, Size, Align, EltArray, ClassTy,
1976                                         FullName);
1977 }
1978 
1979 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1980   Qualifiers Quals;
1981   do {
1982     Qualifiers InnerQuals = T.getLocalQualifiers();
1983     // Qualifiers::operator+() doesn't like it if you add a Qualifier
1984     // that is already there.
1985     Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1986     Quals += InnerQuals;
1987     QualType LastT = T;
1988     switch (T->getTypeClass()) {
1989     default:
1990       return C.getQualifiedType(T.getTypePtr(), Quals);
1991     case Type::TemplateSpecialization: {
1992       const auto *Spec = cast<TemplateSpecializationType>(T);
1993       if (Spec->isTypeAlias())
1994         return C.getQualifiedType(T.getTypePtr(), Quals);
1995       T = Spec->desugar();
1996       break;
1997     }
1998     case Type::TypeOfExpr:
1999       T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
2000       break;
2001     case Type::TypeOf:
2002       T = cast<TypeOfType>(T)->getUnderlyingType();
2003       break;
2004     case Type::Decltype:
2005       T = cast<DecltypeType>(T)->getUnderlyingType();
2006       break;
2007     case Type::UnaryTransform:
2008       T = cast<UnaryTransformType>(T)->getUnderlyingType();
2009       break;
2010     case Type::Attributed:
2011       T = cast<AttributedType>(T)->getEquivalentType();
2012       break;
2013     case Type::Elaborated:
2014       T = cast<ElaboratedType>(T)->getNamedType();
2015       break;
2016     case Type::Paren:
2017       T = cast<ParenType>(T)->getInnerType();
2018       break;
2019     case Type::SubstTemplateTypeParm:
2020       T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
2021       break;
2022     case Type::Auto:
2023       QualType DT = cast<AutoType>(T)->getDeducedType();
2024       assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
2025       T = DT;
2026       break;
2027     }
2028 
2029     assert(T != LastT && "Type unwrapping failed to unwrap!");
2030     (void)LastT;
2031   } while (true);
2032 }
2033 
2034 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
2035 
2036   // Unwrap the type as needed for debug information.
2037   Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2038 
2039   auto it = TypeCache.find(Ty.getAsOpaquePtr());
2040   if (it != TypeCache.end()) {
2041     // Verify that the debug info still exists.
2042     if (llvm::Metadata *V = it->second)
2043       return cast<llvm::DIType>(V);
2044   }
2045 
2046   return nullptr;
2047 }
2048 
2049 void CGDebugInfo::completeTemplateDefinition(
2050     const ClassTemplateSpecializationDecl &SD) {
2051   if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2052     return;
2053 
2054   completeClassData(&SD);
2055   // In case this type has no member function definitions being emitted, ensure
2056   // it is retained
2057   RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr());
2058 }
2059 
2060 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
2061   if (Ty.isNull())
2062     return nullptr;
2063 
2064   // Unwrap the type as needed for debug information.
2065   Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2066 
2067   if (auto *T = getTypeOrNull(Ty))
2068     return T;
2069 
2070   // Otherwise create the type.
2071   llvm::DIType *Res = CreateTypeNode(Ty, Unit);
2072   void *TyPtr = Ty.getAsOpaquePtr();
2073 
2074   // And update the type cache.
2075   TypeCache[TyPtr].reset(Res);
2076 
2077   return Res;
2078 }
2079 
2080 unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
2081   // The assumption is that the number of ivars can only increase
2082   // monotonically, so it is safe to just use their current number as
2083   // a checksum.
2084   unsigned Sum = 0;
2085   for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2086        Ivar != nullptr; Ivar = Ivar->getNextIvar())
2087     ++Sum;
2088 
2089   return Sum;
2090 }
2091 
2092 ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2093   switch (Ty->getTypeClass()) {
2094   case Type::ObjCObjectPointer:
2095     return getObjCInterfaceDecl(
2096         cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2097   case Type::ObjCInterface:
2098     return cast<ObjCInterfaceType>(Ty)->getDecl();
2099   default:
2100     return nullptr;
2101   }
2102 }
2103 
2104 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
2105   // Handle qualifiers, which recursively handles what they refer to.
2106   if (Ty.hasLocalQualifiers())
2107     return CreateQualifiedType(Ty, Unit);
2108 
2109   // Work out details of type.
2110   switch (Ty->getTypeClass()) {
2111 #define TYPE(Class, Base)
2112 #define ABSTRACT_TYPE(Class, Base)
2113 #define NON_CANONICAL_TYPE(Class, Base)
2114 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2115 #include "clang/AST/TypeNodes.def"
2116     llvm_unreachable("Dependent types cannot show up in debug information");
2117 
2118   case Type::ExtVector:
2119   case Type::Vector:
2120     return CreateType(cast<VectorType>(Ty), Unit);
2121   case Type::ObjCObjectPointer:
2122     return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2123   case Type::ObjCObject:
2124     return CreateType(cast<ObjCObjectType>(Ty), Unit);
2125   case Type::ObjCInterface:
2126     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2127   case Type::Builtin:
2128     return CreateType(cast<BuiltinType>(Ty));
2129   case Type::Complex:
2130     return CreateType(cast<ComplexType>(Ty));
2131   case Type::Pointer:
2132     return CreateType(cast<PointerType>(Ty), Unit);
2133   case Type::Adjusted:
2134   case Type::Decayed:
2135     // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
2136     return CreateType(
2137         cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
2138   case Type::BlockPointer:
2139     return CreateType(cast<BlockPointerType>(Ty), Unit);
2140   case Type::Typedef:
2141     return CreateType(cast<TypedefType>(Ty), Unit);
2142   case Type::Record:
2143     return CreateType(cast<RecordType>(Ty));
2144   case Type::Enum:
2145     return CreateEnumType(cast<EnumType>(Ty));
2146   case Type::FunctionProto:
2147   case Type::FunctionNoProto:
2148     return CreateType(cast<FunctionType>(Ty), Unit);
2149   case Type::ConstantArray:
2150   case Type::VariableArray:
2151   case Type::IncompleteArray:
2152     return CreateType(cast<ArrayType>(Ty), Unit);
2153 
2154   case Type::LValueReference:
2155     return CreateType(cast<LValueReferenceType>(Ty), Unit);
2156   case Type::RValueReference:
2157     return CreateType(cast<RValueReferenceType>(Ty), Unit);
2158 
2159   case Type::MemberPointer:
2160     return CreateType(cast<MemberPointerType>(Ty), Unit);
2161 
2162   case Type::Atomic:
2163     return CreateType(cast<AtomicType>(Ty), Unit);
2164 
2165   case Type::TemplateSpecialization:
2166     return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
2167 
2168   case Type::Auto:
2169   case Type::Attributed:
2170   case Type::Elaborated:
2171   case Type::Paren:
2172   case Type::SubstTemplateTypeParm:
2173   case Type::TypeOfExpr:
2174   case Type::TypeOf:
2175   case Type::Decltype:
2176   case Type::UnaryTransform:
2177   case Type::PackExpansion:
2178     break;
2179   }
2180 
2181   llvm_unreachable("type should have been unwrapped!");
2182 }
2183 
2184 llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
2185                                                            llvm::DIFile *Unit) {
2186   QualType QTy(Ty, 0);
2187 
2188   auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
2189 
2190   // We may have cached a forward decl when we could have created
2191   // a non-forward decl. Go ahead and create a non-forward decl
2192   // now.
2193   if (T && !T->isForwardDecl())
2194     return T;
2195 
2196   // Otherwise create the type.
2197   llvm::DICompositeType *Res = CreateLimitedType(Ty);
2198 
2199   // Propagate members from the declaration to the definition
2200   // CreateType(const RecordType*) will overwrite this with the members in the
2201   // correct order if the full type is needed.
2202   DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
2203 
2204   // And update the type cache.
2205   TypeCache[QTy.getAsOpaquePtr()].reset(Res);
2206   return Res;
2207 }
2208 
2209 // TODO: Currently used for context chains when limiting debug info.
2210 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2211   RecordDecl *RD = Ty->getDecl();
2212 
2213   // Get overall information about the record type for the debug info.
2214   llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2215   unsigned Line = getLineNumber(RD->getLocation());
2216   StringRef RDName = getClassName(RD);
2217 
2218   llvm::DIScope *RDContext =
2219       getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2220 
2221   // If we ended up creating the type during the context chain construction,
2222   // just return that.
2223   auto *T = cast_or_null<llvm::DICompositeType>(
2224       getTypeOrNull(CGM.getContext().getRecordType(RD)));
2225   if (T && (!T->isForwardDecl() || !RD->getDefinition()))
2226     return T;
2227 
2228   // If this is just a forward or incomplete declaration, construct an
2229   // appropriately marked node and just return it.
2230   const RecordDecl *D = RD->getDefinition();
2231   if (!D || !D->isCompleteDefinition())
2232     return getOrCreateRecordFwdDecl(Ty, RDContext);
2233 
2234   uint64_t Size = CGM.getContext().getTypeSize(Ty);
2235   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2236 
2237   SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2238 
2239   llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
2240       getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align, 0,
2241       FullName);
2242 
2243   RegionMap[Ty->getDecl()].reset(RealDecl);
2244   TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
2245 
2246   if (const ClassTemplateSpecializationDecl *TSpecial =
2247           dyn_cast<ClassTemplateSpecializationDecl>(RD))
2248     DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
2249                            CollectCXXTemplateParams(TSpecial, DefUnit));
2250   return RealDecl;
2251 }
2252 
2253 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2254                                         llvm::DICompositeType *RealDecl) {
2255   // A class's primary base or the class itself contains the vtable.
2256   llvm::DICompositeType *ContainingType = nullptr;
2257   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2258   if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2259     // Seek non-virtual primary base root.
2260     while (1) {
2261       const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2262       const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2263       if (PBT && !BRL.isPrimaryBaseVirtual())
2264         PBase = PBT;
2265       else
2266         break;
2267     }
2268     ContainingType = cast<llvm::DICompositeType>(
2269         getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2270                         getOrCreateFile(RD->getLocation())));
2271   } else if (RD->isDynamicClass())
2272     ContainingType = RealDecl;
2273 
2274   DBuilder.replaceVTableHolder(RealDecl, ContainingType);
2275 }
2276 
2277 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
2278                                             StringRef Name, uint64_t *Offset) {
2279   llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2280   uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2281   unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2282   llvm::DIType *Ty = DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize,
2283                                                FieldAlign, *Offset, 0, FieldTy);
2284   *Offset += FieldSize;
2285   return Ty;
2286 }
2287 
2288 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
2289                                            StringRef &Name,
2290                                            StringRef &LinkageName,
2291                                            llvm::DIScope *&FDContext,
2292                                            llvm::DINodeArray &TParamsArray,
2293                                            unsigned &Flags) {
2294   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2295   Name = getFunctionName(FD);
2296   // Use mangled name as linkage name for C/C++ functions.
2297   if (FD->hasPrototype()) {
2298     LinkageName = CGM.getMangledName(GD);
2299     Flags |= llvm::DINode::FlagPrototyped;
2300   }
2301   // No need to replicate the linkage name if it isn't different from the
2302   // subprogram name, no need to have it at all unless coverage is enabled or
2303   // debug is set to more than just line tables.
2304   if (LinkageName == Name ||
2305       (!CGM.getCodeGenOpts().EmitGcovArcs &&
2306        !CGM.getCodeGenOpts().EmitGcovNotes &&
2307        DebugKind <= CodeGenOptions::DebugLineTablesOnly))
2308     LinkageName = StringRef();
2309 
2310   if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
2311     if (const NamespaceDecl *NSDecl =
2312         dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2313       FDContext = getOrCreateNameSpace(NSDecl);
2314     else if (const RecordDecl *RDecl =
2315              dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2316       FDContext = getContextDescriptor(cast<Decl>(RDecl));
2317     // Collect template parameters.
2318     TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2319   }
2320 }
2321 
2322 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
2323                                       unsigned &LineNo, QualType &T,
2324                                       StringRef &Name, StringRef &LinkageName,
2325                                       llvm::DIScope *&VDContext) {
2326   Unit = getOrCreateFile(VD->getLocation());
2327   LineNo = getLineNumber(VD->getLocation());
2328 
2329   setLocation(VD->getLocation());
2330 
2331   T = VD->getType();
2332   if (T->isIncompleteArrayType()) {
2333     // CodeGen turns int[] into int[1] so we'll do the same here.
2334     llvm::APInt ConstVal(32, 1);
2335     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2336 
2337     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2338                                               ArrayType::Normal, 0);
2339   }
2340 
2341   Name = VD->getName();
2342   if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
2343       !isa<ObjCMethodDecl>(VD->getDeclContext()))
2344     LinkageName = CGM.getMangledName(VD);
2345   if (LinkageName == Name)
2346     LinkageName = StringRef();
2347 
2348   // Since we emit declarations (DW_AT_members) for static members, place the
2349   // definition of those static members in the namespace they were declared in
2350   // in the source code (the lexical decl context).
2351   // FIXME: Generalize this for even non-member global variables where the
2352   // declaration and definition may have different lexical decl contexts, once
2353   // we have support for emitting declarations of (non-member) global variables.
2354   const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
2355                                                    : VD->getDeclContext();
2356   // When a record type contains an in-line initialization of a static data
2357   // member, and the record type is marked as __declspec(dllexport), an implicit
2358   // definition of the member will be created in the record context.  DWARF
2359   // doesn't seem to have a nice way to describe this in a form that consumers
2360   // are likely to understand, so fake the "normal" situation of a definition
2361   // outside the class by putting it in the global scope.
2362   if (DC->isRecord())
2363     DC = CGM.getContext().getTranslationUnitDecl();
2364   VDContext = getContextDescriptor(dyn_cast<Decl>(DC));
2365 }
2366 
2367 llvm::DISubprogram *
2368 CGDebugInfo::getFunctionForwardDeclaration(const FunctionDecl *FD) {
2369   llvm::DINodeArray TParamsArray;
2370   StringRef Name, LinkageName;
2371   unsigned Flags = 0;
2372   SourceLocation Loc = FD->getLocation();
2373   llvm::DIFile *Unit = getOrCreateFile(Loc);
2374   llvm::DIScope *DContext = Unit;
2375   unsigned Line = getLineNumber(Loc);
2376 
2377   collectFunctionDeclProps(FD, Unit, Name, LinkageName, DContext,
2378                            TParamsArray, Flags);
2379   // Build function type.
2380   SmallVector<QualType, 16> ArgTypes;
2381   for (const ParmVarDecl *Parm: FD->parameters())
2382     ArgTypes.push_back(Parm->getType());
2383   QualType FnType =
2384     CGM.getContext().getFunctionType(FD->getReturnType(), ArgTypes,
2385                                      FunctionProtoType::ExtProtoInfo());
2386   llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
2387       DContext, Name, LinkageName, Unit, Line,
2388       getOrCreateFunctionType(FD, FnType, Unit), !FD->isExternallyVisible(),
2389       false /*declaration*/, 0, Flags, CGM.getLangOpts().Optimize, nullptr,
2390       TParamsArray.get(), getFunctionDeclaration(FD));
2391   const FunctionDecl *CanonDecl = cast<FunctionDecl>(FD->getCanonicalDecl());
2392   FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
2393                                  std::make_tuple(CanonDecl),
2394                                  std::make_tuple(SP));
2395   return SP;
2396 }
2397 
2398 llvm::DIGlobalVariable *
2399 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
2400   QualType T;
2401   StringRef Name, LinkageName;
2402   SourceLocation Loc = VD->getLocation();
2403   llvm::DIFile *Unit = getOrCreateFile(Loc);
2404   llvm::DIScope *DContext = Unit;
2405   unsigned Line = getLineNumber(Loc);
2406 
2407   collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, DContext);
2408   auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
2409       DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
2410       !VD->isExternallyVisible(), nullptr, nullptr);
2411   FwdDeclReplaceMap.emplace_back(
2412       std::piecewise_construct,
2413       std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
2414       std::make_tuple(static_cast<llvm::Metadata *>(GV)));
2415   return GV;
2416 }
2417 
2418 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2419   // We only need a declaration (not a definition) of the type - so use whatever
2420   // we would otherwise do to get a type for a pointee. (forward declarations in
2421   // limited debug info, full definitions (if the type definition is available)
2422   // in unlimited debug info)
2423   if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2424     return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
2425                            getOrCreateFile(TD->getLocation()));
2426   auto I = DeclCache.find(D->getCanonicalDecl());
2427 
2428   if (I != DeclCache.end())
2429     return dyn_cast_or_null<llvm::DINode>(I->second);
2430 
2431   // No definition for now. Emit a forward definition that might be
2432   // merged with a potential upcoming definition.
2433   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
2434     return getFunctionForwardDeclaration(FD);
2435   else if (const auto *VD = dyn_cast<VarDecl>(D))
2436     return getGlobalVariableForwardDeclaration(VD);
2437 
2438   return nullptr;
2439 }
2440 
2441 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2442   if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2443     return nullptr;
2444 
2445   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2446   if (!FD)
2447     return nullptr;
2448 
2449   // Setup context.
2450   auto *S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
2451 
2452   auto MI = SPCache.find(FD->getCanonicalDecl());
2453   if (MI == SPCache.end()) {
2454     if (const CXXMethodDecl *MD =
2455             dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
2456       return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
2457                                      cast<llvm::DICompositeType>(S));
2458     }
2459   }
2460   if (MI != SPCache.end()) {
2461     auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
2462     if (SP && !SP->isDefinition())
2463       return SP;
2464   }
2465 
2466   for (auto NextFD : FD->redecls()) {
2467     auto MI = SPCache.find(NextFD->getCanonicalDecl());
2468     if (MI != SPCache.end()) {
2469       auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
2470       if (SP && !SP->isDefinition())
2471         return SP;
2472     }
2473   }
2474   return nullptr;
2475 }
2476 
2477 // getOrCreateFunctionType - Construct type. If it is a c++ method, include
2478 // implicit parameter "this".
2479 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2480                                                              QualType FnType,
2481                                                              llvm::DIFile *F) {
2482   if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2483     // Create fake but valid subroutine type. Otherwise -verify would fail, and
2484     // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
2485     return DBuilder.createSubroutineType(F,
2486                                          DBuilder.getOrCreateTypeArray(None));
2487 
2488   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2489     return getOrCreateMethodType(Method, F);
2490   if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2491     // Add "self" and "_cmd"
2492     SmallVector<llvm::Metadata *, 16> Elts;
2493 
2494     // First element is always return type. For 'void' functions it is NULL.
2495     QualType ResultTy = OMethod->getReturnType();
2496 
2497     // Replace the instancetype keyword with the actual type.
2498     if (ResultTy == CGM.getContext().getObjCInstanceType())
2499       ResultTy = CGM.getContext().getPointerType(
2500           QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2501 
2502     Elts.push_back(getOrCreateType(ResultTy, F));
2503     // "self" pointer is always first argument.
2504     QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2505     Elts.push_back(CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
2506     // "_cmd" pointer is always second argument.
2507     Elts.push_back(DBuilder.createArtificialType(
2508         getOrCreateType(OMethod->getCmdDecl()->getType(), F)));
2509     // Get rest of the arguments.
2510     for (const auto *PI : OMethod->params())
2511       Elts.push_back(getOrCreateType(PI->getType(), F));
2512     // Variadic methods need a special marker at the end of the type list.
2513     if (OMethod->isVariadic())
2514       Elts.push_back(DBuilder.createUnspecifiedParameter());
2515 
2516     llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
2517     return DBuilder.createSubroutineType(F, EltTypeArray);
2518   }
2519 
2520   // Handle variadic function types; they need an additional
2521   // unspecified parameter.
2522   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2523     if (FD->isVariadic()) {
2524       SmallVector<llvm::Metadata *, 16> EltTys;
2525       EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
2526       if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
2527         for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
2528           EltTys.push_back(getOrCreateType(FPT->getParamType(i), F));
2529       EltTys.push_back(DBuilder.createUnspecifiedParameter());
2530       llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
2531       return DBuilder.createSubroutineType(F, EltTypeArray);
2532     }
2533 
2534   return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
2535 }
2536 
2537 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
2538                                     SourceLocation ScopeLoc, QualType FnType,
2539                                     llvm::Function *Fn, CGBuilderTy &Builder) {
2540 
2541   StringRef Name;
2542   StringRef LinkageName;
2543 
2544   FnBeginRegionCount.push_back(LexicalBlockStack.size());
2545 
2546   const Decl *D = GD.getDecl();
2547   bool HasDecl = (D != nullptr);
2548 
2549   unsigned Flags = 0;
2550   llvm::DIFile *Unit = getOrCreateFile(Loc);
2551   llvm::DIScope *FDContext = Unit;
2552   llvm::DINodeArray TParamsArray;
2553   if (!HasDecl) {
2554     // Use llvm function name.
2555     LinkageName = Fn->getName();
2556   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2557     // If there is a subprogram for this function available then use it.
2558     auto FI = SPCache.find(FD->getCanonicalDecl());
2559     if (FI != SPCache.end()) {
2560       auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
2561       if (SP && SP->isDefinition()) {
2562         LexicalBlockStack.emplace_back(SP);
2563         RegionMap[D].reset(SP);
2564         return;
2565       }
2566     }
2567     collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
2568                              TParamsArray, Flags);
2569   } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2570     Name = getObjCMethodName(OMD);
2571     Flags |= llvm::DINode::FlagPrototyped;
2572   } else {
2573     // Use llvm function name.
2574     Name = Fn->getName();
2575     Flags |= llvm::DINode::FlagPrototyped;
2576   }
2577   if (!Name.empty() && Name[0] == '\01')
2578     Name = Name.substr(1);
2579 
2580   if (!HasDecl || D->isImplicit()) {
2581     Flags |= llvm::DINode::FlagArtificial;
2582     // Artificial functions without a location should not silently reuse CurLoc.
2583     if (Loc.isInvalid())
2584       CurLoc = SourceLocation();
2585   }
2586   unsigned LineNo = getLineNumber(Loc);
2587   unsigned ScopeLine = getLineNumber(ScopeLoc);
2588 
2589   // FIXME: The function declaration we're constructing here is mostly reusing
2590   // declarations from CXXMethodDecl and not constructing new ones for arbitrary
2591   // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
2592   // all subprograms instead of the actual context since subprogram definitions
2593   // are emitted as CU level entities by the backend.
2594   llvm::DISubprogram *SP = DBuilder.createFunction(
2595       FDContext, Name, LinkageName, Unit, LineNo,
2596       getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
2597       true /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize, Fn,
2598       TParamsArray.get(), getFunctionDeclaration(D));
2599   // We might get here with a VarDecl in the case we're generating
2600   // code for the initialization of globals. Do not record these decls
2601   // as they will overwrite the actual VarDecl Decl in the cache.
2602   if (HasDecl && isa<FunctionDecl>(D))
2603     DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(SP));
2604 
2605   // Push the function onto the lexical block stack.
2606   LexicalBlockStack.emplace_back(SP);
2607 
2608   if (HasDecl)
2609     RegionMap[D].reset(SP);
2610 }
2611 
2612 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
2613   // Update our current location
2614   setLocation(Loc);
2615 
2616   if (CurLoc.isInvalid() || CurLoc.isMacroID())
2617     return;
2618 
2619   llvm::MDNode *Scope = LexicalBlockStack.back();
2620   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
2621       getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope));
2622 }
2623 
2624 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2625   llvm::MDNode *Back = nullptr;
2626   if (!LexicalBlockStack.empty())
2627     Back = LexicalBlockStack.back().get();
2628   LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
2629       cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
2630       getColumnNumber(CurLoc)));
2631 }
2632 
2633 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2634                                         SourceLocation Loc) {
2635   // Set our current location.
2636   setLocation(Loc);
2637 
2638   // Emit a line table change for the current location inside the new scope.
2639   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
2640       getLineNumber(Loc), getColumnNumber(Loc), LexicalBlockStack.back()));
2641 
2642   if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2643     return;
2644 
2645   // Create a new lexical block and push it on the stack.
2646   CreateLexicalBlock(Loc);
2647 }
2648 
2649 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2650                                       SourceLocation Loc) {
2651   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2652 
2653   // Provide an entry in the line table for the end of the block.
2654   EmitLocation(Builder, Loc);
2655 
2656   if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2657     return;
2658 
2659   LexicalBlockStack.pop_back();
2660 }
2661 
2662 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2663   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2664   unsigned RCount = FnBeginRegionCount.back();
2665   assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2666 
2667   // Pop all regions for this function.
2668   while (LexicalBlockStack.size() != RCount) {
2669     // Provide an entry in the line table for the end of the block.
2670     EmitLocation(Builder, CurLoc);
2671     LexicalBlockStack.pop_back();
2672   }
2673   FnBeginRegionCount.pop_back();
2674 }
2675 
2676 llvm::DIType *CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2677                                                         uint64_t *XOffset) {
2678 
2679   SmallVector<llvm::Metadata *, 5> EltTys;
2680   QualType FType;
2681   uint64_t FieldSize, FieldOffset;
2682   unsigned FieldAlign;
2683 
2684   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
2685   QualType Type = VD->getType();
2686 
2687   FieldOffset = 0;
2688   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2689   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2690   EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2691   FType = CGM.getContext().IntTy;
2692   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2693   EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2694 
2695   bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2696   if (HasCopyAndDispose) {
2697     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2698     EltTys.push_back(
2699         CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
2700     EltTys.push_back(
2701         CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
2702   }
2703   bool HasByrefExtendedLayout;
2704   Qualifiers::ObjCLifetime Lifetime;
2705   if (CGM.getContext().getByrefLifetime(Type, Lifetime,
2706                                         HasByrefExtendedLayout) &&
2707       HasByrefExtendedLayout) {
2708     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2709     EltTys.push_back(
2710         CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
2711   }
2712 
2713   CharUnits Align = CGM.getContext().getDeclAlign(VD);
2714   if (Align > CGM.getContext().toCharUnitsFromBits(
2715                   CGM.getTarget().getPointerAlign(0))) {
2716     CharUnits FieldOffsetInBytes =
2717         CGM.getContext().toCharUnitsFromBits(FieldOffset);
2718     CharUnits AlignedOffsetInBytes =
2719         FieldOffsetInBytes.RoundUpToAlignment(Align);
2720     CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
2721 
2722     if (NumPaddingBytes.isPositive()) {
2723       llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2724       FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2725                                                     pad, ArrayType::Normal, 0);
2726       EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2727     }
2728   }
2729 
2730   FType = Type;
2731   llvm::DIType *FieldTy = getOrCreateType(FType, Unit);
2732   FieldSize = CGM.getContext().getTypeSize(FType);
2733   FieldAlign = CGM.getContext().toBits(Align);
2734 
2735   *XOffset = FieldOffset;
2736   FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 0, FieldSize,
2737                                       FieldAlign, FieldOffset, 0, FieldTy);
2738   EltTys.push_back(FieldTy);
2739   FieldOffset += FieldSize;
2740 
2741   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2742 
2743   unsigned Flags = llvm::DINode::FlagBlockByrefStruct;
2744 
2745   return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2746                                    nullptr, Elements);
2747 }
2748 
2749 void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::Value *Storage,
2750                               llvm::Optional<unsigned> ArgNo,
2751                               CGBuilderTy &Builder) {
2752   assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2753   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2754 
2755   bool Unwritten =
2756       VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2757                            cast<Decl>(VD->getDeclContext())->isImplicit());
2758   llvm::DIFile *Unit = nullptr;
2759   if (!Unwritten)
2760     Unit = getOrCreateFile(VD->getLocation());
2761   llvm::DIType *Ty;
2762   uint64_t XOffset = 0;
2763   if (VD->hasAttr<BlocksAttr>())
2764     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2765   else
2766     Ty = getOrCreateType(VD->getType(), Unit);
2767 
2768   // If there is no debug info for this type then do not emit debug info
2769   // for this variable.
2770   if (!Ty)
2771     return;
2772 
2773   // Get location information.
2774   unsigned Line = 0;
2775   unsigned Column = 0;
2776   if (!Unwritten) {
2777     Line = getLineNumber(VD->getLocation());
2778     Column = getColumnNumber(VD->getLocation());
2779   }
2780   SmallVector<int64_t, 9> Expr;
2781   unsigned Flags = 0;
2782   if (VD->isImplicit())
2783     Flags |= llvm::DINode::FlagArtificial;
2784   // If this is the first argument and it is implicit then
2785   // give it an object pointer flag.
2786   // FIXME: There has to be a better way to do this, but for static
2787   // functions there won't be an implicit param at arg1 and
2788   // otherwise it is 'self' or 'this'.
2789   if (isa<ImplicitParamDecl>(VD) && ArgNo && *ArgNo == 1)
2790     Flags |= llvm::DINode::FlagObjectPointer;
2791   if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
2792     if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2793         !VD->getType()->isPointerType())
2794       Expr.push_back(llvm::dwarf::DW_OP_deref);
2795 
2796   auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
2797 
2798   StringRef Name = VD->getName();
2799   if (!Name.empty()) {
2800     if (VD->hasAttr<BlocksAttr>()) {
2801       CharUnits offset = CharUnits::fromQuantity(32);
2802       Expr.push_back(llvm::dwarf::DW_OP_plus);
2803       // offset of __forwarding field
2804       offset = CGM.getContext().toCharUnitsFromBits(
2805           CGM.getTarget().getPointerWidth(0));
2806       Expr.push_back(offset.getQuantity());
2807       Expr.push_back(llvm::dwarf::DW_OP_deref);
2808       Expr.push_back(llvm::dwarf::DW_OP_plus);
2809       // offset of x field
2810       offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2811       Expr.push_back(offset.getQuantity());
2812 
2813       // Create the descriptor for the variable.
2814       auto *D = ArgNo
2815                     ? DBuilder.createParameterVariable(Scope, VD->getName(),
2816                                                        *ArgNo, Unit, Line, Ty)
2817                     : DBuilder.createAutoVariable(Scope, VD->getName(), Unit,
2818                                                   Line, Ty);
2819 
2820       // Insert an llvm.dbg.declare into the current block.
2821       DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
2822                              llvm::DebugLoc::get(Line, Column, Scope),
2823                              Builder.GetInsertBlock());
2824       return;
2825     } else if (isa<VariableArrayType>(VD->getType()))
2826       Expr.push_back(llvm::dwarf::DW_OP_deref);
2827   } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2828     // If VD is an anonymous union then Storage represents value for
2829     // all union fields.
2830     const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2831     if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
2832       // GDB has trouble finding local variables in anonymous unions, so we emit
2833       // artifical local variables for each of the members.
2834       //
2835       // FIXME: Remove this code as soon as GDB supports this.
2836       // The debug info verifier in LLVM operates based on the assumption that a
2837       // variable has the same size as its storage and we had to disable the check
2838       // for artificial variables.
2839       for (const auto *Field : RD->fields()) {
2840         llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
2841         StringRef FieldName = Field->getName();
2842 
2843         // Ignore unnamed fields. Do not ignore unnamed records.
2844         if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2845           continue;
2846 
2847         // Use VarDecl's Tag, Scope and Line number.
2848         auto *D = DBuilder.createAutoVariable(
2849             Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
2850             Flags | llvm::DINode::FlagArtificial);
2851 
2852         // Insert an llvm.dbg.declare into the current block.
2853         DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
2854                                llvm::DebugLoc::get(Line, Column, Scope),
2855                                Builder.GetInsertBlock());
2856       }
2857     }
2858   }
2859 
2860   // Create the descriptor for the variable.
2861   auto *D =
2862       ArgNo
2863           ? DBuilder.createParameterVariable(Scope, Name, *ArgNo, Unit, Line,
2864                                              Ty, CGM.getLangOpts().Optimize,
2865                                              Flags)
2866           : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
2867                                         CGM.getLangOpts().Optimize, Flags);
2868 
2869   // Insert an llvm.dbg.declare into the current block.
2870   DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
2871                          llvm::DebugLoc::get(Line, Column, Scope),
2872                          Builder.GetInsertBlock());
2873 }
2874 
2875 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2876                                             llvm::Value *Storage,
2877                                             CGBuilderTy &Builder) {
2878   assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2879   EmitDeclare(VD, Storage, llvm::None, Builder);
2880 }
2881 
2882 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
2883                                           llvm::DIType *Ty) {
2884   llvm::DIType *CachedTy = getTypeOrNull(QualTy);
2885   if (CachedTy)
2886     Ty = CachedTy;
2887   return DBuilder.createObjectPointerType(Ty);
2888 }
2889 
2890 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
2891     const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
2892     const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
2893   assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2894   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2895 
2896   if (Builder.GetInsertBlock() == nullptr)
2897     return;
2898 
2899   bool isByRef = VD->hasAttr<BlocksAttr>();
2900 
2901   uint64_t XOffset = 0;
2902   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
2903   llvm::DIType *Ty;
2904   if (isByRef)
2905     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2906   else
2907     Ty = getOrCreateType(VD->getType(), Unit);
2908 
2909   // Self is passed along as an implicit non-arg variable in a
2910   // block. Mark it as the object pointer.
2911   if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
2912     Ty = CreateSelfType(VD->getType(), Ty);
2913 
2914   // Get location information.
2915   unsigned Line = getLineNumber(VD->getLocation());
2916   unsigned Column = getColumnNumber(VD->getLocation());
2917 
2918   const llvm::DataLayout &target = CGM.getDataLayout();
2919 
2920   CharUnits offset = CharUnits::fromQuantity(
2921       target.getStructLayout(blockInfo.StructureType)
2922           ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2923 
2924   SmallVector<int64_t, 9> addr;
2925   if (isa<llvm::AllocaInst>(Storage))
2926     addr.push_back(llvm::dwarf::DW_OP_deref);
2927   addr.push_back(llvm::dwarf::DW_OP_plus);
2928   addr.push_back(offset.getQuantity());
2929   if (isByRef) {
2930     addr.push_back(llvm::dwarf::DW_OP_deref);
2931     addr.push_back(llvm::dwarf::DW_OP_plus);
2932     // offset of __forwarding field
2933     offset =
2934         CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
2935     addr.push_back(offset.getQuantity());
2936     addr.push_back(llvm::dwarf::DW_OP_deref);
2937     addr.push_back(llvm::dwarf::DW_OP_plus);
2938     // offset of x field
2939     offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2940     addr.push_back(offset.getQuantity());
2941   }
2942 
2943   // Create the descriptor for the variable.
2944   auto *D = DBuilder.createAutoVariable(
2945       cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
2946       Line, Ty);
2947 
2948   // Insert an llvm.dbg.declare into the current block.
2949   auto DL = llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back());
2950   if (InsertPoint)
2951     DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
2952                            InsertPoint);
2953   else
2954     DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
2955                            Builder.GetInsertBlock());
2956 }
2957 
2958 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2959                                            unsigned ArgNo,
2960                                            CGBuilderTy &Builder) {
2961   assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2962   EmitDeclare(VD, AI, ArgNo, Builder);
2963 }
2964 
2965 namespace {
2966 struct BlockLayoutChunk {
2967   uint64_t OffsetInBits;
2968   const BlockDecl::Capture *Capture;
2969 };
2970 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2971   return l.OffsetInBits < r.OffsetInBits;
2972 }
2973 }
2974 
2975 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2976                                                        llvm::Value *Arg,
2977                                                        unsigned ArgNo,
2978                                                        llvm::Value *LocalAddr,
2979                                                        CGBuilderTy &Builder) {
2980   assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2981   ASTContext &C = CGM.getContext();
2982   const BlockDecl *blockDecl = block.getBlockDecl();
2983 
2984   // Collect some general information about the block's location.
2985   SourceLocation loc = blockDecl->getCaretLocation();
2986   llvm::DIFile *tunit = getOrCreateFile(loc);
2987   unsigned line = getLineNumber(loc);
2988   unsigned column = getColumnNumber(loc);
2989 
2990   // Build the debug-info type for the block literal.
2991   getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2992 
2993   const llvm::StructLayout *blockLayout =
2994       CGM.getDataLayout().getStructLayout(block.StructureType);
2995 
2996   SmallVector<llvm::Metadata *, 16> fields;
2997   fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2998                                    blockLayout->getElementOffsetInBits(0),
2999                                    tunit, tunit));
3000   fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
3001                                    blockLayout->getElementOffsetInBits(1),
3002                                    tunit, tunit));
3003   fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
3004                                    blockLayout->getElementOffsetInBits(2),
3005                                    tunit, tunit));
3006   auto *FnTy = block.getBlockExpr()->getFunctionType();
3007   auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
3008   fields.push_back(createFieldType("__FuncPtr", FnPtrType, 0, loc, AS_public,
3009                                    blockLayout->getElementOffsetInBits(3),
3010                                    tunit, tunit));
3011   fields.push_back(createFieldType(
3012       "__descriptor", C.getPointerType(block.NeedsCopyDispose
3013                                            ? C.getBlockDescriptorExtendedType()
3014                                            : C.getBlockDescriptorType()),
3015       0, loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit));
3016 
3017   // We want to sort the captures by offset, not because DWARF
3018   // requires this, but because we're paranoid about debuggers.
3019   SmallVector<BlockLayoutChunk, 8> chunks;
3020 
3021   // 'this' capture.
3022   if (blockDecl->capturesCXXThis()) {
3023     BlockLayoutChunk chunk;
3024     chunk.OffsetInBits =
3025         blockLayout->getElementOffsetInBits(block.CXXThisIndex);
3026     chunk.Capture = nullptr;
3027     chunks.push_back(chunk);
3028   }
3029 
3030   // Variable captures.
3031   for (const auto &capture : blockDecl->captures()) {
3032     const VarDecl *variable = capture.getVariable();
3033     const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3034 
3035     // Ignore constant captures.
3036     if (captureInfo.isConstant())
3037       continue;
3038 
3039     BlockLayoutChunk chunk;
3040     chunk.OffsetInBits =
3041         blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3042     chunk.Capture = &capture;
3043     chunks.push_back(chunk);
3044   }
3045 
3046   // Sort by offset.
3047   llvm::array_pod_sort(chunks.begin(), chunks.end());
3048 
3049   for (SmallVectorImpl<BlockLayoutChunk>::iterator i = chunks.begin(),
3050                                                    e = chunks.end();
3051        i != e; ++i) {
3052     uint64_t offsetInBits = i->OffsetInBits;
3053     const BlockDecl::Capture *capture = i->Capture;
3054 
3055     // If we have a null capture, this must be the C++ 'this' capture.
3056     if (!capture) {
3057       const CXXMethodDecl *method =
3058           cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3059       QualType type = method->getThisType(C);
3060 
3061       fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3062                                        offsetInBits, tunit, tunit));
3063       continue;
3064     }
3065 
3066     const VarDecl *variable = capture->getVariable();
3067     StringRef name = variable->getName();
3068 
3069     llvm::DIType *fieldType;
3070     if (capture->isByRef()) {
3071       TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
3072 
3073       // FIXME: this creates a second copy of this type!
3074       uint64_t xoffset;
3075       fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3076       fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
3077       fieldType =
3078           DBuilder.createMemberType(tunit, name, tunit, line, PtrInfo.Width,
3079                                     PtrInfo.Align, offsetInBits, 0, fieldType);
3080     } else {
3081       fieldType = createFieldType(name, variable->getType(), 0, loc, AS_public,
3082                                   offsetInBits, tunit, tunit);
3083     }
3084     fields.push_back(fieldType);
3085   }
3086 
3087   SmallString<36> typeName;
3088   llvm::raw_svector_ostream(typeName) << "__block_literal_"
3089                                       << CGM.getUniqueBlockCount();
3090 
3091   llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
3092 
3093   llvm::DIType *type = DBuilder.createStructType(
3094       tunit, typeName.str(), tunit, line,
3095       CGM.getContext().toBits(block.BlockSize),
3096       CGM.getContext().toBits(block.BlockAlign), 0, nullptr, fieldsArray);
3097   type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3098 
3099   // Get overall information about the block.
3100   unsigned flags = llvm::DINode::FlagArtificial;
3101   auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
3102 
3103   // Create the descriptor for the parameter.
3104   auto *debugVar = DBuilder.createParameterVariable(
3105       scope, Arg->getName(), ArgNo, tunit, line, type,
3106       CGM.getLangOpts().Optimize, flags);
3107 
3108   if (LocalAddr) {
3109     // Insert an llvm.dbg.value into the current block.
3110     DBuilder.insertDbgValueIntrinsic(
3111         LocalAddr, 0, debugVar, DBuilder.createExpression(),
3112         llvm::DebugLoc::get(line, column, scope), Builder.GetInsertBlock());
3113   }
3114 
3115   // Insert an llvm.dbg.declare into the current block.
3116   DBuilder.insertDeclare(Arg, debugVar, DBuilder.createExpression(),
3117                          llvm::DebugLoc::get(line, column, scope),
3118                          Builder.GetInsertBlock());
3119 }
3120 
3121 llvm::DIDerivedType *
3122 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3123   if (!D->isStaticDataMember())
3124     return nullptr;
3125 
3126   auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
3127   if (MI != StaticDataMemberCache.end()) {
3128     assert(MI->second && "Static data member declaration should still exist");
3129     return MI->second;
3130   }
3131 
3132   // If the member wasn't found in the cache, lazily construct and add it to the
3133   // type (used when a limited form of the type is emitted).
3134   auto DC = D->getDeclContext();
3135   auto *Ctxt =
3136       cast<llvm::DICompositeType>(getContextDescriptor(cast<Decl>(DC)));
3137   return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
3138 }
3139 
3140 llvm::DIGlobalVariable *CGDebugInfo::CollectAnonRecordDecls(
3141     const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
3142     StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
3143   llvm::DIGlobalVariable *GV = nullptr;
3144 
3145   for (const auto *Field : RD->fields()) {
3146     llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3147     StringRef FieldName = Field->getName();
3148 
3149     // Ignore unnamed fields, but recurse into anonymous records.
3150     if (FieldName.empty()) {
3151       const RecordType *RT = dyn_cast<RecordType>(Field->getType());
3152       if (RT)
3153         GV = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
3154                                     Var, DContext);
3155       continue;
3156     }
3157     // Use VarDecl's Tag, Scope and Line number.
3158     GV = DBuilder.createGlobalVariable(DContext, FieldName, LinkageName, Unit,
3159                                        LineNo, FieldTy,
3160                                        Var->hasInternalLinkage(), Var, nullptr);
3161   }
3162   return GV;
3163 }
3164 
3165 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3166                                      const VarDecl *D) {
3167   assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3168   // Create global variable debug descriptor.
3169   llvm::DIFile *Unit = nullptr;
3170   llvm::DIScope *DContext = nullptr;
3171   unsigned LineNo;
3172   StringRef DeclName, LinkageName;
3173   QualType T;
3174   collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, DContext);
3175 
3176   // Attempt to store one global variable for the declaration - even if we
3177   // emit a lot of fields.
3178   llvm::DIGlobalVariable *GV = nullptr;
3179 
3180   // If this is an anonymous union then we'll want to emit a global
3181   // variable for each member of the anonymous union so that it's possible
3182   // to find the name of any field in the union.
3183   if (T->isUnionType() && DeclName.empty()) {
3184     const RecordDecl *RD = cast<RecordType>(T)->getDecl();
3185     assert(RD->isAnonymousStructOrUnion() &&
3186            "unnamed non-anonymous struct or union?");
3187     GV = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
3188   } else {
3189     GV = DBuilder.createGlobalVariable(
3190         DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3191         Var->hasInternalLinkage(), Var,
3192         getOrCreateStaticDataMemberDeclarationOrNull(D));
3193   }
3194   DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(GV));
3195 }
3196 
3197 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3198                                      llvm::Constant *Init) {
3199   assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3200   // Create the descriptor for the variable.
3201   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3202   StringRef Name = VD->getName();
3203   llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
3204   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3205     const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3206     assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3207     Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3208   }
3209   // Do not use global variables for enums.
3210   //
3211   // FIXME: why not?
3212   if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3213     return;
3214   // Do not emit separate definitions for function local const/statics.
3215   if (isa<FunctionDecl>(VD->getDeclContext()))
3216     return;
3217   VD = cast<ValueDecl>(VD->getCanonicalDecl());
3218   auto *VarD = cast<VarDecl>(VD);
3219   if (VarD->isStaticDataMember()) {
3220     auto *RD = cast<RecordDecl>(VarD->getDeclContext());
3221     getContextDescriptor(RD);
3222     // Ensure that the type is retained even though it's otherwise unreferenced.
3223     RetainedTypes.push_back(
3224         CGM.getContext().getRecordType(RD).getAsOpaquePtr());
3225     return;
3226   }
3227 
3228   llvm::DIScope *DContext =
3229       getContextDescriptor(dyn_cast<Decl>(VD->getDeclContext()));
3230 
3231   auto &GV = DeclCache[VD];
3232   if (GV)
3233     return;
3234   GV.reset(DBuilder.createGlobalVariable(
3235       DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
3236       true, Init, getOrCreateStaticDataMemberDeclarationOrNull(VarD)));
3237 }
3238 
3239 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3240   if (!LexicalBlockStack.empty())
3241     return LexicalBlockStack.back();
3242   return getContextDescriptor(D);
3243 }
3244 
3245 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
3246   if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3247     return;
3248   DBuilder.createImportedModule(
3249       getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3250       getOrCreateNameSpace(UD.getNominatedNamespace()),
3251       getLineNumber(UD.getLocation()));
3252 }
3253 
3254 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3255   if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3256     return;
3257   assert(UD.shadow_size() &&
3258          "We shouldn't be codegening an invalid UsingDecl containing no decls");
3259   // Emitting one decl is sufficient - debuggers can detect that this is an
3260   // overloaded name & provide lookup for all the overloads.
3261   const UsingShadowDecl &USD = **UD.shadow_begin();
3262   if (llvm::DINode *Target =
3263           getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3264     DBuilder.createImportedDeclaration(
3265         getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3266         getLineNumber(USD.getLocation()));
3267 }
3268 
3269 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
3270   auto *Reader = CGM.getContext().getExternalSource();
3271   auto Info = Reader->getSourceDescriptor(*ID.getImportedModule());
3272   DBuilder.createImportedDeclaration(
3273     getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
3274                                 getOrCreateModuleRef(Info),
3275                                 getLineNumber(ID.getLocation()));
3276 }
3277 
3278 llvm::DIImportedEntity *
3279 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3280   if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3281     return nullptr;
3282   auto &VH = NamespaceAliasCache[&NA];
3283   if (VH)
3284     return cast<llvm::DIImportedEntity>(VH);
3285   llvm::DIImportedEntity *R;
3286   if (const NamespaceAliasDecl *Underlying =
3287           dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3288     // This could cache & dedup here rather than relying on metadata deduping.
3289     R = DBuilder.createImportedDeclaration(
3290         getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3291         EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3292         NA.getName());
3293   else
3294     R = DBuilder.createImportedDeclaration(
3295         getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3296         getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3297         getLineNumber(NA.getLocation()), NA.getName());
3298   VH.reset(R);
3299   return R;
3300 }
3301 
3302 llvm::DINamespace *
3303 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
3304   NSDecl = NSDecl->getCanonicalDecl();
3305   auto I = NameSpaceCache.find(NSDecl);
3306   if (I != NameSpaceCache.end())
3307     return cast<llvm::DINamespace>(I->second);
3308 
3309   unsigned LineNo = getLineNumber(NSDecl->getLocation());
3310   llvm::DIFile *FileD = getOrCreateFile(NSDecl->getLocation());
3311   llvm::DIScope *Context =
3312       getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3313   llvm::DINamespace *NS =
3314       DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3315   NameSpaceCache[NSDecl].reset(NS);
3316   return NS;
3317 }
3318 
3319 void CGDebugInfo::finalize() {
3320   // Creating types might create further types - invalidating the current
3321   // element and the size(), so don't cache/reference them.
3322   for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
3323     ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
3324     llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
3325                            ? CreateTypeDefinition(E.Type, E.Unit)
3326                            : E.Decl;
3327     DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
3328   }
3329 
3330   for (auto p : ReplaceMap) {
3331     assert(p.second);
3332     auto *Ty = cast<llvm::DIType>(p.second);
3333     assert(Ty->isForwardDecl());
3334 
3335     auto it = TypeCache.find(p.first);
3336     assert(it != TypeCache.end());
3337     assert(it->second);
3338 
3339     DBuilder.replaceTemporary(llvm::TempDIType(Ty),
3340                               cast<llvm::DIType>(it->second));
3341   }
3342 
3343   for (const auto &p : FwdDeclReplaceMap) {
3344     assert(p.second);
3345     llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(p.second));
3346     llvm::Metadata *Repl;
3347 
3348     auto it = DeclCache.find(p.first);
3349     // If there has been no definition for the declaration, call RAUW
3350     // with ourselves, that will destroy the temporary MDNode and
3351     // replace it with a standard one, avoiding leaking memory.
3352     if (it == DeclCache.end())
3353       Repl = p.second;
3354     else
3355       Repl = it->second;
3356 
3357     DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
3358   }
3359 
3360   // We keep our own list of retained types, because we need to look
3361   // up the final type in the type cache.
3362   for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3363          RE = RetainedTypes.end(); RI != RE; ++RI)
3364     DBuilder.retainType(cast<llvm::DIType>(TypeCache[*RI]));
3365 
3366   DBuilder.finalize();
3367 }
3368 
3369 void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
3370   if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3371     return;
3372 
3373   if (auto *DieTy = getOrCreateType(Ty, getOrCreateMainFile()))
3374     // Don't ignore in case of explicit cast where it is referenced indirectly.
3375     DBuilder.retainType(DieTy);
3376 }
3377