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