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