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