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