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