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