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