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