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" 39 using namespace clang; 40 using namespace clang::CodeGen; 41 42 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM) 43 : CGM(CGM), DBuilder(CGM.getModule()), 44 BlockLiteralGenericSet(false) { 45 CreateCompileUnit(); 46 } 47 48 CGDebugInfo::~CGDebugInfo() { 49 assert(LexicalBlockStack.empty() && 50 "Region stack mismatch, stack not empty!"); 51 } 52 53 void 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. 92 llvm::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. 118 StringRef 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 133 StringRef 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. 158 StringRef 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. 166 StringRef 167 CGDebugInfo::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. 199 llvm::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. 229 llvm::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. 235 unsigned 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. 244 unsigned 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 251 StringRef 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. 265 void 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. 322 llvm::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 417 llvm::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. 433 llvm::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 468 llvm::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 476 llvm::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. 483 llvm::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. 509 llvm::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. 538 llvm::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 564 llvm::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 582 llvm::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 645 llvm::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 662 llvm::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 EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit)); 676 } 677 678 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys); 679 680 llvm::DIType DbgTy = DBuilder.createSubroutineType(Unit, EltTypeArray); 681 return DbgTy; 682 } 683 684 llvm::DIType CGDebugInfo::createFieldType(StringRef name, 685 QualType type, 686 uint64_t sizeInBitsOverride, 687 SourceLocation loc, 688 AccessSpecifier AS, 689 uint64_t offsetInBits, 690 llvm::DIFile tunit, 691 llvm::DIDescriptor scope) { 692 llvm::DIType debugType = getOrCreateType(type, tunit); 693 694 // Get the location for the field. 695 llvm::DIFile file = getOrCreateFile(loc); 696 unsigned line = getLineNumber(loc); 697 698 uint64_t sizeInBits = 0; 699 unsigned alignInBits = 0; 700 if (!type->isIncompleteArrayType()) { 701 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type); 702 703 if (sizeInBitsOverride) 704 sizeInBits = sizeInBitsOverride; 705 } 706 707 unsigned flags = 0; 708 if (AS == clang::AS_private) 709 flags |= llvm::DIDescriptor::FlagPrivate; 710 else if (AS == clang::AS_protected) 711 flags |= llvm::DIDescriptor::FlagProtected; 712 713 return DBuilder.createMemberType(scope, name, file, line, sizeInBits, 714 alignInBits, offsetInBits, flags, debugType); 715 } 716 717 /// CollectRecordFields - A helper function to collect debug info for 718 /// record fields. This is used while creating debug info entry for a Record. 719 void CGDebugInfo:: 720 CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit, 721 SmallVectorImpl<llvm::Value *> &elements, 722 llvm::DIType RecordTy) { 723 unsigned fieldNo = 0; 724 const FieldDecl *LastFD = 0; 725 bool IsMsStruct = record->hasAttr<MsStructAttr>(); 726 727 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record); 728 for (RecordDecl::field_iterator I = record->field_begin(), 729 E = record->field_end(); 730 I != E; ++I, ++fieldNo) { 731 FieldDecl *field = *I; 732 if (IsMsStruct) { 733 // Zero-length bitfields following non-bitfield members are ignored 734 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD)) { 735 --fieldNo; 736 continue; 737 } 738 LastFD = field; 739 } 740 741 StringRef name = field->getName(); 742 QualType type = field->getType(); 743 744 // Ignore unnamed fields unless they're anonymous structs/unions. 745 if (name.empty() && !type->isRecordType()) { 746 LastFD = field; 747 continue; 748 } 749 750 uint64_t SizeInBitsOverride = 0; 751 if (field->isBitField()) { 752 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext()); 753 assert(SizeInBitsOverride && "found named 0-width bitfield"); 754 } 755 756 llvm::DIType fieldType 757 = createFieldType(name, type, SizeInBitsOverride, 758 field->getLocation(), field->getAccess(), 759 layout.getFieldOffset(fieldNo), tunit, RecordTy); 760 761 elements.push_back(fieldType); 762 } 763 } 764 765 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This 766 /// function type is not updated to include implicit "this" pointer. Use this 767 /// routine to get a method type which includes "this" pointer. 768 llvm::DIType 769 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method, 770 llvm::DIFile Unit) { 771 llvm::DIType FnTy 772 = getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoType>(), 773 0), 774 Unit); 775 776 // Add "this" pointer. 777 llvm::DIArray Args = llvm::DICompositeType(FnTy).getTypeArray(); 778 assert (Args.getNumElements() && "Invalid number of arguments!"); 779 780 SmallVector<llvm::Value *, 16> Elts; 781 782 // First element is always return type. For 'void' functions it is NULL. 783 Elts.push_back(Args.getElement(0)); 784 785 if (!Method->isStatic()) { 786 // "this" pointer is always first argument. 787 QualType ThisPtr = Method->getThisType(CGM.getContext()); 788 789 const CXXRecordDecl *RD = Method->getParent(); 790 if (isa<ClassTemplateSpecializationDecl>(RD)) { 791 // Create pointer type directly in this case. 792 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr); 793 QualType PointeeTy = ThisPtrTy->getPointeeType(); 794 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy); 795 uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS); 796 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy); 797 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit); 798 llvm::DIType ThisPtrType = 799 DBuilder.createArtificialType 800 (DBuilder.createPointerType(PointeeType, Size, Align)); 801 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType; 802 Elts.push_back(ThisPtrType); 803 } else { 804 llvm::DIType ThisPtrType = 805 DBuilder.createArtificialType(getOrCreateType(ThisPtr, Unit)); 806 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType; 807 Elts.push_back(ThisPtrType); 808 } 809 } 810 811 // Copy rest of the arguments. 812 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i) 813 Elts.push_back(Args.getElement(i)); 814 815 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts); 816 817 return DBuilder.createSubroutineType(Unit, EltTypeArray); 818 } 819 820 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined 821 /// inside a function. 822 static bool isFunctionLocalClass(const CXXRecordDecl *RD) { 823 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext())) 824 return isFunctionLocalClass(NRD); 825 if (isa<FunctionDecl>(RD->getDeclContext())) 826 return true; 827 return false; 828 } 829 830 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for 831 /// a single member function GlobalDecl. 832 llvm::DISubprogram 833 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method, 834 llvm::DIFile Unit, 835 llvm::DIType RecordTy) { 836 bool IsCtorOrDtor = 837 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method); 838 839 StringRef MethodName = getFunctionName(Method); 840 llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit); 841 842 // Since a single ctor/dtor corresponds to multiple functions, it doesn't 843 // make sense to give a single ctor/dtor a linkage name. 844 StringRef MethodLinkageName; 845 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent())) 846 MethodLinkageName = CGM.getMangledName(Method); 847 848 // Get the location for the method. 849 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation()); 850 unsigned MethodLine = getLineNumber(Method->getLocation()); 851 852 // Collect virtual method info. 853 llvm::DIType ContainingType; 854 unsigned Virtuality = 0; 855 unsigned VIndex = 0; 856 857 if (Method->isVirtual()) { 858 if (Method->isPure()) 859 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual; 860 else 861 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual; 862 863 // It doesn't make sense to give a virtual destructor a vtable index, 864 // since a single destructor has two entries in the vtable. 865 if (!isa<CXXDestructorDecl>(Method)) 866 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method); 867 ContainingType = RecordTy; 868 } 869 870 unsigned Flags = 0; 871 if (Method->isImplicit()) 872 Flags |= llvm::DIDescriptor::FlagArtificial; 873 AccessSpecifier Access = Method->getAccess(); 874 if (Access == clang::AS_private) 875 Flags |= llvm::DIDescriptor::FlagPrivate; 876 else if (Access == clang::AS_protected) 877 Flags |= llvm::DIDescriptor::FlagProtected; 878 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) { 879 if (CXXC->isExplicit()) 880 Flags |= llvm::DIDescriptor::FlagExplicit; 881 } else if (const CXXConversionDecl *CXXC = 882 dyn_cast<CXXConversionDecl>(Method)) { 883 if (CXXC->isExplicit()) 884 Flags |= llvm::DIDescriptor::FlagExplicit; 885 } 886 if (Method->hasPrototype()) 887 Flags |= llvm::DIDescriptor::FlagPrototyped; 888 889 llvm::DISubprogram SP = 890 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName, 891 MethodDefUnit, MethodLine, 892 MethodTy, /*isLocalToUnit=*/false, 893 /* isDefinition=*/ false, 894 Virtuality, VIndex, ContainingType, 895 Flags, CGM.getLangOptions().Optimize); 896 897 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP); 898 899 return SP; 900 } 901 902 /// CollectCXXMemberFunctions - A helper function to collect debug info for 903 /// C++ member functions. This is used while creating debug info entry for 904 /// a Record. 905 void CGDebugInfo:: 906 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit, 907 SmallVectorImpl<llvm::Value *> &EltTys, 908 llvm::DIType RecordTy) { 909 for(CXXRecordDecl::method_iterator I = RD->method_begin(), 910 E = RD->method_end(); I != E; ++I) { 911 const CXXMethodDecl *Method = *I; 912 913 if (Method->isImplicit() && !Method->isUsed()) 914 continue; 915 916 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy)); 917 } 918 } 919 920 /// CollectCXXFriends - A helper function to collect debug info for 921 /// C++ base classes. This is used while creating debug info entry for 922 /// a Record. 923 void CGDebugInfo:: 924 CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit, 925 SmallVectorImpl<llvm::Value *> &EltTys, 926 llvm::DIType RecordTy) { 927 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(), 928 BE = RD->friend_end(); BI != BE; ++BI) { 929 if ((*BI)->isUnsupportedFriend()) 930 continue; 931 if (TypeSourceInfo *TInfo = (*BI)->getFriendType()) 932 EltTys.push_back(DBuilder.createFriend(RecordTy, 933 getOrCreateType(TInfo->getType(), 934 Unit))); 935 } 936 } 937 938 /// CollectCXXBases - A helper function to collect debug info for 939 /// C++ base classes. This is used while creating debug info entry for 940 /// a Record. 941 void CGDebugInfo:: 942 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit, 943 SmallVectorImpl<llvm::Value *> &EltTys, 944 llvm::DIType RecordTy) { 945 946 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 947 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(), 948 BE = RD->bases_end(); BI != BE; ++BI) { 949 unsigned BFlags = 0; 950 uint64_t BaseOffset; 951 952 const CXXRecordDecl *Base = 953 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl()); 954 955 if (BI->isVirtual()) { 956 // virtual base offset offset is -ve. The code generator emits dwarf 957 // expression where it expects +ve number. 958 BaseOffset = 959 0 - CGM.getVTableContext() 960 .getVirtualBaseOffsetOffset(RD, Base).getQuantity(); 961 BFlags = llvm::DIDescriptor::FlagVirtual; 962 } else 963 BaseOffset = RL.getBaseClassOffsetInBits(Base); 964 // FIXME: Inconsistent units for BaseOffset. It is in bytes when 965 // BI->isVirtual() and bits when not. 966 967 AccessSpecifier Access = BI->getAccessSpecifier(); 968 if (Access == clang::AS_private) 969 BFlags |= llvm::DIDescriptor::FlagPrivate; 970 else if (Access == clang::AS_protected) 971 BFlags |= llvm::DIDescriptor::FlagProtected; 972 973 llvm::DIType DTy = 974 DBuilder.createInheritance(RecordTy, 975 getOrCreateType(BI->getType(), Unit), 976 BaseOffset, BFlags); 977 EltTys.push_back(DTy); 978 } 979 } 980 981 /// CollectTemplateParams - A helper function to collect template parameters. 982 llvm::DIArray CGDebugInfo:: 983 CollectTemplateParams(const TemplateParameterList *TPList, 984 const TemplateArgumentList &TAList, 985 llvm::DIFile Unit) { 986 SmallVector<llvm::Value *, 16> TemplateParams; 987 for (unsigned i = 0, e = TAList.size(); i != e; ++i) { 988 const TemplateArgument &TA = TAList[i]; 989 const NamedDecl *ND = TPList->getParam(i); 990 if (TA.getKind() == TemplateArgument::Type) { 991 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit); 992 llvm::DITemplateTypeParameter TTP = 993 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy); 994 TemplateParams.push_back(TTP); 995 } else if (TA.getKind() == TemplateArgument::Integral) { 996 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit); 997 llvm::DITemplateValueParameter TVP = 998 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, 999 TA.getAsIntegral()->getZExtValue()); 1000 TemplateParams.push_back(TVP); 1001 } 1002 } 1003 return DBuilder.getOrCreateArray(TemplateParams); 1004 } 1005 1006 /// CollectFunctionTemplateParams - A helper function to collect debug 1007 /// info for function template parameters. 1008 llvm::DIArray CGDebugInfo:: 1009 CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) { 1010 if (FD->getTemplatedKind() == 1011 FunctionDecl::TK_FunctionTemplateSpecialization) { 1012 const TemplateParameterList *TList = 1013 FD->getTemplateSpecializationInfo()->getTemplate() 1014 ->getTemplateParameters(); 1015 return 1016 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit); 1017 } 1018 return llvm::DIArray(); 1019 } 1020 1021 /// CollectCXXTemplateParams - A helper function to collect debug info for 1022 /// template parameters. 1023 llvm::DIArray CGDebugInfo:: 1024 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial, 1025 llvm::DIFile Unit) { 1026 llvm::PointerUnion<ClassTemplateDecl *, 1027 ClassTemplatePartialSpecializationDecl *> 1028 PU = TSpecial->getSpecializedTemplateOrPartial(); 1029 1030 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ? 1031 PU.get<ClassTemplateDecl *>()->getTemplateParameters() : 1032 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters(); 1033 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs(); 1034 return CollectTemplateParams(TPList, TAList, Unit); 1035 } 1036 1037 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable. 1038 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) { 1039 if (VTablePtrType.isValid()) 1040 return VTablePtrType; 1041 1042 ASTContext &Context = CGM.getContext(); 1043 1044 /* Function type */ 1045 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit); 1046 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy); 1047 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements); 1048 unsigned Size = Context.getTypeSize(Context.VoidPtrTy); 1049 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0, 1050 "__vtbl_ptr_type"); 1051 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size); 1052 return VTablePtrType; 1053 } 1054 1055 /// getVTableName - Get vtable name for the given Class. 1056 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) { 1057 // Otherwise construct gdb compatible name name. 1058 std::string Name = "_vptr$" + RD->getNameAsString(); 1059 1060 // Copy this name on the side and use its reference. 1061 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length()); 1062 memcpy(StrPtr, Name.data(), Name.length()); 1063 return StringRef(StrPtr, Name.length()); 1064 } 1065 1066 1067 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate 1068 /// debug info entry in EltTys vector. 1069 void CGDebugInfo:: 1070 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit, 1071 SmallVectorImpl<llvm::Value *> &EltTys) { 1072 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 1073 1074 // If there is a primary base then it will hold vtable info. 1075 if (RL.getPrimaryBase()) 1076 return; 1077 1078 // If this class is not dynamic then there is not any vtable info to collect. 1079 if (!RD->isDynamicClass()) 1080 return; 1081 1082 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 1083 llvm::DIType VPTR 1084 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 1085 0, Size, 0, 0, 0, 1086 getOrCreateVTablePtrType(Unit)); 1087 EltTys.push_back(VPTR); 1088 } 1089 1090 /// getOrCreateRecordType - Emit record type's standalone debug info. 1091 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy, 1092 SourceLocation Loc) { 1093 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc)); 1094 DBuilder.retainType(T); 1095 return T; 1096 } 1097 1098 /// CreateType - get structure or union type. 1099 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) { 1100 RecordDecl *RD = Ty->getDecl(); 1101 llvm::DIFile Unit = getOrCreateFile(RD->getLocation()); 1102 1103 // Get overall information about the record type for the debug info. 1104 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 1105 unsigned Line = getLineNumber(RD->getLocation()); 1106 1107 // Records and classes and unions can all be recursive. To handle them, we 1108 // first generate a debug descriptor for the struct as a forward declaration. 1109 // Then (if it is a definition) we go through and get debug info for all of 1110 // its members. Finally, we create a descriptor for the complete type (which 1111 // may refer to the forward decl if the struct is recursive) and replace all 1112 // uses of the forward declaration with the final definition. 1113 1114 llvm::DIDescriptor FDContext; 1115 if (CGM.getCodeGenOpts().LimitDebugInfo) 1116 FDContext = createContextChain(cast<Decl>(RD->getDeclContext())); 1117 else 1118 FDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext())); 1119 1120 // If this is just a forward declaration, construct an appropriately 1121 // marked node and just return it. 1122 if (!RD->getDefinition()) { 1123 llvm::DIType FwdDecl = 1124 DBuilder.createStructType(FDContext, RD->getName(), 1125 DefUnit, Line, 0, 0, 1126 llvm::DIDescriptor::FlagFwdDecl, 1127 llvm::DIArray()); 1128 1129 return FwdDecl; 1130 } 1131 1132 llvm::DIType FwdDecl = DBuilder.createTemporaryType(DefUnit); 1133 1134 llvm::MDNode *MN = FwdDecl; 1135 llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN; 1136 // Otherwise, insert it into the TypeCache so that recursive uses will find 1137 // it. 1138 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl; 1139 // Push the struct on region stack. 1140 LexicalBlockStack.push_back(FwdDeclNode); 1141 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl); 1142 1143 // Convert all the elements. 1144 SmallVector<llvm::Value *, 16> EltTys; 1145 1146 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 1147 if (CXXDecl) { 1148 CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl); 1149 CollectVTableInfo(CXXDecl, Unit, EltTys); 1150 } 1151 1152 // Collect static variables with initializers. 1153 for (RecordDecl::decl_iterator I = RD->decls_begin(), E = RD->decls_end(); 1154 I != E; ++I) 1155 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) { 1156 if (V->getInit()) { 1157 const APValue *Value = V->evaluateValue(); 1158 if (Value && Value->isInt()) { 1159 llvm::ConstantInt *CI 1160 = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt()); 1161 1162 // Create the descriptor for static variable. 1163 llvm::DIFile VUnit = getOrCreateFile(V->getLocation()); 1164 StringRef VName = V->getName(); 1165 llvm::DIType VTy = getOrCreateType(V->getType(), VUnit); 1166 // Do not use DIGlobalVariable for enums. 1167 if (VTy.getTag() != llvm::dwarf::DW_TAG_enumeration_type) { 1168 DBuilder.createStaticVariable(FwdDecl, VName, VName, VUnit, 1169 getLineNumber(V->getLocation()), 1170 VTy, true, CI); 1171 } 1172 } 1173 } 1174 } 1175 1176 CollectRecordFields(RD, Unit, EltTys, FwdDecl); 1177 llvm::DIArray TParamsArray; 1178 if (CXXDecl) { 1179 CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl); 1180 CollectCXXFriends(CXXDecl, Unit, EltTys, FwdDecl); 1181 if (const ClassTemplateSpecializationDecl *TSpecial 1182 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) 1183 TParamsArray = CollectCXXTemplateParams(TSpecial, Unit); 1184 } 1185 1186 LexicalBlockStack.pop_back(); 1187 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI = 1188 RegionMap.find(Ty->getDecl()); 1189 if (RI != RegionMap.end()) 1190 RegionMap.erase(RI); 1191 1192 llvm::DIDescriptor RDContext = 1193 getContextDescriptor(cast<Decl>(RD->getDeclContext())); 1194 StringRef RDName = RD->getName(); 1195 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1196 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1197 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys); 1198 llvm::MDNode *RealDecl = NULL; 1199 1200 if (RD->isUnion()) 1201 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line, 1202 Size, Align, 0, Elements); 1203 else if (CXXDecl) { 1204 RDName = getClassName(RD); 1205 // A class's primary base or the class itself contains the vtable. 1206 llvm::MDNode *ContainingType = NULL; 1207 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 1208 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) { 1209 // Seek non virtual primary base root. 1210 while (1) { 1211 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase); 1212 const CXXRecordDecl *PBT = BRL.getPrimaryBase(); 1213 if (PBT && !BRL.isPrimaryBaseVirtual()) 1214 PBase = PBT; 1215 else 1216 break; 1217 } 1218 ContainingType = 1219 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit); 1220 } 1221 else if (CXXDecl->isDynamicClass()) 1222 ContainingType = FwdDecl; 1223 1224 // FIXME: This could be a struct type giving a default visibility different 1225 // than C++ class type, but needs llvm metadata changes first. 1226 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line, 1227 Size, Align, 0, 0, llvm::DIType(), 1228 Elements, ContainingType, 1229 TParamsArray); 1230 } else 1231 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line, 1232 Size, Align, 0, Elements); 1233 1234 // Now that we have a real decl for the struct, replace anything using the 1235 // old decl with the new one. This will recursively update the debug info. 1236 llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl); 1237 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl); 1238 return llvm::DIType(RealDecl); 1239 } 1240 1241 /// CreateType - get objective-c object type. 1242 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty, 1243 llvm::DIFile Unit) { 1244 // Ignore protocols. 1245 return getOrCreateType(Ty->getBaseType(), Unit); 1246 } 1247 1248 /// CreateType - get objective-c interface type. 1249 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, 1250 llvm::DIFile Unit) { 1251 ObjCInterfaceDecl *ID = Ty->getDecl(); 1252 if (!ID) 1253 return llvm::DIType(); 1254 1255 // Get overall information about the record type for the debug info. 1256 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation()); 1257 unsigned Line = getLineNumber(ID->getLocation()); 1258 unsigned RuntimeLang = TheCU.getLanguage(); 1259 1260 // If this is just a forward declaration return a special forward-declaration 1261 // debug type since we won't be able to lay out the entire type. 1262 ObjCInterfaceDecl *Def = ID->getDefinition(); 1263 if (!Def) { 1264 llvm::DIType FwdDecl = 1265 DBuilder.createStructType(Unit, ID->getName(), 1266 DefUnit, Line, 0, 0, 1267 llvm::DIDescriptor::FlagFwdDecl, 1268 llvm::DIArray(), RuntimeLang); 1269 return FwdDecl; 1270 } 1271 ID = Def; 1272 1273 // To handle a recursive interface, we first generate a debug descriptor 1274 // for the struct as a forward declaration. Then (if it is a definition) 1275 // we go through and get debug info for all of its members. Finally, we 1276 // create a descriptor for the complete type (which may refer to the 1277 // forward decl if the struct is recursive) and replace all uses of the 1278 // forward declaration with the final definition. 1279 llvm::DIType FwdDecl = DBuilder.createTemporaryType(DefUnit); 1280 1281 llvm::MDNode *MN = FwdDecl; 1282 llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN; 1283 // Otherwise, insert it into the TypeCache so that recursive uses will find 1284 // it. 1285 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl; 1286 // Push the struct on region stack. 1287 LexicalBlockStack.push_back(FwdDeclNode); 1288 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl); 1289 1290 // Convert all the elements. 1291 SmallVector<llvm::Value *, 16> EltTys; 1292 1293 ObjCInterfaceDecl *SClass = ID->getSuperClass(); 1294 if (SClass) { 1295 llvm::DIType SClassTy = 1296 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit); 1297 if (!SClassTy.isValid()) 1298 return llvm::DIType(); 1299 1300 llvm::DIType InhTag = 1301 DBuilder.createInheritance(FwdDecl, SClassTy, 0, 0); 1302 EltTys.push_back(InhTag); 1303 } 1304 1305 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID); 1306 ObjCImplementationDecl *ImpD = ID->getImplementation(); 1307 unsigned FieldNo = 0; 1308 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field; 1309 Field = Field->getNextIvar(), ++FieldNo) { 1310 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 1311 if (!FieldTy.isValid()) 1312 return llvm::DIType(); 1313 1314 StringRef FieldName = Field->getName(); 1315 1316 // Ignore unnamed fields. 1317 if (FieldName.empty()) 1318 continue; 1319 1320 // Get the location for the field. 1321 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation()); 1322 unsigned FieldLine = getLineNumber(Field->getLocation()); 1323 QualType FType = Field->getType(); 1324 uint64_t FieldSize = 0; 1325 unsigned FieldAlign = 0; 1326 1327 if (!FType->isIncompleteArrayType()) { 1328 1329 // Bit size, align and offset of the type. 1330 FieldSize = Field->isBitField() 1331 ? Field->getBitWidthValue(CGM.getContext()) 1332 : CGM.getContext().getTypeSize(FType); 1333 FieldAlign = CGM.getContext().getTypeAlign(FType); 1334 } 1335 1336 // We can't know the offset of our ivar in the structure if we're using 1337 // the non-fragile abi and the debugger should ignore the value anyways. 1338 // Call it the FieldNo+1 due to how debuggers use the information, 1339 // e.g. negating the value when it needs a lookup in the dynamic table. 1340 uint64_t FieldOffset = CGM.getLangOptions().ObjCNonFragileABI ? FieldNo+1 1341 : RL.getFieldOffset(FieldNo); 1342 1343 unsigned Flags = 0; 1344 if (Field->getAccessControl() == ObjCIvarDecl::Protected) 1345 Flags = llvm::DIDescriptor::FlagProtected; 1346 else if (Field->getAccessControl() == ObjCIvarDecl::Private) 1347 Flags = llvm::DIDescriptor::FlagPrivate; 1348 1349 StringRef PropertyName; 1350 StringRef PropertyGetter; 1351 StringRef PropertySetter; 1352 unsigned PropertyAttributes = 0; 1353 ObjCPropertyDecl *PD = NULL; 1354 if (ImpD) 1355 if (ObjCPropertyImplDecl *PImpD = 1356 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) 1357 PD = PImpD->getPropertyDecl(); 1358 if (PD) { 1359 PropertyName = PD->getName(); 1360 PropertyGetter = getSelectorName(PD->getGetterName()); 1361 PropertySetter = getSelectorName(PD->getSetterName()); 1362 PropertyAttributes = PD->getPropertyAttributes(); 1363 } 1364 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, 1365 FieldLine, FieldSize, FieldAlign, 1366 FieldOffset, Flags, FieldTy, 1367 PropertyName, PropertyGetter, 1368 PropertySetter, PropertyAttributes); 1369 EltTys.push_back(FieldTy); 1370 } 1371 1372 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys); 1373 1374 LexicalBlockStack.pop_back(); 1375 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI = 1376 RegionMap.find(Ty->getDecl()); 1377 if (RI != RegionMap.end()) 1378 RegionMap.erase(RI); 1379 1380 // Bit size, align and offset of the type. 1381 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1382 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1383 1384 unsigned Flags = 0; 1385 if (ID->getImplementation()) 1386 Flags |= llvm::DIDescriptor::FlagObjcClassComplete; 1387 1388 llvm::DIType RealDecl = 1389 DBuilder.createStructType(Unit, ID->getName(), DefUnit, 1390 Line, Size, Align, Flags, 1391 Elements, RuntimeLang); 1392 1393 // Now that we have a real decl for the struct, replace anything using the 1394 // old decl with the new one. This will recursively update the debug info. 1395 llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl); 1396 RegionMap[ID] = llvm::WeakVH(RealDecl); 1397 1398 return RealDecl; 1399 } 1400 1401 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) { 1402 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit); 1403 int64_t NumElems = Ty->getNumElements(); 1404 int64_t LowerBound = 0; 1405 if (NumElems == 0) 1406 // If number of elements are not known then this is an unbounded array. 1407 // Use Low = 1, Hi = 0 to express such arrays. 1408 LowerBound = 1; 1409 else 1410 --NumElems; 1411 1412 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(LowerBound, NumElems); 1413 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript); 1414 1415 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1416 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1417 1418 return 1419 DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray); 1420 } 1421 1422 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty, 1423 llvm::DIFile Unit) { 1424 uint64_t Size; 1425 uint64_t Align; 1426 1427 1428 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types 1429 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) { 1430 Size = 0; 1431 Align = 1432 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT)); 1433 } else if (Ty->isIncompleteArrayType()) { 1434 Size = 0; 1435 Align = CGM.getContext().getTypeAlign(Ty->getElementType()); 1436 } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) { 1437 Size = 0; 1438 Align = 0; 1439 } else { 1440 // Size and align of the whole array, not the element type. 1441 Size = CGM.getContext().getTypeSize(Ty); 1442 Align = CGM.getContext().getTypeAlign(Ty); 1443 } 1444 1445 // Add the dimensions of the array. FIXME: This loses CV qualifiers from 1446 // interior arrays, do we care? Why aren't nested arrays represented the 1447 // obvious/recursive way? 1448 SmallVector<llvm::Value *, 8> Subscripts; 1449 QualType EltTy(Ty, 0); 1450 if (Ty->isIncompleteArrayType()) 1451 EltTy = Ty->getElementType(); 1452 else { 1453 while ((Ty = dyn_cast<ArrayType>(EltTy))) { 1454 int64_t UpperBound = 0; 1455 int64_t LowerBound = 0; 1456 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) { 1457 if (CAT->getSize().getZExtValue()) 1458 UpperBound = CAT->getSize().getZExtValue() - 1; 1459 } else 1460 // This is an unbounded array. Use Low = 1, Hi = 0 to express such 1461 // arrays. 1462 LowerBound = 1; 1463 1464 // FIXME: Verify this is right for VLAs. 1465 Subscripts.push_back(DBuilder.getOrCreateSubrange(LowerBound, 1466 UpperBound)); 1467 EltTy = Ty->getElementType(); 1468 } 1469 } 1470 1471 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts); 1472 1473 llvm::DIType DbgTy = 1474 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit), 1475 SubscriptArray); 1476 return DbgTy; 1477 } 1478 1479 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty, 1480 llvm::DIFile Unit) { 1481 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, 1482 Ty, Ty->getPointeeType(), Unit); 1483 } 1484 1485 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty, 1486 llvm::DIFile Unit) { 1487 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, 1488 Ty, Ty->getPointeeType(), Unit); 1489 } 1490 1491 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty, 1492 llvm::DIFile U) { 1493 QualType PointerDiffTy = CGM.getContext().getPointerDiffType(); 1494 llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U); 1495 1496 if (!Ty->getPointeeType()->isFunctionType()) { 1497 // We have a data member pointer type. 1498 return PointerDiffDITy; 1499 } 1500 1501 // We have a member function pointer type. Treat it as a struct with two 1502 // ptrdiff_t members. 1503 std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty); 1504 1505 uint64_t FieldOffset = 0; 1506 llvm::Value *ElementTypes[2]; 1507 1508 // FIXME: This should probably be a function type instead. 1509 ElementTypes[0] = 1510 DBuilder.createMemberType(U, "ptr", U, 0, 1511 Info.first, Info.second, FieldOffset, 0, 1512 PointerDiffDITy); 1513 FieldOffset += Info.first; 1514 1515 ElementTypes[1] = 1516 DBuilder.createMemberType(U, "ptr", U, 0, 1517 Info.first, Info.second, FieldOffset, 0, 1518 PointerDiffDITy); 1519 1520 llvm::DIArray Elements = DBuilder.getOrCreateArray(ElementTypes); 1521 1522 return DBuilder.createStructType(U, StringRef("test"), 1523 U, 0, FieldOffset, 1524 0, 0, Elements); 1525 } 1526 1527 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty, 1528 llvm::DIFile U) { 1529 // Ignore the atomic wrapping 1530 // FIXME: What is the correct representation? 1531 return getOrCreateType(Ty->getValueType(), U); 1532 } 1533 1534 /// CreateEnumType - get enumeration type. 1535 llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) { 1536 llvm::DIFile Unit = getOrCreateFile(ED->getLocation()); 1537 SmallVector<llvm::Value *, 16> Enumerators; 1538 1539 // Create DIEnumerator elements for each enumerator. 1540 for (EnumDecl::enumerator_iterator 1541 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end(); 1542 Enum != EnumEnd; ++Enum) { 1543 Enumerators.push_back( 1544 DBuilder.createEnumerator(Enum->getName(), 1545 Enum->getInitVal().getZExtValue())); 1546 } 1547 1548 // Return a CompositeType for the enum itself. 1549 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators); 1550 1551 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation()); 1552 unsigned Line = getLineNumber(ED->getLocation()); 1553 uint64_t Size = 0; 1554 uint64_t Align = 0; 1555 if (!ED->getTypeForDecl()->isIncompleteType()) { 1556 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); 1557 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl()); 1558 } 1559 llvm::DIDescriptor EnumContext = 1560 getContextDescriptor(cast<Decl>(ED->getDeclContext())); 1561 llvm::DIType DbgTy = 1562 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line, 1563 Size, Align, EltArray); 1564 return DbgTy; 1565 } 1566 1567 static QualType UnwrapTypeForDebugInfo(QualType T) { 1568 do { 1569 QualType LastT = T; 1570 switch (T->getTypeClass()) { 1571 default: 1572 return T; 1573 case Type::TemplateSpecialization: 1574 T = cast<TemplateSpecializationType>(T)->desugar(); 1575 break; 1576 case Type::TypeOfExpr: 1577 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType(); 1578 break; 1579 case Type::TypeOf: 1580 T = cast<TypeOfType>(T)->getUnderlyingType(); 1581 break; 1582 case Type::Decltype: 1583 T = cast<DecltypeType>(T)->getUnderlyingType(); 1584 break; 1585 case Type::UnaryTransform: 1586 T = cast<UnaryTransformType>(T)->getUnderlyingType(); 1587 break; 1588 case Type::Attributed: 1589 T = cast<AttributedType>(T)->getEquivalentType(); 1590 break; 1591 case Type::Elaborated: 1592 T = cast<ElaboratedType>(T)->getNamedType(); 1593 break; 1594 case Type::Paren: 1595 T = cast<ParenType>(T)->getInnerType(); 1596 break; 1597 case Type::SubstTemplateTypeParm: 1598 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType(); 1599 break; 1600 case Type::Auto: 1601 T = cast<AutoType>(T)->getDeducedType(); 1602 break; 1603 } 1604 1605 assert(T != LastT && "Type unwrapping failed to unwrap!"); 1606 if (T == LastT) 1607 return T; 1608 } while (true); 1609 } 1610 1611 /// getType - Get the type from the cache or return null type if it doesn't exist. 1612 llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) { 1613 1614 // Unwrap the type as needed for debug information. 1615 Ty = UnwrapTypeForDebugInfo(Ty); 1616 1617 // Check for existing entry. 1618 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 1619 TypeCache.find(Ty.getAsOpaquePtr()); 1620 if (it != TypeCache.end()) { 1621 // Verify that the debug info still exists. 1622 if (&*it->second) 1623 return llvm::DIType(cast<llvm::MDNode>(it->second)); 1624 } 1625 1626 return llvm::DIType(); 1627 } 1628 1629 /// getOrCreateType - Get the type from the cache or create a new 1630 /// one if necessary. 1631 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) { 1632 if (Ty.isNull()) 1633 return llvm::DIType(); 1634 1635 // Unwrap the type as needed for debug information. 1636 Ty = UnwrapTypeForDebugInfo(Ty); 1637 1638 llvm::DIType T = getTypeOrNull(Ty); 1639 if (T.Verify()) return T; 1640 1641 // Otherwise create the type. 1642 llvm::DIType Res = CreateTypeNode(Ty, Unit); 1643 1644 // And update the type cache. 1645 TypeCache[Ty.getAsOpaquePtr()] = Res; 1646 return Res; 1647 } 1648 1649 /// CreateTypeNode - Create a new debug type node. 1650 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) { 1651 // Handle qualifiers, which recursively handles what they refer to. 1652 if (Ty.hasLocalQualifiers()) 1653 return CreateQualifiedType(Ty, Unit); 1654 1655 const char *Diag = 0; 1656 1657 // Work out details of type. 1658 switch (Ty->getTypeClass()) { 1659 #define TYPE(Class, Base) 1660 #define ABSTRACT_TYPE(Class, Base) 1661 #define NON_CANONICAL_TYPE(Class, Base) 1662 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1663 #include "clang/AST/TypeNodes.def" 1664 llvm_unreachable("Dependent types cannot show up in debug information"); 1665 1666 case Type::ExtVector: 1667 case Type::Vector: 1668 return CreateType(cast<VectorType>(Ty), Unit); 1669 case Type::ObjCObjectPointer: 1670 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit); 1671 case Type::ObjCObject: 1672 return CreateType(cast<ObjCObjectType>(Ty), Unit); 1673 case Type::ObjCInterface: 1674 return CreateType(cast<ObjCInterfaceType>(Ty), Unit); 1675 case Type::Builtin: 1676 return CreateType(cast<BuiltinType>(Ty)); 1677 case Type::Complex: 1678 return CreateType(cast<ComplexType>(Ty)); 1679 case Type::Pointer: 1680 return CreateType(cast<PointerType>(Ty), Unit); 1681 case Type::BlockPointer: 1682 return CreateType(cast<BlockPointerType>(Ty), Unit); 1683 case Type::Typedef: 1684 return CreateType(cast<TypedefType>(Ty), Unit); 1685 case Type::Record: 1686 return CreateType(cast<RecordType>(Ty)); 1687 case Type::Enum: 1688 return CreateEnumType(cast<EnumType>(Ty)->getDecl()); 1689 case Type::FunctionProto: 1690 case Type::FunctionNoProto: 1691 return CreateType(cast<FunctionType>(Ty), Unit); 1692 case Type::ConstantArray: 1693 case Type::VariableArray: 1694 case Type::IncompleteArray: 1695 return CreateType(cast<ArrayType>(Ty), Unit); 1696 1697 case Type::LValueReference: 1698 return CreateType(cast<LValueReferenceType>(Ty), Unit); 1699 case Type::RValueReference: 1700 return CreateType(cast<RValueReferenceType>(Ty), Unit); 1701 1702 case Type::MemberPointer: 1703 return CreateType(cast<MemberPointerType>(Ty), Unit); 1704 1705 case Type::Atomic: 1706 return CreateType(cast<AtomicType>(Ty), Unit); 1707 1708 case Type::Attributed: 1709 case Type::TemplateSpecialization: 1710 case Type::Elaborated: 1711 case Type::Paren: 1712 case Type::SubstTemplateTypeParm: 1713 case Type::TypeOfExpr: 1714 case Type::TypeOf: 1715 case Type::Decltype: 1716 case Type::UnaryTransform: 1717 case Type::Auto: 1718 llvm_unreachable("type should have been unwrapped!"); 1719 } 1720 1721 assert(Diag && "Fall through without a diagnostic?"); 1722 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error, 1723 "debug information for %0 is not yet supported"); 1724 CGM.getDiags().Report(DiagID) 1725 << Diag; 1726 return llvm::DIType(); 1727 } 1728 1729 /// CreateMemberType - Create new member and increase Offset by FType's size. 1730 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType, 1731 StringRef Name, 1732 uint64_t *Offset) { 1733 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 1734 uint64_t FieldSize = CGM.getContext().getTypeSize(FType); 1735 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType); 1736 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0, 1737 FieldSize, FieldAlign, 1738 *Offset, 0, FieldTy); 1739 *Offset += FieldSize; 1740 return Ty; 1741 } 1742 1743 /// getFunctionDeclaration - Return debug info descriptor to describe method 1744 /// declaration for the given method definition. 1745 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) { 1746 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 1747 if (!FD) return llvm::DISubprogram(); 1748 1749 // Setup context. 1750 getContextDescriptor(cast<Decl>(D->getDeclContext())); 1751 1752 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator 1753 MI = SPCache.find(FD->getCanonicalDecl()); 1754 if (MI != SPCache.end()) { 1755 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second)); 1756 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition()) 1757 return SP; 1758 } 1759 1760 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(), 1761 E = FD->redecls_end(); I != E; ++I) { 1762 const FunctionDecl *NextFD = *I; 1763 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator 1764 MI = SPCache.find(NextFD->getCanonicalDecl()); 1765 if (MI != SPCache.end()) { 1766 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second)); 1767 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition()) 1768 return SP; 1769 } 1770 } 1771 return llvm::DISubprogram(); 1772 } 1773 1774 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include 1775 // implicit parameter "this". 1776 llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl * D, 1777 QualType FnType, 1778 llvm::DIFile F) { 1779 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1780 return getOrCreateMethodType(Method, F); 1781 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) { 1782 // Add "self" and "_cmd" 1783 SmallVector<llvm::Value *, 16> Elts; 1784 1785 // First element is always return type. For 'void' functions it is NULL. 1786 Elts.push_back(getOrCreateType(OMethod->getResultType(), F)); 1787 // "self" pointer is always first argument. 1788 Elts.push_back(getOrCreateType(OMethod->getSelfDecl()->getType(), F)); 1789 // "cmd" pointer is always second argument. 1790 Elts.push_back(getOrCreateType(OMethod->getCmdDecl()->getType(), F)); 1791 // Get rest of the arguments. 1792 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(), 1793 PE = OMethod->param_end(); PI != PE; ++PI) 1794 Elts.push_back(getOrCreateType((*PI)->getType(), F)); 1795 1796 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts); 1797 return DBuilder.createSubroutineType(F, EltTypeArray); 1798 } 1799 return getOrCreateType(FnType, F); 1800 } 1801 1802 /// EmitFunctionStart - Constructs the debug code for entering a function - 1803 /// "llvm.dbg.func.start.". 1804 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType, 1805 llvm::Function *Fn, 1806 CGBuilderTy &Builder) { 1807 1808 StringRef Name; 1809 StringRef LinkageName; 1810 1811 FnBeginRegionCount.push_back(LexicalBlockStack.size()); 1812 1813 const Decl *D = GD.getDecl(); 1814 1815 unsigned Flags = 0; 1816 llvm::DIFile Unit = getOrCreateFile(CurLoc); 1817 llvm::DIDescriptor FDContext(Unit); 1818 llvm::DIArray TParamsArray; 1819 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1820 // If there is a DISubprogram for this function available then use it. 1821 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator 1822 FI = SPCache.find(FD->getCanonicalDecl()); 1823 if (FI != SPCache.end()) { 1824 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(&*FI->second)); 1825 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) { 1826 llvm::MDNode *SPN = SP; 1827 LexicalBlockStack.push_back(SPN); 1828 RegionMap[D] = llvm::WeakVH(SP); 1829 return; 1830 } 1831 } 1832 Name = getFunctionName(FD); 1833 // Use mangled name as linkage name for c/c++ functions. 1834 if (!Fn->hasInternalLinkage()) 1835 LinkageName = CGM.getMangledName(GD); 1836 if (LinkageName == Name) 1837 LinkageName = StringRef(); 1838 if (FD->hasPrototype()) 1839 Flags |= llvm::DIDescriptor::FlagPrototyped; 1840 if (const NamespaceDecl *NSDecl = 1841 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext())) 1842 FDContext = getOrCreateNameSpace(NSDecl); 1843 else if (const RecordDecl *RDecl = 1844 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) 1845 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext())); 1846 1847 // Collect template parameters. 1848 TParamsArray = CollectFunctionTemplateParams(FD, Unit); 1849 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) { 1850 Name = getObjCMethodName(OMD); 1851 Flags |= llvm::DIDescriptor::FlagPrototyped; 1852 } else { 1853 // Use llvm function name. 1854 Name = Fn->getName(); 1855 Flags |= llvm::DIDescriptor::FlagPrototyped; 1856 } 1857 if (!Name.empty() && Name[0] == '\01') 1858 Name = Name.substr(1); 1859 1860 // It is expected that CurLoc is set before using EmitFunctionStart. 1861 // Usually, CurLoc points to the left bracket location of compound 1862 // statement representing function body. 1863 unsigned LineNo = getLineNumber(CurLoc); 1864 if (D->isImplicit()) 1865 Flags |= llvm::DIDescriptor::FlagArtificial; 1866 llvm::DISubprogram SPDecl = getFunctionDeclaration(D); 1867 llvm::DISubprogram SP = 1868 DBuilder.createFunction(FDContext, Name, LinkageName, Unit, 1869 LineNo, getOrCreateFunctionType(D, FnType, Unit), 1870 Fn->hasInternalLinkage(), true/*definition*/, 1871 Flags, CGM.getLangOptions().Optimize, Fn, 1872 TParamsArray, SPDecl); 1873 1874 // Push function on region stack. 1875 llvm::MDNode *SPN = SP; 1876 LexicalBlockStack.push_back(SPN); 1877 RegionMap[D] = llvm::WeakVH(SP); 1878 } 1879 1880 /// EmitLocation - Emit metadata to indicate a change in line/column 1881 /// information in the source file. 1882 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) { 1883 1884 // Update our current location 1885 setLocation(Loc); 1886 1887 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return; 1888 1889 // Don't bother if things are the same as last time. 1890 SourceManager &SM = CGM.getContext().getSourceManager(); 1891 if (CurLoc == PrevLoc || 1892 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc)) 1893 // New Builder may not be in sync with CGDebugInfo. 1894 if (!Builder.getCurrentDebugLocation().isUnknown()) 1895 return; 1896 1897 // Update last state. 1898 PrevLoc = CurLoc; 1899 1900 llvm::MDNode *Scope = LexicalBlockStack.back(); 1901 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc), 1902 getColumnNumber(CurLoc), 1903 Scope)); 1904 } 1905 1906 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on 1907 /// the stack. 1908 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) { 1909 llvm::DIDescriptor D = 1910 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ? 1911 llvm::DIDescriptor() : 1912 llvm::DIDescriptor(LexicalBlockStack.back()), 1913 getOrCreateFile(CurLoc), 1914 getLineNumber(CurLoc), 1915 getColumnNumber(CurLoc)); 1916 llvm::MDNode *DN = D; 1917 LexicalBlockStack.push_back(DN); 1918 } 1919 1920 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative 1921 /// region - beginning of a DW_TAG_lexical_block. 1922 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) { 1923 // Set our current location. 1924 setLocation(Loc); 1925 1926 // Create a new lexical block and push it on the stack. 1927 CreateLexicalBlock(Loc); 1928 1929 // Emit a line table change for the current location inside the new scope. 1930 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc), 1931 getColumnNumber(Loc), 1932 LexicalBlockStack.back())); 1933 } 1934 1935 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative 1936 /// region - end of a DW_TAG_lexical_block. 1937 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) { 1938 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 1939 1940 // Provide an entry in the line table for the end of the block. 1941 EmitLocation(Builder, Loc); 1942 1943 LexicalBlockStack.pop_back(); 1944 } 1945 1946 /// EmitFunctionEnd - Constructs the debug code for exiting a function. 1947 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) { 1948 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 1949 unsigned RCount = FnBeginRegionCount.back(); 1950 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch"); 1951 1952 // Pop all regions for this function. 1953 while (LexicalBlockStack.size() != RCount) 1954 EmitLexicalBlockEnd(Builder, CurLoc); 1955 FnBeginRegionCount.pop_back(); 1956 } 1957 1958 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref. 1959 // See BuildByRefType. 1960 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD, 1961 uint64_t *XOffset) { 1962 1963 SmallVector<llvm::Value *, 5> EltTys; 1964 QualType FType; 1965 uint64_t FieldSize, FieldOffset; 1966 unsigned FieldAlign; 1967 1968 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 1969 QualType Type = VD->getType(); 1970 1971 FieldOffset = 0; 1972 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 1973 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 1974 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset)); 1975 FType = CGM.getContext().IntTy; 1976 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 1977 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset)); 1978 1979 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type); 1980 if (HasCopyAndDispose) { 1981 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 1982 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper", 1983 &FieldOffset)); 1984 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper", 1985 &FieldOffset)); 1986 } 1987 1988 CharUnits Align = CGM.getContext().getDeclAlign(VD); 1989 if (Align > CGM.getContext().toCharUnitsFromBits( 1990 CGM.getContext().getTargetInfo().getPointerAlign(0))) { 1991 CharUnits FieldOffsetInBytes 1992 = CGM.getContext().toCharUnitsFromBits(FieldOffset); 1993 CharUnits AlignedOffsetInBytes 1994 = FieldOffsetInBytes.RoundUpToAlignment(Align); 1995 CharUnits NumPaddingBytes 1996 = AlignedOffsetInBytes - FieldOffsetInBytes; 1997 1998 if (NumPaddingBytes.isPositive()) { 1999 llvm::APInt pad(32, NumPaddingBytes.getQuantity()); 2000 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy, 2001 pad, ArrayType::Normal, 0); 2002 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset)); 2003 } 2004 } 2005 2006 FType = Type; 2007 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 2008 FieldSize = CGM.getContext().getTypeSize(FType); 2009 FieldAlign = CGM.getContext().toBits(Align); 2010 2011 *XOffset = FieldOffset; 2012 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 2013 0, FieldSize, FieldAlign, 2014 FieldOffset, 0, FieldTy); 2015 EltTys.push_back(FieldTy); 2016 FieldOffset += FieldSize; 2017 2018 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys); 2019 2020 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct; 2021 2022 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags, 2023 Elements); 2024 } 2025 2026 /// EmitDeclare - Emit local variable declaration debug info. 2027 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag, 2028 llvm::Value *Storage, 2029 unsigned ArgNo, CGBuilderTy &Builder) { 2030 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2031 2032 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 2033 llvm::DIType Ty; 2034 uint64_t XOffset = 0; 2035 if (VD->hasAttr<BlocksAttr>()) 2036 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 2037 else 2038 Ty = getOrCreateType(VD->getType(), Unit); 2039 2040 // If there is not any debug info for type then do not emit debug info 2041 // for this variable. 2042 if (!Ty) 2043 return; 2044 2045 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) { 2046 // If Storage is an aggregate returned as 'sret' then let debugger know 2047 // about this. 2048 if (Arg->hasStructRetAttr()) 2049 Ty = DBuilder.createReferenceType(Ty); 2050 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) { 2051 // If an aggregate variable has non trivial destructor or non trivial copy 2052 // constructor than it is pass indirectly. Let debug info know about this 2053 // by using reference of the aggregate type as a argument type. 2054 if (!Record->hasTrivialCopyConstructor() || 2055 !Record->hasTrivialDestructor()) 2056 Ty = DBuilder.createReferenceType(Ty); 2057 } 2058 } 2059 2060 // Get location information. 2061 unsigned Line = getLineNumber(VD->getLocation()); 2062 unsigned Column = getColumnNumber(VD->getLocation()); 2063 unsigned Flags = 0; 2064 if (VD->isImplicit()) 2065 Flags |= llvm::DIDescriptor::FlagArtificial; 2066 llvm::MDNode *Scope = LexicalBlockStack.back(); 2067 2068 StringRef Name = VD->getName(); 2069 if (!Name.empty()) { 2070 if (VD->hasAttr<BlocksAttr>()) { 2071 CharUnits offset = CharUnits::fromQuantity(32); 2072 SmallVector<llvm::Value *, 9> addr; 2073 llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext()); 2074 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2075 // offset of __forwarding field 2076 offset = CGM.getContext().toCharUnitsFromBits( 2077 CGM.getContext().getTargetInfo().getPointerWidth(0)); 2078 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2079 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 2080 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2081 // offset of x field 2082 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 2083 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2084 2085 // Create the descriptor for the variable. 2086 llvm::DIVariable D = 2087 DBuilder.createComplexVariable(Tag, 2088 llvm::DIDescriptor(Scope), 2089 VD->getName(), Unit, Line, Ty, 2090 addr, ArgNo); 2091 2092 // Insert an llvm.dbg.declare into the current block. 2093 // Insert an llvm.dbg.declare into the current block. 2094 llvm::Instruction *Call = 2095 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 2096 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 2097 return; 2098 } 2099 // Create the descriptor for the variable. 2100 llvm::DIVariable D = 2101 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope), 2102 Name, Unit, Line, Ty, 2103 CGM.getLangOptions().Optimize, Flags, ArgNo); 2104 2105 // Insert an llvm.dbg.declare into the current block. 2106 llvm::Instruction *Call = 2107 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 2108 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 2109 return; 2110 } 2111 2112 // If VD is an anonymous union then Storage represents value for 2113 // all union fields. 2114 if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) { 2115 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 2116 if (RD->isUnion()) { 2117 for (RecordDecl::field_iterator I = RD->field_begin(), 2118 E = RD->field_end(); 2119 I != E; ++I) { 2120 FieldDecl *Field = *I; 2121 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 2122 StringRef FieldName = Field->getName(); 2123 2124 // Ignore unnamed fields. Do not ignore unnamed records. 2125 if (FieldName.empty() && !isa<RecordType>(Field->getType())) 2126 continue; 2127 2128 // Use VarDecl's Tag, Scope and Line number. 2129 llvm::DIVariable D = 2130 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope), 2131 FieldName, Unit, Line, FieldTy, 2132 CGM.getLangOptions().Optimize, Flags, 2133 ArgNo); 2134 2135 // Insert an llvm.dbg.declare into the current block. 2136 llvm::Instruction *Call = 2137 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 2138 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 2139 } 2140 } 2141 } 2142 } 2143 2144 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, 2145 llvm::Value *Storage, 2146 CGBuilderTy &Builder) { 2147 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder); 2148 } 2149 2150 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable( 2151 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder, 2152 const CGBlockInfo &blockInfo) { 2153 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2154 2155 if (Builder.GetInsertBlock() == 0) 2156 return; 2157 2158 bool isByRef = VD->hasAttr<BlocksAttr>(); 2159 2160 uint64_t XOffset = 0; 2161 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 2162 llvm::DIType Ty; 2163 if (isByRef) 2164 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 2165 else 2166 Ty = getOrCreateType(VD->getType(), Unit); 2167 2168 // Get location information. 2169 unsigned Line = getLineNumber(VD->getLocation()); 2170 unsigned Column = getColumnNumber(VD->getLocation()); 2171 2172 const llvm::TargetData &target = CGM.getTargetData(); 2173 2174 CharUnits offset = CharUnits::fromQuantity( 2175 target.getStructLayout(blockInfo.StructureType) 2176 ->getElementOffset(blockInfo.getCapture(VD).getIndex())); 2177 2178 SmallVector<llvm::Value *, 9> addr; 2179 llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext()); 2180 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2181 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2182 if (isByRef) { 2183 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 2184 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2185 // offset of __forwarding field 2186 offset = CGM.getContext() 2187 .toCharUnitsFromBits(target.getPointerSizeInBits()); 2188 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2189 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 2190 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2191 // offset of x field 2192 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 2193 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2194 } 2195 2196 // Create the descriptor for the variable. 2197 llvm::DIVariable D = 2198 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable, 2199 llvm::DIDescriptor(LexicalBlockStack.back()), 2200 VD->getName(), Unit, Line, Ty, addr); 2201 // Insert an llvm.dbg.declare into the current block. 2202 llvm::Instruction *Call = 2203 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint()); 2204 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, 2205 LexicalBlockStack.back())); 2206 } 2207 2208 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument 2209 /// variable declaration. 2210 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI, 2211 unsigned ArgNo, 2212 CGBuilderTy &Builder) { 2213 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder); 2214 } 2215 2216 namespace { 2217 struct BlockLayoutChunk { 2218 uint64_t OffsetInBits; 2219 const BlockDecl::Capture *Capture; 2220 }; 2221 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) { 2222 return l.OffsetInBits < r.OffsetInBits; 2223 } 2224 } 2225 2226 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, 2227 llvm::Value *addr, 2228 CGBuilderTy &Builder) { 2229 ASTContext &C = CGM.getContext(); 2230 const BlockDecl *blockDecl = block.getBlockDecl(); 2231 2232 // Collect some general information about the block's location. 2233 SourceLocation loc = blockDecl->getCaretLocation(); 2234 llvm::DIFile tunit = getOrCreateFile(loc); 2235 unsigned line = getLineNumber(loc); 2236 unsigned column = getColumnNumber(loc); 2237 2238 // Build the debug-info type for the block literal. 2239 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext())); 2240 2241 const llvm::StructLayout *blockLayout = 2242 CGM.getTargetData().getStructLayout(block.StructureType); 2243 2244 SmallVector<llvm::Value*, 16> fields; 2245 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public, 2246 blockLayout->getElementOffsetInBits(0), 2247 tunit, tunit)); 2248 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public, 2249 blockLayout->getElementOffsetInBits(1), 2250 tunit, tunit)); 2251 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public, 2252 blockLayout->getElementOffsetInBits(2), 2253 tunit, tunit)); 2254 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public, 2255 blockLayout->getElementOffsetInBits(3), 2256 tunit, tunit)); 2257 fields.push_back(createFieldType("__descriptor", 2258 C.getPointerType(block.NeedsCopyDispose ? 2259 C.getBlockDescriptorExtendedType() : 2260 C.getBlockDescriptorType()), 2261 0, loc, AS_public, 2262 blockLayout->getElementOffsetInBits(4), 2263 tunit, tunit)); 2264 2265 // We want to sort the captures by offset, not because DWARF 2266 // requires this, but because we're paranoid about debuggers. 2267 SmallVector<BlockLayoutChunk, 8> chunks; 2268 2269 // 'this' capture. 2270 if (blockDecl->capturesCXXThis()) { 2271 BlockLayoutChunk chunk; 2272 chunk.OffsetInBits = 2273 blockLayout->getElementOffsetInBits(block.CXXThisIndex); 2274 chunk.Capture = 0; 2275 chunks.push_back(chunk); 2276 } 2277 2278 // Variable captures. 2279 for (BlockDecl::capture_const_iterator 2280 i = blockDecl->capture_begin(), e = blockDecl->capture_end(); 2281 i != e; ++i) { 2282 const BlockDecl::Capture &capture = *i; 2283 const VarDecl *variable = capture.getVariable(); 2284 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable); 2285 2286 // Ignore constant captures. 2287 if (captureInfo.isConstant()) 2288 continue; 2289 2290 BlockLayoutChunk chunk; 2291 chunk.OffsetInBits = 2292 blockLayout->getElementOffsetInBits(captureInfo.getIndex()); 2293 chunk.Capture = &capture; 2294 chunks.push_back(chunk); 2295 } 2296 2297 // Sort by offset. 2298 llvm::array_pod_sort(chunks.begin(), chunks.end()); 2299 2300 for (SmallVectorImpl<BlockLayoutChunk>::iterator 2301 i = chunks.begin(), e = chunks.end(); i != e; ++i) { 2302 uint64_t offsetInBits = i->OffsetInBits; 2303 const BlockDecl::Capture *capture = i->Capture; 2304 2305 // If we have a null capture, this must be the C++ 'this' capture. 2306 if (!capture) { 2307 const CXXMethodDecl *method = 2308 cast<CXXMethodDecl>(blockDecl->getNonClosureContext()); 2309 QualType type = method->getThisType(C); 2310 2311 fields.push_back(createFieldType("this", type, 0, loc, AS_public, 2312 offsetInBits, tunit, tunit)); 2313 continue; 2314 } 2315 2316 const VarDecl *variable = capture->getVariable(); 2317 StringRef name = variable->getName(); 2318 2319 llvm::DIType fieldType; 2320 if (capture->isByRef()) { 2321 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy); 2322 2323 // FIXME: this creates a second copy of this type! 2324 uint64_t xoffset; 2325 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset); 2326 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first); 2327 fieldType = DBuilder.createMemberType(tunit, name, tunit, line, 2328 ptrInfo.first, ptrInfo.second, 2329 offsetInBits, 0, fieldType); 2330 } else { 2331 fieldType = createFieldType(name, variable->getType(), 0, 2332 loc, AS_public, offsetInBits, tunit, tunit); 2333 } 2334 fields.push_back(fieldType); 2335 } 2336 2337 llvm::SmallString<36> typeName; 2338 llvm::raw_svector_ostream(typeName) 2339 << "__block_literal_" << CGM.getUniqueBlockCount(); 2340 2341 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields); 2342 2343 llvm::DIType type = 2344 DBuilder.createStructType(tunit, typeName.str(), tunit, line, 2345 CGM.getContext().toBits(block.BlockSize), 2346 CGM.getContext().toBits(block.BlockAlign), 2347 0, fieldsArray); 2348 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits); 2349 2350 // Get overall information about the block. 2351 unsigned flags = llvm::DIDescriptor::FlagArtificial; 2352 llvm::MDNode *scope = LexicalBlockStack.back(); 2353 StringRef name = ".block_descriptor"; 2354 2355 // Create the descriptor for the parameter. 2356 llvm::DIVariable debugVar = 2357 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable, 2358 llvm::DIDescriptor(scope), 2359 name, tunit, line, type, 2360 CGM.getLangOptions().Optimize, flags, 2361 cast<llvm::Argument>(addr)->getArgNo() + 1); 2362 2363 // Insert an llvm.dbg.value into the current block. 2364 llvm::Instruction *declare = 2365 DBuilder.insertDbgValueIntrinsic(addr, 0, debugVar, 2366 Builder.GetInsertBlock()); 2367 declare->setDebugLoc(llvm::DebugLoc::get(line, column, scope)); 2368 } 2369 2370 /// EmitGlobalVariable - Emit information about a global variable. 2371 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 2372 const VarDecl *D) { 2373 // Create global variable debug descriptor. 2374 llvm::DIFile Unit = getOrCreateFile(D->getLocation()); 2375 unsigned LineNo = getLineNumber(D->getLocation()); 2376 2377 setLocation(D->getLocation()); 2378 2379 QualType T = D->getType(); 2380 if (T->isIncompleteArrayType()) { 2381 2382 // CodeGen turns int[] into int[1] so we'll do the same here. 2383 llvm::APSInt ConstVal(32); 2384 2385 ConstVal = 1; 2386 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 2387 2388 T = CGM.getContext().getConstantArrayType(ET, ConstVal, 2389 ArrayType::Normal, 0); 2390 } 2391 StringRef DeclName = D->getName(); 2392 StringRef LinkageName; 2393 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext()) 2394 && !isa<ObjCMethodDecl>(D->getDeclContext())) 2395 LinkageName = Var->getName(); 2396 if (LinkageName == DeclName) 2397 LinkageName = StringRef(); 2398 llvm::DIDescriptor DContext = 2399 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext())); 2400 DBuilder.createStaticVariable(DContext, DeclName, LinkageName, 2401 Unit, LineNo, getOrCreateType(T, Unit), 2402 Var->hasInternalLinkage(), Var); 2403 } 2404 2405 /// EmitGlobalVariable - Emit information about an objective-c interface. 2406 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 2407 ObjCInterfaceDecl *ID) { 2408 // Create global variable debug descriptor. 2409 llvm::DIFile Unit = getOrCreateFile(ID->getLocation()); 2410 unsigned LineNo = getLineNumber(ID->getLocation()); 2411 2412 StringRef Name = ID->getName(); 2413 2414 QualType T = CGM.getContext().getObjCInterfaceType(ID); 2415 if (T->isIncompleteArrayType()) { 2416 2417 // CodeGen turns int[] into int[1] so we'll do the same here. 2418 llvm::APSInt ConstVal(32); 2419 2420 ConstVal = 1; 2421 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 2422 2423 T = CGM.getContext().getConstantArrayType(ET, ConstVal, 2424 ArrayType::Normal, 0); 2425 } 2426 2427 DBuilder.createGlobalVariable(Name, Unit, LineNo, 2428 getOrCreateType(T, Unit), 2429 Var->hasInternalLinkage(), Var); 2430 } 2431 2432 /// EmitGlobalVariable - Emit global variable's debug info. 2433 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, 2434 llvm::Constant *Init) { 2435 // Create the descriptor for the variable. 2436 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 2437 StringRef Name = VD->getName(); 2438 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit); 2439 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) { 2440 if (const EnumDecl *ED = dyn_cast<EnumDecl>(ECD->getDeclContext())) 2441 Ty = CreateEnumType(ED); 2442 } 2443 // Do not use DIGlobalVariable for enums. 2444 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type) 2445 return; 2446 DBuilder.createStaticVariable(Unit, Name, Name, Unit, 2447 getLineNumber(VD->getLocation()), 2448 Ty, true, Init); 2449 } 2450 2451 /// getOrCreateNamesSpace - Return namespace descriptor for the given 2452 /// namespace decl. 2453 llvm::DINameSpace 2454 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) { 2455 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I = 2456 NameSpaceCache.find(NSDecl); 2457 if (I != NameSpaceCache.end()) 2458 return llvm::DINameSpace(cast<llvm::MDNode>(I->second)); 2459 2460 unsigned LineNo = getLineNumber(NSDecl->getLocation()); 2461 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation()); 2462 llvm::DIDescriptor Context = 2463 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext())); 2464 llvm::DINameSpace NS = 2465 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo); 2466 NameSpaceCache[NSDecl] = llvm::WeakVH(NS); 2467 return NS; 2468 } 2469 2470 /// UpdateCompletedType - Update type cache because the type is now 2471 /// translated. 2472 void CGDebugInfo::UpdateCompletedType(const TagDecl *TD) { 2473 QualType Ty = CGM.getContext().getTagDeclType(TD); 2474 2475 // If the type exist in type cache then remove it from the cache. 2476 // There is no need to prepare debug info for the completed type 2477 // right now. It will be generated on demand lazily. 2478 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 2479 TypeCache.find(Ty.getAsOpaquePtr()); 2480 if (it != TypeCache.end()) 2481 TypeCache.erase(it); 2482 } 2483