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