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