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