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