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 (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(), 1155 SE = FTD->spec_end(); 1156 SI != SE; ++SI) { 1157 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI = 1158 SPCache.find(cast<CXXMethodDecl>(*SI)->getCanonicalDecl()); 1159 if (MI != SPCache.end()) 1160 EltTys.push_back(MI->second); 1161 } 1162 } 1163 } 1164 } 1165 1166 /// CollectCXXBases - A helper function to collect debug info for 1167 /// C++ base classes. This is used while creating debug info entry for 1168 /// a Record. 1169 void CGDebugInfo:: 1170 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit, 1171 SmallVectorImpl<llvm::Value *> &EltTys, 1172 llvm::DIType RecordTy) { 1173 1174 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 1175 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(), 1176 BE = RD->bases_end(); BI != BE; ++BI) { 1177 unsigned BFlags = 0; 1178 uint64_t BaseOffset; 1179 1180 const CXXRecordDecl *Base = 1181 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl()); 1182 1183 if (BI->isVirtual()) { 1184 // virtual base offset offset is -ve. The code generator emits dwarf 1185 // expression where it expects +ve number. 1186 BaseOffset = 1187 0 - CGM.getItaniumVTableContext() 1188 .getVirtualBaseOffsetOffset(RD, Base).getQuantity(); 1189 BFlags = llvm::DIDescriptor::FlagVirtual; 1190 } else 1191 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base)); 1192 // FIXME: Inconsistent units for BaseOffset. It is in bytes when 1193 // BI->isVirtual() and bits when not. 1194 1195 AccessSpecifier Access = BI->getAccessSpecifier(); 1196 if (Access == clang::AS_private) 1197 BFlags |= llvm::DIDescriptor::FlagPrivate; 1198 else if (Access == clang::AS_protected) 1199 BFlags |= llvm::DIDescriptor::FlagProtected; 1200 1201 llvm::DIType DTy = 1202 DBuilder.createInheritance(RecordTy, 1203 getOrCreateType(BI->getType(), Unit), 1204 BaseOffset, BFlags); 1205 EltTys.push_back(DTy); 1206 } 1207 } 1208 1209 /// CollectTemplateParams - A helper function to collect template parameters. 1210 llvm::DIArray CGDebugInfo:: 1211 CollectTemplateParams(const TemplateParameterList *TPList, 1212 ArrayRef<TemplateArgument> TAList, 1213 llvm::DIFile Unit) { 1214 SmallVector<llvm::Value *, 16> TemplateParams; 1215 for (unsigned i = 0, e = TAList.size(); i != e; ++i) { 1216 const TemplateArgument &TA = TAList[i]; 1217 StringRef Name; 1218 if (TPList) 1219 Name = TPList->getParam(i)->getName(); 1220 switch (TA.getKind()) { 1221 case TemplateArgument::Type: { 1222 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit); 1223 llvm::DITemplateTypeParameter TTP = 1224 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy); 1225 TemplateParams.push_back(TTP); 1226 } break; 1227 case TemplateArgument::Integral: { 1228 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit); 1229 llvm::DITemplateValueParameter TVP = 1230 DBuilder.createTemplateValueParameter( 1231 TheCU, Name, TTy, 1232 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())); 1233 TemplateParams.push_back(TVP); 1234 } break; 1235 case TemplateArgument::Declaration: { 1236 const ValueDecl *D = TA.getAsDecl(); 1237 bool InstanceMember = D->isCXXInstanceMember(); 1238 QualType T = InstanceMember 1239 ? CGM.getContext().getMemberPointerType( 1240 D->getType(), cast<RecordDecl>(D->getDeclContext()) 1241 ->getTypeForDecl()) 1242 : CGM.getContext().getPointerType(D->getType()); 1243 llvm::DIType TTy = getOrCreateType(T, Unit); 1244 llvm::Value *V = 0; 1245 // Variable pointer template parameters have a value that is the address 1246 // of the variable. 1247 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1248 V = CGM.GetAddrOfGlobalVar(VD); 1249 // Member function pointers have special support for building them, though 1250 // this is currently unsupported in LLVM CodeGen. 1251 if (InstanceMember) { 1252 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D)) 1253 V = CGM.getCXXABI().EmitMemberPointer(method); 1254 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 1255 V = CGM.GetAddrOfFunction(FD); 1256 // Member data pointers have special handling too to compute the fixed 1257 // offset within the object. 1258 if (isa<FieldDecl>(D)) { 1259 // These five lines (& possibly the above member function pointer 1260 // handling) might be able to be refactored to use similar code in 1261 // CodeGenModule::getMemberPointerConstant 1262 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D); 1263 CharUnits chars = 1264 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset); 1265 V = CGM.getCXXABI().EmitMemberDataPointer( 1266 cast<MemberPointerType>(T.getTypePtr()), chars); 1267 } 1268 llvm::DITemplateValueParameter TVP = 1269 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, 1270 V->stripPointerCasts()); 1271 TemplateParams.push_back(TVP); 1272 } break; 1273 case TemplateArgument::NullPtr: { 1274 QualType T = TA.getNullPtrType(); 1275 llvm::DIType TTy = getOrCreateType(T, Unit); 1276 llvm::Value *V = 0; 1277 // Special case member data pointer null values since they're actually -1 1278 // instead of zero. 1279 if (const MemberPointerType *MPT = 1280 dyn_cast<MemberPointerType>(T.getTypePtr())) 1281 // But treat member function pointers as simple zero integers because 1282 // it's easier than having a special case in LLVM's CodeGen. If LLVM 1283 // CodeGen grows handling for values of non-null member function 1284 // pointers then perhaps we could remove this special case and rely on 1285 // EmitNullMemberPointer for member function pointers. 1286 if (MPT->isMemberDataPointer()) 1287 V = CGM.getCXXABI().EmitNullMemberPointer(MPT); 1288 if (!V) 1289 V = llvm::ConstantInt::get(CGM.Int8Ty, 0); 1290 llvm::DITemplateValueParameter TVP = 1291 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V); 1292 TemplateParams.push_back(TVP); 1293 } break; 1294 case TemplateArgument::Template: { 1295 llvm::DITemplateValueParameter TVP = 1296 DBuilder.createTemplateTemplateParameter( 1297 TheCU, Name, llvm::DIType(), 1298 TA.getAsTemplate().getAsTemplateDecl() 1299 ->getQualifiedNameAsString()); 1300 TemplateParams.push_back(TVP); 1301 } break; 1302 case TemplateArgument::Pack: { 1303 llvm::DITemplateValueParameter TVP = 1304 DBuilder.createTemplateParameterPack( 1305 TheCU, Name, llvm::DIType(), 1306 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit)); 1307 TemplateParams.push_back(TVP); 1308 } break; 1309 case TemplateArgument::Expression: { 1310 const Expr *E = TA.getAsExpr(); 1311 QualType T = E->getType(); 1312 llvm::Value *V = CGM.EmitConstantExpr(E, T); 1313 assert(V && "Expression in template argument isn't constant"); 1314 llvm::DIType TTy = getOrCreateType(T, Unit); 1315 llvm::DITemplateValueParameter TVP = 1316 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, 1317 V->stripPointerCasts()); 1318 TemplateParams.push_back(TVP); 1319 } break; 1320 // And the following should never occur: 1321 case TemplateArgument::TemplateExpansion: 1322 case TemplateArgument::Null: 1323 llvm_unreachable( 1324 "These argument types shouldn't exist in concrete types"); 1325 } 1326 } 1327 return DBuilder.getOrCreateArray(TemplateParams); 1328 } 1329 1330 /// CollectFunctionTemplateParams - A helper function to collect debug 1331 /// info for function template parameters. 1332 llvm::DIArray CGDebugInfo:: 1333 CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) { 1334 if (FD->getTemplatedKind() == 1335 FunctionDecl::TK_FunctionTemplateSpecialization) { 1336 const TemplateParameterList *TList = 1337 FD->getTemplateSpecializationInfo()->getTemplate() 1338 ->getTemplateParameters(); 1339 return CollectTemplateParams( 1340 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit); 1341 } 1342 return llvm::DIArray(); 1343 } 1344 1345 /// CollectCXXTemplateParams - A helper function to collect debug info for 1346 /// template parameters. 1347 llvm::DIArray CGDebugInfo:: 1348 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial, 1349 llvm::DIFile Unit) { 1350 llvm::PointerUnion<ClassTemplateDecl *, 1351 ClassTemplatePartialSpecializationDecl *> 1352 PU = TSpecial->getSpecializedTemplateOrPartial(); 1353 1354 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ? 1355 PU.get<ClassTemplateDecl *>()->getTemplateParameters() : 1356 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters(); 1357 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs(); 1358 return CollectTemplateParams(TPList, TAList.asArray(), Unit); 1359 } 1360 1361 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable. 1362 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) { 1363 if (VTablePtrType.isValid()) 1364 return VTablePtrType; 1365 1366 ASTContext &Context = CGM.getContext(); 1367 1368 /* Function type */ 1369 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit); 1370 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy); 1371 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements); 1372 unsigned Size = Context.getTypeSize(Context.VoidPtrTy); 1373 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0, 1374 "__vtbl_ptr_type"); 1375 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size); 1376 return VTablePtrType; 1377 } 1378 1379 /// getVTableName - Get vtable name for the given Class. 1380 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) { 1381 // Copy the gdb compatible name on the side and use its reference. 1382 return internString("_vptr$", RD->getNameAsString()); 1383 } 1384 1385 1386 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate 1387 /// debug info entry in EltTys vector. 1388 void CGDebugInfo:: 1389 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit, 1390 SmallVectorImpl<llvm::Value *> &EltTys) { 1391 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 1392 1393 // If there is a primary base then it will hold vtable info. 1394 if (RL.getPrimaryBase()) 1395 return; 1396 1397 // If this class is not dynamic then there is not any vtable info to collect. 1398 if (!RD->isDynamicClass()) 1399 return; 1400 1401 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 1402 llvm::DIType VPTR 1403 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 1404 0, Size, 0, 0, 1405 llvm::DIDescriptor::FlagArtificial, 1406 getOrCreateVTablePtrType(Unit)); 1407 EltTys.push_back(VPTR); 1408 } 1409 1410 /// getOrCreateRecordType - Emit record type's standalone debug info. 1411 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy, 1412 SourceLocation Loc) { 1413 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 1414 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc)); 1415 return T; 1416 } 1417 1418 /// getOrCreateInterfaceType - Emit an objective c interface type standalone 1419 /// debug info. 1420 llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D, 1421 SourceLocation Loc) { 1422 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 1423 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc)); 1424 RetainedTypes.push_back(D.getAsOpaquePtr()); 1425 return T; 1426 } 1427 1428 void CGDebugInfo::completeType(const RecordDecl *RD) { 1429 if (DebugKind > CodeGenOptions::LimitedDebugInfo || 1430 !CGM.getLangOpts().CPlusPlus) 1431 completeRequiredType(RD); 1432 } 1433 1434 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) { 1435 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 1436 return; 1437 1438 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) 1439 if (CXXDecl->isDynamicClass()) 1440 return; 1441 1442 QualType Ty = CGM.getContext().getRecordType(RD); 1443 llvm::DIType T = getTypeOrNull(Ty); 1444 if (T && T.isForwardDecl()) 1445 completeClassData(RD); 1446 } 1447 1448 void CGDebugInfo::completeClassData(const RecordDecl *RD) { 1449 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 1450 return; 1451 QualType Ty = CGM.getContext().getRecordType(RD); 1452 void* TyPtr = Ty.getAsOpaquePtr(); 1453 if (CompletedTypeCache.count(TyPtr)) 1454 return; 1455 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>()); 1456 assert(!Res.isForwardDecl()); 1457 CompletedTypeCache[TyPtr] = Res; 1458 TypeCache[TyPtr] = Res; 1459 } 1460 1461 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I, 1462 CXXRecordDecl::method_iterator End) { 1463 for (; I != End; ++I) 1464 if (FunctionDecl *Tmpl = I->getInstantiatedFromMemberFunction()) 1465 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() && 1466 !I->getMemberSpecializationInfo()->isExplicitSpecialization()) 1467 return true; 1468 return false; 1469 } 1470 1471 static bool shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind, 1472 const RecordDecl *RD, 1473 const LangOptions &LangOpts) { 1474 if (DebugKind > CodeGenOptions::LimitedDebugInfo) 1475 return false; 1476 1477 if (!LangOpts.CPlusPlus) 1478 return false; 1479 1480 if (!RD->isCompleteDefinitionRequired()) 1481 return true; 1482 1483 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 1484 1485 if (!CXXDecl) 1486 return false; 1487 1488 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass()) 1489 return true; 1490 1491 TemplateSpecializationKind Spec = TSK_Undeclared; 1492 if (const ClassTemplateSpecializationDecl *SD = 1493 dyn_cast<ClassTemplateSpecializationDecl>(RD)) 1494 Spec = SD->getSpecializationKind(); 1495 1496 if (Spec == TSK_ExplicitInstantiationDeclaration && 1497 hasExplicitMemberDefinition(CXXDecl->method_begin(), 1498 CXXDecl->method_end())) 1499 return true; 1500 1501 return false; 1502 } 1503 1504 /// CreateType - get structure or union type. 1505 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) { 1506 RecordDecl *RD = Ty->getDecl(); 1507 llvm::DICompositeType T(getTypeOrNull(QualType(Ty, 0))); 1508 if (T || shouldOmitDefinition(DebugKind, RD, CGM.getLangOpts())) { 1509 if (!T) 1510 T = getOrCreateRecordFwdDecl( 1511 Ty, getContextDescriptor(cast<Decl>(RD->getDeclContext()))); 1512 return T; 1513 } 1514 1515 return CreateTypeDefinition(Ty); 1516 } 1517 1518 llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) { 1519 RecordDecl *RD = Ty->getDecl(); 1520 1521 // Get overall information about the record type for the debug info. 1522 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 1523 1524 // Records and classes and unions can all be recursive. To handle them, we 1525 // first generate a debug descriptor for the struct as a forward declaration. 1526 // Then (if it is a definition) we go through and get debug info for all of 1527 // its members. Finally, we create a descriptor for the complete type (which 1528 // may refer to the forward decl if the struct is recursive) and replace all 1529 // uses of the forward declaration with the final definition. 1530 1531 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit)); 1532 assert(FwdDecl.isCompositeType() && 1533 "The debug type of a RecordType should be a llvm::DICompositeType"); 1534 1535 if (FwdDecl.isForwardDecl()) 1536 return FwdDecl; 1537 1538 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) 1539 CollectContainingType(CXXDecl, FwdDecl); 1540 1541 // Push the struct on region stack. 1542 LexicalBlockStack.push_back(&*FwdDecl); 1543 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl); 1544 1545 // Add this to the completed-type cache while we're completing it recursively. 1546 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl; 1547 1548 // Convert all the elements. 1549 SmallVector<llvm::Value *, 16> EltTys; 1550 // what about nested types? 1551 1552 // Note: The split of CXXDecl information here is intentional, the 1553 // gdb tests will depend on a certain ordering at printout. The debug 1554 // information offsets are still correct if we merge them all together 1555 // though. 1556 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 1557 if (CXXDecl) { 1558 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl); 1559 CollectVTableInfo(CXXDecl, DefUnit, EltTys); 1560 } 1561 1562 // Collect data fields (including static variables and any initializers). 1563 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl); 1564 if (CXXDecl) 1565 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl); 1566 1567 LexicalBlockStack.pop_back(); 1568 RegionMap.erase(Ty->getDecl()); 1569 1570 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys); 1571 FwdDecl.setTypeArray(Elements); 1572 1573 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl); 1574 return FwdDecl; 1575 } 1576 1577 /// CreateType - get objective-c object type. 1578 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty, 1579 llvm::DIFile Unit) { 1580 // Ignore protocols. 1581 return getOrCreateType(Ty->getBaseType(), Unit); 1582 } 1583 1584 1585 /// \return true if Getter has the default name for the property PD. 1586 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD, 1587 const ObjCMethodDecl *Getter) { 1588 assert(PD); 1589 if (!Getter) 1590 return true; 1591 1592 assert(Getter->getDeclName().isObjCZeroArgSelector()); 1593 return PD->getName() == 1594 Getter->getDeclName().getObjCSelector().getNameForSlot(0); 1595 } 1596 1597 /// \return true if Setter has the default name for the property PD. 1598 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD, 1599 const ObjCMethodDecl *Setter) { 1600 assert(PD); 1601 if (!Setter) 1602 return true; 1603 1604 assert(Setter->getDeclName().isObjCOneArgSelector()); 1605 return SelectorTable::constructSetterName(PD->getName()) == 1606 Setter->getDeclName().getObjCSelector().getNameForSlot(0); 1607 } 1608 1609 /// CreateType - get objective-c interface type. 1610 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, 1611 llvm::DIFile Unit) { 1612 ObjCInterfaceDecl *ID = Ty->getDecl(); 1613 if (!ID) 1614 return llvm::DIType(); 1615 1616 // Get overall information about the record type for the debug info. 1617 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation()); 1618 unsigned Line = getLineNumber(ID->getLocation()); 1619 unsigned RuntimeLang = TheCU.getLanguage(); 1620 1621 // If this is just a forward declaration return a special forward-declaration 1622 // debug type since we won't be able to lay out the entire type. 1623 ObjCInterfaceDecl *Def = ID->getDefinition(); 1624 if (!Def) { 1625 llvm::DIType FwdDecl = 1626 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 1627 ID->getName(), TheCU, DefUnit, Line, 1628 RuntimeLang); 1629 return FwdDecl; 1630 } 1631 1632 ID = Def; 1633 1634 // Bit size, align and offset of the type. 1635 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1636 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1637 1638 unsigned Flags = 0; 1639 if (ID->getImplementation()) 1640 Flags |= llvm::DIDescriptor::FlagObjcClassComplete; 1641 1642 llvm::DICompositeType RealDecl = 1643 DBuilder.createStructType(Unit, ID->getName(), DefUnit, 1644 Line, Size, Align, Flags, 1645 llvm::DIType(), llvm::DIArray(), RuntimeLang); 1646 1647 // Otherwise, insert it into the CompletedTypeCache so that recursive uses 1648 // will find it and we're emitting the complete type. 1649 QualType QualTy = QualType(Ty, 0); 1650 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl; 1651 1652 // Push the struct on region stack. 1653 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl)); 1654 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl); 1655 1656 // Convert all the elements. 1657 SmallVector<llvm::Value *, 16> EltTys; 1658 1659 ObjCInterfaceDecl *SClass = ID->getSuperClass(); 1660 if (SClass) { 1661 llvm::DIType SClassTy = 1662 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit); 1663 if (!SClassTy.isValid()) 1664 return llvm::DIType(); 1665 1666 llvm::DIType InhTag = 1667 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0); 1668 EltTys.push_back(InhTag); 1669 } 1670 1671 // Create entries for all of the properties. 1672 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(), 1673 E = ID->prop_end(); I != E; ++I) { 1674 const ObjCPropertyDecl *PD = *I; 1675 SourceLocation Loc = PD->getLocation(); 1676 llvm::DIFile PUnit = getOrCreateFile(Loc); 1677 unsigned PLine = getLineNumber(Loc); 1678 ObjCMethodDecl *Getter = PD->getGetterMethodDecl(); 1679 ObjCMethodDecl *Setter = PD->getSetterMethodDecl(); 1680 llvm::MDNode *PropertyNode = 1681 DBuilder.createObjCProperty(PD->getName(), 1682 PUnit, PLine, 1683 hasDefaultGetterName(PD, Getter) ? "" : 1684 getSelectorName(PD->getGetterName()), 1685 hasDefaultSetterName(PD, Setter) ? "" : 1686 getSelectorName(PD->getSetterName()), 1687 PD->getPropertyAttributes(), 1688 getOrCreateType(PD->getType(), PUnit)); 1689 EltTys.push_back(PropertyNode); 1690 } 1691 1692 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID); 1693 unsigned FieldNo = 0; 1694 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field; 1695 Field = Field->getNextIvar(), ++FieldNo) { 1696 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 1697 if (!FieldTy.isValid()) 1698 return llvm::DIType(); 1699 1700 StringRef FieldName = Field->getName(); 1701 1702 // Ignore unnamed fields. 1703 if (FieldName.empty()) 1704 continue; 1705 1706 // Get the location for the field. 1707 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation()); 1708 unsigned FieldLine = getLineNumber(Field->getLocation()); 1709 QualType FType = Field->getType(); 1710 uint64_t FieldSize = 0; 1711 unsigned FieldAlign = 0; 1712 1713 if (!FType->isIncompleteArrayType()) { 1714 1715 // Bit size, align and offset of the type. 1716 FieldSize = Field->isBitField() 1717 ? Field->getBitWidthValue(CGM.getContext()) 1718 : CGM.getContext().getTypeSize(FType); 1719 FieldAlign = CGM.getContext().getTypeAlign(FType); 1720 } 1721 1722 uint64_t FieldOffset; 1723 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { 1724 // We don't know the runtime offset of an ivar if we're using the 1725 // non-fragile ABI. For bitfields, use the bit offset into the first 1726 // byte of storage of the bitfield. For other fields, use zero. 1727 if (Field->isBitField()) { 1728 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset( 1729 CGM, ID, Field); 1730 FieldOffset %= CGM.getContext().getCharWidth(); 1731 } else { 1732 FieldOffset = 0; 1733 } 1734 } else { 1735 FieldOffset = RL.getFieldOffset(FieldNo); 1736 } 1737 1738 unsigned Flags = 0; 1739 if (Field->getAccessControl() == ObjCIvarDecl::Protected) 1740 Flags = llvm::DIDescriptor::FlagProtected; 1741 else if (Field->getAccessControl() == ObjCIvarDecl::Private) 1742 Flags = llvm::DIDescriptor::FlagPrivate; 1743 1744 llvm::MDNode *PropertyNode = NULL; 1745 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) { 1746 if (ObjCPropertyImplDecl *PImpD = 1747 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) { 1748 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) { 1749 SourceLocation Loc = PD->getLocation(); 1750 llvm::DIFile PUnit = getOrCreateFile(Loc); 1751 unsigned PLine = getLineNumber(Loc); 1752 ObjCMethodDecl *Getter = PD->getGetterMethodDecl(); 1753 ObjCMethodDecl *Setter = PD->getSetterMethodDecl(); 1754 PropertyNode = 1755 DBuilder.createObjCProperty(PD->getName(), 1756 PUnit, PLine, 1757 hasDefaultGetterName(PD, Getter) ? "" : 1758 getSelectorName(PD->getGetterName()), 1759 hasDefaultSetterName(PD, Setter) ? "" : 1760 getSelectorName(PD->getSetterName()), 1761 PD->getPropertyAttributes(), 1762 getOrCreateType(PD->getType(), PUnit)); 1763 } 1764 } 1765 } 1766 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, 1767 FieldLine, FieldSize, FieldAlign, 1768 FieldOffset, Flags, FieldTy, 1769 PropertyNode); 1770 EltTys.push_back(FieldTy); 1771 } 1772 1773 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys); 1774 RealDecl.setTypeArray(Elements); 1775 1776 // If the implementation is not yet set, we do not want to mark it 1777 // as complete. An implementation may declare additional 1778 // private ivars that we would miss otherwise. 1779 if (ID->getImplementation() == 0) 1780 CompletedTypeCache.erase(QualTy.getAsOpaquePtr()); 1781 1782 LexicalBlockStack.pop_back(); 1783 return RealDecl; 1784 } 1785 1786 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) { 1787 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit); 1788 int64_t Count = Ty->getNumElements(); 1789 if (Count == 0) 1790 // If number of elements are not known then this is an unbounded array. 1791 // Use Count == -1 to express such arrays. 1792 Count = -1; 1793 1794 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count); 1795 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript); 1796 1797 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1798 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1799 1800 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray); 1801 } 1802 1803 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty, 1804 llvm::DIFile Unit) { 1805 uint64_t Size; 1806 uint64_t Align; 1807 1808 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types 1809 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) { 1810 Size = 0; 1811 Align = 1812 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT)); 1813 } else if (Ty->isIncompleteArrayType()) { 1814 Size = 0; 1815 if (Ty->getElementType()->isIncompleteType()) 1816 Align = 0; 1817 else 1818 Align = CGM.getContext().getTypeAlign(Ty->getElementType()); 1819 } else if (Ty->isIncompleteType()) { 1820 Size = 0; 1821 Align = 0; 1822 } else { 1823 // Size and align of the whole array, not the element type. 1824 Size = CGM.getContext().getTypeSize(Ty); 1825 Align = CGM.getContext().getTypeAlign(Ty); 1826 } 1827 1828 // Add the dimensions of the array. FIXME: This loses CV qualifiers from 1829 // interior arrays, do we care? Why aren't nested arrays represented the 1830 // obvious/recursive way? 1831 SmallVector<llvm::Value *, 8> Subscripts; 1832 QualType EltTy(Ty, 0); 1833 while ((Ty = dyn_cast<ArrayType>(EltTy))) { 1834 // If the number of elements is known, then count is that number. Otherwise, 1835 // it's -1. This allows us to represent a subrange with an array of 0 1836 // elements, like this: 1837 // 1838 // struct foo { 1839 // int x[0]; 1840 // }; 1841 int64_t Count = -1; // Count == -1 is an unbounded array. 1842 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) 1843 Count = CAT->getSize().getZExtValue(); 1844 1845 // FIXME: Verify this is right for VLAs. 1846 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count)); 1847 EltTy = Ty->getElementType(); 1848 } 1849 1850 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts); 1851 1852 llvm::DIType DbgTy = 1853 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit), 1854 SubscriptArray); 1855 return DbgTy; 1856 } 1857 1858 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty, 1859 llvm::DIFile Unit) { 1860 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, 1861 Ty, Ty->getPointeeType(), Unit); 1862 } 1863 1864 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty, 1865 llvm::DIFile Unit) { 1866 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, 1867 Ty, Ty->getPointeeType(), Unit); 1868 } 1869 1870 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty, 1871 llvm::DIFile U) { 1872 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U); 1873 if (!Ty->getPointeeType()->isFunctionType()) 1874 return DBuilder.createMemberPointerType( 1875 getOrCreateType(Ty->getPointeeType(), U), ClassType); 1876 1877 const FunctionProtoType *FPT = 1878 Ty->getPointeeType()->getAs<FunctionProtoType>(); 1879 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType( 1880 CGM.getContext().getPointerType(QualType(Ty->getClass(), 1881 FPT->getTypeQuals())), 1882 FPT, U), ClassType); 1883 } 1884 1885 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty, 1886 llvm::DIFile U) { 1887 // Ignore the atomic wrapping 1888 // FIXME: What is the correct representation? 1889 return getOrCreateType(Ty->getValueType(), U); 1890 } 1891 1892 /// CreateEnumType - get enumeration type. 1893 llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) { 1894 const EnumDecl *ED = Ty->getDecl(); 1895 uint64_t Size = 0; 1896 uint64_t Align = 0; 1897 if (!ED->getTypeForDecl()->isIncompleteType()) { 1898 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); 1899 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl()); 1900 } 1901 1902 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU); 1903 1904 // If this is just a forward declaration, construct an appropriately 1905 // marked node and just return it. 1906 if (!ED->getDefinition()) { 1907 llvm::DIDescriptor EDContext; 1908 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext())); 1909 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation()); 1910 unsigned Line = getLineNumber(ED->getLocation()); 1911 StringRef EDName = ED->getName(); 1912 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type, 1913 EDName, EDContext, DefUnit, Line, 0, 1914 Size, Align, FullName); 1915 } 1916 1917 // Create DIEnumerator elements for each enumerator. 1918 SmallVector<llvm::Value *, 16> Enumerators; 1919 ED = ED->getDefinition(); 1920 for (EnumDecl::enumerator_iterator 1921 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end(); 1922 Enum != EnumEnd; ++Enum) { 1923 Enumerators.push_back( 1924 DBuilder.createEnumerator(Enum->getName(), 1925 Enum->getInitVal().getSExtValue())); 1926 } 1927 1928 // Return a CompositeType for the enum itself. 1929 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators); 1930 1931 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation()); 1932 unsigned Line = getLineNumber(ED->getLocation()); 1933 llvm::DIDescriptor EnumContext = 1934 getContextDescriptor(cast<Decl>(ED->getDeclContext())); 1935 llvm::DIType ClassTy = ED->isFixed() ? 1936 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType(); 1937 llvm::DIType DbgTy = 1938 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line, 1939 Size, Align, EltArray, 1940 ClassTy, FullName); 1941 return DbgTy; 1942 } 1943 1944 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) { 1945 Qualifiers Quals; 1946 do { 1947 Qualifiers InnerQuals = T.getLocalQualifiers(); 1948 // Qualifiers::operator+() doesn't like it if you add a Qualifier 1949 // that is already there. 1950 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals); 1951 Quals += InnerQuals; 1952 QualType LastT = T; 1953 switch (T->getTypeClass()) { 1954 default: 1955 return C.getQualifiedType(T.getTypePtr(), Quals); 1956 case Type::TemplateSpecialization: 1957 T = cast<TemplateSpecializationType>(T)->desugar(); 1958 break; 1959 case Type::TypeOfExpr: 1960 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType(); 1961 break; 1962 case Type::TypeOf: 1963 T = cast<TypeOfType>(T)->getUnderlyingType(); 1964 break; 1965 case Type::Decltype: 1966 T = cast<DecltypeType>(T)->getUnderlyingType(); 1967 break; 1968 case Type::UnaryTransform: 1969 T = cast<UnaryTransformType>(T)->getUnderlyingType(); 1970 break; 1971 case Type::Attributed: 1972 T = cast<AttributedType>(T)->getEquivalentType(); 1973 break; 1974 case Type::Elaborated: 1975 T = cast<ElaboratedType>(T)->getNamedType(); 1976 break; 1977 case Type::Paren: 1978 T = cast<ParenType>(T)->getInnerType(); 1979 break; 1980 case Type::SubstTemplateTypeParm: 1981 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType(); 1982 break; 1983 case Type::Auto: 1984 QualType DT = cast<AutoType>(T)->getDeducedType(); 1985 if (DT.isNull()) 1986 return T; 1987 T = DT; 1988 break; 1989 } 1990 1991 assert(T != LastT && "Type unwrapping failed to unwrap!"); 1992 (void)LastT; 1993 } while (true); 1994 } 1995 1996 /// getType - Get the type from the cache or return null type if it doesn't 1997 /// exist. 1998 llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) { 1999 2000 // Unwrap the type as needed for debug information. 2001 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 2002 2003 // Check for existing entry. 2004 if (Ty->getTypeClass() == Type::ObjCInterface) { 2005 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty); 2006 if (V) 2007 return llvm::DIType(cast<llvm::MDNode>(V)); 2008 else return llvm::DIType(); 2009 } 2010 2011 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 2012 TypeCache.find(Ty.getAsOpaquePtr()); 2013 if (it != TypeCache.end()) { 2014 // Verify that the debug info still exists. 2015 if (llvm::Value *V = it->second) 2016 return llvm::DIType(cast<llvm::MDNode>(V)); 2017 } 2018 2019 return llvm::DIType(); 2020 } 2021 2022 /// getCompletedTypeOrNull - Get the type from the cache or return null if it 2023 /// doesn't exist. 2024 llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) { 2025 2026 // Unwrap the type as needed for debug information. 2027 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 2028 2029 // Check for existing entry. 2030 llvm::Value *V = 0; 2031 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 2032 CompletedTypeCache.find(Ty.getAsOpaquePtr()); 2033 if (it != CompletedTypeCache.end()) 2034 V = it->second; 2035 else { 2036 V = getCachedInterfaceTypeOrNull(Ty); 2037 } 2038 2039 // Verify that any cached debug info still exists. 2040 return llvm::DIType(cast_or_null<llvm::MDNode>(V)); 2041 } 2042 2043 void CGDebugInfo::completeTemplateDefinition( 2044 const ClassTemplateSpecializationDecl &SD) { 2045 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 2046 return; 2047 2048 completeClassData(&SD); 2049 // In case this type has no member function definitions being emitted, ensure 2050 // it is retained 2051 RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr()); 2052 } 2053 2054 /// getCachedInterfaceTypeOrNull - Get the type from the interface 2055 /// cache, unless it needs to regenerated. Otherwise return null. 2056 llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) { 2057 // Is there a cached interface that hasn't changed? 2058 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > > 2059 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr()); 2060 2061 if (it1 != ObjCInterfaceCache.end()) 2062 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) 2063 if (Checksum(Decl) == it1->second.second) 2064 // Return cached forward declaration. 2065 return it1->second.first; 2066 2067 return 0; 2068 } 2069 2070 /// getOrCreateType - Get the type from the cache or create a new 2071 /// one if necessary. 2072 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) { 2073 if (Ty.isNull()) 2074 return llvm::DIType(); 2075 2076 // Unwrap the type as needed for debug information. 2077 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 2078 2079 if (llvm::DIType T = getCompletedTypeOrNull(Ty)) 2080 return T; 2081 2082 // Otherwise create the type. 2083 llvm::DIType Res = CreateTypeNode(Ty, Unit); 2084 void* TyPtr = Ty.getAsOpaquePtr(); 2085 2086 // And update the type cache. 2087 TypeCache[TyPtr] = Res; 2088 2089 // FIXME: this getTypeOrNull call seems silly when we just inserted the type 2090 // into the cache - but getTypeOrNull has a special case for cached interface 2091 // types. We should probably just pull that out as a special case for the 2092 // "else" block below & skip the otherwise needless lookup. 2093 llvm::DIType TC = getTypeOrNull(Ty); 2094 if (TC && TC.isForwardDecl()) 2095 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC))); 2096 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) { 2097 // Interface types may have elements added to them by a 2098 // subsequent implementation or extension, so we keep them in 2099 // the ObjCInterfaceCache together with a checksum. Instead of 2100 // the (possibly) incomplete interface type, we return a forward 2101 // declaration that gets RAUW'd in CGDebugInfo::finalize(). 2102 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr]; 2103 if (V.first) 2104 return llvm::DIType(cast<llvm::MDNode>(V.first)); 2105 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 2106 Decl->getName(), TheCU, Unit, 2107 getLineNumber(Decl->getLocation()), 2108 TheCU.getLanguage()); 2109 // Store the forward declaration in the cache. 2110 V.first = TC; 2111 V.second = Checksum(Decl); 2112 2113 // Register the type for replacement in finalize(). 2114 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC))); 2115 2116 return TC; 2117 } 2118 2119 if (!Res.isForwardDecl()) 2120 CompletedTypeCache[TyPtr] = Res; 2121 2122 return Res; 2123 } 2124 2125 /// Currently the checksum of an interface includes the number of 2126 /// ivars and property accessors. 2127 unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) { 2128 // The assumption is that the number of ivars can only increase 2129 // monotonically, so it is safe to just use their current number as 2130 // a checksum. 2131 unsigned Sum = 0; 2132 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin(); 2133 Ivar != 0; Ivar = Ivar->getNextIvar()) 2134 ++Sum; 2135 2136 return Sum; 2137 } 2138 2139 ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) { 2140 switch (Ty->getTypeClass()) { 2141 case Type::ObjCObjectPointer: 2142 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty) 2143 ->getPointeeType()); 2144 case Type::ObjCInterface: 2145 return cast<ObjCInterfaceType>(Ty)->getDecl(); 2146 default: 2147 return 0; 2148 } 2149 } 2150 2151 /// CreateTypeNode - Create a new debug type node. 2152 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) { 2153 // Handle qualifiers, which recursively handles what they refer to. 2154 if (Ty.hasLocalQualifiers()) 2155 return CreateQualifiedType(Ty, Unit); 2156 2157 const char *Diag = 0; 2158 2159 // Work out details of type. 2160 switch (Ty->getTypeClass()) { 2161 #define TYPE(Class, Base) 2162 #define ABSTRACT_TYPE(Class, Base) 2163 #define NON_CANONICAL_TYPE(Class, Base) 2164 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 2165 #include "clang/AST/TypeNodes.def" 2166 llvm_unreachable("Dependent types cannot show up in debug information"); 2167 2168 case Type::ExtVector: 2169 case Type::Vector: 2170 return CreateType(cast<VectorType>(Ty), Unit); 2171 case Type::ObjCObjectPointer: 2172 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit); 2173 case Type::ObjCObject: 2174 return CreateType(cast<ObjCObjectType>(Ty), Unit); 2175 case Type::ObjCInterface: 2176 return CreateType(cast<ObjCInterfaceType>(Ty), Unit); 2177 case Type::Builtin: 2178 return CreateType(cast<BuiltinType>(Ty)); 2179 case Type::Complex: 2180 return CreateType(cast<ComplexType>(Ty)); 2181 case Type::Pointer: 2182 return CreateType(cast<PointerType>(Ty), Unit); 2183 case Type::Adjusted: 2184 case Type::Decayed: 2185 // Decayed and adjusted types use the adjusted type in LLVM and DWARF. 2186 return CreateType( 2187 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit); 2188 case Type::BlockPointer: 2189 return CreateType(cast<BlockPointerType>(Ty), Unit); 2190 case Type::Typedef: 2191 return CreateType(cast<TypedefType>(Ty), Unit); 2192 case Type::Record: 2193 return CreateType(cast<RecordType>(Ty)); 2194 case Type::Enum: 2195 return CreateEnumType(cast<EnumType>(Ty)); 2196 case Type::FunctionProto: 2197 case Type::FunctionNoProto: 2198 return CreateType(cast<FunctionType>(Ty), Unit); 2199 case Type::ConstantArray: 2200 case Type::VariableArray: 2201 case Type::IncompleteArray: 2202 return CreateType(cast<ArrayType>(Ty), Unit); 2203 2204 case Type::LValueReference: 2205 return CreateType(cast<LValueReferenceType>(Ty), Unit); 2206 case Type::RValueReference: 2207 return CreateType(cast<RValueReferenceType>(Ty), Unit); 2208 2209 case Type::MemberPointer: 2210 return CreateType(cast<MemberPointerType>(Ty), Unit); 2211 2212 case Type::Atomic: 2213 return CreateType(cast<AtomicType>(Ty), Unit); 2214 2215 case Type::Attributed: 2216 case Type::TemplateSpecialization: 2217 case Type::Elaborated: 2218 case Type::Paren: 2219 case Type::SubstTemplateTypeParm: 2220 case Type::TypeOfExpr: 2221 case Type::TypeOf: 2222 case Type::Decltype: 2223 case Type::UnaryTransform: 2224 case Type::PackExpansion: 2225 llvm_unreachable("type should have been unwrapped!"); 2226 case Type::Auto: 2227 Diag = "auto"; 2228 break; 2229 } 2230 2231 assert(Diag && "Fall through without a diagnostic?"); 2232 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error, 2233 "debug information for %0 is not yet supported"); 2234 CGM.getDiags().Report(DiagID) 2235 << Diag; 2236 return llvm::DIType(); 2237 } 2238 2239 /// getOrCreateLimitedType - Get the type from the cache or create a new 2240 /// limited type if necessary. 2241 llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty, 2242 llvm::DIFile Unit) { 2243 QualType QTy(Ty, 0); 2244 2245 llvm::DICompositeType T(getTypeOrNull(QTy)); 2246 2247 // We may have cached a forward decl when we could have created 2248 // a non-forward decl. Go ahead and create a non-forward decl 2249 // now. 2250 if (T && !T.isForwardDecl()) return T; 2251 2252 // Otherwise create the type. 2253 llvm::DICompositeType Res = CreateLimitedType(Ty); 2254 2255 // Propagate members from the declaration to the definition 2256 // CreateType(const RecordType*) will overwrite this with the members in the 2257 // correct order if the full type is needed. 2258 Res.setTypeArray(T.getTypeArray()); 2259 2260 if (T && T.isForwardDecl()) 2261 ReplaceMap.push_back( 2262 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T))); 2263 2264 // And update the type cache. 2265 TypeCache[QTy.getAsOpaquePtr()] = Res; 2266 return Res; 2267 } 2268 2269 // TODO: Currently used for context chains when limiting debug info. 2270 llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) { 2271 RecordDecl *RD = Ty->getDecl(); 2272 2273 // Get overall information about the record type for the debug info. 2274 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 2275 unsigned Line = getLineNumber(RD->getLocation()); 2276 StringRef RDName = getClassName(RD); 2277 2278 llvm::DIDescriptor RDContext = 2279 getContextDescriptor(cast<Decl>(RD->getDeclContext())); 2280 2281 // If we ended up creating the type during the context chain construction, 2282 // just return that. 2283 // FIXME: this could be dealt with better if the type was recorded as 2284 // completed before we started this (see the CompletedTypeCache usage in 2285 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to 2286 // be pushed to before context creation, but after it was known to be 2287 // destined for completion (might still have an issue if this caller only 2288 // required a declaration but the context construction ended up creating a 2289 // definition) 2290 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD))); 2291 if (T && (!T.isForwardDecl() || !RD->getDefinition())) 2292 return T; 2293 2294 // If this is just a forward or incomplete declaration, construct an 2295 // appropriately marked node and just return it. 2296 const RecordDecl *D = RD->getDefinition(); 2297 if (!D || !D->isCompleteDefinition()) 2298 return getOrCreateRecordFwdDecl(Ty, RDContext); 2299 2300 uint64_t Size = CGM.getContext().getTypeSize(Ty); 2301 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 2302 llvm::DICompositeType RealDecl; 2303 2304 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU); 2305 2306 if (RD->isUnion()) 2307 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line, 2308 Size, Align, 0, llvm::DIArray(), 0, 2309 FullName); 2310 else if (RD->isClass()) { 2311 // FIXME: This could be a struct type giving a default visibility different 2312 // than C++ class type, but needs llvm metadata changes first. 2313 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line, 2314 Size, Align, 0, 0, llvm::DIType(), 2315 llvm::DIArray(), llvm::DIType(), 2316 llvm::DIArray(), FullName); 2317 } else 2318 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line, 2319 Size, Align, 0, llvm::DIType(), 2320 llvm::DIArray(), 0, llvm::DIType(), 2321 FullName); 2322 2323 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl); 2324 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl; 2325 2326 if (const ClassTemplateSpecializationDecl *TSpecial = 2327 dyn_cast<ClassTemplateSpecializationDecl>(RD)) 2328 RealDecl.setTypeArray(llvm::DIArray(), 2329 CollectCXXTemplateParams(TSpecial, DefUnit)); 2330 return RealDecl; 2331 } 2332 2333 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD, 2334 llvm::DICompositeType RealDecl) { 2335 // A class's primary base or the class itself contains the vtable. 2336 llvm::DICompositeType ContainingType; 2337 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 2338 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) { 2339 // Seek non-virtual primary base root. 2340 while (1) { 2341 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase); 2342 const CXXRecordDecl *PBT = BRL.getPrimaryBase(); 2343 if (PBT && !BRL.isPrimaryBaseVirtual()) 2344 PBase = PBT; 2345 else 2346 break; 2347 } 2348 ContainingType = llvm::DICompositeType( 2349 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), 2350 getOrCreateFile(RD->getLocation()))); 2351 } else if (RD->isDynamicClass()) 2352 ContainingType = RealDecl; 2353 2354 RealDecl.setContainingType(ContainingType); 2355 } 2356 2357 /// CreateMemberType - Create new member and increase Offset by FType's size. 2358 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType, 2359 StringRef Name, 2360 uint64_t *Offset) { 2361 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 2362 uint64_t FieldSize = CGM.getContext().getTypeSize(FType); 2363 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType); 2364 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0, 2365 FieldSize, FieldAlign, 2366 *Offset, 0, FieldTy); 2367 *Offset += FieldSize; 2368 return Ty; 2369 } 2370 2371 llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) { 2372 // We only need a declaration (not a definition) of the type - so use whatever 2373 // we would otherwise do to get a type for a pointee. (forward declarations in 2374 // limited debug info, full definitions (if the type definition is available) 2375 // in unlimited debug info) 2376 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) 2377 return getOrCreateType(CGM.getContext().getTypeDeclType(TD), 2378 getOrCreateFile(TD->getLocation())); 2379 // Otherwise fall back to a fairly rudimentary cache of existing declarations. 2380 // This doesn't handle providing declarations (for functions or variables) for 2381 // entities without definitions in this TU, nor when the definition proceeds 2382 // the call to this function. 2383 // FIXME: This should be split out into more specific maps with support for 2384 // emitting forward declarations and merging definitions with declarations, 2385 // the same way as we do for types. 2386 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I = 2387 DeclCache.find(D->getCanonicalDecl()); 2388 if (I == DeclCache.end()) 2389 return llvm::DIDescriptor(); 2390 llvm::Value *V = I->second; 2391 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V)); 2392 } 2393 2394 /// getFunctionDeclaration - Return debug info descriptor to describe method 2395 /// declaration for the given method definition. 2396 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) { 2397 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly) 2398 return llvm::DISubprogram(); 2399 2400 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 2401 if (!FD) return llvm::DISubprogram(); 2402 2403 // Setup context. 2404 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext())); 2405 2406 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator 2407 MI = SPCache.find(FD->getCanonicalDecl()); 2408 if (MI == SPCache.end()) { 2409 if (const CXXMethodDecl *MD = 2410 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) { 2411 llvm::DICompositeType T(S); 2412 llvm::DISubprogram SP = 2413 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T); 2414 return SP; 2415 } 2416 } 2417 if (MI != SPCache.end()) { 2418 llvm::Value *V = MI->second; 2419 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V)); 2420 if (SP.isSubprogram() && !SP.isDefinition()) 2421 return SP; 2422 } 2423 2424 for (auto NextFD : FD->redecls()) { 2425 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator 2426 MI = SPCache.find(NextFD->getCanonicalDecl()); 2427 if (MI != SPCache.end()) { 2428 llvm::Value *V = MI->second; 2429 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V)); 2430 if (SP.isSubprogram() && !SP.isDefinition()) 2431 return SP; 2432 } 2433 } 2434 return llvm::DISubprogram(); 2435 } 2436 2437 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include 2438 // implicit parameter "this". 2439 llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D, 2440 QualType FnType, 2441 llvm::DIFile F) { 2442 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly) 2443 // Create fake but valid subroutine type. Otherwise 2444 // llvm::DISubprogram::Verify() would return false, and 2445 // subprogram DIE will miss DW_AT_decl_file and 2446 // DW_AT_decl_line fields. 2447 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None)); 2448 2449 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 2450 return getOrCreateMethodType(Method, F); 2451 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) { 2452 // Add "self" and "_cmd" 2453 SmallVector<llvm::Value *, 16> Elts; 2454 2455 // First element is always return type. For 'void' functions it is NULL. 2456 QualType ResultTy = OMethod->getReturnType(); 2457 2458 // Replace the instancetype keyword with the actual type. 2459 if (ResultTy == CGM.getContext().getObjCInstanceType()) 2460 ResultTy = CGM.getContext().getPointerType( 2461 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0)); 2462 2463 Elts.push_back(getOrCreateType(ResultTy, F)); 2464 // "self" pointer is always first argument. 2465 QualType SelfDeclTy = OMethod->getSelfDecl()->getType(); 2466 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F); 2467 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy)); 2468 // "_cmd" pointer is always second argument. 2469 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F); 2470 Elts.push_back(DBuilder.createArtificialType(CmdTy)); 2471 // Get rest of the arguments. 2472 for (const auto *PI : OMethod->params()) 2473 Elts.push_back(getOrCreateType(PI->getType(), F)); 2474 2475 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts); 2476 return DBuilder.createSubroutineType(F, EltTypeArray); 2477 } 2478 2479 // Handle variadic function types; they need an additional 2480 // unspecified parameter. 2481 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2482 if (FD->isVariadic()) { 2483 SmallVector<llvm::Value *, 16> EltTys; 2484 EltTys.push_back(getOrCreateType(FD->getReturnType(), F)); 2485 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType)) 2486 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i) 2487 EltTys.push_back(getOrCreateType(FPT->getParamType(i), F)); 2488 EltTys.push_back(DBuilder.createUnspecifiedParameter()); 2489 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys); 2490 return DBuilder.createSubroutineType(F, EltTypeArray); 2491 } 2492 2493 return llvm::DICompositeType(getOrCreateType(FnType, F)); 2494 } 2495 2496 /// EmitFunctionStart - Constructs the debug code for entering a function. 2497 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType, 2498 llvm::Function *Fn, 2499 CGBuilderTy &Builder) { 2500 2501 StringRef Name; 2502 StringRef LinkageName; 2503 2504 FnBeginRegionCount.push_back(LexicalBlockStack.size()); 2505 2506 const Decl *D = GD.getDecl(); 2507 // Function may lack declaration in source code if it is created by Clang 2508 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk). 2509 bool HasDecl = (D != 0); 2510 // Use the location of the declaration. 2511 SourceLocation Loc; 2512 if (HasDecl) 2513 Loc = D->getLocation(); 2514 2515 unsigned Flags = 0; 2516 llvm::DIFile Unit = getOrCreateFile(Loc); 2517 llvm::DIDescriptor FDContext(Unit); 2518 llvm::DIArray TParamsArray; 2519 if (!HasDecl) { 2520 // Use llvm function name. 2521 LinkageName = Fn->getName(); 2522 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2523 // If there is a DISubprogram for this function available then use it. 2524 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator 2525 FI = SPCache.find(FD->getCanonicalDecl()); 2526 if (FI != SPCache.end()) { 2527 llvm::Value *V = FI->second; 2528 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V)); 2529 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) { 2530 llvm::MDNode *SPN = SP; 2531 LexicalBlockStack.push_back(SPN); 2532 RegionMap[D] = llvm::WeakVH(SP); 2533 return; 2534 } 2535 } 2536 Name = getFunctionName(FD); 2537 // Use mangled name as linkage name for C/C++ functions. 2538 if (FD->hasPrototype()) { 2539 LinkageName = CGM.getMangledName(GD); 2540 Flags |= llvm::DIDescriptor::FlagPrototyped; 2541 } 2542 // No need to replicate the linkage name if it isn't different from the 2543 // subprogram name, no need to have it at all unless coverage is enabled or 2544 // debug is set to more than just line tables. 2545 if (LinkageName == Name || 2546 (!CGM.getCodeGenOpts().EmitGcovArcs && 2547 !CGM.getCodeGenOpts().EmitGcovNotes && 2548 DebugKind <= CodeGenOptions::DebugLineTablesOnly)) 2549 LinkageName = StringRef(); 2550 2551 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) { 2552 if (const NamespaceDecl *NSDecl = 2553 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext())) 2554 FDContext = getOrCreateNameSpace(NSDecl); 2555 else if (const RecordDecl *RDecl = 2556 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) 2557 FDContext = getContextDescriptor(cast<Decl>(RDecl)); 2558 2559 // Collect template parameters. 2560 TParamsArray = CollectFunctionTemplateParams(FD, Unit); 2561 } 2562 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) { 2563 Name = getObjCMethodName(OMD); 2564 Flags |= llvm::DIDescriptor::FlagPrototyped; 2565 } else { 2566 // Use llvm function name. 2567 Name = Fn->getName(); 2568 Flags |= llvm::DIDescriptor::FlagPrototyped; 2569 } 2570 if (!Name.empty() && Name[0] == '\01') 2571 Name = Name.substr(1); 2572 2573 unsigned LineNo = getLineNumber(Loc); 2574 if (!HasDecl || D->isImplicit()) 2575 Flags |= llvm::DIDescriptor::FlagArtificial; 2576 2577 llvm::DISubprogram SP = 2578 DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo, 2579 getOrCreateFunctionType(D, FnType, Unit), 2580 Fn->hasInternalLinkage(), true /*definition*/, 2581 getLineNumber(CurLoc), Flags, 2582 CGM.getLangOpts().Optimize, Fn, TParamsArray, 2583 getFunctionDeclaration(D)); 2584 if (HasDecl) 2585 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP))); 2586 2587 // Push function on region stack. 2588 llvm::MDNode *SPN = SP; 2589 LexicalBlockStack.push_back(SPN); 2590 if (HasDecl) 2591 RegionMap[D] = llvm::WeakVH(SP); 2592 } 2593 2594 /// EmitLocation - Emit metadata to indicate a change in line/column 2595 /// information in the source file. If the location is invalid, the 2596 /// previous location will be reused. 2597 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc, 2598 bool ForceColumnInfo) { 2599 // Update our current location 2600 setLocation(Loc); 2601 2602 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return; 2603 2604 // Don't bother if things are the same as last time. 2605 SourceManager &SM = CGM.getContext().getSourceManager(); 2606 if (CurLoc == PrevLoc || 2607 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc)) 2608 // New Builder may not be in sync with CGDebugInfo. 2609 if (!Builder.getCurrentDebugLocation().isUnknown() && 2610 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) == 2611 LexicalBlockStack.back()) 2612 return; 2613 2614 // Update last state. 2615 PrevLoc = CurLoc; 2616 2617 llvm::MDNode *Scope = LexicalBlockStack.back(); 2618 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get 2619 (getLineNumber(CurLoc), 2620 getColumnNumber(CurLoc, ForceColumnInfo), 2621 Scope)); 2622 } 2623 2624 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on 2625 /// the stack. 2626 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) { 2627 llvm::DIDescriptor D = 2628 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ? 2629 llvm::DIDescriptor() : 2630 llvm::DIDescriptor(LexicalBlockStack.back()), 2631 getOrCreateFile(CurLoc), 2632 getLineNumber(CurLoc), 2633 getColumnNumber(CurLoc), 2634 0); 2635 llvm::MDNode *DN = D; 2636 LexicalBlockStack.push_back(DN); 2637 } 2638 2639 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative 2640 /// region - beginning of a DW_TAG_lexical_block. 2641 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, 2642 SourceLocation Loc) { 2643 // Set our current location. 2644 setLocation(Loc); 2645 2646 // Create a new lexical block and push it on the stack. 2647 CreateLexicalBlock(Loc); 2648 2649 // Emit a line table change for the current location inside the new scope. 2650 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc), 2651 getColumnNumber(Loc), 2652 LexicalBlockStack.back())); 2653 } 2654 2655 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative 2656 /// region - end of a DW_TAG_lexical_block. 2657 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, 2658 SourceLocation Loc) { 2659 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2660 2661 // Provide an entry in the line table for the end of the block. 2662 EmitLocation(Builder, Loc); 2663 2664 LexicalBlockStack.pop_back(); 2665 } 2666 2667 /// EmitFunctionEnd - Constructs the debug code for exiting a function. 2668 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) { 2669 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2670 unsigned RCount = FnBeginRegionCount.back(); 2671 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch"); 2672 2673 // Pop all regions for this function. 2674 while (LexicalBlockStack.size() != RCount) 2675 EmitLexicalBlockEnd(Builder, CurLoc); 2676 FnBeginRegionCount.pop_back(); 2677 } 2678 2679 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref. 2680 // See BuildByRefType. 2681 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD, 2682 uint64_t *XOffset) { 2683 2684 SmallVector<llvm::Value *, 5> EltTys; 2685 QualType FType; 2686 uint64_t FieldSize, FieldOffset; 2687 unsigned FieldAlign; 2688 2689 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 2690 QualType Type = VD->getType(); 2691 2692 FieldOffset = 0; 2693 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 2694 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 2695 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset)); 2696 FType = CGM.getContext().IntTy; 2697 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 2698 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset)); 2699 2700 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD); 2701 if (HasCopyAndDispose) { 2702 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 2703 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper", 2704 &FieldOffset)); 2705 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper", 2706 &FieldOffset)); 2707 } 2708 bool HasByrefExtendedLayout; 2709 Qualifiers::ObjCLifetime Lifetime; 2710 if (CGM.getContext().getByrefLifetime(Type, 2711 Lifetime, HasByrefExtendedLayout) 2712 && HasByrefExtendedLayout) { 2713 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 2714 EltTys.push_back(CreateMemberType(Unit, FType, 2715 "__byref_variable_layout", 2716 &FieldOffset)); 2717 } 2718 2719 CharUnits Align = CGM.getContext().getDeclAlign(VD); 2720 if (Align > CGM.getContext().toCharUnitsFromBits( 2721 CGM.getTarget().getPointerAlign(0))) { 2722 CharUnits FieldOffsetInBytes 2723 = CGM.getContext().toCharUnitsFromBits(FieldOffset); 2724 CharUnits AlignedOffsetInBytes 2725 = FieldOffsetInBytes.RoundUpToAlignment(Align); 2726 CharUnits NumPaddingBytes 2727 = AlignedOffsetInBytes - FieldOffsetInBytes; 2728 2729 if (NumPaddingBytes.isPositive()) { 2730 llvm::APInt pad(32, NumPaddingBytes.getQuantity()); 2731 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy, 2732 pad, ArrayType::Normal, 0); 2733 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset)); 2734 } 2735 } 2736 2737 FType = Type; 2738 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 2739 FieldSize = CGM.getContext().getTypeSize(FType); 2740 FieldAlign = CGM.getContext().toBits(Align); 2741 2742 *XOffset = FieldOffset; 2743 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 2744 0, FieldSize, FieldAlign, 2745 FieldOffset, 0, FieldTy); 2746 EltTys.push_back(FieldTy); 2747 FieldOffset += FieldSize; 2748 2749 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys); 2750 2751 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct; 2752 2753 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags, 2754 llvm::DIType(), Elements); 2755 } 2756 2757 /// EmitDeclare - Emit local variable declaration debug info. 2758 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag, 2759 llvm::Value *Storage, 2760 unsigned ArgNo, CGBuilderTy &Builder) { 2761 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 2762 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2763 2764 bool Unwritten = 2765 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) && 2766 cast<Decl>(VD->getDeclContext())->isImplicit()); 2767 llvm::DIFile Unit; 2768 if (!Unwritten) 2769 Unit = getOrCreateFile(VD->getLocation()); 2770 llvm::DIType Ty; 2771 uint64_t XOffset = 0; 2772 if (VD->hasAttr<BlocksAttr>()) 2773 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 2774 else 2775 Ty = getOrCreateType(VD->getType(), Unit); 2776 2777 // If there is no debug info for this type then do not emit debug info 2778 // for this variable. 2779 if (!Ty) 2780 return; 2781 2782 // Get location information. 2783 unsigned Line = 0; 2784 unsigned Column = 0; 2785 if (!Unwritten) { 2786 Line = getLineNumber(VD->getLocation()); 2787 Column = getColumnNumber(VD->getLocation()); 2788 } 2789 unsigned Flags = 0; 2790 if (VD->isImplicit()) 2791 Flags |= llvm::DIDescriptor::FlagArtificial; 2792 // If this is the first argument and it is implicit then 2793 // give it an object pointer flag. 2794 // FIXME: There has to be a better way to do this, but for static 2795 // functions there won't be an implicit param at arg1 and 2796 // otherwise it is 'self' or 'this'. 2797 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1) 2798 Flags |= llvm::DIDescriptor::FlagObjectPointer; 2799 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) 2800 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() && 2801 !VD->getType()->isPointerType()) 2802 Flags |= llvm::DIDescriptor::FlagIndirectVariable; 2803 2804 llvm::MDNode *Scope = LexicalBlockStack.back(); 2805 2806 StringRef Name = VD->getName(); 2807 if (!Name.empty()) { 2808 if (VD->hasAttr<BlocksAttr>()) { 2809 CharUnits offset = CharUnits::fromQuantity(32); 2810 SmallVector<llvm::Value *, 9> addr; 2811 llvm::Type *Int64Ty = CGM.Int64Ty; 2812 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2813 // offset of __forwarding field 2814 offset = CGM.getContext().toCharUnitsFromBits( 2815 CGM.getTarget().getPointerWidth(0)); 2816 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2817 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 2818 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2819 // offset of x field 2820 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 2821 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2822 2823 // Create the descriptor for the variable. 2824 llvm::DIVariable D = 2825 DBuilder.createComplexVariable(Tag, 2826 llvm::DIDescriptor(Scope), 2827 VD->getName(), Unit, Line, Ty, 2828 addr, ArgNo); 2829 2830 // Insert an llvm.dbg.declare into the current block. 2831 llvm::Instruction *Call = 2832 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 2833 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 2834 return; 2835 } else if (isa<VariableArrayType>(VD->getType())) 2836 Flags |= llvm::DIDescriptor::FlagIndirectVariable; 2837 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) { 2838 // If VD is an anonymous union then Storage represents value for 2839 // all union fields. 2840 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 2841 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) { 2842 for (RecordDecl::field_iterator I = RD->field_begin(), 2843 E = RD->field_end(); 2844 I != E; ++I) { 2845 FieldDecl *Field = *I; 2846 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 2847 StringRef FieldName = Field->getName(); 2848 2849 // Ignore unnamed fields. Do not ignore unnamed records. 2850 if (FieldName.empty() && !isa<RecordType>(Field->getType())) 2851 continue; 2852 2853 // Use VarDecl's Tag, Scope and Line number. 2854 llvm::DIVariable D = 2855 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope), 2856 FieldName, Unit, Line, FieldTy, 2857 CGM.getLangOpts().Optimize, Flags, 2858 ArgNo); 2859 2860 // Insert an llvm.dbg.declare into the current block. 2861 llvm::Instruction *Call = 2862 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 2863 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 2864 } 2865 return; 2866 } 2867 } 2868 2869 // Create the descriptor for the variable. 2870 llvm::DIVariable D = 2871 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope), 2872 Name, Unit, Line, Ty, 2873 CGM.getLangOpts().Optimize, Flags, ArgNo); 2874 2875 // Insert an llvm.dbg.declare into the current block. 2876 llvm::Instruction *Call = 2877 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 2878 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 2879 } 2880 2881 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, 2882 llvm::Value *Storage, 2883 CGBuilderTy &Builder) { 2884 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 2885 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder); 2886 } 2887 2888 /// Look up the completed type for a self pointer in the TypeCache and 2889 /// create a copy of it with the ObjectPointer and Artificial flags 2890 /// set. If the type is not cached, a new one is created. This should 2891 /// never happen though, since creating a type for the implicit self 2892 /// argument implies that we already parsed the interface definition 2893 /// and the ivar declarations in the implementation. 2894 llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy, 2895 llvm::DIType Ty) { 2896 llvm::DIType CachedTy = getTypeOrNull(QualTy); 2897 if (CachedTy) Ty = CachedTy; 2898 else DEBUG(llvm::dbgs() << "No cached type for self."); 2899 return DBuilder.createObjectPointerType(Ty); 2900 } 2901 2902 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD, 2903 llvm::Value *Storage, 2904 CGBuilderTy &Builder, 2905 const CGBlockInfo &blockInfo) { 2906 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 2907 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2908 2909 if (Builder.GetInsertBlock() == 0) 2910 return; 2911 2912 bool isByRef = VD->hasAttr<BlocksAttr>(); 2913 2914 uint64_t XOffset = 0; 2915 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 2916 llvm::DIType Ty; 2917 if (isByRef) 2918 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 2919 else 2920 Ty = getOrCreateType(VD->getType(), Unit); 2921 2922 // Self is passed along as an implicit non-arg variable in a 2923 // block. Mark it as the object pointer. 2924 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self") 2925 Ty = CreateSelfType(VD->getType(), Ty); 2926 2927 // Get location information. 2928 unsigned Line = getLineNumber(VD->getLocation()); 2929 unsigned Column = getColumnNumber(VD->getLocation()); 2930 2931 const llvm::DataLayout &target = CGM.getDataLayout(); 2932 2933 CharUnits offset = CharUnits::fromQuantity( 2934 target.getStructLayout(blockInfo.StructureType) 2935 ->getElementOffset(blockInfo.getCapture(VD).getIndex())); 2936 2937 SmallVector<llvm::Value *, 9> addr; 2938 llvm::Type *Int64Ty = CGM.Int64Ty; 2939 if (isa<llvm::AllocaInst>(Storage)) 2940 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 2941 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2942 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2943 if (isByRef) { 2944 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 2945 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2946 // offset of __forwarding field 2947 offset = CGM.getContext() 2948 .toCharUnitsFromBits(target.getPointerSizeInBits(0)); 2949 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2950 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 2951 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2952 // offset of x field 2953 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 2954 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2955 } 2956 2957 // Create the descriptor for the variable. 2958 llvm::DIVariable D = 2959 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable, 2960 llvm::DIDescriptor(LexicalBlockStack.back()), 2961 VD->getName(), Unit, Line, Ty, addr); 2962 2963 // Insert an llvm.dbg.declare into the current block. 2964 llvm::Instruction *Call = 2965 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint()); 2966 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, 2967 LexicalBlockStack.back())); 2968 } 2969 2970 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument 2971 /// variable declaration. 2972 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI, 2973 unsigned ArgNo, 2974 CGBuilderTy &Builder) { 2975 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 2976 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder); 2977 } 2978 2979 namespace { 2980 struct BlockLayoutChunk { 2981 uint64_t OffsetInBits; 2982 const BlockDecl::Capture *Capture; 2983 }; 2984 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) { 2985 return l.OffsetInBits < r.OffsetInBits; 2986 } 2987 } 2988 2989 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, 2990 llvm::Value *Arg, 2991 llvm::Value *LocalAddr, 2992 CGBuilderTy &Builder) { 2993 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 2994 ASTContext &C = CGM.getContext(); 2995 const BlockDecl *blockDecl = block.getBlockDecl(); 2996 2997 // Collect some general information about the block's location. 2998 SourceLocation loc = blockDecl->getCaretLocation(); 2999 llvm::DIFile tunit = getOrCreateFile(loc); 3000 unsigned line = getLineNumber(loc); 3001 unsigned column = getColumnNumber(loc); 3002 3003 // Build the debug-info type for the block literal. 3004 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext())); 3005 3006 const llvm::StructLayout *blockLayout = 3007 CGM.getDataLayout().getStructLayout(block.StructureType); 3008 3009 SmallVector<llvm::Value*, 16> fields; 3010 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public, 3011 blockLayout->getElementOffsetInBits(0), 3012 tunit, tunit)); 3013 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public, 3014 blockLayout->getElementOffsetInBits(1), 3015 tunit, tunit)); 3016 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public, 3017 blockLayout->getElementOffsetInBits(2), 3018 tunit, tunit)); 3019 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public, 3020 blockLayout->getElementOffsetInBits(3), 3021 tunit, tunit)); 3022 fields.push_back(createFieldType("__descriptor", 3023 C.getPointerType(block.NeedsCopyDispose ? 3024 C.getBlockDescriptorExtendedType() : 3025 C.getBlockDescriptorType()), 3026 0, loc, AS_public, 3027 blockLayout->getElementOffsetInBits(4), 3028 tunit, tunit)); 3029 3030 // We want to sort the captures by offset, not because DWARF 3031 // requires this, but because we're paranoid about debuggers. 3032 SmallVector<BlockLayoutChunk, 8> chunks; 3033 3034 // 'this' capture. 3035 if (blockDecl->capturesCXXThis()) { 3036 BlockLayoutChunk chunk; 3037 chunk.OffsetInBits = 3038 blockLayout->getElementOffsetInBits(block.CXXThisIndex); 3039 chunk.Capture = 0; 3040 chunks.push_back(chunk); 3041 } 3042 3043 // Variable captures. 3044 for (BlockDecl::capture_const_iterator 3045 i = blockDecl->capture_begin(), e = blockDecl->capture_end(); 3046 i != e; ++i) { 3047 const BlockDecl::Capture &capture = *i; 3048 const VarDecl *variable = capture.getVariable(); 3049 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable); 3050 3051 // Ignore constant captures. 3052 if (captureInfo.isConstant()) 3053 continue; 3054 3055 BlockLayoutChunk chunk; 3056 chunk.OffsetInBits = 3057 blockLayout->getElementOffsetInBits(captureInfo.getIndex()); 3058 chunk.Capture = &capture; 3059 chunks.push_back(chunk); 3060 } 3061 3062 // Sort by offset. 3063 llvm::array_pod_sort(chunks.begin(), chunks.end()); 3064 3065 for (SmallVectorImpl<BlockLayoutChunk>::iterator 3066 i = chunks.begin(), e = chunks.end(); i != e; ++i) { 3067 uint64_t offsetInBits = i->OffsetInBits; 3068 const BlockDecl::Capture *capture = i->Capture; 3069 3070 // If we have a null capture, this must be the C++ 'this' capture. 3071 if (!capture) { 3072 const CXXMethodDecl *method = 3073 cast<CXXMethodDecl>(blockDecl->getNonClosureContext()); 3074 QualType type = method->getThisType(C); 3075 3076 fields.push_back(createFieldType("this", type, 0, loc, AS_public, 3077 offsetInBits, tunit, tunit)); 3078 continue; 3079 } 3080 3081 const VarDecl *variable = capture->getVariable(); 3082 StringRef name = variable->getName(); 3083 3084 llvm::DIType fieldType; 3085 if (capture->isByRef()) { 3086 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy); 3087 3088 // FIXME: this creates a second copy of this type! 3089 uint64_t xoffset; 3090 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset); 3091 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first); 3092 fieldType = DBuilder.createMemberType(tunit, name, tunit, line, 3093 ptrInfo.first, ptrInfo.second, 3094 offsetInBits, 0, fieldType); 3095 } else { 3096 fieldType = createFieldType(name, variable->getType(), 0, 3097 loc, AS_public, offsetInBits, tunit, tunit); 3098 } 3099 fields.push_back(fieldType); 3100 } 3101 3102 SmallString<36> typeName; 3103 llvm::raw_svector_ostream(typeName) 3104 << "__block_literal_" << CGM.getUniqueBlockCount(); 3105 3106 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields); 3107 3108 llvm::DIType type = 3109 DBuilder.createStructType(tunit, typeName.str(), tunit, line, 3110 CGM.getContext().toBits(block.BlockSize), 3111 CGM.getContext().toBits(block.BlockAlign), 3112 0, llvm::DIType(), fieldsArray); 3113 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits); 3114 3115 // Get overall information about the block. 3116 unsigned flags = llvm::DIDescriptor::FlagArtificial; 3117 llvm::MDNode *scope = LexicalBlockStack.back(); 3118 3119 // Create the descriptor for the parameter. 3120 llvm::DIVariable debugVar = 3121 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable, 3122 llvm::DIDescriptor(scope), 3123 Arg->getName(), tunit, line, type, 3124 CGM.getLangOpts().Optimize, flags, 3125 cast<llvm::Argument>(Arg)->getArgNo() + 1); 3126 3127 if (LocalAddr) { 3128 // Insert an llvm.dbg.value into the current block. 3129 llvm::Instruction *DbgVal = 3130 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar, 3131 Builder.GetInsertBlock()); 3132 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope)); 3133 } 3134 3135 // Insert an llvm.dbg.declare into the current block. 3136 llvm::Instruction *DbgDecl = 3137 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock()); 3138 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope)); 3139 } 3140 3141 /// If D is an out-of-class definition of a static data member of a class, find 3142 /// its corresponding in-class declaration. 3143 llvm::DIDerivedType 3144 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) { 3145 if (!D->isStaticDataMember()) 3146 return llvm::DIDerivedType(); 3147 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI = 3148 StaticDataMemberCache.find(D->getCanonicalDecl()); 3149 if (MI != StaticDataMemberCache.end()) { 3150 assert(MI->second && "Static data member declaration should still exist"); 3151 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)); 3152 } 3153 3154 // If the member wasn't found in the cache, lazily construct and add it to the 3155 // type (used when a limited form of the type is emitted). 3156 llvm::DICompositeType Ctxt( 3157 getContextDescriptor(cast<Decl>(D->getDeclContext()))); 3158 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt); 3159 return T; 3160 } 3161 3162 /// EmitGlobalVariable - Emit information about a global variable. 3163 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 3164 const VarDecl *D) { 3165 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 3166 // Create global variable debug descriptor. 3167 llvm::DIFile Unit = getOrCreateFile(D->getLocation()); 3168 unsigned LineNo = getLineNumber(D->getLocation()); 3169 3170 setLocation(D->getLocation()); 3171 3172 QualType T = D->getType(); 3173 if (T->isIncompleteArrayType()) { 3174 3175 // CodeGen turns int[] into int[1] so we'll do the same here. 3176 llvm::APInt ConstVal(32, 1); 3177 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 3178 3179 T = CGM.getContext().getConstantArrayType(ET, ConstVal, 3180 ArrayType::Normal, 0); 3181 } 3182 StringRef DeclName = D->getName(); 3183 StringRef LinkageName; 3184 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext()) 3185 && !isa<ObjCMethodDecl>(D->getDeclContext())) 3186 LinkageName = Var->getName(); 3187 if (LinkageName == DeclName) 3188 LinkageName = StringRef(); 3189 llvm::DIDescriptor DContext = 3190 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext())); 3191 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable( 3192 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit), 3193 Var->hasInternalLinkage(), Var, 3194 getOrCreateStaticDataMemberDeclarationOrNull(D)); 3195 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV))); 3196 } 3197 3198 /// EmitGlobalVariable - Emit information about an objective-c interface. 3199 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 3200 ObjCInterfaceDecl *ID) { 3201 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 3202 // Create global variable debug descriptor. 3203 llvm::DIFile Unit = getOrCreateFile(ID->getLocation()); 3204 unsigned LineNo = getLineNumber(ID->getLocation()); 3205 3206 StringRef Name = ID->getName(); 3207 3208 QualType T = CGM.getContext().getObjCInterfaceType(ID); 3209 if (T->isIncompleteArrayType()) { 3210 3211 // CodeGen turns int[] into int[1] so we'll do the same here. 3212 llvm::APInt ConstVal(32, 1); 3213 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 3214 3215 T = CGM.getContext().getConstantArrayType(ET, ConstVal, 3216 ArrayType::Normal, 0); 3217 } 3218 3219 DBuilder.createGlobalVariable(Name, Unit, LineNo, 3220 getOrCreateType(T, Unit), 3221 Var->hasInternalLinkage(), Var); 3222 } 3223 3224 /// EmitGlobalVariable - Emit global variable's debug info. 3225 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, 3226 llvm::Constant *Init) { 3227 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 3228 // Create the descriptor for the variable. 3229 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 3230 StringRef Name = VD->getName(); 3231 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit); 3232 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) { 3233 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext()); 3234 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?"); 3235 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit); 3236 } 3237 // Do not use DIGlobalVariable for enums. 3238 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type) 3239 return; 3240 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable( 3241 Unit, Name, Name, Unit, getLineNumber(VD->getLocation()), Ty, true, Init, 3242 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD))); 3243 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV))); 3244 } 3245 3246 llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) { 3247 if (!LexicalBlockStack.empty()) 3248 return llvm::DIScope(LexicalBlockStack.back()); 3249 return getContextDescriptor(D); 3250 } 3251 3252 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) { 3253 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo) 3254 return; 3255 DBuilder.createImportedModule( 3256 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())), 3257 getOrCreateNameSpace(UD.getNominatedNamespace()), 3258 getLineNumber(UD.getLocation())); 3259 } 3260 3261 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) { 3262 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo) 3263 return; 3264 assert(UD.shadow_size() && 3265 "We shouldn't be codegening an invalid UsingDecl containing no decls"); 3266 // Emitting one decl is sufficient - debuggers can detect that this is an 3267 // overloaded name & provide lookup for all the overloads. 3268 const UsingShadowDecl &USD = **UD.shadow_begin(); 3269 if (llvm::DIDescriptor Target = 3270 getDeclarationOrDefinition(USD.getUnderlyingDecl())) 3271 DBuilder.createImportedDeclaration( 3272 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target, 3273 getLineNumber(USD.getLocation())); 3274 } 3275 3276 llvm::DIImportedEntity 3277 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) { 3278 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo) 3279 return llvm::DIImportedEntity(0); 3280 llvm::WeakVH &VH = NamespaceAliasCache[&NA]; 3281 if (VH) 3282 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH)); 3283 llvm::DIImportedEntity R(0); 3284 if (const NamespaceAliasDecl *Underlying = 3285 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace())) 3286 // This could cache & dedup here rather than relying on metadata deduping. 3287 R = DBuilder.createImportedModule( 3288 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())), 3289 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()), 3290 NA.getName()); 3291 else 3292 R = DBuilder.createImportedModule( 3293 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())), 3294 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())), 3295 getLineNumber(NA.getLocation()), NA.getName()); 3296 VH = R; 3297 return R; 3298 } 3299 3300 /// getOrCreateNamesSpace - Return namespace descriptor for the given 3301 /// namespace decl. 3302 llvm::DINameSpace 3303 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) { 3304 NSDecl = NSDecl->getCanonicalDecl(); 3305 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I = 3306 NameSpaceCache.find(NSDecl); 3307 if (I != NameSpaceCache.end()) 3308 return llvm::DINameSpace(cast<llvm::MDNode>(I->second)); 3309 3310 unsigned LineNo = getLineNumber(NSDecl->getLocation()); 3311 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation()); 3312 llvm::DIDescriptor Context = 3313 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext())); 3314 llvm::DINameSpace NS = 3315 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo); 3316 NameSpaceCache[NSDecl] = llvm::WeakVH(NS); 3317 return NS; 3318 } 3319 3320 void CGDebugInfo::finalize() { 3321 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI 3322 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) { 3323 llvm::DIType Ty, RepTy; 3324 // Verify that the debug info still exists. 3325 if (llvm::Value *V = VI->second) 3326 Ty = llvm::DIType(cast<llvm::MDNode>(V)); 3327 3328 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 3329 TypeCache.find(VI->first); 3330 if (it != TypeCache.end()) { 3331 // Verify that the debug info still exists. 3332 if (llvm::Value *V = it->second) 3333 RepTy = llvm::DIType(cast<llvm::MDNode>(V)); 3334 } 3335 3336 if (Ty && Ty.isForwardDecl() && RepTy) 3337 Ty.replaceAllUsesWith(RepTy); 3338 } 3339 3340 // We keep our own list of retained types, because we need to look 3341 // up the final type in the type cache. 3342 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(), 3343 RE = RetainedTypes.end(); RI != RE; ++RI) 3344 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI]))); 3345 3346 DBuilder.finalize(); 3347 } 3348