CGDebugInfo.cpp revision c9e814ba193f38a7b08268612248f63beb279bb3
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 "clang/AST/ASTContext.h" 18#include "clang/AST/DeclFriend.h" 19#include "clang/AST/DeclObjC.h" 20#include "clang/AST/DeclTemplate.h" 21#include "clang/AST/Expr.h" 22#include "clang/AST/RecordLayout.h" 23#include "clang/Basic/SourceManager.h" 24#include "clang/Basic/FileManager.h" 25#include "clang/Basic/Version.h" 26#include "clang/Frontend/CodeGenOptions.h" 27#include "llvm/Constants.h" 28#include "llvm/DerivedTypes.h" 29#include "llvm/Instructions.h" 30#include "llvm/Intrinsics.h" 31#include "llvm/Module.h" 32#include "llvm/ADT/StringExtras.h" 33#include "llvm/ADT/SmallVector.h" 34#include "llvm/Support/Dwarf.h" 35#include "llvm/System/Path.h" 36#include "llvm/Target/TargetMachine.h" 37using namespace clang; 38using namespace clang::CodeGen; 39 40CGDebugInfo::CGDebugInfo(CodeGenModule &CGM) 41 : CGM(CGM), DebugFactory(CGM.getModule()), 42 BlockLiteralGenericSet(false) { 43 CreateCompileUnit(); 44} 45 46CGDebugInfo::~CGDebugInfo() { 47 assert(RegionStack.empty() && "Region stack mismatch, stack not empty!"); 48} 49 50void CGDebugInfo::setLocation(SourceLocation Loc) { 51 if (Loc.isValid()) 52 CurLoc = CGM.getContext().getSourceManager().getInstantiationLoc(Loc); 53} 54 55/// getContextDescriptor - Get context info for the decl. 56llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context, 57 llvm::DIDescriptor &CompileUnit) { 58 if (!Context) 59 return CompileUnit; 60 61 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator 62 I = RegionMap.find(Context); 63 if (I != RegionMap.end()) 64 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(&*I->second)); 65 66 // Check namespace. 67 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context)) 68 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl, CompileUnit)); 69 70 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) { 71 if (!RDecl->isDependentType()) { 72 llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl), 73 llvm::DIFile(CompileUnit)); 74 return llvm::DIDescriptor(Ty); 75 } 76 } 77 return CompileUnit; 78} 79 80/// getFunctionName - Get function name for the given FunctionDecl. If the 81/// name is constructred on demand (e.g. C++ destructor) then the name 82/// is stored on the side. 83llvm::StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) { 84 assert (FD && "Invalid FunctionDecl!"); 85 IdentifierInfo *FII = FD->getIdentifier(); 86 if (FII) 87 return FII->getName(); 88 89 // Otherwise construct human readable name for debug info. 90 std::string NS = FD->getNameAsString(); 91 92 // Copy this name on the side and use its reference. 93 char *StrPtr = DebugInfoNames.Allocate<char>(NS.length()); 94 memcpy(StrPtr, NS.data(), NS.length()); 95 return llvm::StringRef(StrPtr, NS.length()); 96} 97 98llvm::StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) { 99 llvm::SmallString<256> MethodName; 100 llvm::raw_svector_ostream OS(MethodName); 101 OS << (OMD->isInstanceMethod() ? '-' : '+') << '['; 102 const DeclContext *DC = OMD->getDeclContext(); 103 if (const ObjCImplementationDecl *OID = 104 dyn_cast<const ObjCImplementationDecl>(DC)) { 105 OS << OID->getName(); 106 } else if (const ObjCInterfaceDecl *OID = 107 dyn_cast<const ObjCInterfaceDecl>(DC)) { 108 OS << OID->getName(); 109 } else if (const ObjCCategoryImplDecl *OCD = 110 dyn_cast<const ObjCCategoryImplDecl>(DC)){ 111 OS << ((NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' << 112 OCD->getIdentifier()->getNameStart() << ')'; 113 } 114 OS << ' ' << OMD->getSelector().getAsString() << ']'; 115 116 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell()); 117 memcpy(StrPtr, MethodName.begin(), OS.tell()); 118 return llvm::StringRef(StrPtr, OS.tell()); 119} 120 121/// getClassName - Get class name including template argument list. 122llvm::StringRef 123CGDebugInfo::getClassName(RecordDecl *RD) { 124 ClassTemplateSpecializationDecl *Spec 125 = dyn_cast<ClassTemplateSpecializationDecl>(RD); 126 if (!Spec) 127 return RD->getName(); 128 129 const TemplateArgument *Args; 130 unsigned NumArgs; 131 std::string Buffer; 132 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) { 133 const TemplateSpecializationType *TST = 134 cast<TemplateSpecializationType>(TAW->getType()); 135 Args = TST->getArgs(); 136 NumArgs = TST->getNumArgs(); 137 } else { 138 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 139 Args = TemplateArgs.data(); 140 NumArgs = TemplateArgs.size(); 141 } 142 Buffer = RD->getIdentifier()->getNameStart(); 143 PrintingPolicy Policy(CGM.getLangOptions()); 144 Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args, 145 NumArgs, 146 Policy); 147 148 // Copy this name on the side and use its reference. 149 char *StrPtr = DebugInfoNames.Allocate<char>(Buffer.length()); 150 memcpy(StrPtr, Buffer.data(), Buffer.length()); 151 return llvm::StringRef(StrPtr, Buffer.length()); 152} 153 154/// getOrCreateFile - Get the file debug info descriptor for the input location. 155llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) { 156 SourceManager &SM = CGM.getContext().getSourceManager(); 157 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 158 159 if (PLoc.isInvalid()) 160 // If the location is not valid then use main input file. 161 return DebugFactory.CreateFile(TheCU.getFilename(), TheCU.getDirectory(), 162 TheCU); 163 164 // Cache the results. 165 const char *fname = PLoc.getFilename(); 166 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it = 167 DIFileCache.find(fname); 168 169 if (it != DIFileCache.end()) { 170 // Verify that the information still exists. 171 if (&*it->second) 172 return llvm::DIFile(cast<llvm::MDNode>(it->second)); 173 } 174 175 llvm::DIFile F = DebugFactory.CreateFile(PLoc.getFilename(), 176 getCurrentDirname(), TheCU); 177 178 DIFileCache[fname] = F; 179 return F; 180 181} 182 183/// getOrCreateMainFile - Get the file info for main compile unit. 184llvm::DIFile CGDebugInfo::getOrCreateMainFile() { 185 return DebugFactory.CreateFile(TheCU.getFilename(), TheCU.getDirectory(), 186 TheCU); 187} 188 189/// getLineNumber - Get line number for the location. If location is invalid 190/// then use current location. 191unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) { 192 assert (CurLoc.isValid() && "Invalid current location!"); 193 SourceManager &SM = CGM.getContext().getSourceManager(); 194 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc); 195 return PLoc.isValid()? PLoc.getLine() : 0; 196} 197 198/// getColumnNumber - Get column number for the location. If location is 199/// invalid then use current location. 200unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) { 201 assert (CurLoc.isValid() && "Invalid current location!"); 202 SourceManager &SM = CGM.getContext().getSourceManager(); 203 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc); 204 return PLoc.isValid()? PLoc.getColumn() : 0; 205} 206 207llvm::StringRef CGDebugInfo::getCurrentDirname() { 208 if (!CWDName.empty()) 209 return CWDName; 210 char *CompDirnamePtr = NULL; 211 llvm::sys::Path CWD = llvm::sys::Path::GetCurrentDirectory(); 212 CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size()); 213 memcpy(CompDirnamePtr, CWD.c_str(), CWD.size()); 214 return CWDName = llvm::StringRef(CompDirnamePtr, CWD.size()); 215} 216 217/// CreateCompileUnit - Create new compile unit. 218void CGDebugInfo::CreateCompileUnit() { 219 220 // Get absolute path name. 221 SourceManager &SM = CGM.getContext().getSourceManager(); 222 std::string MainFileName = CGM.getCodeGenOpts().MainFileName; 223 if (MainFileName.empty()) 224 MainFileName = "<unknown>"; 225 226 // The main file name provided via the "-main-file-name" option contains just 227 // the file name itself with no path information. This file name may have had 228 // a relative path, so we look into the actual file entry for the main 229 // file to determine the real absolute path for the file. 230 std::string MainFileDir; 231 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 232 MainFileDir = MainFile->getDir()->getName(); 233 if (MainFileDir != ".") 234 MainFileName = MainFileDir + "/" + MainFileName; 235 } 236 237 // Save filename string. 238 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length()); 239 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length()); 240 llvm::StringRef Filename(FilenamePtr, MainFileName.length()); 241 242 unsigned LangTag; 243 const LangOptions &LO = CGM.getLangOptions(); 244 if (LO.CPlusPlus) { 245 if (LO.ObjC1) 246 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus; 247 else 248 LangTag = llvm::dwarf::DW_LANG_C_plus_plus; 249 } else if (LO.ObjC1) { 250 LangTag = llvm::dwarf::DW_LANG_ObjC; 251 } else if (LO.C99) { 252 LangTag = llvm::dwarf::DW_LANG_C99; 253 } else { 254 LangTag = llvm::dwarf::DW_LANG_C89; 255 } 256 257 std::string Producer = getClangFullVersion(); 258 259 // Figure out which version of the ObjC runtime we have. 260 unsigned RuntimeVers = 0; 261 if (LO.ObjC1) 262 RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1; 263 264 // Create new compile unit. 265 TheCU = DebugFactory.CreateCompileUnit( 266 LangTag, Filename, getCurrentDirname(), 267 Producer, true, 268 LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers); 269} 270 271/// CreateType - Get the Basic type from the cache or create a new 272/// one if necessary. 273llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) { 274 unsigned Encoding = 0; 275 const char *BTName = NULL; 276 switch (BT->getKind()) { 277 default: 278 case BuiltinType::Void: 279 return llvm::DIType(); 280 case BuiltinType::ObjCClass: 281 return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type, 282 TheCU, "objc_class", 283 getOrCreateMainFile(), 0, 0, 0, 284 0, llvm::DIDescriptor::FlagFwdDecl, 285 llvm::DIType(), llvm::DIArray()); 286 case BuiltinType::ObjCId: { 287 // typedef struct objc_class *Class; 288 // typedef struct objc_object { 289 // Class isa; 290 // } *id; 291 292 llvm::DIType OCTy = 293 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type, 294 TheCU, "objc_class", 295 getOrCreateMainFile(), 0, 0, 0, 0, 296 llvm::DIDescriptor::FlagFwdDecl, 297 llvm::DIType(), llvm::DIArray()); 298 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 299 300 llvm::DIType ISATy = 301 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, 302 TheCU, "", getOrCreateMainFile(), 303 0, Size, 0, 0, 0, OCTy); 304 305 llvm::SmallVector<llvm::DIDescriptor, 16> EltTys; 306 307 llvm::DIType FieldTy = 308 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, TheCU, 309 "isa", getOrCreateMainFile(), 310 0,Size, 0, 0, 0, ISATy); 311 EltTys.push_back(FieldTy); 312 llvm::DIArray Elements = 313 DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size()); 314 315 return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type, 316 TheCU, "objc_object", 317 getOrCreateMainFile(), 318 0, 0, 0, 0, 0, 319 llvm::DIType(), Elements); 320 } 321 case BuiltinType::UChar: 322 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break; 323 case BuiltinType::Char_S: 324 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break; 325 case BuiltinType::UShort: 326 case BuiltinType::UInt: 327 case BuiltinType::ULong: 328 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break; 329 case BuiltinType::Short: 330 case BuiltinType::Int: 331 case BuiltinType::Long: 332 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break; 333 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break; 334 case BuiltinType::Float: 335 case BuiltinType::LongDouble: 336 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break; 337 } 338 339 switch (BT->getKind()) { 340 case BuiltinType::Long: BTName = "long int"; break; 341 case BuiltinType::LongLong: BTName = "long long int"; break; 342 case BuiltinType::ULong: BTName = "long unsigned int"; break; 343 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break; 344 default: 345 BTName = BT->getName(CGM.getContext().getLangOptions()); 346 break; 347 } 348 // Bit size, align and offset of the type. 349 uint64_t Size = CGM.getContext().getTypeSize(BT); 350 uint64_t Align = CGM.getContext().getTypeAlign(BT); 351 uint64_t Offset = 0; 352 llvm::DIType DbgTy = 353 DebugFactory.CreateBasicType(TheCU, BTName, getOrCreateMainFile(), 354 0, Size, Align, Offset, /*flags*/ 0, Encoding); 355 return DbgTy; 356} 357 358llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty, 359 llvm::DIFile Unit) { 360 // Bit size, align and offset of the type. 361 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float; 362 if (Ty->isComplexIntegerType()) 363 Encoding = llvm::dwarf::DW_ATE_lo_user; 364 365 uint64_t Size = CGM.getContext().getTypeSize(Ty); 366 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 367 uint64_t Offset = 0; 368 369 llvm::DIType DbgTy = 370 DebugFactory.CreateBasicType(TheCU, "complex", getOrCreateMainFile(), 371 0, Size, Align, Offset, /*flags*/ 0, Encoding); 372 return DbgTy; 373} 374 375/// CreateCVRType - Get the qualified type from the cache or create 376/// a new one if necessary. 377llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) { 378 QualifierCollector Qc; 379 const Type *T = Qc.strip(Ty); 380 381 // Ignore these qualifiers for now. 382 Qc.removeObjCGCAttr(); 383 Qc.removeAddressSpace(); 384 385 // We will create one Derived type for one qualifier and recurse to handle any 386 // additional ones. 387 unsigned Tag; 388 if (Qc.hasConst()) { 389 Tag = llvm::dwarf::DW_TAG_const_type; 390 Qc.removeConst(); 391 } else if (Qc.hasVolatile()) { 392 Tag = llvm::dwarf::DW_TAG_volatile_type; 393 Qc.removeVolatile(); 394 } else if (Qc.hasRestrict()) { 395 Tag = llvm::dwarf::DW_TAG_restrict_type; 396 Qc.removeRestrict(); 397 } else { 398 assert(Qc.empty() && "Unknown type qualifier for debug info"); 399 return getOrCreateType(QualType(T, 0), Unit); 400 } 401 402 llvm::DIType FromTy = getOrCreateType(Qc.apply(T), Unit); 403 404 // No need to fill in the Name, Line, Size, Alignment, Offset in case of 405 // CVR derived types. 406 llvm::DIType DbgTy = 407 DebugFactory.CreateDerivedType(Tag, Unit, "", Unit, 408 0, 0, 0, 0, 0, FromTy); 409 return DbgTy; 410} 411 412llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty, 413 llvm::DIFile Unit) { 414 llvm::DIType DbgTy = 415 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 416 Ty->getPointeeType(), Unit); 417 return DbgTy; 418} 419 420llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty, 421 llvm::DIFile Unit) { 422 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 423 Ty->getPointeeType(), Unit); 424} 425 426/// CreatePointeeType - Create PointTee type. If Pointee is a record 427/// then emit record's fwd if debug info size reduction is enabled. 428llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy, 429 llvm::DIFile Unit) { 430 if (!CGM.getCodeGenOpts().LimitDebugInfo) 431 return getOrCreateType(PointeeTy, Unit); 432 433 if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) { 434 RecordDecl *RD = RTy->getDecl(); 435 unsigned RTag; 436 if (RD->isStruct()) 437 RTag = llvm::dwarf::DW_TAG_structure_type; 438 else if (RD->isUnion()) 439 RTag = llvm::dwarf::DW_TAG_union_type; 440 else { 441 assert(RD->isClass() && "Unknown RecordType!"); 442 RTag = llvm::dwarf::DW_TAG_class_type; 443 } 444 445 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 446 unsigned Line = getLineNumber(RD->getLocation()); 447 llvm::DIDescriptor FDContext = 448 getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit); 449 450 return 451 DebugFactory.CreateCompositeType(RTag, FDContext, RD->getName(), 452 DefUnit, Line, 0, 0, 0, 453 llvm::DIType::FlagFwdDecl, 454 llvm::DIType(), llvm::DIArray()); 455 } 456 return getOrCreateType(PointeeTy, Unit); 457 458} 459 460llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag, 461 const Type *Ty, 462 QualType PointeeTy, 463 llvm::DIFile Unit) { 464 // Bit size, align and offset of the type. 465 466 // Size is always the size of a pointer. We can't use getTypeSize here 467 // because that does not return the correct value for references. 468 uint64_t Size = 469 CGM.getContext().Target.getPointerWidth(PointeeTy.getAddressSpace()); 470 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 471 472 return DebugFactory.CreateDerivedType(Tag, Unit, "", Unit, 473 0, Size, Align, 0, 0, 474 CreatePointeeType(PointeeTy, Unit)); 475 476} 477 478llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty, 479 llvm::DIFile Unit) { 480 if (BlockLiteralGenericSet) 481 return BlockLiteralGeneric; 482 483 unsigned Tag = llvm::dwarf::DW_TAG_structure_type; 484 485 llvm::SmallVector<llvm::DIDescriptor, 5> EltTys; 486 487 llvm::DIType FieldTy; 488 489 QualType FType; 490 uint64_t FieldSize, FieldOffset; 491 unsigned FieldAlign; 492 493 llvm::DIArray Elements; 494 llvm::DIType EltTy, DescTy; 495 496 FieldOffset = 0; 497 FType = CGM.getContext().UnsignedLongTy; 498 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset)); 499 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset)); 500 501 Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size()); 502 EltTys.clear(); 503 504 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock; 505 unsigned LineNo = getLineNumber(CurLoc); 506 507 EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_descriptor", 508 Unit, LineNo, FieldOffset, 0, 0, 509 Flags, llvm::DIType(), Elements); 510 511 // Bit size, align and offset of the type. 512 uint64_t Size = CGM.getContext().getTypeSize(Ty); 513 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 514 515 DescTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, 516 Unit, "", Unit, 517 LineNo, Size, Align, 0, 0, EltTy); 518 519 FieldOffset = 0; 520 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 521 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 522 FType = CGM.getContext().IntTy; 523 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 524 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset)); 525 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 526 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset)); 527 528 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 529 FieldTy = DescTy; 530 FieldSize = CGM.getContext().getTypeSize(Ty); 531 FieldAlign = CGM.getContext().getTypeAlign(Ty); 532 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit, 533 "__descriptor", Unit, 534 LineNo, FieldSize, FieldAlign, 535 FieldOffset, 0, FieldTy); 536 EltTys.push_back(FieldTy); 537 538 FieldOffset += FieldSize; 539 Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size()); 540 541 EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_literal_generic", 542 Unit, LineNo, FieldOffset, 0, 0, 543 Flags, llvm::DIType(), Elements); 544 545 BlockLiteralGenericSet = true; 546 BlockLiteralGeneric 547 = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit, 548 "", Unit, 549 LineNo, Size, Align, 0, 0, EltTy); 550 return BlockLiteralGeneric; 551} 552 553llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, 554 llvm::DIFile Unit) { 555 // Typedefs are derived from some other type. If we have a typedef of a 556 // typedef, make sure to emit the whole chain. 557 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit); 558 559 // We don't set size information, but do specify where the typedef was 560 // declared. 561 unsigned Line = getLineNumber(Ty->getDecl()->getLocation()); 562 563 llvm::DIDescriptor TyContext 564 = getContextDescriptor(dyn_cast<Decl>(Ty->getDecl()->getDeclContext()), 565 Unit); 566 llvm::DIType DbgTy = 567 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_typedef, 568 TyContext, 569 Ty->getDecl()->getName(), Unit, 570 Line, 0, 0, 0, 0, Src); 571 return DbgTy; 572} 573 574llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty, 575 llvm::DIFile Unit) { 576 llvm::SmallVector<llvm::DIDescriptor, 16> EltTys; 577 578 // Add the result type at least. 579 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit)); 580 581 // Set up remainder of arguments if there is a prototype. 582 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'! 583 if (isa<FunctionNoProtoType>(Ty)) 584 EltTys.push_back(DebugFactory.CreateUnspecifiedParameter()); 585 else if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) { 586 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i) 587 EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit)); 588 } 589 590 llvm::DIArray EltTypeArray = 591 DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size()); 592 593 llvm::DIType DbgTy = 594 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type, 595 Unit, "", Unit, 596 0, 0, 0, 0, 0, 597 llvm::DIType(), EltTypeArray); 598 return DbgTy; 599} 600 601/// CollectRecordFields - A helper function to collect debug info for 602/// record fields. This is used while creating debug info entry for a Record. 603void CGDebugInfo:: 604CollectRecordFields(const RecordDecl *RD, llvm::DIFile Unit, 605 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) { 606 unsigned FieldNo = 0; 607 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 608 for (RecordDecl::field_iterator I = RD->field_begin(), 609 E = RD->field_end(); 610 I != E; ++I, ++FieldNo) { 611 FieldDecl *Field = *I; 612 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 613 llvm::StringRef FieldName = Field->getName(); 614 615 // Ignore unnamed fields. Do not ignore unnamed records. 616 if (FieldName.empty() && !isa<RecordType>(Field->getType())) 617 continue; 618 619 // Get the location for the field. 620 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation()); 621 unsigned FieldLine = getLineNumber(Field->getLocation()); 622 QualType FType = Field->getType(); 623 uint64_t FieldSize = 0; 624 unsigned FieldAlign = 0; 625 if (!FType->isIncompleteArrayType()) { 626 627 // Bit size, align and offset of the type. 628 FieldSize = CGM.getContext().getTypeSize(FType); 629 Expr *BitWidth = Field->getBitWidth(); 630 if (BitWidth) 631 FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue(); 632 FieldAlign = CGM.getContext().getTypeAlign(FType); 633 } 634 635 uint64_t FieldOffset = RL.getFieldOffset(FieldNo); 636 637 unsigned Flags = 0; 638 AccessSpecifier Access = I->getAccess(); 639 if (Access == clang::AS_private) 640 Flags |= llvm::DIDescriptor::FlagPrivate; 641 else if (Access == clang::AS_protected) 642 Flags |= llvm::DIDescriptor::FlagProtected; 643 644 // Create a DW_TAG_member node to remember the offset of this field in the 645 // struct. FIXME: This is an absolutely insane way to capture this 646 // information. When we gut debug info, this should be fixed. 647 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit, 648 FieldName, FieldDefUnit, 649 FieldLine, FieldSize, FieldAlign, 650 FieldOffset, Flags, FieldTy); 651 EltTys.push_back(FieldTy); 652 } 653} 654 655/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This 656/// function type is not updated to include implicit "this" pointer. Use this 657/// routine to get a method type which includes "this" pointer. 658llvm::DIType 659CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method, 660 llvm::DIFile Unit) { 661 llvm::DIType FnTy 662 = getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoType>(), 663 0), 664 Unit); 665 666 // Add "this" pointer. 667 668 llvm::DIArray Args = llvm::DICompositeType(FnTy).getTypeArray(); 669 assert (Args.getNumElements() && "Invalid number of arguments!"); 670 671 llvm::SmallVector<llvm::DIDescriptor, 16> Elts; 672 673 // First element is always return type. For 'void' functions it is NULL. 674 Elts.push_back(Args.getElement(0)); 675 676 if (!Method->isStatic()) 677 { 678 // "this" pointer is always first argument. 679 ASTContext &Context = CGM.getContext(); 680 QualType ThisPtr = 681 Context.getPointerType(Context.getTagDeclType(Method->getParent())); 682 llvm::DIType ThisPtrType = 683 DebugFactory.CreateArtificialType(getOrCreateType(ThisPtr, Unit)); 684 685 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType; 686 Elts.push_back(ThisPtrType); 687 } 688 689 // Copy rest of the arguments. 690 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i) 691 Elts.push_back(Args.getElement(i)); 692 693 llvm::DIArray EltTypeArray = 694 DebugFactory.GetOrCreateArray(Elts.data(), Elts.size()); 695 696 return 697 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type, 698 Unit, "", Unit, 699 0, 0, 0, 0, 0, 700 llvm::DIType(), EltTypeArray); 701} 702 703/// isFunctionLocalClass - Return true if CXXRecordDecl is defined 704/// inside a function. 705static bool isFunctionLocalClass(const CXXRecordDecl *RD) { 706 if (const CXXRecordDecl *NRD = 707 dyn_cast<CXXRecordDecl>(RD->getDeclContext())) 708 return isFunctionLocalClass(NRD); 709 else if (isa<FunctionDecl>(RD->getDeclContext())) 710 return true; 711 return false; 712 713} 714/// CreateCXXMemberFunction - A helper function to create a DISubprogram for 715/// a single member function GlobalDecl. 716llvm::DISubprogram 717CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method, 718 llvm::DIFile Unit, 719 llvm::DIType RecordTy) { 720 bool IsCtorOrDtor = 721 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method); 722 723 llvm::StringRef MethodName = getFunctionName(Method); 724 llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit); 725 726 // Since a single ctor/dtor corresponds to multiple functions, it doesn't 727 // make sense to give a single ctor/dtor a linkage name. 728 llvm::StringRef MethodLinkageName; 729 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent())) 730 MethodLinkageName = CGM.getMangledName(Method); 731 732 // Get the location for the method. 733 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation()); 734 unsigned MethodLine = getLineNumber(Method->getLocation()); 735 736 // Collect virtual method info. 737 llvm::DIType ContainingType; 738 unsigned Virtuality = 0; 739 unsigned VIndex = 0; 740 741 if (Method->isVirtual()) { 742 if (Method->isPure()) 743 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual; 744 else 745 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual; 746 747 // It doesn't make sense to give a virtual destructor a vtable index, 748 // since a single destructor has two entries in the vtable. 749 if (!isa<CXXDestructorDecl>(Method)) 750 VIndex = CGM.getVTables().getMethodVTableIndex(Method); 751 ContainingType = RecordTy; 752 } 753 754 unsigned Flags = 0; 755 if (Method->isImplicit()) 756 Flags |= llvm::DIDescriptor::FlagArtificial; 757 AccessSpecifier Access = Method->getAccess(); 758 if (Access == clang::AS_private) 759 Flags |= llvm::DIDescriptor::FlagPrivate; 760 else if (Access == clang::AS_protected) 761 Flags |= llvm::DIDescriptor::FlagProtected; 762 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) { 763 if (CXXC->isExplicit()) 764 Flags |= llvm::DIDescriptor::FlagExplicit; 765 } else if (const CXXConversionDecl *CXXC = 766 dyn_cast<CXXConversionDecl>(Method)) { 767 if (CXXC->isExplicit()) 768 Flags |= llvm::DIDescriptor::FlagExplicit; 769 } 770 if (Method->hasPrototype()) 771 Flags |= llvm::DIDescriptor::FlagPrototyped; 772 773 llvm::DISubprogram SP = 774 DebugFactory.CreateSubprogram(RecordTy , MethodName, MethodName, 775 MethodLinkageName, 776 MethodDefUnit, MethodLine, 777 MethodTy, /*isLocalToUnit=*/false, 778 /* isDefinition=*/ false, 779 Virtuality, VIndex, ContainingType, 780 Flags, 781 CGM.getLangOptions().Optimize); 782 783 // Don't cache ctors or dtors since we have to emit multiple functions for 784 // a single ctor or dtor. 785 if (!IsCtorOrDtor && Method->isThisDeclarationADefinition()) 786 SPCache[Method] = llvm::WeakVH(SP); 787 788 return SP; 789} 790 791/// CollectCXXMemberFunctions - A helper function to collect debug info for 792/// C++ member functions.This is used while creating debug info entry for 793/// a Record. 794void CGDebugInfo:: 795CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit, 796 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys, 797 llvm::DIType RecordTy) { 798 for(CXXRecordDecl::method_iterator I = RD->method_begin(), 799 E = RD->method_end(); I != E; ++I) { 800 const CXXMethodDecl *Method = *I; 801 802 if (Method->isImplicit() && !Method->isUsed()) 803 continue; 804 805 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy)); 806 } 807} 808 809/// CollectCXXFriends - A helper function to collect debug info for 810/// C++ base classes. This is used while creating debug info entry for 811/// a Record. 812void CGDebugInfo:: 813CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit, 814 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys, 815 llvm::DIType RecordTy) { 816 817 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(), 818 BE = RD->friend_end(); BI != BE; ++BI) { 819 820 TypeSourceInfo *TInfo = (*BI)->getFriendType(); 821 if(TInfo) 822 { 823 llvm::DIType Ty = getOrCreateType(TInfo->getType(), Unit); 824 825 llvm::DIType DTy = 826 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_friend, 827 RecordTy, llvm::StringRef(), 828 Unit, 0, 0, 0, 829 0, 0, Ty); 830 831 EltTys.push_back(DTy); 832 } 833 834 } 835} 836 837/// CollectCXXBases - A helper function to collect debug info for 838/// C++ base classes. This is used while creating debug info entry for 839/// a Record. 840void CGDebugInfo:: 841CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit, 842 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys, 843 llvm::DIType RecordTy) { 844 845 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 846 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(), 847 BE = RD->bases_end(); BI != BE; ++BI) { 848 unsigned BFlags = 0; 849 uint64_t BaseOffset; 850 851 const CXXRecordDecl *Base = 852 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl()); 853 854 if (BI->isVirtual()) { 855 // virtual base offset offset is -ve. The code generator emits dwarf 856 // expression where it expects +ve number. 857 BaseOffset = 0 - CGM.getVTables().getVirtualBaseOffsetOffset(RD, Base); 858 BFlags = llvm::DIDescriptor::FlagVirtual; 859 } else 860 BaseOffset = RL.getBaseClassOffsetInBits(Base); 861 862 AccessSpecifier Access = BI->getAccessSpecifier(); 863 if (Access == clang::AS_private) 864 BFlags |= llvm::DIDescriptor::FlagPrivate; 865 else if (Access == clang::AS_protected) 866 BFlags |= llvm::DIDescriptor::FlagProtected; 867 868 llvm::DIType DTy = 869 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance, 870 RecordTy, llvm::StringRef(), 871 Unit, 0, 0, 0, 872 BaseOffset, BFlags, 873 getOrCreateType(BI->getType(), 874 Unit)); 875 EltTys.push_back(DTy); 876 } 877} 878 879/// getOrCreateVTablePtrType - Return debug info descriptor for vtable. 880llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) { 881 if (VTablePtrType.isValid()) 882 return VTablePtrType; 883 884 ASTContext &Context = CGM.getContext(); 885 886 /* Function type */ 887 llvm::DIDescriptor STy = getOrCreateType(Context.IntTy, Unit); 888 llvm::DIArray SElements = DebugFactory.GetOrCreateArray(&STy, 1); 889 llvm::DIType SubTy = 890 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type, 891 Unit, "", Unit, 892 0, 0, 0, 0, 0, llvm::DIType(), SElements); 893 894 unsigned Size = Context.getTypeSize(Context.VoidPtrTy); 895 llvm::DIType vtbl_ptr_type 896 = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, 897 Unit, "__vtbl_ptr_type", Unit, 898 0, Size, 0, 0, 0, SubTy); 899 900 VTablePtrType = 901 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, 902 Unit, "", Unit, 903 0, Size, 0, 0, 0, vtbl_ptr_type); 904 return VTablePtrType; 905} 906 907/// getVTableName - Get vtable name for the given Class. 908llvm::StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) { 909 // Otherwise construct gdb compatible name name. 910 std::string Name = "_vptr$" + RD->getNameAsString(); 911 912 // Copy this name on the side and use its reference. 913 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length()); 914 memcpy(StrPtr, Name.data(), Name.length()); 915 return llvm::StringRef(StrPtr, Name.length()); 916} 917 918 919/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate 920/// debug info entry in EltTys vector. 921void CGDebugInfo:: 922CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit, 923 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) { 924 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 925 926 // If there is a primary base then it will hold vtable info. 927 if (RL.getPrimaryBase()) 928 return; 929 930 // If this class is not dynamic then there is not any vtable info to collect. 931 if (!RD->isDynamicClass()) 932 return; 933 934 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 935 llvm::DIType VPTR 936 = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit, 937 getVTableName(RD), Unit, 938 0, Size, 0, 0, 0, 939 getOrCreateVTablePtrType(Unit)); 940 EltTys.push_back(VPTR); 941} 942 943/// getOrCreateRecordType - Emit record type's standalone debug info. 944llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy, 945 SourceLocation Loc) { 946 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc)); 947 DebugFactory.RecordType(T); 948 return T; 949} 950 951/// CreateType - get structure or union type. 952llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, 953 llvm::DIFile Unit) { 954 RecordDecl *RD = Ty->getDecl(); 955 956 unsigned Tag; 957 if (RD->isStruct()) 958 Tag = llvm::dwarf::DW_TAG_structure_type; 959 else if (RD->isUnion()) 960 Tag = llvm::dwarf::DW_TAG_union_type; 961 else { 962 assert(RD->isClass() && "Unknown RecordType!"); 963 Tag = llvm::dwarf::DW_TAG_class_type; 964 } 965 966 // Get overall information about the record type for the debug info. 967 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 968 unsigned Line = getLineNumber(RD->getLocation()); 969 970 // Records and classes and unions can all be recursive. To handle them, we 971 // first generate a debug descriptor for the struct as a forward declaration. 972 // Then (if it is a definition) we go through and get debug info for all of 973 // its members. Finally, we create a descriptor for the complete type (which 974 // may refer to the forward decl if the struct is recursive) and replace all 975 // uses of the forward declaration with the final definition. 976 llvm::DIDescriptor FDContext = 977 getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit); 978 979 // If this is just a forward declaration, construct an appropriately 980 // marked node and just return it. 981 if (!RD->getDefinition()) { 982 llvm::DICompositeType FwdDecl = 983 DebugFactory.CreateCompositeType(Tag, FDContext, RD->getName(), 984 DefUnit, Line, 0, 0, 0, 985 llvm::DIDescriptor::FlagFwdDecl, 986 llvm::DIType(), llvm::DIArray()); 987 988 return FwdDecl; 989 } 990 991 llvm::DIType FwdDecl = DebugFactory.CreateTemporaryType(); 992 993 llvm::MDNode *MN = FwdDecl; 994 llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN; 995 // Otherwise, insert it into the TypeCache so that recursive uses will find 996 // it. 997 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl; 998 // Push the struct on region stack. 999 RegionStack.push_back(FwdDeclNode); 1000 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl); 1001 1002 // Convert all the elements. 1003 llvm::SmallVector<llvm::DIDescriptor, 16> EltTys; 1004 1005 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 1006 if (CXXDecl) { 1007 CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl); 1008 CollectVTableInfo(CXXDecl, Unit, EltTys); 1009 } 1010 1011 // Collect static variables with initializers. 1012 for (RecordDecl::decl_iterator I = RD->decls_begin(), E = RD->decls_end(); 1013 I != E; ++I) 1014 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) { 1015 if (const Expr *Init = V->getInit()) { 1016 Expr::EvalResult Result; 1017 if (Init->Evaluate(Result, CGM.getContext()) && Result.Val.isInt()) { 1018 llvm::ConstantInt *CI 1019 = llvm::ConstantInt::get(CGM.getLLVMContext(), Result.Val.getInt()); 1020 1021 // Create the descriptor for static variable. 1022 llvm::DIFile VUnit = getOrCreateFile(V->getLocation()); 1023 llvm::StringRef VName = V->getName(); 1024 llvm::DIType VTy = getOrCreateType(V->getType(), VUnit); 1025 // Do not use DIGlobalVariable for enums. 1026 if (VTy.getTag() != llvm::dwarf::DW_TAG_enumeration_type) { 1027 DebugFactory.CreateGlobalVariable(FwdDecl, VName, VName, VName, VUnit, 1028 getLineNumber(V->getLocation()), 1029 VTy, true, true, CI); 1030 } 1031 } 1032 } 1033 } 1034 1035 CollectRecordFields(RD, Unit, EltTys); 1036 llvm::MDNode *ContainingType = NULL; 1037 if (CXXDecl) { 1038 CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl); 1039 CollectCXXFriends(CXXDecl, Unit, EltTys, FwdDecl); 1040 1041 // A class's primary base or the class itself contains the vtable. 1042 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 1043 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) { 1044 // Seek non virtual primary base root. 1045 while (1) { 1046 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase); 1047 const CXXRecordDecl *PBT = BRL.getPrimaryBase(); 1048 if (PBT && !BRL.isPrimaryBaseVirtual()) 1049 PBase = PBT; 1050 else 1051 break; 1052 } 1053 ContainingType = 1054 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit); 1055 } 1056 else if (CXXDecl->isDynamicClass()) 1057 ContainingType = FwdDecl; 1058 } 1059 1060 llvm::DIArray Elements = 1061 DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size()); 1062 1063 // Bit size, align and offset of the type. 1064 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1065 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1066 1067 RegionStack.pop_back(); 1068 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI = 1069 RegionMap.find(Ty->getDecl()); 1070 if (RI != RegionMap.end()) 1071 RegionMap.erase(RI); 1072 1073 llvm::DIDescriptor RDContext = 1074 getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit); 1075 1076 llvm::StringRef RDName = RD->getName(); 1077 // If this is a class, include the template arguments also. 1078 if (Tag == llvm::dwarf::DW_TAG_class_type) 1079 RDName = getClassName(RD); 1080 1081 llvm::DICompositeType RealDecl = 1082 DebugFactory.CreateCompositeType(Tag, RDContext, 1083 RDName, 1084 DefUnit, Line, Size, Align, 0, 0, 1085 llvm::DIType(), Elements, 1086 0, ContainingType); 1087 1088 // Now that we have a real decl for the struct, replace anything using the 1089 // old decl with the new one. This will recursively update the debug info. 1090 llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl); 1091 RegionMap[RD] = llvm::WeakVH(RealDecl); 1092 return RealDecl; 1093} 1094 1095/// CreateType - get objective-c object type. 1096llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty, 1097 llvm::DIFile Unit) { 1098 // Ignore protocols. 1099 return getOrCreateType(Ty->getBaseType(), Unit); 1100} 1101 1102/// CreateType - get objective-c interface type. 1103llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, 1104 llvm::DIFile Unit) { 1105 ObjCInterfaceDecl *ID = Ty->getDecl(); 1106 unsigned Tag = llvm::dwarf::DW_TAG_structure_type; 1107 1108 // Get overall information about the record type for the debug info. 1109 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation()); 1110 unsigned Line = getLineNumber(ID->getLocation()); 1111 unsigned RuntimeLang = TheCU.getLanguage(); 1112 1113 // If this is just a forward declaration, return a special forward-declaration 1114 // debug type. 1115 if (ID->isForwardDecl()) { 1116 llvm::DICompositeType FwdDecl = 1117 DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(), 1118 DefUnit, Line, 0, 0, 0, 0, 1119 llvm::DIType(), llvm::DIArray(), 1120 RuntimeLang); 1121 return FwdDecl; 1122 } 1123 1124 // To handle recursive interface, we 1125 // first generate a debug descriptor for the struct as a forward declaration. 1126 // Then (if it is a definition) we go through and get debug info for all of 1127 // its members. Finally, we create a descriptor for the complete type (which 1128 // may refer to the forward decl if the struct is recursive) and replace all 1129 // uses of the forward declaration with the final definition. 1130 llvm::DIType FwdDecl = DebugFactory.CreateTemporaryType(); 1131 1132 llvm::MDNode *MN = FwdDecl; 1133 llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN; 1134 // Otherwise, insert it into the TypeCache so that recursive uses will find 1135 // it. 1136 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl; 1137 // Push the struct on region stack. 1138 RegionStack.push_back(FwdDeclNode); 1139 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl); 1140 1141 // Convert all the elements. 1142 llvm::SmallVector<llvm::DIDescriptor, 16> EltTys; 1143 1144 ObjCInterfaceDecl *SClass = ID->getSuperClass(); 1145 if (SClass) { 1146 llvm::DIType SClassTy = 1147 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit); 1148 llvm::DIType InhTag = 1149 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance, 1150 Unit, "", Unit, 0, 0, 0, 1151 0 /* offset */, 0, SClassTy); 1152 EltTys.push_back(InhTag); 1153 } 1154 1155 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID); 1156 1157 unsigned FieldNo = 0; 1158 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field; 1159 Field = Field->getNextIvar(), ++FieldNo) { 1160 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 1161 1162 llvm::StringRef FieldName = Field->getName(); 1163 1164 // Ignore unnamed fields. 1165 if (FieldName.empty()) 1166 continue; 1167 1168 // Get the location for the field. 1169 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation()); 1170 unsigned FieldLine = getLineNumber(Field->getLocation()); 1171 QualType FType = Field->getType(); 1172 uint64_t FieldSize = 0; 1173 unsigned FieldAlign = 0; 1174 1175 if (!FType->isIncompleteArrayType()) { 1176 1177 // Bit size, align and offset of the type. 1178 FieldSize = CGM.getContext().getTypeSize(FType); 1179 Expr *BitWidth = Field->getBitWidth(); 1180 if (BitWidth) 1181 FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue(); 1182 1183 FieldAlign = CGM.getContext().getTypeAlign(FType); 1184 } 1185 1186 uint64_t FieldOffset = RL.getFieldOffset(FieldNo); 1187 1188 unsigned Flags = 0; 1189 if (Field->getAccessControl() == ObjCIvarDecl::Protected) 1190 Flags = llvm::DIDescriptor::FlagProtected; 1191 else if (Field->getAccessControl() == ObjCIvarDecl::Private) 1192 Flags = llvm::DIDescriptor::FlagPrivate; 1193 1194 // Create a DW_TAG_member node to remember the offset of this field in the 1195 // struct. FIXME: This is an absolutely insane way to capture this 1196 // information. When we gut debug info, this should be fixed. 1197 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit, 1198 FieldName, FieldDefUnit, 1199 FieldLine, FieldSize, FieldAlign, 1200 FieldOffset, Flags, FieldTy); 1201 EltTys.push_back(FieldTy); 1202 } 1203 1204 llvm::DIArray Elements = 1205 DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size()); 1206 1207 RegionStack.pop_back(); 1208 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI = 1209 RegionMap.find(Ty->getDecl()); 1210 if (RI != RegionMap.end()) 1211 RegionMap.erase(RI); 1212 1213 // Bit size, align and offset of the type. 1214 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1215 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1216 1217 llvm::DICompositeType RealDecl = 1218 DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(), DefUnit, 1219 Line, Size, Align, 0, 0, llvm::DIType(), 1220 Elements, RuntimeLang); 1221 1222 // Now that we have a real decl for the struct, replace anything using the 1223 // old decl with the new one. This will recursively update the debug info. 1224 llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl); 1225 RegionMap[ID] = llvm::WeakVH(RealDecl); 1226 1227 return RealDecl; 1228} 1229 1230llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty, 1231 llvm::DIFile Unit) { 1232 return CreateEnumType(Ty->getDecl(), Unit); 1233 1234} 1235 1236llvm::DIType CGDebugInfo::CreateType(const TagType *Ty, 1237 llvm::DIFile Unit) { 1238 if (const RecordType *RT = dyn_cast<RecordType>(Ty)) 1239 return CreateType(RT, Unit); 1240 else if (const EnumType *ET = dyn_cast<EnumType>(Ty)) 1241 return CreateType(ET, Unit); 1242 1243 return llvm::DIType(); 1244} 1245 1246llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, 1247 llvm::DIFile Unit) { 1248 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit); 1249 uint64_t NumElems = Ty->getNumElements(); 1250 if (NumElems > 0) 1251 --NumElems; 1252 1253 llvm::DIDescriptor Subscript = DebugFactory.GetOrCreateSubrange(0, NumElems); 1254 llvm::DIArray SubscriptArray = DebugFactory.GetOrCreateArray(&Subscript, 1); 1255 1256 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1257 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1258 1259 return 1260 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_vector_type, 1261 Unit, "", Unit, 1262 0, Size, Align, 0, 0, 1263 ElementTy, SubscriptArray); 1264} 1265 1266llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty, 1267 llvm::DIFile Unit) { 1268 uint64_t Size; 1269 uint64_t Align; 1270 1271 1272 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types 1273 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) { 1274 Size = 0; 1275 Align = 1276 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT)); 1277 } else if (Ty->isIncompleteArrayType()) { 1278 Size = 0; 1279 Align = CGM.getContext().getTypeAlign(Ty->getElementType()); 1280 } else { 1281 // Size and align of the whole array, not the element type. 1282 Size = CGM.getContext().getTypeSize(Ty); 1283 Align = CGM.getContext().getTypeAlign(Ty); 1284 } 1285 1286 // Add the dimensions of the array. FIXME: This loses CV qualifiers from 1287 // interior arrays, do we care? Why aren't nested arrays represented the 1288 // obvious/recursive way? 1289 llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts; 1290 QualType EltTy(Ty, 0); 1291 if (Ty->isIncompleteArrayType()) 1292 EltTy = Ty->getElementType(); 1293 else { 1294 while ((Ty = dyn_cast<ArrayType>(EltTy))) { 1295 uint64_t Upper = 0; 1296 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) 1297 if (CAT->getSize().getZExtValue()) 1298 Upper = CAT->getSize().getZExtValue() - 1; 1299 // FIXME: Verify this is right for VLAs. 1300 Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper)); 1301 EltTy = Ty->getElementType(); 1302 } 1303 } 1304 1305 llvm::DIArray SubscriptArray = 1306 DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size()); 1307 1308 llvm::DIType DbgTy = 1309 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_array_type, 1310 Unit, "", Unit, 1311 0, Size, Align, 0, 0, 1312 getOrCreateType(EltTy, Unit), 1313 SubscriptArray); 1314 return DbgTy; 1315} 1316 1317llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty, 1318 llvm::DIFile Unit) { 1319 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, 1320 Ty, Ty->getPointeeType(), Unit); 1321} 1322 1323llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty, 1324 llvm::DIFile U) { 1325 QualType PointerDiffTy = CGM.getContext().getPointerDiffType(); 1326 llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U); 1327 1328 if (!Ty->getPointeeType()->isFunctionType()) { 1329 // We have a data member pointer type. 1330 return PointerDiffDITy; 1331 } 1332 1333 // We have a member function pointer type. Treat it as a struct with two 1334 // ptrdiff_t members. 1335 std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty); 1336 1337 uint64_t FieldOffset = 0; 1338 llvm::DIDescriptor ElementTypes[2]; 1339 1340 // FIXME: This should probably be a function type instead. 1341 ElementTypes[0] = 1342 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U, 1343 "ptr", U, 0, 1344 Info.first, Info.second, FieldOffset, 0, 1345 PointerDiffDITy); 1346 FieldOffset += Info.first; 1347 1348 ElementTypes[1] = 1349 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U, 1350 "ptr", U, 0, 1351 Info.first, Info.second, FieldOffset, 0, 1352 PointerDiffDITy); 1353 1354 llvm::DIArray Elements = 1355 DebugFactory.GetOrCreateArray(&ElementTypes[0], 1356 llvm::array_lengthof(ElementTypes)); 1357 1358 return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type, 1359 U, llvm::StringRef("test"), 1360 U, 0, FieldOffset, 1361 0, 0, 0, llvm::DIType(), Elements); 1362} 1363 1364/// CreateEnumType - get enumeration type. 1365llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED, llvm::DIFile Unit){ 1366 llvm::SmallVector<llvm::DIDescriptor, 32> Enumerators; 1367 1368 // Create DIEnumerator elements for each enumerator. 1369 for (EnumDecl::enumerator_iterator 1370 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end(); 1371 Enum != EnumEnd; ++Enum) { 1372 Enumerators.push_back(DebugFactory.CreateEnumerator(Enum->getName(), 1373 Enum->getInitVal().getZExtValue())); 1374 } 1375 1376 // Return a CompositeType for the enum itself. 1377 llvm::DIArray EltArray = 1378 DebugFactory.GetOrCreateArray(Enumerators.data(), Enumerators.size()); 1379 1380 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation()); 1381 unsigned Line = getLineNumber(ED->getLocation()); 1382 uint64_t Size = 0; 1383 uint64_t Align = 0; 1384 if (!ED->getTypeForDecl()->isIncompleteType()) { 1385 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); 1386 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl()); 1387 } 1388 llvm::DIDescriptor EnumContext = 1389 getContextDescriptor(dyn_cast<Decl>(ED->getDeclContext()), Unit); 1390 llvm::DIType DbgTy = 1391 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type, 1392 EnumContext, ED->getName(), 1393 DefUnit, Line, Size, Align, 0, 0, 1394 llvm::DIType(), EltArray); 1395 return DbgTy; 1396} 1397 1398static QualType UnwrapTypeForDebugInfo(QualType T) { 1399 do { 1400 QualType LastT = T; 1401 switch (T->getTypeClass()) { 1402 default: 1403 return T; 1404 case Type::TemplateSpecialization: 1405 T = cast<TemplateSpecializationType>(T)->desugar(); 1406 break; 1407 case Type::TypeOfExpr: { 1408 TypeOfExprType *Ty = cast<TypeOfExprType>(T); 1409 T = Ty->getUnderlyingExpr()->getType(); 1410 break; 1411 } 1412 case Type::TypeOf: 1413 T = cast<TypeOfType>(T)->getUnderlyingType(); 1414 break; 1415 case Type::Decltype: 1416 T = cast<DecltypeType>(T)->getUnderlyingType(); 1417 break; 1418 case Type::Elaborated: 1419 T = cast<ElaboratedType>(T)->getNamedType(); 1420 break; 1421 case Type::SubstTemplateTypeParm: 1422 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType(); 1423 break; 1424 } 1425 1426 assert(T != LastT && "Type unwrapping failed to unwrap!"); 1427 if (T == LastT) 1428 return T; 1429 } while (true); 1430 1431 return T; 1432} 1433 1434/// getOrCreateType - Get the type from the cache or create a new 1435/// one if necessary. 1436llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, 1437 llvm::DIFile Unit) { 1438 if (Ty.isNull()) 1439 return llvm::DIType(); 1440 1441 // Unwrap the type as needed for debug information. 1442 Ty = UnwrapTypeForDebugInfo(Ty); 1443 1444 // Check for existing entry. 1445 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 1446 TypeCache.find(Ty.getAsOpaquePtr()); 1447 if (it != TypeCache.end()) { 1448 // Verify that the debug info still exists. 1449 if (&*it->second) 1450 return llvm::DIType(cast<llvm::MDNode>(it->second)); 1451 } 1452 1453 // Otherwise create the type. 1454 llvm::DIType Res = CreateTypeNode(Ty, Unit); 1455 1456 // And update the type cache. 1457 TypeCache[Ty.getAsOpaquePtr()] = Res; 1458 return Res; 1459} 1460 1461/// CreateTypeNode - Create a new debug type node. 1462llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, 1463 llvm::DIFile Unit) { 1464 // Handle qualifiers, which recursively handles what they refer to. 1465 if (Ty.hasLocalQualifiers()) 1466 return CreateQualifiedType(Ty, Unit); 1467 1468 const char *Diag = 0; 1469 1470 // Work out details of type. 1471 switch (Ty->getTypeClass()) { 1472#define TYPE(Class, Base) 1473#define ABSTRACT_TYPE(Class, Base) 1474#define NON_CANONICAL_TYPE(Class, Base) 1475#define DEPENDENT_TYPE(Class, Base) case Type::Class: 1476#include "clang/AST/TypeNodes.def" 1477 assert(false && "Dependent types cannot show up in debug information"); 1478 1479 // FIXME: Handle these. 1480 case Type::ExtVector: 1481 return llvm::DIType(); 1482 1483 case Type::Vector: 1484 return CreateType(cast<VectorType>(Ty), Unit); 1485 case Type::ObjCObjectPointer: 1486 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit); 1487 case Type::ObjCObject: 1488 return CreateType(cast<ObjCObjectType>(Ty), Unit); 1489 case Type::ObjCInterface: 1490 return CreateType(cast<ObjCInterfaceType>(Ty), Unit); 1491 case Type::Builtin: return CreateType(cast<BuiltinType>(Ty)); 1492 case Type::Complex: return CreateType(cast<ComplexType>(Ty), Unit); 1493 case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit); 1494 case Type::BlockPointer: 1495 return CreateType(cast<BlockPointerType>(Ty), Unit); 1496 case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit); 1497 case Type::Record: 1498 case Type::Enum: 1499 return CreateType(cast<TagType>(Ty), Unit); 1500 case Type::FunctionProto: 1501 case Type::FunctionNoProto: 1502 return CreateType(cast<FunctionType>(Ty), Unit); 1503 case Type::ConstantArray: 1504 case Type::VariableArray: 1505 case Type::IncompleteArray: 1506 return CreateType(cast<ArrayType>(Ty), Unit); 1507 1508 case Type::LValueReference: 1509 return CreateType(cast<LValueReferenceType>(Ty), Unit); 1510 1511 case Type::MemberPointer: 1512 return CreateType(cast<MemberPointerType>(Ty), Unit); 1513 1514 case Type::TemplateSpecialization: 1515 case Type::Elaborated: 1516 case Type::SubstTemplateTypeParm: 1517 case Type::TypeOfExpr: 1518 case Type::TypeOf: 1519 case Type::Decltype: 1520 llvm_unreachable("type should have been unwrapped!"); 1521 return llvm::DIType(); 1522 1523 case Type::RValueReference: 1524 // FIXME: Implement! 1525 Diag = "rvalue references"; 1526 break; 1527 } 1528 1529 assert(Diag && "Fall through without a diagnostic?"); 1530 unsigned DiagID = CGM.getDiags().getCustomDiagID(Diagnostic::Error, 1531 "debug information for %0 is not yet supported"); 1532 CGM.getDiags().Report(DiagID) 1533 << Diag; 1534 return llvm::DIType(); 1535} 1536 1537/// CreateMemberType - Create new member and increase Offset by FType's size. 1538llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType, 1539 llvm::StringRef Name, 1540 uint64_t *Offset) { 1541 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 1542 uint64_t FieldSize = CGM.getContext().getTypeSize(FType); 1543 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType); 1544 llvm::DIType Ty = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, 1545 Unit, Name, Unit, 0, 1546 FieldSize, FieldAlign, 1547 *Offset, 0, FieldTy); 1548 *Offset += FieldSize; 1549 return Ty; 1550} 1551 1552/// EmitFunctionStart - Constructs the debug code for entering a function - 1553/// "llvm.dbg.func.start.". 1554void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType, 1555 llvm::Function *Fn, 1556 CGBuilderTy &Builder) { 1557 1558 llvm::StringRef Name; 1559 llvm::StringRef LinkageName; 1560 1561 FnBeginRegionCount.push_back(RegionStack.size()); 1562 1563 const Decl *D = GD.getDecl(); 1564 unsigned Flags = 0; 1565 llvm::DIFile Unit = getOrCreateFile(CurLoc); 1566 llvm::DIDescriptor FDContext(Unit); 1567 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1568 // If there is a DISubprogram for this function available then use it. 1569 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator 1570 FI = SPCache.find(FD); 1571 if (FI != SPCache.end()) { 1572 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(&*FI->second)); 1573 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) { 1574 llvm::MDNode *SPN = SP; 1575 RegionStack.push_back(SPN); 1576 RegionMap[D] = llvm::WeakVH(SP); 1577 return; 1578 } 1579 } 1580 Name = getFunctionName(FD); 1581 // Use mangled name as linkage name for c/c++ functions. 1582 LinkageName = CGM.getMangledName(GD); 1583 if (LinkageName == Name) 1584 LinkageName = llvm::StringRef(); 1585 if (FD->hasPrototype()) 1586 Flags |= llvm::DIDescriptor::FlagPrototyped; 1587 if (const NamespaceDecl *NSDecl = 1588 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext())) 1589 FDContext = getOrCreateNameSpace(NSDecl, Unit); 1590 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) { 1591 Name = getObjCMethodName(OMD); 1592 Flags |= llvm::DIDescriptor::FlagPrototyped; 1593 } else { 1594 // Use llvm function name. 1595 Name = Fn->getName(); 1596 Flags |= llvm::DIDescriptor::FlagPrototyped; 1597 } 1598 if (!Name.empty() && Name[0] == '\01') 1599 Name = Name.substr(1); 1600 1601 // It is expected that CurLoc is set before using EmitFunctionStart. 1602 // Usually, CurLoc points to the left bracket location of compound 1603 // statement representing function body. 1604 unsigned LineNo = getLineNumber(CurLoc); 1605 if (D->isImplicit()) 1606 Flags |= llvm::DIDescriptor::FlagArtificial; 1607 llvm::DISubprogram SP = 1608 DebugFactory.CreateSubprogram(FDContext, Name, Name, LinkageName, Unit, 1609 LineNo, getOrCreateType(FnType, Unit), 1610 Fn->hasInternalLinkage(), true/*definition*/, 1611 0, 0, llvm::DIType(), 1612 Flags, 1613 CGM.getLangOptions().Optimize, Fn); 1614 1615 // Push function on region stack. 1616 llvm::MDNode *SPN = SP; 1617 RegionStack.push_back(SPN); 1618 RegionMap[D] = llvm::WeakVH(SP); 1619 1620 // Clear stack used to keep track of #line directives. 1621 LineDirectiveFiles.clear(); 1622} 1623 1624 1625void CGDebugInfo::EmitStopPoint(CGBuilderTy &Builder) { 1626 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return; 1627 1628 // Don't bother if things are the same as last time. 1629 SourceManager &SM = CGM.getContext().getSourceManager(); 1630 if (CurLoc == PrevLoc 1631 || (SM.getInstantiationLineNumber(CurLoc) == 1632 SM.getInstantiationLineNumber(PrevLoc) 1633 && SM.isFromSameFile(CurLoc, PrevLoc))) 1634 // New Builder may not be in sync with CGDebugInfo. 1635 if (!Builder.getCurrentDebugLocation().isUnknown()) 1636 return; 1637 1638 // Update last state. 1639 PrevLoc = CurLoc; 1640 1641 llvm::MDNode *Scope = RegionStack.back(); 1642 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc), 1643 getColumnNumber(CurLoc), 1644 Scope)); 1645} 1646 1647/// UpdateLineDirectiveRegion - Update region stack only if #line directive 1648/// has introduced scope change. 1649void CGDebugInfo::UpdateLineDirectiveRegion(CGBuilderTy &Builder) { 1650 if (CurLoc.isInvalid() || CurLoc.isMacroID() || 1651 PrevLoc.isInvalid() || PrevLoc.isMacroID()) 1652 return; 1653 SourceManager &SM = CGM.getContext().getSourceManager(); 1654 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc); 1655 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc); 1656 1657 if (PCLoc.isInvalid() || PPLoc.isInvalid() || 1658 !strcmp(PPLoc.getFilename(), PCLoc.getFilename())) 1659 return; 1660 1661 // If #line directive stack is empty then we are entering a new scope. 1662 if (LineDirectiveFiles.empty()) { 1663 EmitRegionStart(Builder); 1664 LineDirectiveFiles.push_back(PCLoc.getFilename()); 1665 return; 1666 } 1667 1668 assert (RegionStack.size() >= LineDirectiveFiles.size() 1669 && "error handling #line regions!"); 1670 1671 bool SeenThisFile = false; 1672 // Chek if current file is already seen earlier. 1673 for(std::vector<const char *>::iterator I = LineDirectiveFiles.begin(), 1674 E = LineDirectiveFiles.end(); I != E; ++I) 1675 if (!strcmp(PCLoc.getFilename(), *I)) { 1676 SeenThisFile = true; 1677 break; 1678 } 1679 1680 // If #line for this file is seen earlier then pop out #line regions. 1681 if (SeenThisFile) { 1682 while (!LineDirectiveFiles.empty()) { 1683 const char *LastFile = LineDirectiveFiles.back(); 1684 RegionStack.pop_back(); 1685 LineDirectiveFiles.pop_back(); 1686 if (!strcmp(PPLoc.getFilename(), LastFile)) 1687 break; 1688 } 1689 return; 1690 } 1691 1692 // .. otherwise insert new #line region. 1693 EmitRegionStart(Builder); 1694 LineDirectiveFiles.push_back(PCLoc.getFilename()); 1695 1696 return; 1697} 1698/// EmitRegionStart- Constructs the debug code for entering a declarative 1699/// region - "llvm.dbg.region.start.". 1700void CGDebugInfo::EmitRegionStart(CGBuilderTy &Builder) { 1701 llvm::DIDescriptor D = 1702 DebugFactory.CreateLexicalBlock(RegionStack.empty() ? 1703 llvm::DIDescriptor() : 1704 llvm::DIDescriptor(RegionStack.back()), 1705 getOrCreateFile(CurLoc), 1706 getLineNumber(CurLoc), 1707 getColumnNumber(CurLoc)); 1708 llvm::MDNode *DN = D; 1709 RegionStack.push_back(DN); 1710} 1711 1712/// EmitRegionEnd - Constructs the debug code for exiting a declarative 1713/// region - "llvm.dbg.region.end." 1714void CGDebugInfo::EmitRegionEnd(CGBuilderTy &Builder) { 1715 assert(!RegionStack.empty() && "Region stack mismatch, stack empty!"); 1716 1717 // Provide an region stop point. 1718 EmitStopPoint(Builder); 1719 1720 RegionStack.pop_back(); 1721} 1722 1723/// EmitFunctionEnd - Constructs the debug code for exiting a function. 1724void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) { 1725 assert(!RegionStack.empty() && "Region stack mismatch, stack empty!"); 1726 unsigned RCount = FnBeginRegionCount.back(); 1727 assert(RCount <= RegionStack.size() && "Region stack mismatch"); 1728 1729 // Pop all regions for this function. 1730 while (RegionStack.size() != RCount) 1731 EmitRegionEnd(Builder); 1732 FnBeginRegionCount.pop_back(); 1733} 1734 1735// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref. 1736// See BuildByRefType. 1737llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD, 1738 uint64_t *XOffset) { 1739 1740 llvm::SmallVector<llvm::DIDescriptor, 5> EltTys; 1741 1742 QualType FType; 1743 uint64_t FieldSize, FieldOffset; 1744 unsigned FieldAlign; 1745 1746 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 1747 QualType Type = VD->getType(); 1748 1749 FieldOffset = 0; 1750 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 1751 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 1752 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset)); 1753 FType = CGM.getContext().IntTy; 1754 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 1755 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset)); 1756 1757 bool HasCopyAndDispose = CGM.BlockRequiresCopying(Type); 1758 if (HasCopyAndDispose) { 1759 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 1760 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper", 1761 &FieldOffset)); 1762 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper", 1763 &FieldOffset)); 1764 } 1765 1766 CharUnits Align = CGM.getContext().getDeclAlign(VD); 1767 if (Align > CharUnits::fromQuantity( 1768 CGM.getContext().Target.getPointerAlign(0) / 8)) { 1769 unsigned AlignedOffsetInBytes 1770 = llvm::RoundUpToAlignment(FieldOffset/8, Align.getQuantity()); 1771 unsigned NumPaddingBytes 1772 = AlignedOffsetInBytes - FieldOffset/8; 1773 1774 if (NumPaddingBytes > 0) { 1775 llvm::APInt pad(32, NumPaddingBytes); 1776 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy, 1777 pad, ArrayType::Normal, 0); 1778 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset)); 1779 } 1780 } 1781 1782 FType = Type; 1783 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 1784 FieldSize = CGM.getContext().getTypeSize(FType); 1785 FieldAlign = Align.getQuantity()*8; 1786 1787 *XOffset = FieldOffset; 1788 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit, 1789 VD->getName(), Unit, 1790 0, FieldSize, FieldAlign, 1791 FieldOffset, 0, FieldTy); 1792 EltTys.push_back(FieldTy); 1793 FieldOffset += FieldSize; 1794 1795 llvm::DIArray Elements = 1796 DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size()); 1797 1798 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct; 1799 1800 return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type, 1801 Unit, "", Unit, 1802 0, FieldOffset, 0, 0, Flags, 1803 llvm::DIType(), Elements); 1804 1805} 1806/// EmitDeclare - Emit local variable declaration debug info. 1807void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag, 1808 llvm::Value *Storage, CGBuilderTy &Builder) { 1809 assert(!RegionStack.empty() && "Region stack mismatch, stack empty!"); 1810 1811 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 1812 llvm::DIType Ty; 1813 uint64_t XOffset = 0; 1814 if (VD->hasAttr<BlocksAttr>()) 1815 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 1816 else 1817 Ty = getOrCreateType(VD->getType(), Unit); 1818 1819 // If there is not any debug info for type then do not emit debug info 1820 // for this variable. 1821 if (!Ty) 1822 return; 1823 1824 // Get location information. 1825 unsigned Line = getLineNumber(VD->getLocation()); 1826 unsigned Column = getColumnNumber(VD->getLocation()); 1827 unsigned Flags = 0; 1828 if (VD->isImplicit()) 1829 Flags |= llvm::DIDescriptor::FlagArtificial; 1830 llvm::MDNode *Scope = RegionStack.back(); 1831 1832 llvm::StringRef Name = VD->getName(); 1833 if (!Name.empty()) { 1834 // Create the descriptor for the variable. 1835 llvm::DIVariable D = 1836 DebugFactory.CreateVariable(Tag, llvm::DIDescriptor(Scope), 1837 Name, Unit, Line, Ty, 1838 CGM.getLangOptions().Optimize, Flags); 1839 1840 // Insert an llvm.dbg.declare into the current block. 1841 llvm::Instruction *Call = 1842 DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock()); 1843 1844 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 1845 return; 1846 } 1847 1848 // If VD is an anonymous union then Storage represents value for 1849 // all union fields. 1850 if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) 1851 if (const RecordDecl *RD = dyn_cast<RecordDecl>(RT->getDecl())) 1852 if (RD->isUnion()) { 1853 for (RecordDecl::field_iterator I = RD->field_begin(), 1854 E = RD->field_end(); 1855 I != E; ++I) { 1856 FieldDecl *Field = *I; 1857 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 1858 llvm::StringRef FieldName = Field->getName(); 1859 1860 // Ignore unnamed fields. Do not ignore unnamed records. 1861 if (FieldName.empty() && !isa<RecordType>(Field->getType())) 1862 continue; 1863 1864 // Use VarDecl's Tag, Scope and Line number. 1865 llvm::DIVariable D = 1866 DebugFactory.CreateVariable(Tag, llvm::DIDescriptor(Scope), 1867 FieldName, Unit, Line, FieldTy, 1868 CGM.getLangOptions().Optimize, Flags); 1869 1870 // Insert an llvm.dbg.declare into the current block. 1871 llvm::Instruction *Call = 1872 DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock()); 1873 1874 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 1875 } 1876 } 1877} 1878 1879/// EmitDeclare - Emit local variable declaration debug info. 1880void CGDebugInfo::EmitDeclare(const BlockDeclRefExpr *BDRE, unsigned Tag, 1881 llvm::Value *Storage, CGBuilderTy &Builder, 1882 CodeGenFunction *CGF) { 1883 const ValueDecl *VD = BDRE->getDecl(); 1884 assert(!RegionStack.empty() && "Region stack mismatch, stack empty!"); 1885 1886 if (Builder.GetInsertBlock() == 0) 1887 return; 1888 1889 uint64_t XOffset = 0; 1890 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 1891 llvm::DIType Ty; 1892 if (VD->hasAttr<BlocksAttr>()) 1893 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 1894 else 1895 Ty = getOrCreateType(VD->getType(), Unit); 1896 1897 // Get location information. 1898 unsigned Line = getLineNumber(VD->getLocation()); 1899 unsigned Column = getColumnNumber(VD->getLocation()); 1900 1901 CharUnits offset = CGF->BlockDecls[VD]; 1902 llvm::SmallVector<llvm::Value *, 9> addr; 1903 const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext()); 1904 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref)); 1905 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus)); 1906 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 1907 if (BDRE->isByRef()) { 1908 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref)); 1909 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus)); 1910 // offset of __forwarding field 1911 offset = CharUnits::fromQuantity(CGF->LLVMPointerWidth/8); 1912 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 1913 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref)); 1914 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus)); 1915 // offset of x field 1916 offset = CharUnits::fromQuantity(XOffset/8); 1917 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 1918 } 1919 1920 // Create the descriptor for the variable. 1921 llvm::DIVariable D = 1922 DebugFactory.CreateComplexVariable(Tag, 1923 llvm::DIDescriptor(RegionStack.back()), 1924 VD->getName(), Unit, Line, Ty, 1925 addr.data(), addr.size()); 1926 // Insert an llvm.dbg.declare into the current block. 1927 llvm::Instruction *Call = 1928 DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock()); 1929 1930 llvm::MDNode *Scope = RegionStack.back(); 1931 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 1932} 1933 1934void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, 1935 llvm::Value *Storage, 1936 CGBuilderTy &Builder) { 1937 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder); 1938} 1939 1940void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable( 1941 const BlockDeclRefExpr *BDRE, llvm::Value *Storage, CGBuilderTy &Builder, 1942 CodeGenFunction *CGF) { 1943 EmitDeclare(BDRE, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder, CGF); 1944} 1945 1946/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument 1947/// variable declaration. 1948void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI, 1949 CGBuilderTy &Builder) { 1950 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, Builder); 1951} 1952 1953 1954 1955/// EmitGlobalVariable - Emit information about a global variable. 1956void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 1957 const VarDecl *D) { 1958 1959 // Create global variable debug descriptor. 1960 llvm::DIFile Unit = getOrCreateFile(D->getLocation()); 1961 unsigned LineNo = getLineNumber(D->getLocation()); 1962 1963 QualType T = D->getType(); 1964 if (T->isIncompleteArrayType()) { 1965 1966 // CodeGen turns int[] into int[1] so we'll do the same here. 1967 llvm::APSInt ConstVal(32); 1968 1969 ConstVal = 1; 1970 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 1971 1972 T = CGM.getContext().getConstantArrayType(ET, ConstVal, 1973 ArrayType::Normal, 0); 1974 } 1975 llvm::StringRef DeclName = D->getName(); 1976 llvm::StringRef LinkageName; 1977 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())) 1978 LinkageName = Var->getName(); 1979 if (LinkageName == DeclName) 1980 LinkageName = llvm::StringRef(); 1981 llvm::DIDescriptor DContext = 1982 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()), Unit); 1983 DebugFactory.CreateGlobalVariable(DContext, DeclName, DeclName, LinkageName, 1984 Unit, LineNo, getOrCreateType(T, Unit), 1985 Var->hasInternalLinkage(), 1986 true/*definition*/, Var); 1987} 1988 1989/// EmitGlobalVariable - Emit information about an objective-c interface. 1990void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 1991 ObjCInterfaceDecl *ID) { 1992 // Create global variable debug descriptor. 1993 llvm::DIFile Unit = getOrCreateFile(ID->getLocation()); 1994 unsigned LineNo = getLineNumber(ID->getLocation()); 1995 1996 llvm::StringRef Name = ID->getName(); 1997 1998 QualType T = CGM.getContext().getObjCInterfaceType(ID); 1999 if (T->isIncompleteArrayType()) { 2000 2001 // CodeGen turns int[] into int[1] so we'll do the same here. 2002 llvm::APSInt ConstVal(32); 2003 2004 ConstVal = 1; 2005 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 2006 2007 T = CGM.getContext().getConstantArrayType(ET, ConstVal, 2008 ArrayType::Normal, 0); 2009 } 2010 2011 DebugFactory.CreateGlobalVariable(Unit, Name, Name, Name, Unit, LineNo, 2012 getOrCreateType(T, Unit), 2013 Var->hasInternalLinkage(), 2014 true/*definition*/, Var); 2015} 2016 2017/// EmitGlobalVariable - Emit global variable's debug info. 2018void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, 2019 llvm::Constant *Init) { 2020 // Create the descriptor for the variable. 2021 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 2022 llvm::StringRef Name = VD->getName(); 2023 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit); 2024 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) { 2025 if (const EnumDecl *ED = dyn_cast<EnumDecl>(ECD->getDeclContext())) 2026 Ty = CreateEnumType(ED, Unit); 2027 } 2028 // Do not use DIGlobalVariable for enums. 2029 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type) 2030 return; 2031 DebugFactory.CreateGlobalVariable(Unit, Name, Name, Name, Unit, 2032 getLineNumber(VD->getLocation()), 2033 Ty, true, true, Init); 2034} 2035 2036/// getOrCreateNamesSpace - Return namespace descriptor for the given 2037/// namespace decl. 2038llvm::DINameSpace 2039CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl, 2040 llvm::DIDescriptor Unit) { 2041 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I = 2042 NameSpaceCache.find(NSDecl); 2043 if (I != NameSpaceCache.end()) 2044 return llvm::DINameSpace(cast<llvm::MDNode>(I->second)); 2045 2046 unsigned LineNo = getLineNumber(NSDecl->getLocation()); 2047 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation()); 2048 llvm::DIDescriptor Context = 2049 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()), Unit); 2050 llvm::DINameSpace NS = 2051 DebugFactory.CreateNameSpace(Context, NSDecl->getName(), FileD, LineNo); 2052 NameSpaceCache[NSDecl] = llvm::WeakVH(NS); 2053 return NS; 2054} 2055