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