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