CGDebugInfo.cpp 94 KB

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