CGDebugInfo.cpp 98 KB

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