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