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