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