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