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