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