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