CGDebugInfo.cpp revision 912964863c344dd84976ee281bd213d0485645ba
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 "CGBlocks.h" 16#include "CGCXXABI.h" 17#include "CGObjCRuntime.h" 18#include "CodeGenFunction.h" 19#include "CodeGenModule.h" 20#include "clang/AST/ASTContext.h" 21#include "clang/AST/DeclFriend.h" 22#include "clang/AST/DeclObjC.h" 23#include "clang/AST/DeclTemplate.h" 24#include "clang/AST/Expr.h" 25#include "clang/AST/RecordLayout.h" 26#include "clang/Basic/FileManager.h" 27#include "clang/Basic/SourceManager.h" 28#include "clang/Basic/Version.h" 29#include "clang/Frontend/CodeGenOptions.h" 30#include "llvm/ADT/SmallVector.h" 31#include "llvm/ADT/StringExtras.h" 32#include "llvm/IR/Constants.h" 33#include "llvm/IR/DataLayout.h" 34#include "llvm/IR/DerivedTypes.h" 35#include "llvm/IR/Instructions.h" 36#include "llvm/IR/Intrinsics.h" 37#include "llvm/IR/Module.h" 38#include "llvm/Support/Dwarf.h" 39#include "llvm/Support/FileSystem.h" 40using namespace clang; 41using namespace clang::CodeGen; 42 43CGDebugInfo::CGDebugInfo(CodeGenModule &CGM) 44 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()), 45 DBuilder(CGM.getModule()), 46 BlockLiteralGenericSet(false) { 47 CreateCompileUnit(); 48} 49 50CGDebugInfo::~CGDebugInfo() { 51 assert(LexicalBlockStack.empty() && 52 "Region stack mismatch, stack not empty!"); 53} 54 55void CGDebugInfo::setLocation(SourceLocation Loc) { 56 // If the new location isn't valid return. 57 if (!Loc.isValid()) return; 58 59 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc); 60 61 // If we've changed files in the middle of a lexical scope go ahead 62 // and create a new lexical scope with file node if it's different 63 // from the one in the scope. 64 if (LexicalBlockStack.empty()) return; 65 66 SourceManager &SM = CGM.getContext().getSourceManager(); 67 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc); 68 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc); 69 70 if (PCLoc.isInvalid() || PPLoc.isInvalid() || 71 !strcmp(PPLoc.getFilename(), PCLoc.getFilename())) 72 return; 73 74 llvm::MDNode *LB = LexicalBlockStack.back(); 75 llvm::DIScope Scope = llvm::DIScope(LB); 76 if (Scope.isLexicalBlockFile()) { 77 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB); 78 llvm::DIDescriptor D 79 = DBuilder.createLexicalBlockFile(LBF.getScope(), 80 getOrCreateFile(CurLoc)); 81 llvm::MDNode *N = D; 82 LexicalBlockStack.pop_back(); 83 LexicalBlockStack.push_back(N); 84 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) { 85 llvm::DIDescriptor D 86 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)); 87 llvm::MDNode *N = D; 88 LexicalBlockStack.pop_back(); 89 LexicalBlockStack.push_back(N); 90 } 91} 92 93/// getContextDescriptor - Get context info for the decl. 94llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) { 95 if (!Context) 96 return TheCU; 97 98 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator 99 I = RegionMap.find(Context); 100 if (I != RegionMap.end()) { 101 llvm::Value *V = I->second; 102 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V)); 103 } 104 105 // Check namespace. 106 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context)) 107 return getOrCreateNameSpace(NSDecl); 108 109 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) 110 if (!RDecl->isDependentType()) 111 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl), 112 getOrCreateMainFile()); 113 return TheCU; 114} 115 116/// getFunctionName - Get function name for the given FunctionDecl. If the 117/// name is constructred on demand (e.g. C++ destructor) then the name 118/// is stored on the side. 119StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) { 120 assert (FD && "Invalid FunctionDecl!"); 121 IdentifierInfo *FII = FD->getIdentifier(); 122 FunctionTemplateSpecializationInfo *Info 123 = FD->getTemplateSpecializationInfo(); 124 if (!Info && FII) 125 return FII->getName(); 126 127 // Otherwise construct human readable name for debug info. 128 SmallString<128> NS; 129 llvm::raw_svector_ostream OS(NS); 130 FD->printName(OS); 131 132 // Add any template specialization args. 133 if (Info) { 134 const TemplateArgumentList *TArgs = Info->TemplateArguments; 135 const TemplateArgument *Args = TArgs->data(); 136 unsigned NumArgs = TArgs->size(); 137 PrintingPolicy Policy(CGM.getLangOpts()); 138 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs, 139 Policy); 140 } 141 142 // Copy this name on the side and use its reference. 143 OS.flush(); 144 char *StrPtr = DebugInfoNames.Allocate<char>(NS.size()); 145 memcpy(StrPtr, NS.data(), NS.size()); 146 return StringRef(StrPtr, NS.size()); 147} 148 149StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) { 150 SmallString<256> MethodName; 151 llvm::raw_svector_ostream OS(MethodName); 152 OS << (OMD->isInstanceMethod() ? '-' : '+') << '['; 153 const DeclContext *DC = OMD->getDeclContext(); 154 if (const ObjCImplementationDecl *OID = 155 dyn_cast<const ObjCImplementationDecl>(DC)) { 156 OS << OID->getName(); 157 } else if (const ObjCInterfaceDecl *OID = 158 dyn_cast<const ObjCInterfaceDecl>(DC)) { 159 OS << OID->getName(); 160 } else if (const ObjCCategoryImplDecl *OCD = 161 dyn_cast<const ObjCCategoryImplDecl>(DC)){ 162 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' << 163 OCD->getIdentifier()->getNameStart() << ')'; 164 } else if (isa<ObjCProtocolDecl>(DC)) { 165 // We can extract the type of the class from the self pointer. 166 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) { 167 QualType ClassTy = 168 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType(); 169 ClassTy.print(OS, PrintingPolicy(LangOptions())); 170 } 171 } 172 OS << ' ' << OMD->getSelector().getAsString() << ']'; 173 174 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell()); 175 memcpy(StrPtr, MethodName.begin(), OS.tell()); 176 return StringRef(StrPtr, OS.tell()); 177} 178 179/// getSelectorName - Return selector name. This is used for debugging 180/// info. 181StringRef CGDebugInfo::getSelectorName(Selector S) { 182 const std::string &SName = S.getAsString(); 183 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size()); 184 memcpy(StrPtr, SName.data(), SName.size()); 185 return StringRef(StrPtr, SName.size()); 186} 187 188/// getClassName - Get class name including template argument list. 189StringRef 190CGDebugInfo::getClassName(const RecordDecl *RD) { 191 const ClassTemplateSpecializationDecl *Spec 192 = dyn_cast<ClassTemplateSpecializationDecl>(RD); 193 if (!Spec) 194 return RD->getName(); 195 196 const TemplateArgument *Args; 197 unsigned NumArgs; 198 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) { 199 const TemplateSpecializationType *TST = 200 cast<TemplateSpecializationType>(TAW->getType()); 201 Args = TST->getArgs(); 202 NumArgs = TST->getNumArgs(); 203 } else { 204 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 205 Args = TemplateArgs.data(); 206 NumArgs = TemplateArgs.size(); 207 } 208 StringRef Name = RD->getIdentifier()->getName(); 209 PrintingPolicy Policy(CGM.getLangOpts()); 210 SmallString<128> TemplateArgList; 211 { 212 llvm::raw_svector_ostream OS(TemplateArgList); 213 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs, 214 Policy); 215 } 216 217 // Copy this name on the side and use its reference. 218 size_t Length = Name.size() + TemplateArgList.size(); 219 char *StrPtr = DebugInfoNames.Allocate<char>(Length); 220 memcpy(StrPtr, Name.data(), Name.size()); 221 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size()); 222 return StringRef(StrPtr, Length); 223} 224 225/// getOrCreateFile - Get the file debug info descriptor for the input location. 226llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) { 227 if (!Loc.isValid()) 228 // If Location is not valid then use main input file. 229 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory()); 230 231 SourceManager &SM = CGM.getContext().getSourceManager(); 232 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 233 234 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty()) 235 // If the location is not valid then use main input file. 236 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory()); 237 238 // Cache the results. 239 const char *fname = PLoc.getFilename(); 240 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it = 241 DIFileCache.find(fname); 242 243 if (it != DIFileCache.end()) { 244 // Verify that the information still exists. 245 if (llvm::Value *V = it->second) 246 return llvm::DIFile(cast<llvm::MDNode>(V)); 247 } 248 249 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname()); 250 251 DIFileCache[fname] = F; 252 return F; 253} 254 255/// getOrCreateMainFile - Get the file info for main compile unit. 256llvm::DIFile CGDebugInfo::getOrCreateMainFile() { 257 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory()); 258} 259 260/// getLineNumber - Get line number for the location. If location is invalid 261/// then use current location. 262unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) { 263 if (Loc.isInvalid() && CurLoc.isInvalid()) 264 return 0; 265 SourceManager &SM = CGM.getContext().getSourceManager(); 266 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc); 267 return PLoc.isValid()? PLoc.getLine() : 0; 268} 269 270/// getColumnNumber - Get column number for the location. 271unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) { 272 // We may not want column information at all. 273 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo) 274 return 0; 275 276 // If the location is invalid then use the current column. 277 if (Loc.isInvalid() && CurLoc.isInvalid()) 278 return 0; 279 SourceManager &SM = CGM.getContext().getSourceManager(); 280 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc); 281 return PLoc.isValid()? PLoc.getColumn() : 0; 282} 283 284StringRef CGDebugInfo::getCurrentDirname() { 285 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty()) 286 return CGM.getCodeGenOpts().DebugCompilationDir; 287 288 if (!CWDName.empty()) 289 return CWDName; 290 SmallString<256> CWD; 291 llvm::sys::fs::current_path(CWD); 292 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size()); 293 memcpy(CompDirnamePtr, CWD.data(), CWD.size()); 294 return CWDName = StringRef(CompDirnamePtr, CWD.size()); 295} 296 297/// CreateCompileUnit - Create new compile unit. 298void CGDebugInfo::CreateCompileUnit() { 299 300 // Get absolute path name. 301 SourceManager &SM = CGM.getContext().getSourceManager(); 302 std::string MainFileName = CGM.getCodeGenOpts().MainFileName; 303 if (MainFileName.empty()) 304 MainFileName = "<unknown>"; 305 306 // The main file name provided via the "-main-file-name" option contains just 307 // the file name itself with no path information. This file name may have had 308 // a relative path, so we look into the actual file entry for the main 309 // file to determine the real absolute path for the file. 310 std::string MainFileDir; 311 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 312 MainFileDir = MainFile->getDir()->getName(); 313 if (MainFileDir != ".") 314 MainFileName = MainFileDir + "/" + MainFileName; 315 } 316 317 // Save filename string. 318 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length()); 319 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length()); 320 StringRef Filename(FilenamePtr, MainFileName.length()); 321 322 // Save split dwarf file string. 323 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile; 324 char *SplitDwarfPtr = DebugInfoNames.Allocate<char>(SplitDwarfFile.length()); 325 memcpy(SplitDwarfPtr, SplitDwarfFile.c_str(), SplitDwarfFile.length()); 326 StringRef SplitDwarfFilename(SplitDwarfPtr, SplitDwarfFile.length()); 327 328 unsigned LangTag; 329 const LangOptions &LO = CGM.getLangOpts(); 330 if (LO.CPlusPlus) { 331 if (LO.ObjC1) 332 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus; 333 else 334 LangTag = llvm::dwarf::DW_LANG_C_plus_plus; 335 } else if (LO.ObjC1) { 336 LangTag = llvm::dwarf::DW_LANG_ObjC; 337 } else if (LO.C99) { 338 LangTag = llvm::dwarf::DW_LANG_C99; 339 } else { 340 LangTag = llvm::dwarf::DW_LANG_C89; 341 } 342 343 std::string Producer = getClangFullVersion(); 344 345 // Figure out which version of the ObjC runtime we have. 346 unsigned RuntimeVers = 0; 347 if (LO.ObjC1) 348 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1; 349 350 // Create new compile unit. 351 DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(), 352 Producer, LO.Optimize, 353 CGM.getCodeGenOpts().DwarfDebugFlags, 354 RuntimeVers, SplitDwarfFilename); 355 // FIXME - Eliminate TheCU. 356 TheCU = llvm::DICompileUnit(DBuilder.getCU()); 357} 358 359/// CreateType - Get the Basic type from the cache or create a new 360/// one if necessary. 361llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) { 362 unsigned Encoding = 0; 363 StringRef BTName; 364 switch (BT->getKind()) { 365#define BUILTIN_TYPE(Id, SingletonId) 366#define PLACEHOLDER_TYPE(Id, SingletonId) \ 367 case BuiltinType::Id: 368#include "clang/AST/BuiltinTypes.def" 369 case BuiltinType::Dependent: 370 llvm_unreachable("Unexpected builtin type"); 371 case BuiltinType::NullPtr: 372 return DBuilder. 373 createNullPtrType(BT->getName(CGM.getLangOpts())); 374 case BuiltinType::Void: 375 return llvm::DIType(); 376 case BuiltinType::ObjCClass: 377 if (ClassTy.Verify()) 378 return ClassTy; 379 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 380 "objc_class", TheCU, 381 getOrCreateMainFile(), 0); 382 return ClassTy; 383 case BuiltinType::ObjCId: { 384 // typedef struct objc_class *Class; 385 // typedef struct objc_object { 386 // Class isa; 387 // } *id; 388 389 if (ObjTy.Verify()) 390 return ObjTy; 391 392 if (!ClassTy.Verify()) 393 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 394 "objc_class", TheCU, 395 getOrCreateMainFile(), 0); 396 397 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 398 399 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size); 400 401 ObjTy = 402 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(), 403 0, 0, 0, 0, llvm::DIType(), llvm::DIArray()); 404 405 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType( 406 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy))); 407 return ObjTy; 408 } 409 case BuiltinType::ObjCSel: { 410 if (SelTy.Verify()) 411 return SelTy; 412 SelTy = 413 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 414 "objc_selector", TheCU, getOrCreateMainFile(), 415 0); 416 return SelTy; 417 } 418 419 case BuiltinType::OCLImage1d: 420 return getOrCreateStructPtrType("opencl_image1d_t", 421 OCLImage1dDITy); 422 case BuiltinType::OCLImage1dArray: 423 return getOrCreateStructPtrType("opencl_image1d_array_t", 424 OCLImage1dArrayDITy); 425 case BuiltinType::OCLImage1dBuffer: 426 return getOrCreateStructPtrType("opencl_image1d_buffer_t", 427 OCLImage1dBufferDITy); 428 case BuiltinType::OCLImage2d: 429 return getOrCreateStructPtrType("opencl_image2d_t", 430 OCLImage2dDITy); 431 case BuiltinType::OCLImage2dArray: 432 return getOrCreateStructPtrType("opencl_image2d_array_t", 433 OCLImage2dArrayDITy); 434 case BuiltinType::OCLImage3d: 435 return getOrCreateStructPtrType("opencl_image3d_t", 436 OCLImage3dDITy); 437 case BuiltinType::OCLSampler: 438 return DBuilder.createBasicType("opencl_sampler_t", 439 CGM.getContext().getTypeSize(BT), 440 CGM.getContext().getTypeAlign(BT), 441 llvm::dwarf::DW_ATE_unsigned); 442 case BuiltinType::OCLEvent: 443 return getOrCreateStructPtrType("opencl_event_t", 444 OCLEventDITy); 445 446 case BuiltinType::UChar: 447 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break; 448 case BuiltinType::Char_S: 449 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break; 450 case BuiltinType::Char16: 451 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break; 452 case BuiltinType::UShort: 453 case BuiltinType::UInt: 454 case BuiltinType::UInt128: 455 case BuiltinType::ULong: 456 case BuiltinType::WChar_U: 457 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break; 458 case BuiltinType::Short: 459 case BuiltinType::Int: 460 case BuiltinType::Int128: 461 case BuiltinType::Long: 462 case BuiltinType::WChar_S: 463 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break; 464 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break; 465 case BuiltinType::Half: 466 case BuiltinType::Float: 467 case BuiltinType::LongDouble: 468 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break; 469 } 470 471 switch (BT->getKind()) { 472 case BuiltinType::Long: BTName = "long int"; break; 473 case BuiltinType::LongLong: BTName = "long long int"; break; 474 case BuiltinType::ULong: BTName = "long unsigned int"; break; 475 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break; 476 default: 477 BTName = BT->getName(CGM.getLangOpts()); 478 break; 479 } 480 // Bit size, align and offset of the type. 481 uint64_t Size = CGM.getContext().getTypeSize(BT); 482 uint64_t Align = CGM.getContext().getTypeAlign(BT); 483 llvm::DIType DbgTy = 484 DBuilder.createBasicType(BTName, Size, Align, Encoding); 485 return DbgTy; 486} 487 488llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) { 489 // Bit size, align and offset of the type. 490 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float; 491 if (Ty->isComplexIntegerType()) 492 Encoding = llvm::dwarf::DW_ATE_lo_user; 493 494 uint64_t Size = CGM.getContext().getTypeSize(Ty); 495 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 496 llvm::DIType DbgTy = 497 DBuilder.createBasicType("complex", Size, Align, Encoding); 498 499 return DbgTy; 500} 501 502/// CreateCVRType - Get the qualified type from the cache or create 503/// a new one if necessary. 504llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) { 505 QualifierCollector Qc; 506 const Type *T = Qc.strip(Ty); 507 508 // Ignore these qualifiers for now. 509 Qc.removeObjCGCAttr(); 510 Qc.removeAddressSpace(); 511 Qc.removeObjCLifetime(); 512 513 // We will create one Derived type for one qualifier and recurse to handle any 514 // additional ones. 515 unsigned Tag; 516 if (Qc.hasConst()) { 517 Tag = llvm::dwarf::DW_TAG_const_type; 518 Qc.removeConst(); 519 } else if (Qc.hasVolatile()) { 520 Tag = llvm::dwarf::DW_TAG_volatile_type; 521 Qc.removeVolatile(); 522 } else if (Qc.hasRestrict()) { 523 Tag = llvm::dwarf::DW_TAG_restrict_type; 524 Qc.removeRestrict(); 525 } else { 526 assert(Qc.empty() && "Unknown type qualifier for debug info"); 527 return getOrCreateType(QualType(T, 0), Unit); 528 } 529 530 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit); 531 532 // No need to fill in the Name, Line, Size, Alignment, Offset in case of 533 // CVR derived types. 534 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy); 535 536 return DbgTy; 537} 538 539llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty, 540 llvm::DIFile Unit) { 541 542 // The frontend treats 'id' as a typedef to an ObjCObjectType, 543 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the 544 // debug info, we want to emit 'id' in both cases. 545 if (Ty->isObjCQualifiedIdType()) 546 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit); 547 548 llvm::DIType DbgTy = 549 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 550 Ty->getPointeeType(), Unit); 551 return DbgTy; 552} 553 554llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty, 555 llvm::DIFile Unit) { 556 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 557 Ty->getPointeeType(), Unit); 558} 559 560// Creates a forward declaration for a RecordDecl in the given context. 561llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD, 562 llvm::DIDescriptor Ctx) { 563 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 564 unsigned Line = getLineNumber(RD->getLocation()); 565 StringRef RDName = getClassName(RD); 566 567 unsigned Tag = 0; 568 if (RD->isStruct() || RD->isInterface()) 569 Tag = llvm::dwarf::DW_TAG_structure_type; 570 else if (RD->isUnion()) 571 Tag = llvm::dwarf::DW_TAG_union_type; 572 else { 573 assert(RD->isClass()); 574 Tag = llvm::dwarf::DW_TAG_class_type; 575 } 576 577 // Create the type. 578 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line); 579} 580 581// Walk up the context chain and create forward decls for record decls, 582// and normal descriptors for namespaces. 583llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) { 584 if (!Context) 585 return TheCU; 586 587 // See if we already have the parent. 588 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator 589 I = RegionMap.find(Context); 590 if (I != RegionMap.end()) { 591 llvm::Value *V = I->second; 592 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V)); 593 } 594 595 // Check namespace. 596 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context)) 597 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl)); 598 599 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) { 600 if (!RD->isDependentType()) { 601 llvm::DIType Ty = 602 getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD), 603 getOrCreateMainFile()); 604 return llvm::DIDescriptor(Ty); 605 } 606 } 607 return TheCU; 608} 609 610/// CreatePointeeType - Create Pointee type. If Pointee is a record 611/// then emit record's fwd if debug info size reduction is enabled. 612llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy, 613 llvm::DIFile Unit) { 614 if (DebugKind > CodeGenOptions::LimitedDebugInfo) 615 return getOrCreateType(PointeeTy, Unit); 616 617 // Limit debug info for the pointee type. 618 619 // If we have an existing type, use that, it's still smaller than creating 620 // a new type. 621 llvm::DIType Ty = getTypeOrNull(PointeeTy); 622 if (Ty.Verify()) return Ty; 623 624 // Handle qualifiers. 625 if (PointeeTy.hasLocalQualifiers()) 626 return CreateQualifiedType(PointeeTy, Unit); 627 628 if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) { 629 RecordDecl *RD = RTy->getDecl(); 630 llvm::DIDescriptor FDContext = 631 getContextDescriptor(cast<Decl>(RD->getDeclContext())); 632 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext); 633 TypeCache[QualType(RTy, 0).getAsOpaquePtr()] = RetTy; 634 return RetTy; 635 } 636 return getOrCreateType(PointeeTy, Unit); 637} 638 639llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag, 640 const Type *Ty, 641 QualType PointeeTy, 642 llvm::DIFile Unit) { 643 if (Tag == llvm::dwarf::DW_TAG_reference_type || 644 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type) 645 return DBuilder.createReferenceType(Tag, 646 CreatePointeeType(PointeeTy, Unit)); 647 648 // Bit size, align and offset of the type. 649 // Size is always the size of a pointer. We can't use getTypeSize here 650 // because that does not return the correct value for references. 651 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy); 652 uint64_t Size = CGM.getTarget().getPointerWidth(AS); 653 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 654 655 return DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit), 656 Size, Align); 657} 658 659llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name, 660 llvm::DIType &Cache) { 661 if (Cache.Verify()) 662 return Cache; 663 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name, 664 TheCU, getOrCreateMainFile(), 0); 665 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 666 Cache = DBuilder.createPointerType(Cache, Size); 667 return Cache; 668} 669 670llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty, 671 llvm::DIFile Unit) { 672 if (BlockLiteralGenericSet) 673 return BlockLiteralGeneric; 674 675 SmallVector<llvm::Value *, 8> EltTys; 676 llvm::DIType FieldTy; 677 QualType FType; 678 uint64_t FieldSize, FieldOffset; 679 unsigned FieldAlign; 680 llvm::DIArray Elements; 681 llvm::DIType EltTy, DescTy; 682 683 FieldOffset = 0; 684 FType = CGM.getContext().UnsignedLongTy; 685 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset)); 686 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset)); 687 688 Elements = DBuilder.getOrCreateArray(EltTys); 689 EltTys.clear(); 690 691 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock; 692 unsigned LineNo = getLineNumber(CurLoc); 693 694 EltTy = DBuilder.createStructType(Unit, "__block_descriptor", 695 Unit, LineNo, FieldOffset, 0, 696 Flags, llvm::DIType(), Elements); 697 698 // Bit size, align and offset of the type. 699 uint64_t Size = CGM.getContext().getTypeSize(Ty); 700 701 DescTy = DBuilder.createPointerType(EltTy, Size); 702 703 FieldOffset = 0; 704 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 705 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 706 FType = CGM.getContext().IntTy; 707 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 708 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset)); 709 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 710 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset)); 711 712 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 713 FieldTy = DescTy; 714 FieldSize = CGM.getContext().getTypeSize(Ty); 715 FieldAlign = CGM.getContext().getTypeAlign(Ty); 716 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit, 717 LineNo, FieldSize, FieldAlign, 718 FieldOffset, 0, FieldTy); 719 EltTys.push_back(FieldTy); 720 721 FieldOffset += FieldSize; 722 Elements = DBuilder.getOrCreateArray(EltTys); 723 724 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic", 725 Unit, LineNo, FieldOffset, 0, 726 Flags, llvm::DIType(), Elements); 727 728 BlockLiteralGenericSet = true; 729 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size); 730 return BlockLiteralGeneric; 731} 732 733llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) { 734 // Typedefs are derived from some other type. If we have a typedef of a 735 // typedef, make sure to emit the whole chain. 736 llvm::DIType Src = CreatePointeeType(Ty->getDecl()->getUnderlyingType(), Unit); 737 if (!Src.Verify()) 738 return llvm::DIType(); 739 // We don't set size information, but do specify where the typedef was 740 // declared. 741 unsigned Line = getLineNumber(Ty->getDecl()->getLocation()); 742 const TypedefNameDecl *TyDecl = Ty->getDecl(); 743 744 llvm::DIDescriptor TypedefContext = 745 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext())); 746 747 return 748 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext); 749} 750 751llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty, 752 llvm::DIFile Unit) { 753 SmallVector<llvm::Value *, 16> EltTys; 754 755 // Add the result type at least. 756 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit)); 757 758 // Set up remainder of arguments if there is a prototype. 759 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'! 760 if (isa<FunctionNoProtoType>(Ty)) 761 EltTys.push_back(DBuilder.createUnspecifiedParameter()); 762 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) { 763 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i) 764 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit)); 765 } 766 767 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys); 768 return DBuilder.createSubroutineType(Unit, EltTypeArray); 769} 770 771 772llvm::DIType CGDebugInfo::createFieldType(StringRef name, 773 QualType type, 774 uint64_t sizeInBitsOverride, 775 SourceLocation loc, 776 AccessSpecifier AS, 777 uint64_t offsetInBits, 778 llvm::DIFile tunit, 779 llvm::DIDescriptor scope) { 780 llvm::DIType debugType = getOrCreateType(type, tunit); 781 782 // Get the location for the field. 783 llvm::DIFile file = getOrCreateFile(loc); 784 unsigned line = getLineNumber(loc); 785 786 uint64_t sizeInBits = 0; 787 unsigned alignInBits = 0; 788 if (!type->isIncompleteArrayType()) { 789 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type); 790 791 if (sizeInBitsOverride) 792 sizeInBits = sizeInBitsOverride; 793 } 794 795 unsigned flags = 0; 796 if (AS == clang::AS_private) 797 flags |= llvm::DIDescriptor::FlagPrivate; 798 else if (AS == clang::AS_protected) 799 flags |= llvm::DIDescriptor::FlagProtected; 800 801 return DBuilder.createMemberType(scope, name, file, line, sizeInBits, 802 alignInBits, offsetInBits, flags, debugType); 803} 804 805/// CollectRecordLambdaFields - Helper for CollectRecordFields. 806void CGDebugInfo:: 807CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl, 808 SmallVectorImpl<llvm::Value *> &elements, 809 llvm::DIType RecordTy) { 810 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture 811 // has the name and the location of the variable so we should iterate over 812 // both concurrently. 813 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl); 814 RecordDecl::field_iterator Field = CXXDecl->field_begin(); 815 unsigned fieldno = 0; 816 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(), 817 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) { 818 const LambdaExpr::Capture C = *I; 819 if (C.capturesVariable()) { 820 VarDecl *V = C.getCapturedVar(); 821 llvm::DIFile VUnit = getOrCreateFile(C.getLocation()); 822 StringRef VName = V->getName(); 823 uint64_t SizeInBitsOverride = 0; 824 if (Field->isBitField()) { 825 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext()); 826 assert(SizeInBitsOverride && "found named 0-width bitfield"); 827 } 828 llvm::DIType fieldType 829 = createFieldType(VName, Field->getType(), SizeInBitsOverride, 830 C.getLocation(), Field->getAccess(), 831 layout.getFieldOffset(fieldno), VUnit, RecordTy); 832 elements.push_back(fieldType); 833 } else { 834 // TODO: Need to handle 'this' in some way by probably renaming the 835 // this of the lambda class and having a field member of 'this' or 836 // by using AT_object_pointer for the function and having that be 837 // used as 'this' for semantic references. 838 assert(C.capturesThis() && "Field that isn't captured and isn't this?"); 839 FieldDecl *f = *Field; 840 llvm::DIFile VUnit = getOrCreateFile(f->getLocation()); 841 QualType type = f->getType(); 842 llvm::DIType fieldType 843 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(), 844 layout.getFieldOffset(fieldno), VUnit, RecordTy); 845 846 elements.push_back(fieldType); 847 } 848 } 849} 850 851/// CollectRecordStaticField - Helper for CollectRecordFields. 852void CGDebugInfo:: 853CollectRecordStaticField(const VarDecl *Var, 854 SmallVectorImpl<llvm::Value *> &elements, 855 llvm::DIType RecordTy) { 856 // Create the descriptor for the static variable, with or without 857 // constant initializers. 858 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation()); 859 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit); 860 861 // Do not describe enums as static members. 862 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type) 863 return; 864 865 unsigned LineNumber = getLineNumber(Var->getLocation()); 866 StringRef VName = Var->getName(); 867 llvm::Constant *C = NULL; 868 if (Var->getInit()) { 869 const APValue *Value = Var->evaluateValue(); 870 if (Value) { 871 if (Value->isInt()) 872 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt()); 873 if (Value->isFloat()) 874 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat()); 875 } 876 } 877 878 unsigned Flags = 0; 879 AccessSpecifier Access = Var->getAccess(); 880 if (Access == clang::AS_private) 881 Flags |= llvm::DIDescriptor::FlagPrivate; 882 else if (Access == clang::AS_protected) 883 Flags |= llvm::DIDescriptor::FlagProtected; 884 885 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit, 886 LineNumber, VTy, Flags, C); 887 elements.push_back(GV); 888 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV); 889} 890 891/// CollectRecordNormalField - Helper for CollectRecordFields. 892void CGDebugInfo:: 893CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits, 894 llvm::DIFile tunit, 895 SmallVectorImpl<llvm::Value *> &elements, 896 llvm::DIType RecordTy) { 897 StringRef name = field->getName(); 898 QualType type = field->getType(); 899 900 // Ignore unnamed fields unless they're anonymous structs/unions. 901 if (name.empty() && !type->isRecordType()) 902 return; 903 904 uint64_t SizeInBitsOverride = 0; 905 if (field->isBitField()) { 906 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext()); 907 assert(SizeInBitsOverride && "found named 0-width bitfield"); 908 } 909 910 llvm::DIType fieldType 911 = createFieldType(name, type, SizeInBitsOverride, 912 field->getLocation(), field->getAccess(), 913 OffsetInBits, tunit, RecordTy); 914 915 elements.push_back(fieldType); 916} 917 918/// CollectRecordFields - A helper function to collect debug info for 919/// record fields. This is used while creating debug info entry for a Record. 920void CGDebugInfo:: 921CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit, 922 SmallVectorImpl<llvm::Value *> &elements, 923 llvm::DIType RecordTy) { 924 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record); 925 926 if (CXXDecl && CXXDecl->isLambda()) 927 CollectRecordLambdaFields(CXXDecl, elements, RecordTy); 928 else { 929 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record); 930 931 // Field number for non-static fields. 932 unsigned fieldNo = 0; 933 934 // Bookkeeping for an ms struct, which ignores certain fields. 935 bool IsMsStruct = record->isMsStruct(CGM.getContext()); 936 const FieldDecl *LastFD = 0; 937 938 // Static and non-static members should appear in the same order as 939 // the corresponding declarations in the source program. 940 for (RecordDecl::decl_iterator I = record->decls_begin(), 941 E = record->decls_end(); I != E; ++I) 942 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) 943 CollectRecordStaticField(V, elements, RecordTy); 944 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) { 945 if (IsMsStruct) { 946 // Zero-length bitfields following non-bitfield members are 947 // completely ignored; we don't even count them. 948 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD)) 949 continue; 950 LastFD = field; 951 } 952 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), 953 tunit, elements, RecordTy); 954 955 // Bump field number for next field. 956 ++fieldNo; 957 } 958 } 959} 960 961/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This 962/// function type is not updated to include implicit "this" pointer. Use this 963/// routine to get a method type which includes "this" pointer. 964llvm::DICompositeType 965CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method, 966 llvm::DIFile Unit) { 967 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>(); 968 if (Method->isStatic()) 969 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit)); 970 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()), 971 Func, Unit); 972} 973 974llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType( 975 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) { 976 // Add "this" pointer. 977 llvm::DIArray Args = llvm::DICompositeType( 978 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray(); 979 assert (Args.getNumElements() && "Invalid number of arguments!"); 980 981 SmallVector<llvm::Value *, 16> Elts; 982 983 // First element is always return type. For 'void' functions it is NULL. 984 Elts.push_back(Args.getElement(0)); 985 986 // "this" pointer is always first argument. 987 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl(); 988 if (isa<ClassTemplateSpecializationDecl>(RD)) { 989 // Create pointer type directly in this case. 990 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr); 991 QualType PointeeTy = ThisPtrTy->getPointeeType(); 992 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy); 993 uint64_t Size = CGM.getTarget().getPointerWidth(AS); 994 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy); 995 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit); 996 llvm::DIType ThisPtrType = 997 DBuilder.createPointerType(PointeeType, Size, Align); 998 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType; 999 // TODO: This and the artificial type below are misleading, the 1000 // types aren't artificial the argument is, but the current 1001 // metadata doesn't represent that. 1002 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType); 1003 Elts.push_back(ThisPtrType); 1004 } else { 1005 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit); 1006 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType; 1007 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType); 1008 Elts.push_back(ThisPtrType); 1009 } 1010 1011 // Copy rest of the arguments. 1012 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i) 1013 Elts.push_back(Args.getElement(i)); 1014 1015 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts); 1016 1017 return DBuilder.createSubroutineType(Unit, EltTypeArray); 1018} 1019 1020/// isFunctionLocalClass - Return true if CXXRecordDecl is defined 1021/// inside a function. 1022static bool isFunctionLocalClass(const CXXRecordDecl *RD) { 1023 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext())) 1024 return isFunctionLocalClass(NRD); 1025 if (isa<FunctionDecl>(RD->getDeclContext())) 1026 return true; 1027 return false; 1028} 1029 1030/// CreateCXXMemberFunction - A helper function to create a DISubprogram for 1031/// a single member function GlobalDecl. 1032llvm::DISubprogram 1033CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method, 1034 llvm::DIFile Unit, 1035 llvm::DIType RecordTy) { 1036 bool IsCtorOrDtor = 1037 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method); 1038 1039 StringRef MethodName = getFunctionName(Method); 1040 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit); 1041 1042 // Since a single ctor/dtor corresponds to multiple functions, it doesn't 1043 // make sense to give a single ctor/dtor a linkage name. 1044 StringRef MethodLinkageName; 1045 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent())) 1046 MethodLinkageName = CGM.getMangledName(Method); 1047 1048 // Get the location for the method. 1049 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation()); 1050 unsigned MethodLine = getLineNumber(Method->getLocation()); 1051 1052 // Collect virtual method info. 1053 llvm::DIType ContainingType; 1054 unsigned Virtuality = 0; 1055 unsigned VIndex = 0; 1056 1057 if (Method->isVirtual()) { 1058 if (Method->isPure()) 1059 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual; 1060 else 1061 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual; 1062 1063 // It doesn't make sense to give a virtual destructor a vtable index, 1064 // since a single destructor has two entries in the vtable. 1065 if (!isa<CXXDestructorDecl>(Method)) 1066 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method); 1067 ContainingType = RecordTy; 1068 } 1069 1070 unsigned Flags = 0; 1071 if (Method->isImplicit()) 1072 Flags |= llvm::DIDescriptor::FlagArtificial; 1073 AccessSpecifier Access = Method->getAccess(); 1074 if (Access == clang::AS_private) 1075 Flags |= llvm::DIDescriptor::FlagPrivate; 1076 else if (Access == clang::AS_protected) 1077 Flags |= llvm::DIDescriptor::FlagProtected; 1078 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) { 1079 if (CXXC->isExplicit()) 1080 Flags |= llvm::DIDescriptor::FlagExplicit; 1081 } else if (const CXXConversionDecl *CXXC = 1082 dyn_cast<CXXConversionDecl>(Method)) { 1083 if (CXXC->isExplicit()) 1084 Flags |= llvm::DIDescriptor::FlagExplicit; 1085 } 1086 if (Method->hasPrototype()) 1087 Flags |= llvm::DIDescriptor::FlagPrototyped; 1088 1089 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit); 1090 llvm::DISubprogram SP = 1091 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName, 1092 MethodDefUnit, MethodLine, 1093 MethodTy, /*isLocalToUnit=*/false, 1094 /* isDefinition=*/ false, 1095 Virtuality, VIndex, ContainingType, 1096 Flags, CGM.getLangOpts().Optimize, NULL, 1097 TParamsArray); 1098 1099 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP); 1100 1101 return SP; 1102} 1103 1104/// CollectCXXMemberFunctions - A helper function to collect debug info for 1105/// C++ member functions. This is used while creating debug info entry for 1106/// a Record. 1107void CGDebugInfo:: 1108CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit, 1109 SmallVectorImpl<llvm::Value *> &EltTys, 1110 llvm::DIType RecordTy) { 1111 1112 // Since we want more than just the individual member decls if we 1113 // have templated functions iterate over every declaration to gather 1114 // the functions. 1115 for(DeclContext::decl_iterator I = RD->decls_begin(), 1116 E = RD->decls_end(); I != E; ++I) { 1117 Decl *D = *I; 1118 if (D->isImplicit() && !D->isUsed()) 1119 continue; 1120 1121 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1122 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy)); 1123 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D)) 1124 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(), 1125 SE = FTD->spec_end(); SI != SE; ++SI) 1126 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit, 1127 RecordTy)); 1128 } 1129} 1130 1131/// CollectCXXFriends - A helper function to collect debug info for 1132/// C++ base classes. This is used while creating debug info entry for 1133/// a Record. 1134void CGDebugInfo:: 1135CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit, 1136 SmallVectorImpl<llvm::Value *> &EltTys, 1137 llvm::DIType RecordTy) { 1138 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(), 1139 BE = RD->friend_end(); BI != BE; ++BI) { 1140 if ((*BI)->isUnsupportedFriend()) 1141 continue; 1142 if (TypeSourceInfo *TInfo = (*BI)->getFriendType()) 1143 EltTys.push_back(DBuilder.createFriend(RecordTy, 1144 getOrCreateType(TInfo->getType(), 1145 Unit))); 1146 } 1147} 1148 1149/// CollectCXXBases - A helper function to collect debug info for 1150/// C++ base classes. This is used while creating debug info entry for 1151/// a Record. 1152void CGDebugInfo:: 1153CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit, 1154 SmallVectorImpl<llvm::Value *> &EltTys, 1155 llvm::DIType RecordTy) { 1156 1157 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 1158 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(), 1159 BE = RD->bases_end(); BI != BE; ++BI) { 1160 unsigned BFlags = 0; 1161 uint64_t BaseOffset; 1162 1163 const CXXRecordDecl *Base = 1164 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl()); 1165 1166 if (BI->isVirtual()) { 1167 // virtual base offset offset is -ve. The code generator emits dwarf 1168 // expression where it expects +ve number. 1169 BaseOffset = 1170 0 - CGM.getVTableContext() 1171 .getVirtualBaseOffsetOffset(RD, Base).getQuantity(); 1172 BFlags = llvm::DIDescriptor::FlagVirtual; 1173 } else 1174 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base)); 1175 // FIXME: Inconsistent units for BaseOffset. It is in bytes when 1176 // BI->isVirtual() and bits when not. 1177 1178 AccessSpecifier Access = BI->getAccessSpecifier(); 1179 if (Access == clang::AS_private) 1180 BFlags |= llvm::DIDescriptor::FlagPrivate; 1181 else if (Access == clang::AS_protected) 1182 BFlags |= llvm::DIDescriptor::FlagProtected; 1183 1184 llvm::DIType DTy = 1185 DBuilder.createInheritance(RecordTy, 1186 getOrCreateType(BI->getType(), Unit), 1187 BaseOffset, BFlags); 1188 EltTys.push_back(DTy); 1189 } 1190} 1191 1192/// CollectTemplateParams - A helper function to collect template parameters. 1193llvm::DIArray CGDebugInfo:: 1194CollectTemplateParams(const TemplateParameterList *TPList, 1195 const TemplateArgumentList &TAList, 1196 llvm::DIFile Unit) { 1197 SmallVector<llvm::Value *, 16> TemplateParams; 1198 for (unsigned i = 0, e = TAList.size(); i != e; ++i) { 1199 const TemplateArgument &TA = TAList[i]; 1200 const NamedDecl *ND = TPList->getParam(i); 1201 switch (TA.getKind()) { 1202 case TemplateArgument::Type: { 1203 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit); 1204 llvm::DITemplateTypeParameter TTP = 1205 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy); 1206 TemplateParams.push_back(TTP); 1207 } break; 1208 case TemplateArgument::Integral: { 1209 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit); 1210 llvm::DITemplateValueParameter TVP = 1211 DBuilder.createTemplateValueParameter( 1212 TheCU, ND->getName(), TTy, 1213 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())); 1214 TemplateParams.push_back(TVP); 1215 } break; 1216 case TemplateArgument::Declaration: { 1217 const ValueDecl *D = TA.getAsDecl(); 1218 bool InstanceMember = D->isCXXInstanceMember(); 1219 QualType T = InstanceMember 1220 ? CGM.getContext().getMemberPointerType( 1221 D->getType(), cast<RecordDecl>(D->getDeclContext()) 1222 ->getTypeForDecl()) 1223 : CGM.getContext().getPointerType(D->getType()); 1224 llvm::DIType TTy = getOrCreateType(T, Unit); 1225 llvm::Value *V = 0; 1226 // Variable pointer template parameters have a value that is the address 1227 // of the variable. 1228 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1229 V = CGM.GetAddrOfGlobalVar(VD); 1230 // Member function pointers have special support for building them, though 1231 // this is currently unsupported in LLVM CodeGen. 1232 if (InstanceMember) { 1233 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D)) 1234 V = CGM.getCXXABI().EmitMemberPointer(method); 1235 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 1236 V = CGM.GetAddrOfFunction(FD); 1237 // Member data pointers have special handling too to compute the fixed 1238 // offset within the object. 1239 if (isa<FieldDecl>(D)) { 1240 // These five lines (& possibly the above member function pointer 1241 // handling) might be able to be refactored to use similar code in 1242 // CodeGenModule::getMemberPointerConstant 1243 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D); 1244 CharUnits chars = 1245 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset); 1246 V = CGM.getCXXABI().EmitMemberDataPointer( 1247 cast<MemberPointerType>(T.getTypePtr()), chars); 1248 } 1249 llvm::DITemplateValueParameter TVP = 1250 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V); 1251 TemplateParams.push_back(TVP); 1252 } break; 1253 case TemplateArgument::NullPtr: { 1254 QualType T = TA.getNullPtrType(); 1255 llvm::DIType TTy = getOrCreateType(T, Unit); 1256 llvm::Value *V = 0; 1257 // Special case member data pointer null values since they're actually -1 1258 // instead of zero. 1259 if (const MemberPointerType *MPT = 1260 dyn_cast<MemberPointerType>(T.getTypePtr())) 1261 // But treat member function pointers as simple zero integers because 1262 // it's easier than having a special case in LLVM's CodeGen. If LLVM 1263 // CodeGen grows handling for values of non-null member function 1264 // pointers then perhaps we could remove this special case and rely on 1265 // EmitNullMemberPointer for member function pointers. 1266 if (MPT->isMemberDataPointer()) 1267 V = CGM.getCXXABI().EmitNullMemberPointer(MPT); 1268 if (!V) 1269 V = llvm::ConstantInt::get(CGM.Int8Ty, 0); 1270 llvm::DITemplateValueParameter TVP = 1271 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V); 1272 TemplateParams.push_back(TVP); 1273 } break; 1274 case TemplateArgument::Template: 1275 // We could support this with the GCC extension 1276 // DW_TAG_GNU_template_template_param 1277 break; 1278 case TemplateArgument::Pack: 1279 // And this with DW_TAG_GNU_template_parameter_pack 1280 break; 1281 // And the following should never occur: 1282 case TemplateArgument::Expression: 1283 case TemplateArgument::TemplateExpansion: 1284 case TemplateArgument::Null: 1285 llvm_unreachable( 1286 "These argument types shouldn't exist in concrete types"); 1287 } 1288 } 1289 return DBuilder.getOrCreateArray(TemplateParams); 1290} 1291 1292/// CollectFunctionTemplateParams - A helper function to collect debug 1293/// info for function template parameters. 1294llvm::DIArray CGDebugInfo:: 1295CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) { 1296 if (FD->getTemplatedKind() == 1297 FunctionDecl::TK_FunctionTemplateSpecialization) { 1298 const TemplateParameterList *TList = 1299 FD->getTemplateSpecializationInfo()->getTemplate() 1300 ->getTemplateParameters(); 1301 return 1302 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit); 1303 } 1304 return llvm::DIArray(); 1305} 1306 1307/// CollectCXXTemplateParams - A helper function to collect debug info for 1308/// template parameters. 1309llvm::DIArray CGDebugInfo:: 1310CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial, 1311 llvm::DIFile Unit) { 1312 llvm::PointerUnion<ClassTemplateDecl *, 1313 ClassTemplatePartialSpecializationDecl *> 1314 PU = TSpecial->getSpecializedTemplateOrPartial(); 1315 1316 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ? 1317 PU.get<ClassTemplateDecl *>()->getTemplateParameters() : 1318 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters(); 1319 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs(); 1320 return CollectTemplateParams(TPList, TAList, Unit); 1321} 1322 1323/// getOrCreateVTablePtrType - Return debug info descriptor for vtable. 1324llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) { 1325 if (VTablePtrType.isValid()) 1326 return VTablePtrType; 1327 1328 ASTContext &Context = CGM.getContext(); 1329 1330 /* Function type */ 1331 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit); 1332 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy); 1333 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements); 1334 unsigned Size = Context.getTypeSize(Context.VoidPtrTy); 1335 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0, 1336 "__vtbl_ptr_type"); 1337 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size); 1338 return VTablePtrType; 1339} 1340 1341/// getVTableName - Get vtable name for the given Class. 1342StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) { 1343 // Construct gdb compatible name name. 1344 std::string Name = "_vptr$" + RD->getNameAsString(); 1345 1346 // Copy this name on the side and use its reference. 1347 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length()); 1348 memcpy(StrPtr, Name.data(), Name.length()); 1349 return StringRef(StrPtr, Name.length()); 1350} 1351 1352 1353/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate 1354/// debug info entry in EltTys vector. 1355void CGDebugInfo:: 1356CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit, 1357 SmallVectorImpl<llvm::Value *> &EltTys) { 1358 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 1359 1360 // If there is a primary base then it will hold vtable info. 1361 if (RL.getPrimaryBase()) 1362 return; 1363 1364 // If this class is not dynamic then there is not any vtable info to collect. 1365 if (!RD->isDynamicClass()) 1366 return; 1367 1368 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 1369 llvm::DIType VPTR 1370 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 1371 0, Size, 0, 0, 1372 llvm::DIDescriptor::FlagArtificial, 1373 getOrCreateVTablePtrType(Unit)); 1374 EltTys.push_back(VPTR); 1375} 1376 1377/// getOrCreateRecordType - Emit record type's standalone debug info. 1378llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy, 1379 SourceLocation Loc) { 1380 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 1381 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc)); 1382 return T; 1383} 1384 1385/// getOrCreateInterfaceType - Emit an objective c interface type standalone 1386/// debug info. 1387llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D, 1388 SourceLocation Loc) { 1389 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 1390 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc)); 1391 RetainedTypes.push_back(D.getAsOpaquePtr()); 1392 return T; 1393} 1394 1395/// CreateType - get structure or union type. 1396llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) { 1397 RecordDecl *RD = Ty->getDecl(); 1398 1399 // Get overall information about the record type for the debug info. 1400 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 1401 1402 // Records and classes and unions can all be recursive. To handle them, we 1403 // first generate a debug descriptor for the struct as a forward declaration. 1404 // Then (if it is a definition) we go through and get debug info for all of 1405 // its members. Finally, we create a descriptor for the complete type (which 1406 // may refer to the forward decl if the struct is recursive) and replace all 1407 // uses of the forward declaration with the final definition. 1408 1409 llvm::DICompositeType FwdDecl( 1410 getOrCreateLimitedType(QualType(Ty, 0), DefUnit)); 1411 assert(FwdDecl.Verify() && 1412 "The debug type of a RecordType should be a llvm::DICompositeType"); 1413 1414 if (FwdDecl.isForwardDecl()) 1415 return FwdDecl; 1416 1417 // Push the struct on region stack. 1418 LexicalBlockStack.push_back(&*FwdDecl); 1419 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl); 1420 1421 // Add this to the completed-type cache while we're completing it recursively. 1422 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl; 1423 1424 // Convert all the elements. 1425 SmallVector<llvm::Value *, 16> EltTys; 1426 1427 // Note: The split of CXXDecl information here is intentional, the 1428 // gdb tests will depend on a certain ordering at printout. The debug 1429 // information offsets are still correct if we merge them all together 1430 // though. 1431 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 1432 if (CXXDecl) { 1433 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl); 1434 CollectVTableInfo(CXXDecl, DefUnit, EltTys); 1435 } 1436 1437 // Collect data fields (including static variables and any initializers). 1438 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl); 1439 llvm::DIArray TParamsArray; 1440 if (CXXDecl) { 1441 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl); 1442 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl); 1443 if (const ClassTemplateSpecializationDecl *TSpecial 1444 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) 1445 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit); 1446 } 1447 1448 LexicalBlockStack.pop_back(); 1449 RegionMap.erase(Ty->getDecl()); 1450 1451 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys); 1452 FwdDecl.setTypeArray(Elements, TParamsArray); 1453 1454 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl); 1455 return FwdDecl; 1456} 1457 1458/// CreateType - get objective-c object type. 1459llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty, 1460 llvm::DIFile Unit) { 1461 // Ignore protocols. 1462 return getOrCreateType(Ty->getBaseType(), Unit); 1463} 1464 1465/// CreateType - get objective-c interface type. 1466llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, 1467 llvm::DIFile Unit) { 1468 ObjCInterfaceDecl *ID = Ty->getDecl(); 1469 if (!ID) 1470 return llvm::DIType(); 1471 1472 // Get overall information about the record type for the debug info. 1473 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation()); 1474 unsigned Line = getLineNumber(ID->getLocation()); 1475 unsigned RuntimeLang = TheCU.getLanguage(); 1476 1477 // If this is just a forward declaration return a special forward-declaration 1478 // debug type since we won't be able to lay out the entire type. 1479 ObjCInterfaceDecl *Def = ID->getDefinition(); 1480 if (!Def) { 1481 llvm::DIType FwdDecl = 1482 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 1483 ID->getName(), TheCU, DefUnit, Line, 1484 RuntimeLang); 1485 return FwdDecl; 1486 } 1487 1488 ID = Def; 1489 1490 // Bit size, align and offset of the type. 1491 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1492 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1493 1494 unsigned Flags = 0; 1495 if (ID->getImplementation()) 1496 Flags |= llvm::DIDescriptor::FlagObjcClassComplete; 1497 1498 llvm::DICompositeType RealDecl = 1499 DBuilder.createStructType(Unit, ID->getName(), DefUnit, 1500 Line, Size, Align, Flags, 1501 llvm::DIType(), llvm::DIArray(), RuntimeLang); 1502 1503 // Otherwise, insert it into the CompletedTypeCache so that recursive uses 1504 // will find it and we're emitting the complete type. 1505 QualType QualTy = QualType(Ty, 0); 1506 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl; 1507 // Push the struct on region stack. 1508 1509 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl)); 1510 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl); 1511 1512 // Convert all the elements. 1513 SmallVector<llvm::Value *, 16> EltTys; 1514 1515 ObjCInterfaceDecl *SClass = ID->getSuperClass(); 1516 if (SClass) { 1517 llvm::DIType SClassTy = 1518 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit); 1519 if (!SClassTy.isValid()) 1520 return llvm::DIType(); 1521 1522 llvm::DIType InhTag = 1523 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0); 1524 EltTys.push_back(InhTag); 1525 } 1526 1527 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(), 1528 E = ID->prop_end(); I != E; ++I) { 1529 const ObjCPropertyDecl *PD = *I; 1530 SourceLocation Loc = PD->getLocation(); 1531 llvm::DIFile PUnit = getOrCreateFile(Loc); 1532 unsigned PLine = getLineNumber(Loc); 1533 ObjCMethodDecl *Getter = PD->getGetterMethodDecl(); 1534 ObjCMethodDecl *Setter = PD->getSetterMethodDecl(); 1535 llvm::MDNode *PropertyNode = 1536 DBuilder.createObjCProperty(PD->getName(), 1537 PUnit, PLine, 1538 (Getter && Getter->isImplicit()) ? "" : 1539 getSelectorName(PD->getGetterName()), 1540 (Setter && Setter->isImplicit()) ? "" : 1541 getSelectorName(PD->getSetterName()), 1542 PD->getPropertyAttributes(), 1543 getOrCreateType(PD->getType(), PUnit)); 1544 EltTys.push_back(PropertyNode); 1545 } 1546 1547 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID); 1548 unsigned FieldNo = 0; 1549 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field; 1550 Field = Field->getNextIvar(), ++FieldNo) { 1551 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 1552 if (!FieldTy.isValid()) 1553 return llvm::DIType(); 1554 1555 StringRef FieldName = Field->getName(); 1556 1557 // Ignore unnamed fields. 1558 if (FieldName.empty()) 1559 continue; 1560 1561 // Get the location for the field. 1562 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation()); 1563 unsigned FieldLine = getLineNumber(Field->getLocation()); 1564 QualType FType = Field->getType(); 1565 uint64_t FieldSize = 0; 1566 unsigned FieldAlign = 0; 1567 1568 if (!FType->isIncompleteArrayType()) { 1569 1570 // Bit size, align and offset of the type. 1571 FieldSize = Field->isBitField() 1572 ? Field->getBitWidthValue(CGM.getContext()) 1573 : CGM.getContext().getTypeSize(FType); 1574 FieldAlign = CGM.getContext().getTypeAlign(FType); 1575 } 1576 1577 uint64_t FieldOffset; 1578 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { 1579 // We don't know the runtime offset of an ivar if we're using the 1580 // non-fragile ABI. For bitfields, use the bit offset into the first 1581 // byte of storage of the bitfield. For other fields, use zero. 1582 if (Field->isBitField()) { 1583 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset( 1584 CGM, ID, Field); 1585 FieldOffset %= CGM.getContext().getCharWidth(); 1586 } else { 1587 FieldOffset = 0; 1588 } 1589 } else { 1590 FieldOffset = RL.getFieldOffset(FieldNo); 1591 } 1592 1593 unsigned Flags = 0; 1594 if (Field->getAccessControl() == ObjCIvarDecl::Protected) 1595 Flags = llvm::DIDescriptor::FlagProtected; 1596 else if (Field->getAccessControl() == ObjCIvarDecl::Private) 1597 Flags = llvm::DIDescriptor::FlagPrivate; 1598 1599 llvm::MDNode *PropertyNode = NULL; 1600 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) { 1601 if (ObjCPropertyImplDecl *PImpD = 1602 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) { 1603 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) { 1604 SourceLocation Loc = PD->getLocation(); 1605 llvm::DIFile PUnit = getOrCreateFile(Loc); 1606 unsigned PLine = getLineNumber(Loc); 1607 ObjCMethodDecl *Getter = PD->getGetterMethodDecl(); 1608 ObjCMethodDecl *Setter = PD->getSetterMethodDecl(); 1609 PropertyNode = 1610 DBuilder.createObjCProperty(PD->getName(), 1611 PUnit, PLine, 1612 (Getter && Getter->isImplicit()) ? "" : 1613 getSelectorName(PD->getGetterName()), 1614 (Setter && Setter->isImplicit()) ? "" : 1615 getSelectorName(PD->getSetterName()), 1616 PD->getPropertyAttributes(), 1617 getOrCreateType(PD->getType(), PUnit)); 1618 } 1619 } 1620 } 1621 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, 1622 FieldLine, FieldSize, FieldAlign, 1623 FieldOffset, Flags, FieldTy, 1624 PropertyNode); 1625 EltTys.push_back(FieldTy); 1626 } 1627 1628 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys); 1629 RealDecl.setTypeArray(Elements); 1630 1631 // If the implementation is not yet set, we do not want to mark it 1632 // as complete. An implementation may declare additional 1633 // private ivars that we would miss otherwise. 1634 if (ID->getImplementation() == 0) 1635 CompletedTypeCache.erase(QualTy.getAsOpaquePtr()); 1636 1637 LexicalBlockStack.pop_back(); 1638 return RealDecl; 1639} 1640 1641llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) { 1642 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit); 1643 int64_t Count = Ty->getNumElements(); 1644 if (Count == 0) 1645 // If number of elements are not known then this is an unbounded array. 1646 // Use Count == -1 to express such arrays. 1647 Count = -1; 1648 1649 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count); 1650 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript); 1651 1652 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1653 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1654 1655 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray); 1656} 1657 1658llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty, 1659 llvm::DIFile Unit) { 1660 uint64_t Size; 1661 uint64_t Align; 1662 1663 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types 1664 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) { 1665 Size = 0; 1666 Align = 1667 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT)); 1668 } else if (Ty->isIncompleteArrayType()) { 1669 Size = 0; 1670 if (Ty->getElementType()->isIncompleteType()) 1671 Align = 0; 1672 else 1673 Align = CGM.getContext().getTypeAlign(Ty->getElementType()); 1674 } else if (Ty->isIncompleteType()) { 1675 Size = 0; 1676 Align = 0; 1677 } else { 1678 // Size and align of the whole array, not the element type. 1679 Size = CGM.getContext().getTypeSize(Ty); 1680 Align = CGM.getContext().getTypeAlign(Ty); 1681 } 1682 1683 // Add the dimensions of the array. FIXME: This loses CV qualifiers from 1684 // interior arrays, do we care? Why aren't nested arrays represented the 1685 // obvious/recursive way? 1686 SmallVector<llvm::Value *, 8> Subscripts; 1687 QualType EltTy(Ty, 0); 1688 while ((Ty = dyn_cast<ArrayType>(EltTy))) { 1689 // If the number of elements is known, then count is that number. Otherwise, 1690 // it's -1. This allows us to represent a subrange with an array of 0 1691 // elements, like this: 1692 // 1693 // struct foo { 1694 // int x[0]; 1695 // }; 1696 int64_t Count = -1; // Count == -1 is an unbounded array. 1697 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) 1698 Count = CAT->getSize().getZExtValue(); 1699 1700 // FIXME: Verify this is right for VLAs. 1701 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count)); 1702 EltTy = Ty->getElementType(); 1703 } 1704 1705 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts); 1706 1707 llvm::DIType DbgTy = 1708 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit), 1709 SubscriptArray); 1710 return DbgTy; 1711} 1712 1713llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty, 1714 llvm::DIFile Unit) { 1715 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, 1716 Ty, Ty->getPointeeType(), Unit); 1717} 1718 1719llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty, 1720 llvm::DIFile Unit) { 1721 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, 1722 Ty, Ty->getPointeeType(), Unit); 1723} 1724 1725llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty, 1726 llvm::DIFile U) { 1727 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U); 1728 if (!Ty->getPointeeType()->isFunctionType()) 1729 return DBuilder.createMemberPointerType( 1730 CreatePointeeType(Ty->getPointeeType(), U), ClassType); 1731 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType( 1732 CGM.getContext().getPointerType( 1733 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())), 1734 Ty->getPointeeType()->getAs<FunctionProtoType>(), U), 1735 ClassType); 1736} 1737 1738llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty, 1739 llvm::DIFile U) { 1740 // Ignore the atomic wrapping 1741 // FIXME: What is the correct representation? 1742 return getOrCreateType(Ty->getValueType(), U); 1743} 1744 1745/// CreateEnumType - get enumeration type. 1746llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) { 1747 uint64_t Size = 0; 1748 uint64_t Align = 0; 1749 if (!ED->getTypeForDecl()->isIncompleteType()) { 1750 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); 1751 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl()); 1752 } 1753 1754 // If this is just a forward declaration, construct an appropriately 1755 // marked node and just return it. 1756 if (!ED->getDefinition()) { 1757 llvm::DIDescriptor EDContext; 1758 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext())); 1759 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation()); 1760 unsigned Line = getLineNumber(ED->getLocation()); 1761 StringRef EDName = ED->getName(); 1762 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type, 1763 EDName, EDContext, DefUnit, Line, 0, 1764 Size, Align); 1765 } 1766 1767 // Create DIEnumerator elements for each enumerator. 1768 SmallVector<llvm::Value *, 16> Enumerators; 1769 ED = ED->getDefinition(); 1770 for (EnumDecl::enumerator_iterator 1771 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end(); 1772 Enum != EnumEnd; ++Enum) { 1773 Enumerators.push_back( 1774 DBuilder.createEnumerator(Enum->getName(), 1775 Enum->getInitVal().getZExtValue())); 1776 } 1777 1778 // Return a CompositeType for the enum itself. 1779 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators); 1780 1781 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation()); 1782 unsigned Line = getLineNumber(ED->getLocation()); 1783 llvm::DIDescriptor EnumContext = 1784 getContextDescriptor(cast<Decl>(ED->getDeclContext())); 1785 llvm::DIType ClassTy = ED->isFixed() ? 1786 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType(); 1787 llvm::DIType DbgTy = 1788 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line, 1789 Size, Align, EltArray, 1790 ClassTy); 1791 return DbgTy; 1792} 1793 1794static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) { 1795 Qualifiers Quals; 1796 do { 1797 Quals += T.getLocalQualifiers(); 1798 QualType LastT = T; 1799 switch (T->getTypeClass()) { 1800 default: 1801 return C.getQualifiedType(T.getTypePtr(), Quals); 1802 case Type::TemplateSpecialization: 1803 T = cast<TemplateSpecializationType>(T)->desugar(); 1804 break; 1805 case Type::TypeOfExpr: 1806 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType(); 1807 break; 1808 case Type::TypeOf: 1809 T = cast<TypeOfType>(T)->getUnderlyingType(); 1810 break; 1811 case Type::Decltype: 1812 T = cast<DecltypeType>(T)->getUnderlyingType(); 1813 break; 1814 case Type::UnaryTransform: 1815 T = cast<UnaryTransformType>(T)->getUnderlyingType(); 1816 break; 1817 case Type::Attributed: 1818 T = cast<AttributedType>(T)->getEquivalentType(); 1819 break; 1820 case Type::Elaborated: 1821 T = cast<ElaboratedType>(T)->getNamedType(); 1822 break; 1823 case Type::Paren: 1824 T = cast<ParenType>(T)->getInnerType(); 1825 break; 1826 case Type::SubstTemplateTypeParm: 1827 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType(); 1828 break; 1829 case Type::Auto: 1830 QualType DT = cast<AutoType>(T)->getDeducedType(); 1831 if (DT.isNull()) 1832 return T; 1833 T = DT; 1834 break; 1835 } 1836 1837 assert(T != LastT && "Type unwrapping failed to unwrap!"); 1838 (void)LastT; 1839 } while (true); 1840} 1841 1842/// getType - Get the type from the cache or return null type if it doesn't 1843/// exist. 1844llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) { 1845 1846 // Unwrap the type as needed for debug information. 1847 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 1848 1849 // Check for existing entry. 1850 if (Ty->getTypeClass() == Type::ObjCInterface) { 1851 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty); 1852 if (V) 1853 return llvm::DIType(cast<llvm::MDNode>(V)); 1854 else return llvm::DIType(); 1855 } 1856 1857 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 1858 TypeCache.find(Ty.getAsOpaquePtr()); 1859 if (it != TypeCache.end()) { 1860 // Verify that the debug info still exists. 1861 if (llvm::Value *V = it->second) 1862 return llvm::DIType(cast<llvm::MDNode>(V)); 1863 } 1864 1865 return llvm::DIType(); 1866} 1867 1868/// getCompletedTypeOrNull - Get the type from the cache or return null if it 1869/// doesn't exist. 1870llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) { 1871 1872 // Unwrap the type as needed for debug information. 1873 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 1874 1875 // Check for existing entry. 1876 llvm::Value *V = 0; 1877 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 1878 CompletedTypeCache.find(Ty.getAsOpaquePtr()); 1879 if (it != CompletedTypeCache.end()) 1880 V = it->second; 1881 else { 1882 V = getCachedInterfaceTypeOrNull(Ty); 1883 } 1884 1885 // Verify that any cached debug info still exists. 1886 if (V != 0) 1887 return llvm::DIType(cast<llvm::MDNode>(V)); 1888 1889 return llvm::DIType(); 1890} 1891 1892/// getCachedInterfaceTypeOrNull - Get the type from the interface 1893/// cache, unless it needs to regenerated. Otherwise return null. 1894llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) { 1895 // Is there a cached interface that hasn't changed? 1896 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > > 1897 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr()); 1898 1899 if (it1 != ObjCInterfaceCache.end()) 1900 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) 1901 if (Checksum(Decl) == it1->second.second) 1902 // Return cached forward declaration. 1903 return it1->second.first; 1904 1905 return 0; 1906} 1907 1908/// getOrCreateType - Get the type from the cache or create a new 1909/// one if necessary. 1910llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) { 1911 if (Ty.isNull()) 1912 return llvm::DIType(); 1913 1914 // Unwrap the type as needed for debug information. 1915 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 1916 1917 llvm::DIType T = getCompletedTypeOrNull(Ty); 1918 1919 if (T.Verify()) 1920 return T; 1921 1922 // Otherwise create the type. 1923 llvm::DIType Res = CreateTypeNode(Ty, Unit); 1924 void* TyPtr = Ty.getAsOpaquePtr(); 1925 1926 // And update the type cache. 1927 TypeCache[TyPtr] = Res; 1928 1929 llvm::DIType TC = getTypeOrNull(Ty); 1930 if (TC.Verify() && TC.isForwardDecl()) 1931 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC))); 1932 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) { 1933 // Interface types may have elements added to them by a 1934 // subsequent implementation or extension, so we keep them in 1935 // the ObjCInterfaceCache together with a checksum. Instead of 1936 // the (possibly) incomplete interface type, we return a forward 1937 // declaration that gets RAUW'd in CGDebugInfo::finalize(). 1938 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr]; 1939 if (V.first) 1940 return llvm::DIType(cast<llvm::MDNode>(V.first)); 1941 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 1942 Decl->getName(), TheCU, Unit, 1943 getLineNumber(Decl->getLocation()), 1944 TheCU.getLanguage()); 1945 // Store the forward declaration in the cache. 1946 V.first = TC; 1947 V.second = Checksum(Decl); 1948 1949 // Register the type for replacement in finalize(). 1950 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC))); 1951 1952 return TC; 1953 } 1954 1955 if (!Res.isForwardDecl()) 1956 CompletedTypeCache[TyPtr] = Res; 1957 1958 return Res; 1959} 1960 1961/// Currently the checksum merely consists of the number of ivars. 1962unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl 1963 *InterfaceDecl) { 1964 unsigned IvarNo = 0; 1965 for (const ObjCIvarDecl *Ivar = InterfaceDecl->all_declared_ivar_begin(); 1966 Ivar != 0; Ivar = Ivar->getNextIvar()) ++IvarNo; 1967 return IvarNo; 1968} 1969 1970ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) { 1971 switch (Ty->getTypeClass()) { 1972 case Type::ObjCObjectPointer: 1973 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty) 1974 ->getPointeeType()); 1975 case Type::ObjCInterface: 1976 return cast<ObjCInterfaceType>(Ty)->getDecl(); 1977 default: 1978 return 0; 1979 } 1980} 1981 1982/// CreateTypeNode - Create a new debug type node. 1983llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) { 1984 // Handle qualifiers, which recursively handles what they refer to. 1985 if (Ty.hasLocalQualifiers()) 1986 return CreateQualifiedType(Ty, Unit); 1987 1988 const char *Diag = 0; 1989 1990 // Work out details of type. 1991 switch (Ty->getTypeClass()) { 1992#define TYPE(Class, Base) 1993#define ABSTRACT_TYPE(Class, Base) 1994#define NON_CANONICAL_TYPE(Class, Base) 1995#define DEPENDENT_TYPE(Class, Base) case Type::Class: 1996#include "clang/AST/TypeNodes.def" 1997 llvm_unreachable("Dependent types cannot show up in debug information"); 1998 1999 case Type::ExtVector: 2000 case Type::Vector: 2001 return CreateType(cast<VectorType>(Ty), Unit); 2002 case Type::ObjCObjectPointer: 2003 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit); 2004 case Type::ObjCObject: 2005 return CreateType(cast<ObjCObjectType>(Ty), Unit); 2006 case Type::ObjCInterface: 2007 return CreateType(cast<ObjCInterfaceType>(Ty), Unit); 2008 case Type::Builtin: 2009 return CreateType(cast<BuiltinType>(Ty)); 2010 case Type::Complex: 2011 return CreateType(cast<ComplexType>(Ty)); 2012 case Type::Pointer: 2013 return CreateType(cast<PointerType>(Ty), Unit); 2014 case Type::BlockPointer: 2015 return CreateType(cast<BlockPointerType>(Ty), Unit); 2016 case Type::Typedef: 2017 return CreateType(cast<TypedefType>(Ty), Unit); 2018 case Type::Record: 2019 return CreateType(cast<RecordType>(Ty)); 2020 case Type::Enum: 2021 return CreateEnumType(cast<EnumType>(Ty)->getDecl()); 2022 case Type::FunctionProto: 2023 case Type::FunctionNoProto: 2024 return CreateType(cast<FunctionType>(Ty), Unit); 2025 case Type::ConstantArray: 2026 case Type::VariableArray: 2027 case Type::IncompleteArray: 2028 return CreateType(cast<ArrayType>(Ty), Unit); 2029 2030 case Type::LValueReference: 2031 return CreateType(cast<LValueReferenceType>(Ty), Unit); 2032 case Type::RValueReference: 2033 return CreateType(cast<RValueReferenceType>(Ty), Unit); 2034 2035 case Type::MemberPointer: 2036 return CreateType(cast<MemberPointerType>(Ty), Unit); 2037 2038 case Type::Atomic: 2039 return CreateType(cast<AtomicType>(Ty), Unit); 2040 2041 case Type::Attributed: 2042 case Type::TemplateSpecialization: 2043 case Type::Elaborated: 2044 case Type::Paren: 2045 case Type::SubstTemplateTypeParm: 2046 case Type::TypeOfExpr: 2047 case Type::TypeOf: 2048 case Type::Decltype: 2049 case Type::UnaryTransform: 2050 llvm_unreachable("type should have been unwrapped!"); 2051 case Type::Auto: 2052 Diag = "auto"; 2053 break; 2054 } 2055 2056 assert(Diag && "Fall through without a diagnostic?"); 2057 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error, 2058 "debug information for %0 is not yet supported"); 2059 CGM.getDiags().Report(DiagID) 2060 << Diag; 2061 return llvm::DIType(); 2062} 2063 2064/// getOrCreateLimitedType - Get the type from the cache or create a new 2065/// limited type if necessary. 2066llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty, 2067 llvm::DIFile Unit) { 2068 if (Ty.isNull()) 2069 return llvm::DIType(); 2070 2071 // Unwrap the type as needed for debug information. 2072 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 2073 2074 llvm::DIType T = getTypeOrNull(Ty); 2075 2076 // We may have cached a forward decl when we could have created 2077 // a non-forward decl. Go ahead and create a non-forward decl 2078 // now. 2079 if (T.Verify() && !T.isForwardDecl()) return T; 2080 2081 // Otherwise create the type. 2082 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit); 2083 2084 if (T.Verify() && T.isForwardDecl()) 2085 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(), 2086 static_cast<llvm::Value*>(T))); 2087 2088 // And update the type cache. 2089 TypeCache[Ty.getAsOpaquePtr()] = Res; 2090 return Res; 2091} 2092 2093// TODO: Currently used for context chains when limiting debug info. 2094llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) { 2095 RecordDecl *RD = Ty->getDecl(); 2096 2097 // Get overall information about the record type for the debug info. 2098 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation()); 2099 unsigned Line = getLineNumber(RD->getLocation()); 2100 StringRef RDName = getClassName(RD); 2101 2102 llvm::DIDescriptor RDContext; 2103 if (DebugKind == CodeGenOptions::LimitedDebugInfo) 2104 RDContext = createContextChain(cast<Decl>(RD->getDeclContext())); 2105 else 2106 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext())); 2107 2108 // If this is just a forward declaration, construct an appropriately 2109 // marked node and just return it. 2110 if (!RD->getDefinition()) 2111 return createRecordFwdDecl(RD, RDContext); 2112 2113 uint64_t Size = CGM.getContext().getTypeSize(Ty); 2114 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 2115 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 2116 llvm::DICompositeType RealDecl; 2117 2118 if (RD->isUnion()) 2119 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line, 2120 Size, Align, 0, llvm::DIArray()); 2121 else if (RD->isClass()) { 2122 // FIXME: This could be a struct type giving a default visibility different 2123 // than C++ class type, but needs llvm metadata changes first. 2124 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line, 2125 Size, Align, 0, 0, llvm::DIType(), 2126 llvm::DIArray(), llvm::DIType(), 2127 llvm::DIArray()); 2128 } else 2129 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line, 2130 Size, Align, 0, llvm::DIType(), 2131 llvm::DIArray()); 2132 2133 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl); 2134 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl; 2135 2136 if (CXXDecl) { 2137 // A class's primary base or the class itself contains the vtable. 2138 llvm::DICompositeType ContainingType; 2139 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 2140 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) { 2141 // Seek non virtual primary base root. 2142 while (1) { 2143 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase); 2144 const CXXRecordDecl *PBT = BRL.getPrimaryBase(); 2145 if (PBT && !BRL.isPrimaryBaseVirtual()) 2146 PBase = PBT; 2147 else 2148 break; 2149 } 2150 ContainingType = llvm::DICompositeType( 2151 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit)); 2152 } else if (CXXDecl->isDynamicClass()) 2153 ContainingType = RealDecl; 2154 2155 RealDecl.setContainingType(ContainingType); 2156 } 2157 return llvm::DIType(RealDecl); 2158} 2159 2160/// CreateLimitedTypeNode - Create a new debug type node, but only forward 2161/// declare composite types that haven't been processed yet. 2162llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) { 2163 2164 // Work out details of type. 2165 switch (Ty->getTypeClass()) { 2166#define TYPE(Class, Base) 2167#define ABSTRACT_TYPE(Class, Base) 2168#define NON_CANONICAL_TYPE(Class, Base) 2169#define DEPENDENT_TYPE(Class, Base) case Type::Class: 2170 #include "clang/AST/TypeNodes.def" 2171 llvm_unreachable("Dependent types cannot show up in debug information"); 2172 2173 case Type::Record: 2174 return CreateLimitedType(cast<RecordType>(Ty)); 2175 default: 2176 return CreateTypeNode(Ty, Unit); 2177 } 2178} 2179 2180/// CreateMemberType - Create new member and increase Offset by FType's size. 2181llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType, 2182 StringRef Name, 2183 uint64_t *Offset) { 2184 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 2185 uint64_t FieldSize = CGM.getContext().getTypeSize(FType); 2186 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType); 2187 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0, 2188 FieldSize, FieldAlign, 2189 *Offset, 0, FieldTy); 2190 *Offset += FieldSize; 2191 return Ty; 2192} 2193 2194llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) { 2195 // We only need a declaration (not a definition) of the type - so use whatever 2196 // we would otherwise do to get a type for a pointee. (forward declarations in 2197 // limited debug info, full definitions (if the type definition is available) 2198 // in unlimited debug info) 2199 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) { 2200 llvm::DIFile DefUnit = getOrCreateFile(TD->getLocation()); 2201 return CreatePointeeType(CGM.getContext().getTypeDeclType(TD), DefUnit); 2202 } 2203 // Otherwise fall back to a fairly rudimentary cache of existing declarations. 2204 // This doesn't handle providing declarations (for functions or variables) for 2205 // entities without definitions in this TU, nor when the definition proceeds 2206 // the call to this function. 2207 // FIXME: This should be split out into more specific maps with support for 2208 // emitting forward declarations and merging definitions with declarations, 2209 // the same way as we do for types. 2210 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I = 2211 DeclCache.find(D->getCanonicalDecl()); 2212 if (I == DeclCache.end()) 2213 return llvm::DIDescriptor(); 2214 llvm::Value *V = I->second; 2215 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V)); 2216} 2217 2218/// getFunctionDeclaration - Return debug info descriptor to describe method 2219/// declaration for the given method definition. 2220llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) { 2221 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 2222 if (!FD) return llvm::DISubprogram(); 2223 2224 // Setup context. 2225 getContextDescriptor(cast<Decl>(D->getDeclContext())); 2226 2227 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator 2228 MI = SPCache.find(FD->getCanonicalDecl()); 2229 if (MI != SPCache.end()) { 2230 llvm::Value *V = MI->second; 2231 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V)); 2232 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition()) 2233 return SP; 2234 } 2235 2236 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(), 2237 E = FD->redecls_end(); I != E; ++I) { 2238 const FunctionDecl *NextFD = *I; 2239 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator 2240 MI = SPCache.find(NextFD->getCanonicalDecl()); 2241 if (MI != SPCache.end()) { 2242 llvm::Value *V = MI->second; 2243 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V)); 2244 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition()) 2245 return SP; 2246 } 2247 } 2248 return llvm::DISubprogram(); 2249} 2250 2251// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include 2252// implicit parameter "this". 2253llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D, 2254 QualType FnType, 2255 llvm::DIFile F) { 2256 2257 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 2258 return getOrCreateMethodType(Method, F); 2259 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) { 2260 // Add "self" and "_cmd" 2261 SmallVector<llvm::Value *, 16> Elts; 2262 2263 // First element is always return type. For 'void' functions it is NULL. 2264 QualType ResultTy = OMethod->getResultType(); 2265 2266 // Replace the instancetype keyword with the actual type. 2267 if (ResultTy == CGM.getContext().getObjCInstanceType()) 2268 ResultTy = CGM.getContext().getPointerType( 2269 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0)); 2270 2271 Elts.push_back(getOrCreateType(ResultTy, F)); 2272 // "self" pointer is always first argument. 2273 QualType SelfDeclTy = OMethod->getSelfDecl()->getType(); 2274 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F); 2275 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy)); 2276 // "_cmd" pointer is always second argument. 2277 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F); 2278 Elts.push_back(DBuilder.createArtificialType(CmdTy)); 2279 // Get rest of the arguments. 2280 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(), 2281 PE = OMethod->param_end(); PI != PE; ++PI) 2282 Elts.push_back(getOrCreateType((*PI)->getType(), F)); 2283 2284 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts); 2285 return DBuilder.createSubroutineType(F, EltTypeArray); 2286 } 2287 return llvm::DICompositeType(getOrCreateType(FnType, F)); 2288} 2289 2290/// EmitFunctionStart - Constructs the debug code for entering a function. 2291void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType, 2292 llvm::Function *Fn, 2293 CGBuilderTy &Builder) { 2294 2295 StringRef Name; 2296 StringRef LinkageName; 2297 2298 FnBeginRegionCount.push_back(LexicalBlockStack.size()); 2299 2300 const Decl *D = GD.getDecl(); 2301 // Function may lack declaration in source code if it is created by Clang 2302 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk). 2303 bool HasDecl = (D != 0); 2304 // Use the location of the declaration. 2305 SourceLocation Loc; 2306 if (HasDecl) 2307 Loc = D->getLocation(); 2308 2309 unsigned Flags = 0; 2310 llvm::DIFile Unit = getOrCreateFile(Loc); 2311 llvm::DIDescriptor FDContext(Unit); 2312 llvm::DIArray TParamsArray; 2313 if (!HasDecl) { 2314 // Use llvm function name. 2315 Name = Fn->getName(); 2316 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2317 // If there is a DISubprogram for this function available then use it. 2318 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator 2319 FI = SPCache.find(FD->getCanonicalDecl()); 2320 if (FI != SPCache.end()) { 2321 llvm::Value *V = FI->second; 2322 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V)); 2323 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) { 2324 llvm::MDNode *SPN = SP; 2325 LexicalBlockStack.push_back(SPN); 2326 RegionMap[D] = llvm::WeakVH(SP); 2327 return; 2328 } 2329 } 2330 Name = getFunctionName(FD); 2331 // Use mangled name as linkage name for C/C++ functions. 2332 if (FD->hasPrototype()) { 2333 LinkageName = CGM.getMangledName(GD); 2334 Flags |= llvm::DIDescriptor::FlagPrototyped; 2335 } 2336 // No need to replicate the linkage name if it isn't different from the 2337 // subprogram name, no need to have it at all unless coverage is enabled or 2338 // debug is set to more than just line tables. 2339 if (LinkageName == Name || 2340 (!CGM.getCodeGenOpts().EmitGcovArcs && 2341 !CGM.getCodeGenOpts().EmitGcovNotes && 2342 DebugKind <= CodeGenOptions::DebugLineTablesOnly)) 2343 LinkageName = StringRef(); 2344 2345 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) { 2346 if (const NamespaceDecl *NSDecl = 2347 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext())) 2348 FDContext = getOrCreateNameSpace(NSDecl); 2349 else if (const RecordDecl *RDecl = 2350 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) 2351 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext())); 2352 2353 // Collect template parameters. 2354 TParamsArray = CollectFunctionTemplateParams(FD, Unit); 2355 } 2356 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) { 2357 Name = getObjCMethodName(OMD); 2358 Flags |= llvm::DIDescriptor::FlagPrototyped; 2359 } else { 2360 // Use llvm function name. 2361 Name = Fn->getName(); 2362 Flags |= llvm::DIDescriptor::FlagPrototyped; 2363 } 2364 if (!Name.empty() && Name[0] == '\01') 2365 Name = Name.substr(1); 2366 2367 unsigned LineNo = getLineNumber(Loc); 2368 if (!HasDecl || D->isImplicit()) 2369 Flags |= llvm::DIDescriptor::FlagArtificial; 2370 2371 llvm::DICompositeType DIFnType; 2372 llvm::DISubprogram SPDecl; 2373 if (HasDecl && 2374 DebugKind >= CodeGenOptions::LimitedDebugInfo) { 2375 DIFnType = getOrCreateFunctionType(D, FnType, Unit); 2376 SPDecl = getFunctionDeclaration(D); 2377 } else { 2378 // Create fake but valid subroutine type. Otherwise 2379 // llvm::DISubprogram::Verify() would return false, and 2380 // subprogram DIE will miss DW_AT_decl_file and 2381 // DW_AT_decl_line fields. 2382 SmallVector<llvm::Value*, 16> Elts; 2383 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts); 2384 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray); 2385 } 2386 llvm::DISubprogram SP; 2387 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit, 2388 LineNo, DIFnType, 2389 Fn->hasInternalLinkage(), true/*definition*/, 2390 getLineNumber(CurLoc), Flags, 2391 CGM.getLangOpts().Optimize, 2392 Fn, TParamsArray, SPDecl); 2393 if (HasDecl) 2394 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP))); 2395 2396 // Push function on region stack. 2397 llvm::MDNode *SPN = SP; 2398 LexicalBlockStack.push_back(SPN); 2399 if (HasDecl) 2400 RegionMap[D] = llvm::WeakVH(SP); 2401} 2402 2403/// EmitLocation - Emit metadata to indicate a change in line/column 2404/// information in the source file. 2405void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc, 2406 bool ForceColumnInfo) { 2407 2408 // Update our current location 2409 setLocation(Loc); 2410 2411 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return; 2412 2413 // Don't bother if things are the same as last time. 2414 SourceManager &SM = CGM.getContext().getSourceManager(); 2415 if (CurLoc == PrevLoc || 2416 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc)) 2417 // New Builder may not be in sync with CGDebugInfo. 2418 if (!Builder.getCurrentDebugLocation().isUnknown() && 2419 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) == 2420 LexicalBlockStack.back()) 2421 return; 2422 2423 // Update last state. 2424 PrevLoc = CurLoc; 2425 2426 llvm::MDNode *Scope = LexicalBlockStack.back(); 2427 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get 2428 (getLineNumber(CurLoc), 2429 getColumnNumber(CurLoc, ForceColumnInfo), 2430 Scope)); 2431} 2432 2433/// CreateLexicalBlock - Creates a new lexical block node and pushes it on 2434/// the stack. 2435void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) { 2436 llvm::DIDescriptor D = 2437 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ? 2438 llvm::DIDescriptor() : 2439 llvm::DIDescriptor(LexicalBlockStack.back()), 2440 getOrCreateFile(CurLoc), 2441 getLineNumber(CurLoc), 2442 getColumnNumber(CurLoc)); 2443 llvm::MDNode *DN = D; 2444 LexicalBlockStack.push_back(DN); 2445} 2446 2447/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative 2448/// region - beginning of a DW_TAG_lexical_block. 2449void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, 2450 SourceLocation Loc) { 2451 // Set our current location. 2452 setLocation(Loc); 2453 2454 // Create a new lexical block and push it on the stack. 2455 CreateLexicalBlock(Loc); 2456 2457 // Emit a line table change for the current location inside the new scope. 2458 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc), 2459 getColumnNumber(Loc), 2460 LexicalBlockStack.back())); 2461} 2462 2463/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative 2464/// region - end of a DW_TAG_lexical_block. 2465void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, 2466 SourceLocation Loc) { 2467 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2468 2469 // Provide an entry in the line table for the end of the block. 2470 EmitLocation(Builder, Loc); 2471 2472 LexicalBlockStack.pop_back(); 2473} 2474 2475/// EmitFunctionEnd - Constructs the debug code for exiting a function. 2476void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) { 2477 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2478 unsigned RCount = FnBeginRegionCount.back(); 2479 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch"); 2480 2481 // Pop all regions for this function. 2482 while (LexicalBlockStack.size() != RCount) 2483 EmitLexicalBlockEnd(Builder, CurLoc); 2484 FnBeginRegionCount.pop_back(); 2485} 2486 2487// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref. 2488// See BuildByRefType. 2489llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD, 2490 uint64_t *XOffset) { 2491 2492 SmallVector<llvm::Value *, 5> EltTys; 2493 QualType FType; 2494 uint64_t FieldSize, FieldOffset; 2495 unsigned FieldAlign; 2496 2497 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 2498 QualType Type = VD->getType(); 2499 2500 FieldOffset = 0; 2501 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 2502 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 2503 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset)); 2504 FType = CGM.getContext().IntTy; 2505 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 2506 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset)); 2507 2508 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD); 2509 if (HasCopyAndDispose) { 2510 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 2511 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper", 2512 &FieldOffset)); 2513 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper", 2514 &FieldOffset)); 2515 } 2516 bool HasByrefExtendedLayout; 2517 Qualifiers::ObjCLifetime Lifetime; 2518 if (CGM.getContext().getByrefLifetime(Type, 2519 Lifetime, HasByrefExtendedLayout) 2520 && HasByrefExtendedLayout) 2521 EltTys.push_back(CreateMemberType(Unit, FType, 2522 "__byref_variable_layout", 2523 &FieldOffset)); 2524 2525 CharUnits Align = CGM.getContext().getDeclAlign(VD); 2526 if (Align > CGM.getContext().toCharUnitsFromBits( 2527 CGM.getTarget().getPointerAlign(0))) { 2528 CharUnits FieldOffsetInBytes 2529 = CGM.getContext().toCharUnitsFromBits(FieldOffset); 2530 CharUnits AlignedOffsetInBytes 2531 = FieldOffsetInBytes.RoundUpToAlignment(Align); 2532 CharUnits NumPaddingBytes 2533 = AlignedOffsetInBytes - FieldOffsetInBytes; 2534 2535 if (NumPaddingBytes.isPositive()) { 2536 llvm::APInt pad(32, NumPaddingBytes.getQuantity()); 2537 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy, 2538 pad, ArrayType::Normal, 0); 2539 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset)); 2540 } 2541 } 2542 2543 FType = Type; 2544 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 2545 FieldSize = CGM.getContext().getTypeSize(FType); 2546 FieldAlign = CGM.getContext().toBits(Align); 2547 2548 *XOffset = FieldOffset; 2549 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 2550 0, FieldSize, FieldAlign, 2551 FieldOffset, 0, FieldTy); 2552 EltTys.push_back(FieldTy); 2553 FieldOffset += FieldSize; 2554 2555 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys); 2556 2557 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct; 2558 2559 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags, 2560 llvm::DIType(), Elements); 2561} 2562 2563/// EmitDeclare - Emit local variable declaration debug info. 2564void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag, 2565 llvm::Value *Storage, 2566 unsigned ArgNo, CGBuilderTy &Builder) { 2567 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 2568 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2569 2570 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 2571 llvm::DIType Ty; 2572 uint64_t XOffset = 0; 2573 if (VD->hasAttr<BlocksAttr>()) 2574 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 2575 else 2576 Ty = getOrCreateType(VD->getType(), Unit); 2577 2578 // If there is no debug info for this type then do not emit debug info 2579 // for this variable. 2580 if (!Ty) 2581 return; 2582 2583 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) { 2584 // If Storage is an aggregate returned as 'sret' then let debugger know 2585 // about this. 2586 if (Arg->hasStructRetAttr()) 2587 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty); 2588 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) { 2589 // If an aggregate variable has non trivial destructor or non trivial copy 2590 // constructor than it is pass indirectly. Let debug info know about this 2591 // by using reference of the aggregate type as a argument type. 2592 if (Record->hasNonTrivialCopyConstructor() || 2593 !Record->hasTrivialDestructor()) 2594 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, 2595 Ty); 2596 } 2597 } 2598 2599 // Get location information. 2600 unsigned Line = getLineNumber(VD->getLocation()); 2601 unsigned Column = getColumnNumber(VD->getLocation()); 2602 unsigned Flags = 0; 2603 if (VD->isImplicit()) 2604 Flags |= llvm::DIDescriptor::FlagArtificial; 2605 // If this is the first argument and it is implicit then 2606 // give it an object pointer flag. 2607 // FIXME: There has to be a better way to do this, but for static 2608 // functions there won't be an implicit param at arg1 and 2609 // otherwise it is 'self' or 'this'. 2610 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1) 2611 Flags |= llvm::DIDescriptor::FlagObjectPointer; 2612 2613 llvm::MDNode *Scope = LexicalBlockStack.back(); 2614 2615 StringRef Name = VD->getName(); 2616 if (!Name.empty()) { 2617 if (VD->hasAttr<BlocksAttr>()) { 2618 CharUnits offset = CharUnits::fromQuantity(32); 2619 SmallVector<llvm::Value *, 9> addr; 2620 llvm::Type *Int64Ty = CGM.Int64Ty; 2621 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2622 // offset of __forwarding field 2623 offset = CGM.getContext().toCharUnitsFromBits( 2624 CGM.getTarget().getPointerWidth(0)); 2625 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2626 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 2627 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2628 // offset of x field 2629 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 2630 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2631 2632 // Create the descriptor for the variable. 2633 llvm::DIVariable D = 2634 DBuilder.createComplexVariable(Tag, 2635 llvm::DIDescriptor(Scope), 2636 VD->getName(), Unit, Line, Ty, 2637 addr, ArgNo); 2638 2639 // Insert an llvm.dbg.declare into the current block. 2640 llvm::Instruction *Call = 2641 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 2642 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 2643 return; 2644 } else if (isa<VariableArrayType>(VD->getType())) { 2645 // These are "complex" variables in that they need an op_deref. 2646 // Create the descriptor for the variable. 2647 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty, 2648 llvm::DIBuilder::OpDeref); 2649 llvm::DIVariable D = 2650 DBuilder.createComplexVariable(Tag, 2651 llvm::DIDescriptor(Scope), 2652 Name, Unit, Line, Ty, 2653 Addr, ArgNo); 2654 2655 // Insert an llvm.dbg.declare into the current block. 2656 llvm::Instruction *Call = 2657 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 2658 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 2659 return; 2660 } 2661 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) { 2662 // If VD is an anonymous union then Storage represents value for 2663 // all union fields. 2664 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 2665 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) { 2666 for (RecordDecl::field_iterator I = RD->field_begin(), 2667 E = RD->field_end(); 2668 I != E; ++I) { 2669 FieldDecl *Field = *I; 2670 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); 2671 StringRef FieldName = Field->getName(); 2672 2673 // Ignore unnamed fields. Do not ignore unnamed records. 2674 if (FieldName.empty() && !isa<RecordType>(Field->getType())) 2675 continue; 2676 2677 // Use VarDecl's Tag, Scope and Line number. 2678 llvm::DIVariable D = 2679 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope), 2680 FieldName, Unit, Line, FieldTy, 2681 CGM.getLangOpts().Optimize, Flags, 2682 ArgNo); 2683 2684 // Insert an llvm.dbg.declare into the current block. 2685 llvm::Instruction *Call = 2686 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 2687 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 2688 } 2689 return; 2690 } 2691 } 2692 2693 // Create the descriptor for the variable. 2694 llvm::DIVariable D = 2695 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope), 2696 Name, Unit, Line, Ty, 2697 CGM.getLangOpts().Optimize, Flags, ArgNo); 2698 2699 // Insert an llvm.dbg.declare into the current block. 2700 llvm::Instruction *Call = 2701 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock()); 2702 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope)); 2703} 2704 2705void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, 2706 llvm::Value *Storage, 2707 CGBuilderTy &Builder) { 2708 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 2709 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder); 2710} 2711 2712/// Look up the completed type for a self pointer in the TypeCache and 2713/// create a copy of it with the ObjectPointer and Artificial flags 2714/// set. If the type is not cached, a new one is created. This should 2715/// never happen though, since creating a type for the implicit self 2716/// argument implies that we already parsed the interface definition 2717/// and the ivar declarations in the implementation. 2718llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy, 2719 llvm::DIType Ty) { 2720 llvm::DIType CachedTy = getTypeOrNull(QualTy); 2721 if (CachedTy.Verify()) Ty = CachedTy; 2722 else DEBUG(llvm::dbgs() << "No cached type for self."); 2723 return DBuilder.createObjectPointerType(Ty); 2724} 2725 2726void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD, 2727 llvm::Value *Storage, 2728 CGBuilderTy &Builder, 2729 const CGBlockInfo &blockInfo) { 2730 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 2731 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2732 2733 if (Builder.GetInsertBlock() == 0) 2734 return; 2735 2736 bool isByRef = VD->hasAttr<BlocksAttr>(); 2737 2738 uint64_t XOffset = 0; 2739 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 2740 llvm::DIType Ty; 2741 if (isByRef) 2742 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 2743 else 2744 Ty = getOrCreateType(VD->getType(), Unit); 2745 2746 // Self is passed along as an implicit non-arg variable in a 2747 // block. Mark it as the object pointer. 2748 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self") 2749 Ty = CreateSelfType(VD->getType(), Ty); 2750 2751 // Get location information. 2752 unsigned Line = getLineNumber(VD->getLocation()); 2753 unsigned Column = getColumnNumber(VD->getLocation()); 2754 2755 const llvm::DataLayout &target = CGM.getDataLayout(); 2756 2757 CharUnits offset = CharUnits::fromQuantity( 2758 target.getStructLayout(blockInfo.StructureType) 2759 ->getElementOffset(blockInfo.getCapture(VD).getIndex())); 2760 2761 SmallVector<llvm::Value *, 9> addr; 2762 llvm::Type *Int64Ty = CGM.Int64Ty; 2763 if (isa<llvm::AllocaInst>(Storage)) 2764 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 2765 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2766 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2767 if (isByRef) { 2768 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 2769 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2770 // offset of __forwarding field 2771 offset = CGM.getContext() 2772 .toCharUnitsFromBits(target.getPointerSizeInBits(0)); 2773 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2774 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref)); 2775 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus)); 2776 // offset of x field 2777 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 2778 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity())); 2779 } 2780 2781 // Create the descriptor for the variable. 2782 llvm::DIVariable D = 2783 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable, 2784 llvm::DIDescriptor(LexicalBlockStack.back()), 2785 VD->getName(), Unit, Line, Ty, addr); 2786 2787 // Insert an llvm.dbg.declare into the current block. 2788 llvm::Instruction *Call = 2789 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint()); 2790 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, 2791 LexicalBlockStack.back())); 2792} 2793 2794/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument 2795/// variable declaration. 2796void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI, 2797 unsigned ArgNo, 2798 CGBuilderTy &Builder) { 2799 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 2800 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder); 2801} 2802 2803namespace { 2804 struct BlockLayoutChunk { 2805 uint64_t OffsetInBits; 2806 const BlockDecl::Capture *Capture; 2807 }; 2808 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) { 2809 return l.OffsetInBits < r.OffsetInBits; 2810 } 2811} 2812 2813void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, 2814 llvm::Value *Arg, 2815 llvm::Value *LocalAddr, 2816 CGBuilderTy &Builder) { 2817 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 2818 ASTContext &C = CGM.getContext(); 2819 const BlockDecl *blockDecl = block.getBlockDecl(); 2820 2821 // Collect some general information about the block's location. 2822 SourceLocation loc = blockDecl->getCaretLocation(); 2823 llvm::DIFile tunit = getOrCreateFile(loc); 2824 unsigned line = getLineNumber(loc); 2825 unsigned column = getColumnNumber(loc); 2826 2827 // Build the debug-info type for the block literal. 2828 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext())); 2829 2830 const llvm::StructLayout *blockLayout = 2831 CGM.getDataLayout().getStructLayout(block.StructureType); 2832 2833 SmallVector<llvm::Value*, 16> fields; 2834 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public, 2835 blockLayout->getElementOffsetInBits(0), 2836 tunit, tunit)); 2837 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public, 2838 blockLayout->getElementOffsetInBits(1), 2839 tunit, tunit)); 2840 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public, 2841 blockLayout->getElementOffsetInBits(2), 2842 tunit, tunit)); 2843 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public, 2844 blockLayout->getElementOffsetInBits(3), 2845 tunit, tunit)); 2846 fields.push_back(createFieldType("__descriptor", 2847 C.getPointerType(block.NeedsCopyDispose ? 2848 C.getBlockDescriptorExtendedType() : 2849 C.getBlockDescriptorType()), 2850 0, loc, AS_public, 2851 blockLayout->getElementOffsetInBits(4), 2852 tunit, tunit)); 2853 2854 // We want to sort the captures by offset, not because DWARF 2855 // requires this, but because we're paranoid about debuggers. 2856 SmallVector<BlockLayoutChunk, 8> chunks; 2857 2858 // 'this' capture. 2859 if (blockDecl->capturesCXXThis()) { 2860 BlockLayoutChunk chunk; 2861 chunk.OffsetInBits = 2862 blockLayout->getElementOffsetInBits(block.CXXThisIndex); 2863 chunk.Capture = 0; 2864 chunks.push_back(chunk); 2865 } 2866 2867 // Variable captures. 2868 for (BlockDecl::capture_const_iterator 2869 i = blockDecl->capture_begin(), e = blockDecl->capture_end(); 2870 i != e; ++i) { 2871 const BlockDecl::Capture &capture = *i; 2872 const VarDecl *variable = capture.getVariable(); 2873 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable); 2874 2875 // Ignore constant captures. 2876 if (captureInfo.isConstant()) 2877 continue; 2878 2879 BlockLayoutChunk chunk; 2880 chunk.OffsetInBits = 2881 blockLayout->getElementOffsetInBits(captureInfo.getIndex()); 2882 chunk.Capture = &capture; 2883 chunks.push_back(chunk); 2884 } 2885 2886 // Sort by offset. 2887 llvm::array_pod_sort(chunks.begin(), chunks.end()); 2888 2889 for (SmallVectorImpl<BlockLayoutChunk>::iterator 2890 i = chunks.begin(), e = chunks.end(); i != e; ++i) { 2891 uint64_t offsetInBits = i->OffsetInBits; 2892 const BlockDecl::Capture *capture = i->Capture; 2893 2894 // If we have a null capture, this must be the C++ 'this' capture. 2895 if (!capture) { 2896 const CXXMethodDecl *method = 2897 cast<CXXMethodDecl>(blockDecl->getNonClosureContext()); 2898 QualType type = method->getThisType(C); 2899 2900 fields.push_back(createFieldType("this", type, 0, loc, AS_public, 2901 offsetInBits, tunit, tunit)); 2902 continue; 2903 } 2904 2905 const VarDecl *variable = capture->getVariable(); 2906 StringRef name = variable->getName(); 2907 2908 llvm::DIType fieldType; 2909 if (capture->isByRef()) { 2910 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy); 2911 2912 // FIXME: this creates a second copy of this type! 2913 uint64_t xoffset; 2914 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset); 2915 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first); 2916 fieldType = DBuilder.createMemberType(tunit, name, tunit, line, 2917 ptrInfo.first, ptrInfo.second, 2918 offsetInBits, 0, fieldType); 2919 } else { 2920 fieldType = createFieldType(name, variable->getType(), 0, 2921 loc, AS_public, offsetInBits, tunit, tunit); 2922 } 2923 fields.push_back(fieldType); 2924 } 2925 2926 SmallString<36> typeName; 2927 llvm::raw_svector_ostream(typeName) 2928 << "__block_literal_" << CGM.getUniqueBlockCount(); 2929 2930 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields); 2931 2932 llvm::DIType type = 2933 DBuilder.createStructType(tunit, typeName.str(), tunit, line, 2934 CGM.getContext().toBits(block.BlockSize), 2935 CGM.getContext().toBits(block.BlockAlign), 2936 0, llvm::DIType(), fieldsArray); 2937 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits); 2938 2939 // Get overall information about the block. 2940 unsigned flags = llvm::DIDescriptor::FlagArtificial; 2941 llvm::MDNode *scope = LexicalBlockStack.back(); 2942 2943 // Create the descriptor for the parameter. 2944 llvm::DIVariable debugVar = 2945 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable, 2946 llvm::DIDescriptor(scope), 2947 Arg->getName(), tunit, line, type, 2948 CGM.getLangOpts().Optimize, flags, 2949 cast<llvm::Argument>(Arg)->getArgNo() + 1); 2950 2951 if (LocalAddr) { 2952 // Insert an llvm.dbg.value into the current block. 2953 llvm::Instruction *DbgVal = 2954 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar, 2955 Builder.GetInsertBlock()); 2956 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope)); 2957 } 2958 2959 // Insert an llvm.dbg.declare into the current block. 2960 llvm::Instruction *DbgDecl = 2961 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock()); 2962 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope)); 2963} 2964 2965/// getStaticDataMemberDeclaration - If D is an out-of-class definition of 2966/// a static data member of a class, find its corresponding in-class 2967/// declaration. 2968llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) { 2969 if (cast<VarDecl>(D)->isStaticDataMember()) { 2970 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator 2971 MI = StaticDataMemberCache.find(D->getCanonicalDecl()); 2972 if (MI != StaticDataMemberCache.end()) 2973 // Verify the info still exists. 2974 if (llvm::Value *V = MI->second) 2975 return llvm::DIDerivedType(cast<llvm::MDNode>(V)); 2976 } 2977 return llvm::DIDerivedType(); 2978} 2979 2980/// EmitGlobalVariable - Emit information about a global variable. 2981void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 2982 const VarDecl *D) { 2983 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 2984 // Create global variable debug descriptor. 2985 llvm::DIFile Unit = getOrCreateFile(D->getLocation()); 2986 unsigned LineNo = getLineNumber(D->getLocation()); 2987 2988 setLocation(D->getLocation()); 2989 2990 QualType T = D->getType(); 2991 if (T->isIncompleteArrayType()) { 2992 2993 // CodeGen turns int[] into int[1] so we'll do the same here. 2994 llvm::APInt ConstVal(32, 1); 2995 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 2996 2997 T = CGM.getContext().getConstantArrayType(ET, ConstVal, 2998 ArrayType::Normal, 0); 2999 } 3000 StringRef DeclName = D->getName(); 3001 StringRef LinkageName; 3002 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext()) 3003 && !isa<ObjCMethodDecl>(D->getDeclContext())) 3004 LinkageName = Var->getName(); 3005 if (LinkageName == DeclName) 3006 LinkageName = StringRef(); 3007 llvm::DIDescriptor DContext = 3008 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext())); 3009 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(DContext, DeclName, LinkageName, 3010 Unit, LineNo, getOrCreateType(T, Unit), 3011 Var->hasInternalLinkage(), Var, 3012 getStaticDataMemberDeclaration(D)); 3013 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV))); 3014} 3015 3016/// EmitGlobalVariable - Emit information about an objective-c interface. 3017void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 3018 ObjCInterfaceDecl *ID) { 3019 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 3020 // Create global variable debug descriptor. 3021 llvm::DIFile Unit = getOrCreateFile(ID->getLocation()); 3022 unsigned LineNo = getLineNumber(ID->getLocation()); 3023 3024 StringRef Name = ID->getName(); 3025 3026 QualType T = CGM.getContext().getObjCInterfaceType(ID); 3027 if (T->isIncompleteArrayType()) { 3028 3029 // CodeGen turns int[] into int[1] so we'll do the same here. 3030 llvm::APInt ConstVal(32, 1); 3031 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 3032 3033 T = CGM.getContext().getConstantArrayType(ET, ConstVal, 3034 ArrayType::Normal, 0); 3035 } 3036 3037 DBuilder.createGlobalVariable(Name, Unit, LineNo, 3038 getOrCreateType(T, Unit), 3039 Var->hasInternalLinkage(), Var); 3040} 3041 3042/// EmitGlobalVariable - Emit global variable's debug info. 3043void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, 3044 llvm::Constant *Init) { 3045 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 3046 // Create the descriptor for the variable. 3047 llvm::DIFile Unit = getOrCreateFile(VD->getLocation()); 3048 StringRef Name = VD->getName(); 3049 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit); 3050 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) { 3051 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext()); 3052 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?"); 3053 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit); 3054 } 3055 // Do not use DIGlobalVariable for enums. 3056 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type) 3057 return; 3058 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(Unit, Name, Name, Unit, 3059 getLineNumber(VD->getLocation()), 3060 Ty, true, Init, 3061 getStaticDataMemberDeclaration(VD)); 3062 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV))); 3063} 3064 3065llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) { 3066 if (!LexicalBlockStack.empty()) 3067 return llvm::DIScope(LexicalBlockStack.back()); 3068 return getContextDescriptor(D); 3069} 3070 3071void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) { 3072 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo) 3073 return; 3074 DBuilder.createImportedModule( 3075 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())), 3076 getOrCreateNameSpace(UD.getNominatedNamespace()), 3077 getLineNumber(UD.getLocation())); 3078} 3079 3080void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) { 3081 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo) 3082 return; 3083 assert(UD.shadow_size() && 3084 "We shouldn't be codegening an invalid UsingDecl containing no decls"); 3085 // Emitting one decl is sufficient - debuggers can detect that this is an 3086 // overloaded name & provide lookup for all the overloads. 3087 const UsingShadowDecl &USD = **UD.shadow_begin(); 3088 if (llvm::DIDescriptor Target = getDeclarationOrDefinition(USD.getUnderlyingDecl())) 3089 DBuilder.createImportedDeclaration( 3090 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target, 3091 getLineNumber(USD.getLocation())); 3092} 3093 3094llvm::DIImportedEntity 3095CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) { 3096 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo) 3097 return llvm::DIImportedEntity(0); 3098 llvm::WeakVH &VH = NamespaceAliasCache[&NA]; 3099 if (VH) 3100 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH)); 3101 llvm::DIImportedEntity R(0); 3102 if (const NamespaceAliasDecl *Underlying = 3103 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace())) 3104 // This could cache & dedup here rather than relying on metadata deduping. 3105 R = DBuilder.createImportedModule( 3106 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())), 3107 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()), 3108 NA.getName()); 3109 else 3110 R = DBuilder.createImportedModule( 3111 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())), 3112 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())), 3113 getLineNumber(NA.getLocation()), NA.getName()); 3114 VH = R; 3115 return R; 3116} 3117 3118/// getOrCreateNamesSpace - Return namespace descriptor for the given 3119/// namespace decl. 3120llvm::DINameSpace 3121CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) { 3122 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I = 3123 NameSpaceCache.find(NSDecl); 3124 if (I != NameSpaceCache.end()) 3125 return llvm::DINameSpace(cast<llvm::MDNode>(I->second)); 3126 3127 unsigned LineNo = getLineNumber(NSDecl->getLocation()); 3128 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation()); 3129 llvm::DIDescriptor Context = 3130 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext())); 3131 llvm::DINameSpace NS = 3132 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo); 3133 NameSpaceCache[NSDecl] = llvm::WeakVH(NS); 3134 return NS; 3135} 3136 3137void CGDebugInfo::finalize() { 3138 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI 3139 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) { 3140 llvm::DIType Ty, RepTy; 3141 // Verify that the debug info still exists. 3142 if (llvm::Value *V = VI->second) 3143 Ty = llvm::DIType(cast<llvm::MDNode>(V)); 3144 3145 llvm::DenseMap<void *, llvm::WeakVH>::iterator it = 3146 TypeCache.find(VI->first); 3147 if (it != TypeCache.end()) { 3148 // Verify that the debug info still exists. 3149 if (llvm::Value *V = it->second) 3150 RepTy = llvm::DIType(cast<llvm::MDNode>(V)); 3151 } 3152 3153 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify()) 3154 Ty.replaceAllUsesWith(RepTy); 3155 } 3156 3157 // We keep our own list of retained types, because we need to look 3158 // up the final type in the type cache. 3159 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(), 3160 RE = RetainedTypes.end(); RI != RE; ++RI) 3161 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI]))); 3162 3163 DBuilder.finalize(); 3164} 3165