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