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