CGDebugInfo.cpp 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395
  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 "CGBlocks.h"
  15. #include "CGCXXABI.h"
  16. #include "CGObjCRuntime.h"
  17. #include "CodeGenFunction.h"
  18. #include "CodeGenModule.h"
  19. #include "clang/AST/ASTContext.h"
  20. #include "clang/AST/DeclFriend.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/DeclTemplate.h"
  23. #include "clang/AST/Expr.h"
  24. #include "clang/AST/RecordLayout.h"
  25. #include "clang/Basic/FileManager.h"
  26. #include "clang/Basic/SourceManager.h"
  27. #include "clang/Basic/Version.h"
  28. #include "clang/Frontend/CodeGenOptions.h"
  29. #include "clang/Lex/HeaderSearchOptions.h"
  30. #include "clang/Lex/PreprocessorOptions.h"
  31. #include "llvm/ADT/SmallVector.h"
  32. #include "llvm/ADT/StringExtras.h"
  33. #include "llvm/IR/Constants.h"
  34. #include "llvm/IR/DataLayout.h"
  35. #include "llvm/IR/DerivedTypes.h"
  36. #include "llvm/IR/Instructions.h"
  37. #include "llvm/IR/Intrinsics.h"
  38. #include "llvm/IR/Module.h"
  39. #include "llvm/Support/Dwarf.h"
  40. #include "llvm/Support/FileSystem.h"
  41. #include "llvm/Support/Path.h"
  42. using namespace clang;
  43. using namespace clang::CodeGen;
  44. CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
  45. : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
  46. DBuilder(CGM.getModule()) {
  47. CreateCompileUnit();
  48. }
  49. CGDebugInfo::~CGDebugInfo() {
  50. assert(LexicalBlockStack.empty() &&
  51. "Region stack mismatch, stack not empty!");
  52. }
  53. ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
  54. SourceLocation TemporaryLocation)
  55. : CGF(CGF) {
  56. init(TemporaryLocation);
  57. }
  58. ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
  59. bool DefaultToEmpty,
  60. SourceLocation TemporaryLocation)
  61. : CGF(CGF) {
  62. init(TemporaryLocation, DefaultToEmpty);
  63. }
  64. void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
  65. bool DefaultToEmpty) {
  66. if (auto *DI = CGF.getDebugInfo()) {
  67. OriginalLocation = CGF.Builder.getCurrentDebugLocation();
  68. if (TemporaryLocation.isInvalid()) {
  69. if (DefaultToEmpty)
  70. CGF.Builder.SetCurrentDebugLocation(llvm::DebugLoc());
  71. else {
  72. // Construct a location that has a valid scope, but no line info.
  73. assert(!DI->LexicalBlockStack.empty());
  74. CGF.Builder.SetCurrentDebugLocation(
  75. llvm::DebugLoc::get(0, 0, DI->LexicalBlockStack.back()));
  76. }
  77. } else
  78. DI->EmitLocation(CGF.Builder, TemporaryLocation);
  79. }
  80. }
  81. ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
  82. : CGF(CGF) {
  83. init(E->getExprLoc());
  84. }
  85. ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
  86. : CGF(CGF) {
  87. if (CGF.getDebugInfo()) {
  88. OriginalLocation = CGF.Builder.getCurrentDebugLocation();
  89. if (Loc)
  90. CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
  91. }
  92. }
  93. ApplyDebugLocation::~ApplyDebugLocation() {
  94. // Query CGF so the location isn't overwritten when location updates are
  95. // temporarily disabled (for C++ default function arguments)
  96. if (CGF.getDebugInfo())
  97. CGF.Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
  98. }
  99. void CGDebugInfo::setLocation(SourceLocation Loc) {
  100. // If the new location isn't valid return.
  101. if (Loc.isInvalid())
  102. return;
  103. CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
  104. // If we've changed files in the middle of a lexical scope go ahead
  105. // and create a new lexical scope with file node if it's different
  106. // from the one in the scope.
  107. if (LexicalBlockStack.empty())
  108. return;
  109. SourceManager &SM = CGM.getContext().getSourceManager();
  110. auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
  111. PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
  112. if (PCLoc.isInvalid() || Scope->getFilename() == PCLoc.getFilename())
  113. return;
  114. if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
  115. LexicalBlockStack.pop_back();
  116. LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
  117. LBF->getScope(), getOrCreateFile(CurLoc)));
  118. } else if (isa<llvm::DILexicalBlock>(Scope) ||
  119. isa<llvm::DISubprogram>(Scope)) {
  120. LexicalBlockStack.pop_back();
  121. LexicalBlockStack.emplace_back(
  122. DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
  123. }
  124. }
  125. llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context) {
  126. if (!Context)
  127. return TheCU;
  128. auto I = RegionMap.find(Context);
  129. if (I != RegionMap.end()) {
  130. llvm::Metadata *V = I->second;
  131. return dyn_cast_or_null<llvm::DIScope>(V);
  132. }
  133. // Check namespace.
  134. if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
  135. return getOrCreateNameSpace(NSDecl);
  136. if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
  137. if (!RDecl->isDependentType())
  138. return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
  139. getOrCreateMainFile());
  140. return TheCU;
  141. }
  142. StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
  143. assert(FD && "Invalid FunctionDecl!");
  144. IdentifierInfo *FII = FD->getIdentifier();
  145. FunctionTemplateSpecializationInfo *Info =
  146. FD->getTemplateSpecializationInfo();
  147. if (!Info && FII)
  148. return FII->getName();
  149. // Otherwise construct human readable name for debug info.
  150. SmallString<128> NS;
  151. llvm::raw_svector_ostream OS(NS);
  152. FD->printName(OS);
  153. // Add any template specialization args.
  154. if (Info) {
  155. const TemplateArgumentList *TArgs = Info->TemplateArguments;
  156. const TemplateArgument *Args = TArgs->data();
  157. unsigned NumArgs = TArgs->size();
  158. PrintingPolicy Policy(CGM.getLangOpts());
  159. TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
  160. Policy);
  161. }
  162. // Copy this name on the side and use its reference.
  163. return internString(OS.str());
  164. }
  165. #if 0 // HLSL Change - no ObjC support
  166. StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
  167. SmallString<256> MethodName;
  168. llvm::raw_svector_ostream OS(MethodName);
  169. OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
  170. const DeclContext *DC = OMD->getDeclContext();
  171. if (const ObjCImplementationDecl *OID =
  172. dyn_cast<const ObjCImplementationDecl>(DC)) {
  173. OS << OID->getName();
  174. } else if (const ObjCInterfaceDecl *OID =
  175. dyn_cast<const ObjCInterfaceDecl>(DC)) {
  176. OS << OID->getName();
  177. } else if (const ObjCCategoryImplDecl *OCD =
  178. dyn_cast<const ObjCCategoryImplDecl>(DC)) {
  179. OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '('
  180. << OCD->getIdentifier()->getNameStart() << ')';
  181. } else if (isa<ObjCProtocolDecl>(DC)) {
  182. // We can extract the type of the class from the self pointer.
  183. if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
  184. QualType ClassTy =
  185. cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
  186. ClassTy.print(OS, PrintingPolicy(LangOptions()));
  187. }
  188. }
  189. OS << ' ' << OMD->getSelector().getAsString() << ']';
  190. return internString(OS.str());
  191. }
  192. #endif // HLSL Change - no ObjC support
  193. StringRef CGDebugInfo::getSelectorName(Selector S) {
  194. return internString(S.getAsString());
  195. }
  196. StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
  197. // quick optimization to avoid having to intern strings that are already
  198. // stored reliably elsewhere
  199. if (!isa<ClassTemplateSpecializationDecl>(RD))
  200. return RD->getName();
  201. SmallString<128> Name;
  202. {
  203. llvm::raw_svector_ostream OS(Name);
  204. RD->getNameForDiagnostic(OS, CGM.getContext().getPrintingPolicy(),
  205. /*Qualified*/ false);
  206. }
  207. // Copy this name on the side and use its reference.
  208. return internString(Name);
  209. }
  210. llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
  211. if (!Loc.isValid())
  212. // If Location is not valid then use main input file.
  213. return DBuilder.createFile(TheCU->getFilename(), TheCU->getDirectory());
  214. SourceManager &SM = CGM.getContext().getSourceManager();
  215. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  216. if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
  217. // If the location is not valid then use main input file.
  218. return DBuilder.createFile(TheCU->getFilename(), TheCU->getDirectory());
  219. // Cache the results.
  220. const char *fname = PLoc.getFilename();
  221. auto it = DIFileCache.find(fname);
  222. if (it != DIFileCache.end()) {
  223. // Verify that the information still exists.
  224. if (llvm::Metadata *V = it->second)
  225. return cast<llvm::DIFile>(V);
  226. }
  227. llvm::DIFile *F =
  228. DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
  229. DIFileCache[fname].reset(F);
  230. return F;
  231. }
  232. llvm::DIFile *CGDebugInfo::getOrCreateMainFile() {
  233. return DBuilder.createFile(TheCU->getFilename(), TheCU->getDirectory());
  234. }
  235. unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
  236. if (Loc.isInvalid() && CurLoc.isInvalid())
  237. return 0;
  238. SourceManager &SM = CGM.getContext().getSourceManager();
  239. PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
  240. return PLoc.isValid() ? PLoc.getLine() : 0;
  241. }
  242. unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
  243. // We may not want column information at all.
  244. if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
  245. return 0;
  246. // If the location is invalid then use the current column.
  247. if (Loc.isInvalid() && CurLoc.isInvalid())
  248. return 0;
  249. SourceManager &SM = CGM.getContext().getSourceManager();
  250. PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
  251. return PLoc.isValid() ? PLoc.getColumn() : 0;
  252. }
  253. StringRef CGDebugInfo::getCurrentDirname() {
  254. if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
  255. return CGM.getCodeGenOpts().DebugCompilationDir;
  256. if (!CWDName.empty())
  257. return CWDName;
  258. SmallString<256> CWD;
  259. llvm::sys::fs::current_path(CWD);
  260. return CWDName = internString(CWD);
  261. }
  262. void CGDebugInfo::CreateCompileUnit() {
  263. // Should we be asking the SourceManager for the main file name, instead of
  264. // accepting it as an argument? This just causes the main file name to
  265. // mismatch with source locations and create extra lexical scopes or
  266. // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
  267. // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
  268. // because that's what the SourceManager says)
  269. // Get absolute path name.
  270. SourceManager &SM = CGM.getContext().getSourceManager();
  271. std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
  272. if (MainFileName.empty())
  273. MainFileName = "<stdin>";
  274. // The main file name provided via the "-main-file-name" option contains just
  275. // the file name itself with no path information. This file name may have had
  276. // a relative path, so we look into the actual file entry for the main
  277. // file to determine the real absolute path for the file.
  278. std::string MainFileDir;
  279. if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  280. MainFileDir = MainFile->getDir()->getName();
  281. if (MainFileDir != ".") {
  282. llvm::SmallString<1024> MainFileDirSS(MainFileDir);
  283. llvm::sys::path::append(MainFileDirSS, MainFileName);
  284. MainFileName = MainFileDirSS.str();
  285. }
  286. }
  287. // Save filename string.
  288. StringRef Filename = internString(MainFileName);
  289. // Save split dwarf file string.
  290. std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
  291. StringRef SplitDwarfFilename = internString(SplitDwarfFile);
  292. llvm::dwarf::SourceLanguage LangTag;
  293. const LangOptions &LO = CGM.getLangOpts();
  294. if (LO.CPlusPlus) {
  295. if (LO.ObjC1)
  296. LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
  297. else
  298. LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
  299. } else if (LO.ObjC1) {
  300. LangTag = llvm::dwarf::DW_LANG_ObjC;
  301. } else if (LO.C99) {
  302. LangTag = llvm::dwarf::DW_LANG_C99;
  303. } else {
  304. LangTag = llvm::dwarf::DW_LANG_C89;
  305. }
  306. std::string Producer = getClangFullVersion();
  307. // Figure out which version of the ObjC runtime we have.
  308. unsigned RuntimeVers = 0;
  309. if (LO.ObjC1)
  310. RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
  311. // Create new compile unit.
  312. // FIXME - Eliminate TheCU.
  313. TheCU = DBuilder.createCompileUnit(
  314. LangTag, Filename, getCurrentDirname(), Producer, LO.Optimize,
  315. CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers, SplitDwarfFilename,
  316. DebugKind <= CodeGenOptions::DebugLineTablesOnly
  317. ? llvm::DIBuilder::LineTablesOnly
  318. : llvm::DIBuilder::FullDebug,
  319. 0 /* DWOid */,
  320. DebugKind != CodeGenOptions::LocTrackingOnly);
  321. }
  322. llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
  323. llvm::dwarf::TypeKind Encoding;
  324. StringRef BTName;
  325. switch (BT->getKind()) {
  326. #define BUILTIN_TYPE(Id, SingletonId)
  327. #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
  328. #include "clang/AST/BuiltinTypes.def"
  329. case BuiltinType::Dependent:
  330. llvm_unreachable("Unexpected builtin type");
  331. case BuiltinType::NullPtr:
  332. return DBuilder.createNullPtrType();
  333. case BuiltinType::Void:
  334. return nullptr;
  335. #if 0 // HLSL Change - no ObjC or OpenCL support
  336. case BuiltinType::ObjCClass:
  337. if (!ClassTy)
  338. ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
  339. "objc_class", TheCU,
  340. getOrCreateMainFile(), 0);
  341. return ClassTy;
  342. case BuiltinType::ObjCId: {
  343. // typedef struct objc_class *Class;
  344. // typedef struct objc_object {
  345. // Class isa;
  346. // } *id;
  347. if (ObjTy)
  348. return ObjTy;
  349. if (!ClassTy)
  350. ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
  351. "objc_class", TheCU,
  352. getOrCreateMainFile(), 0);
  353. unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
  354. auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
  355. ObjTy =
  356. DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
  357. 0, 0, 0, 0, nullptr, llvm::DINodeArray());
  358. DBuilder.replaceArrays(
  359. ObjTy,
  360. DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
  361. ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
  362. return ObjTy;
  363. }
  364. case BuiltinType::ObjCSel: {
  365. if (!SelTy)
  366. SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
  367. "objc_selector", TheCU,
  368. getOrCreateMainFile(), 0);
  369. return SelTy;
  370. }
  371. case BuiltinType::OCLImage1d:
  372. return getOrCreateStructPtrType("opencl_image1d_t", OCLImage1dDITy);
  373. case BuiltinType::OCLImage1dArray:
  374. return getOrCreateStructPtrType("opencl_image1d_array_t",
  375. OCLImage1dArrayDITy);
  376. case BuiltinType::OCLImage1dBuffer:
  377. return getOrCreateStructPtrType("opencl_image1d_buffer_t",
  378. OCLImage1dBufferDITy);
  379. case BuiltinType::OCLImage2d:
  380. return getOrCreateStructPtrType("opencl_image2d_t", OCLImage2dDITy);
  381. case BuiltinType::OCLImage2dArray:
  382. return getOrCreateStructPtrType("opencl_image2d_array_t",
  383. OCLImage2dArrayDITy);
  384. case BuiltinType::OCLImage3d:
  385. return getOrCreateStructPtrType("opencl_image3d_t", OCLImage3dDITy);
  386. case BuiltinType::OCLSampler:
  387. return DBuilder.createBasicType(
  388. "opencl_sampler_t", CGM.getContext().getTypeSize(BT),
  389. CGM.getContext().getTypeAlign(BT), llvm::dwarf::DW_ATE_unsigned);
  390. case BuiltinType::OCLEvent:
  391. return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
  392. #endif // HLSL Change - no ObjC or OpenCL support
  393. case BuiltinType::UChar:
  394. case BuiltinType::Char_U:
  395. Encoding = llvm::dwarf::DW_ATE_unsigned_char;
  396. break;
  397. case BuiltinType::Char_S:
  398. case BuiltinType::SChar:
  399. Encoding = llvm::dwarf::DW_ATE_signed_char;
  400. break;
  401. case BuiltinType::Char16:
  402. case BuiltinType::Char32:
  403. Encoding = llvm::dwarf::DW_ATE_UTF;
  404. break;
  405. case BuiltinType::UShort:
  406. case BuiltinType::UInt:
  407. case BuiltinType::UInt128:
  408. case BuiltinType::ULong:
  409. case BuiltinType::WChar_U:
  410. case BuiltinType::ULongLong:
  411. Encoding = llvm::dwarf::DW_ATE_unsigned;
  412. break;
  413. case BuiltinType::Short:
  414. case BuiltinType::Int:
  415. case BuiltinType::Int128:
  416. case BuiltinType::Long:
  417. case BuiltinType::WChar_S:
  418. case BuiltinType::LongLong:
  419. Encoding = llvm::dwarf::DW_ATE_signed;
  420. break;
  421. case BuiltinType::Bool:
  422. Encoding = llvm::dwarf::DW_ATE_boolean;
  423. break;
  424. case BuiltinType::Half:
  425. case BuiltinType::Float:
  426. case BuiltinType::LongDouble:
  427. case BuiltinType::Double:
  428. Encoding = llvm::dwarf::DW_ATE_float;
  429. break;
  430. }
  431. switch (BT->getKind()) {
  432. case BuiltinType::Long:
  433. BTName = "long int";
  434. break;
  435. case BuiltinType::LongLong:
  436. BTName = "long long int";
  437. break;
  438. case BuiltinType::ULong:
  439. BTName = "long unsigned int";
  440. break;
  441. case BuiltinType::ULongLong:
  442. BTName = "long long unsigned int";
  443. break;
  444. default:
  445. BTName = BT->getName(CGM.getLangOpts());
  446. break;
  447. }
  448. // Bit size, align and offset of the type.
  449. uint64_t Size = CGM.getContext().getTypeSize(BT);
  450. uint64_t Align = CGM.getContext().getTypeAlign(BT);
  451. return DBuilder.createBasicType(BTName, Size, Align, Encoding);
  452. }
  453. llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
  454. // Bit size, align and offset of the type.
  455. llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
  456. if (Ty->isComplexIntegerType())
  457. Encoding = llvm::dwarf::DW_ATE_lo_user;
  458. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  459. uint64_t Align = CGM.getContext().getTypeAlign(Ty);
  460. return DBuilder.createBasicType("complex", Size, Align, Encoding);
  461. }
  462. llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
  463. llvm::DIFile *Unit) {
  464. QualifierCollector Qc;
  465. const Type *T = Qc.strip(Ty);
  466. // Ignore these qualifiers for now.
  467. Qc.removeObjCGCAttr();
  468. Qc.removeAddressSpace();
  469. Qc.removeObjCLifetime();
  470. // We will create one Derived type for one qualifier and recurse to handle any
  471. // additional ones.
  472. llvm::dwarf::Tag Tag;
  473. if (Qc.hasConst()) {
  474. Tag = llvm::dwarf::DW_TAG_const_type;
  475. Qc.removeConst();
  476. } else if (Qc.hasVolatile()) {
  477. Tag = llvm::dwarf::DW_TAG_volatile_type;
  478. Qc.removeVolatile();
  479. } else if (Qc.hasRestrict()) {
  480. Tag = llvm::dwarf::DW_TAG_restrict_type;
  481. Qc.removeRestrict();
  482. } else {
  483. assert(Qc.empty() && "Unknown type qualifier for debug info");
  484. return getOrCreateType(QualType(T, 0), Unit);
  485. }
  486. auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
  487. // No need to fill in the Name, Line, Size, Alignment, Offset in case of
  488. // CVR derived types.
  489. return DBuilder.createQualifiedType(Tag, FromTy);
  490. }
  491. #if 0 // HLSL Change - no ObjC support
  492. llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
  493. llvm::DIFile *Unit) {
  494. // The frontend treats 'id' as a typedef to an ObjCObjectType,
  495. // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
  496. // debug info, we want to emit 'id' in both cases.
  497. if (Ty->isObjCQualifiedIdType())
  498. return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
  499. return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
  500. Ty->getPointeeType(), Unit);
  501. }
  502. #endif // HLSL Change - no ObjC support
  503. llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
  504. llvm::DIFile *Unit) {
  505. return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
  506. Ty->getPointeeType(), Unit);
  507. }
  508. /// \return whether a C++ mangling exists for the type defined by TD.
  509. static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
  510. switch (TheCU->getSourceLanguage()) {
  511. case llvm::dwarf::DW_LANG_C_plus_plus:
  512. return true;
  513. case llvm::dwarf::DW_LANG_ObjC_plus_plus:
  514. return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
  515. default:
  516. return false;
  517. }
  518. }
  519. /// In C++ mode, types have linkage, so we can rely on the ODR and
  520. /// on their mangled names, if they're external.
  521. static SmallString<256> getUniqueTagTypeName(const TagType *Ty,
  522. CodeGenModule &CGM,
  523. llvm::DICompileUnit *TheCU) {
  524. SmallString<256> FullName;
  525. const TagDecl *TD = Ty->getDecl();
  526. if (!hasCXXMangling(TD, TheCU) || !TD->isExternallyVisible())
  527. return FullName;
  528. // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
  529. if (CGM.getTarget().getCXXABI().isMicrosoft())
  530. return FullName;
  531. // TODO: This is using the RTTI name. Is there a better way to get
  532. // a unique string for a type?
  533. llvm::raw_svector_ostream Out(FullName);
  534. CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
  535. Out.flush();
  536. return FullName;
  537. }
  538. /// \return the approproate DWARF tag for a composite type.
  539. static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
  540. llvm::dwarf::Tag Tag;
  541. if (RD->isStruct() || RD->isInterface())
  542. Tag = llvm::dwarf::DW_TAG_structure_type;
  543. else if (RD->isUnion())
  544. Tag = llvm::dwarf::DW_TAG_union_type;
  545. else {
  546. // FIXME: This could be a struct type giving a default visibility different
  547. // than C++ class type, but needs llvm metadata changes first.
  548. assert(RD->isClass());
  549. Tag = llvm::dwarf::DW_TAG_class_type;
  550. }
  551. return Tag;
  552. }
  553. llvm::DICompositeType *
  554. CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
  555. llvm::DIScope *Ctx) {
  556. const RecordDecl *RD = Ty->getDecl();
  557. if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
  558. return cast<llvm::DICompositeType>(T);
  559. llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
  560. unsigned Line = getLineNumber(RD->getLocation());
  561. StringRef RDName = getClassName(RD);
  562. uint64_t Size = 0;
  563. uint64_t Align = 0;
  564. const RecordDecl *D = RD->getDefinition();
  565. if (D && D->isCompleteDefinition()) {
  566. Size = CGM.getContext().getTypeSize(Ty);
  567. Align = CGM.getContext().getTypeAlign(Ty);
  568. }
  569. // Create the type.
  570. SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
  571. llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
  572. getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align,
  573. llvm::DINode::FlagFwdDecl, FullName);
  574. ReplaceMap.emplace_back(
  575. std::piecewise_construct, std::make_tuple(Ty),
  576. std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
  577. return RetTy;
  578. }
  579. llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
  580. const Type *Ty,
  581. QualType PointeeTy,
  582. llvm::DIFile *Unit) {
  583. if (Tag == llvm::dwarf::DW_TAG_reference_type ||
  584. Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
  585. return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
  586. // Bit size, align and offset of the type.
  587. // Size is always the size of a pointer. We can't use getTypeSize here
  588. // because that does not return the correct value for references.
  589. unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
  590. uint64_t Size = CGM.getTarget().getPointerWidth(AS);
  591. uint64_t Align = CGM.getContext().getTypeAlign(Ty);
  592. return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
  593. Align);
  594. }
  595. llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
  596. llvm::DIType *&Cache) {
  597. if (Cache)
  598. return Cache;
  599. Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
  600. TheCU, getOrCreateMainFile(), 0);
  601. unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
  602. Cache = DBuilder.createPointerType(Cache, Size);
  603. return Cache;
  604. }
  605. #if 0 // HLSL Change - no block support
  606. llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
  607. llvm::DIFile *Unit) {
  608. SmallVector<llvm::Metadata *, 8> EltTys;
  609. QualType FType;
  610. uint64_t FieldSize, FieldOffset;
  611. unsigned FieldAlign;
  612. llvm::DINodeArray Elements;
  613. FieldOffset = 0;
  614. FType = CGM.getContext().UnsignedLongTy;
  615. EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
  616. EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
  617. Elements = DBuilder.getOrCreateArray(EltTys);
  618. EltTys.clear();
  619. unsigned Flags = llvm::DINode::FlagAppleBlock;
  620. unsigned LineNo = 0;
  621. auto *EltTy =
  622. DBuilder.createStructType(Unit, "__block_descriptor", nullptr, LineNo,
  623. FieldOffset, 0, Flags, nullptr, Elements);
  624. // Bit size, align and offset of the type.
  625. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  626. auto *DescTy = DBuilder.createPointerType(EltTy, Size);
  627. FieldOffset = 0;
  628. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  629. EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
  630. FType = CGM.getContext().IntTy;
  631. EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
  632. EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
  633. FType = CGM.getContext().getPointerType(Ty->getPointeeType());
  634. EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
  635. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  636. FieldSize = CGM.getContext().getTypeSize(Ty);
  637. FieldAlign = CGM.getContext().getTypeAlign(Ty);
  638. EltTys.push_back(DBuilder.createMemberType(Unit, "__descriptor", nullptr, LineNo,
  639. FieldSize, FieldAlign, FieldOffset,
  640. 0, DescTy));
  641. FieldOffset += FieldSize;
  642. Elements = DBuilder.getOrCreateArray(EltTys);
  643. // The __block_literal_generic structs are marked with a special
  644. // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
  645. // the debugger needs to know about. To allow type uniquing, emit
  646. // them without a name or a location.
  647. EltTy =
  648. DBuilder.createStructType(Unit, "", nullptr, LineNo,
  649. FieldOffset, 0, Flags, nullptr, Elements);
  650. return DBuilder.createPointerType(EltTy, Size);
  651. }
  652. #endif // HLSL Change - no block support
  653. llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
  654. llvm::DIFile *Unit) {
  655. assert(Ty->isTypeAlias());
  656. llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
  657. SmallString<128> NS;
  658. llvm::raw_svector_ostream OS(NS);
  659. Ty->getTemplateName().print(OS, CGM.getContext().getPrintingPolicy(),
  660. /*qualified*/ false);
  661. TemplateSpecializationType::PrintTemplateArgumentList(
  662. OS, Ty->getArgs(), Ty->getNumArgs(),
  663. CGM.getContext().getPrintingPolicy());
  664. TypeAliasDecl *AliasDecl = cast<TypeAliasTemplateDecl>(
  665. Ty->getTemplateName().getAsTemplateDecl())->getTemplatedDecl();
  666. SourceLocation Loc = AliasDecl->getLocation();
  667. return DBuilder.createTypedef(
  668. Src, internString(OS.str()), getOrCreateFile(Loc), getLineNumber(Loc),
  669. getContextDescriptor(cast<Decl>(AliasDecl->getDeclContext())));
  670. }
  671. llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
  672. llvm::DIFile *Unit) {
  673. // We don't set size information, but do specify where the typedef was
  674. // declared.
  675. SourceLocation Loc = Ty->getDecl()->getLocation();
  676. // Typedefs are derived from some other type.
  677. return DBuilder.createTypedef(
  678. getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
  679. Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
  680. getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext())));
  681. }
  682. llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
  683. llvm::DIFile *Unit) {
  684. SmallVector<llvm::Metadata *, 16> EltTys;
  685. // Add the result type at least.
  686. EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
  687. // Set up remainder of arguments if there is a prototype.
  688. // otherwise emit it as a variadic function.
  689. if (isa<FunctionNoProtoType>(Ty))
  690. EltTys.push_back(DBuilder.createUnspecifiedParameter());
  691. else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
  692. for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
  693. EltTys.push_back(getOrCreateType(FPT->getParamType(i), Unit));
  694. if (FPT->isVariadic())
  695. EltTys.push_back(DBuilder.createUnspecifiedParameter());
  696. }
  697. llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
  698. return DBuilder.createSubroutineType(Unit, EltTypeArray);
  699. }
  700. /// Convert an AccessSpecifier into the corresponding DINode flag.
  701. /// As an optimization, return 0 if the access specifier equals the
  702. /// default for the containing type.
  703. static unsigned getAccessFlag(AccessSpecifier Access, const RecordDecl *RD) {
  704. AccessSpecifier Default = clang::AS_none;
  705. if (RD && RD->isClass())
  706. Default = clang::AS_private;
  707. else if (RD && (RD->isStruct() || RD->isUnion()))
  708. Default = clang::AS_public;
  709. if (Access == Default)
  710. return 0;
  711. switch (Access) {
  712. case clang::AS_private:
  713. return llvm::DINode::FlagPrivate;
  714. case clang::AS_protected:
  715. return llvm::DINode::FlagProtected;
  716. case clang::AS_public:
  717. return llvm::DINode::FlagPublic;
  718. case clang::AS_none:
  719. return 0;
  720. }
  721. llvm_unreachable("unexpected access enumerator");
  722. }
  723. llvm::DIType *CGDebugInfo::createFieldType(
  724. StringRef name, QualType type, uint64_t sizeInBitsOverride,
  725. SourceLocation loc, AccessSpecifier AS, uint64_t offsetInBits,
  726. llvm::DIFile *tunit, llvm::DIScope *scope, const RecordDecl *RD) {
  727. llvm::DIType *debugType = getOrCreateType(type, tunit);
  728. // Get the location for the field.
  729. llvm::DIFile *file = getOrCreateFile(loc);
  730. unsigned line = getLineNumber(loc);
  731. uint64_t SizeInBits = 0;
  732. unsigned AlignInBits = 0;
  733. if (!type->isIncompleteArrayType()) {
  734. TypeInfo TI = CGM.getContext().getTypeInfo(type);
  735. SizeInBits = TI.Width;
  736. AlignInBits = TI.Align;
  737. if (sizeInBitsOverride)
  738. SizeInBits = sizeInBitsOverride;
  739. }
  740. unsigned flags = getAccessFlag(AS, RD);
  741. return DBuilder.createMemberType(scope, name, file, line, SizeInBits,
  742. AlignInBits, offsetInBits, flags, debugType);
  743. }
  744. void CGDebugInfo::CollectRecordLambdaFields(
  745. const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
  746. llvm::DIType *RecordTy) {
  747. // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
  748. // has the name and the location of the variable so we should iterate over
  749. // both concurrently.
  750. const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
  751. RecordDecl::field_iterator Field = CXXDecl->field_begin();
  752. unsigned fieldno = 0;
  753. for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
  754. E = CXXDecl->captures_end();
  755. I != E; ++I, ++Field, ++fieldno) {
  756. const LambdaCapture &C = *I;
  757. if (C.capturesVariable()) {
  758. VarDecl *V = C.getCapturedVar();
  759. llvm::DIFile *VUnit = getOrCreateFile(C.getLocation());
  760. StringRef VName = V->getName();
  761. uint64_t SizeInBitsOverride = 0;
  762. if (Field->isBitField()) {
  763. SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
  764. assert(SizeInBitsOverride && "found named 0-width bitfield");
  765. }
  766. llvm::DIType *fieldType = createFieldType(
  767. VName, Field->getType(), SizeInBitsOverride, C.getLocation(),
  768. Field->getAccess(), layout.getFieldOffset(fieldno), VUnit, RecordTy,
  769. CXXDecl);
  770. elements.push_back(fieldType);
  771. } else if (C.capturesThis()) {
  772. // TODO: Need to handle 'this' in some way by probably renaming the
  773. // this of the lambda class and having a field member of 'this' or
  774. // by using AT_object_pointer for the function and having that be
  775. // used as 'this' for semantic references.
  776. FieldDecl *f = *Field;
  777. llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
  778. QualType type = f->getType();
  779. llvm::DIType *fieldType = createFieldType(
  780. "this", type, 0, f->getLocation(), f->getAccess(),
  781. layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
  782. elements.push_back(fieldType);
  783. }
  784. }
  785. }
  786. llvm::DIDerivedType *
  787. CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
  788. const RecordDecl *RD) {
  789. // Create the descriptor for the static variable, with or without
  790. // constant initializers.
  791. Var = Var->getCanonicalDecl();
  792. llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
  793. llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
  794. unsigned LineNumber = getLineNumber(Var->getLocation());
  795. StringRef VName = Var->getName();
  796. llvm::Constant *C = nullptr;
  797. if (Var->getInit()) {
  798. const APValue *Value = Var->evaluateValue();
  799. if (Value) {
  800. if (Value->isInt())
  801. C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
  802. if (Value->isFloat())
  803. C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
  804. }
  805. }
  806. unsigned Flags = getAccessFlag(Var->getAccess(), RD);
  807. llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
  808. RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
  809. StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
  810. return GV;
  811. }
  812. void CGDebugInfo::CollectRecordNormalField(
  813. const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
  814. SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
  815. const RecordDecl *RD) {
  816. StringRef name = field->getName();
  817. QualType type = field->getType();
  818. // Ignore unnamed fields unless they're anonymous structs/unions.
  819. if (name.empty() && !type->isRecordType())
  820. return;
  821. uint64_t SizeInBitsOverride = 0;
  822. if (field->isBitField()) {
  823. SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
  824. assert(SizeInBitsOverride && "found named 0-width bitfield");
  825. }
  826. llvm::DIType *fieldType =
  827. createFieldType(name, type, SizeInBitsOverride, field->getLocation(),
  828. field->getAccess(), OffsetInBits, tunit, RecordTy, RD);
  829. elements.push_back(fieldType);
  830. }
  831. void CGDebugInfo::CollectRecordFields(
  832. const RecordDecl *record, llvm::DIFile *tunit,
  833. SmallVectorImpl<llvm::Metadata *> &elements,
  834. llvm::DICompositeType *RecordTy) {
  835. const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
  836. if (CXXDecl && CXXDecl->isLambda())
  837. CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
  838. else {
  839. const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
  840. // Field number for non-static fields.
  841. unsigned fieldNo = 0;
  842. // Static and non-static members should appear in the same order as
  843. // the corresponding declarations in the source program.
  844. for (const auto *I : record->decls())
  845. if (const auto *V = dyn_cast<VarDecl>(I)) {
  846. // Reuse the existing static member declaration if one exists
  847. auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
  848. if (MI != StaticDataMemberCache.end()) {
  849. assert(MI->second &&
  850. "Static data member declaration should still exist");
  851. elements.push_back(cast<llvm::DIDerivedTypeBase>(MI->second));
  852. } else {
  853. auto Field = CreateRecordStaticField(V, RecordTy, record);
  854. elements.push_back(Field);
  855. }
  856. } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
  857. CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
  858. elements, RecordTy, record);
  859. // Bump field number for next field.
  860. ++fieldNo;
  861. }
  862. }
  863. }
  864. llvm::DISubroutineType *
  865. CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
  866. llvm::DIFile *Unit) {
  867. const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
  868. if (Method->isStatic())
  869. return cast_or_null<llvm::DISubroutineType>(
  870. getOrCreateType(QualType(Func, 0), Unit));
  871. return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
  872. Func, Unit);
  873. }
  874. llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
  875. QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
  876. // Add "this" pointer.
  877. llvm::DITypeRefArray Args(
  878. cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
  879. ->getTypeArray());
  880. assert(Args.size() && "Invalid number of arguments!");
  881. SmallVector<llvm::Metadata *, 16> Elts;
  882. // First element is always return type. For 'void' functions it is NULL.
  883. Elts.push_back(Args[0]);
  884. // "this" pointer is always first argument.
  885. const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
  886. if (isa<ClassTemplateSpecializationDecl>(RD)) {
  887. // Create pointer type directly in this case.
  888. const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
  889. QualType PointeeTy = ThisPtrTy->getPointeeType();
  890. unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
  891. uint64_t Size = CGM.getTarget().getPointerWidth(AS);
  892. uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
  893. llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
  894. llvm::DIType *ThisPtrType =
  895. DBuilder.createPointerType(PointeeType, Size, Align);
  896. TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
  897. // TODO: This and the artificial type below are misleading, the
  898. // types aren't artificial the argument is, but the current
  899. // metadata doesn't represent that.
  900. ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
  901. Elts.push_back(ThisPtrType);
  902. } else {
  903. llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
  904. TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
  905. ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
  906. Elts.push_back(ThisPtrType);
  907. }
  908. // Copy rest of the arguments.
  909. for (unsigned i = 1, e = Args.size(); i != e; ++i)
  910. Elts.push_back(Args[i]);
  911. llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
  912. unsigned Flags = 0;
  913. if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
  914. Flags |= llvm::DINode::FlagLValueReference;
  915. if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
  916. Flags |= llvm::DINode::FlagRValueReference;
  917. return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags);
  918. }
  919. /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
  920. /// inside a function.
  921. static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
  922. if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
  923. return isFunctionLocalClass(NRD);
  924. if (isa<FunctionDecl>(RD->getDeclContext()))
  925. return true;
  926. return false;
  927. }
  928. llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
  929. const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
  930. bool IsCtorOrDtor =
  931. isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
  932. StringRef MethodName = getFunctionName(Method);
  933. llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
  934. // Since a single ctor/dtor corresponds to multiple functions, it doesn't
  935. // make sense to give a single ctor/dtor a linkage name.
  936. StringRef MethodLinkageName;
  937. if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
  938. MethodLinkageName = CGM.getMangledName(Method);
  939. // Get the location for the method.
  940. llvm::DIFile *MethodDefUnit = nullptr;
  941. unsigned MethodLine = 0;
  942. if (!Method->isImplicit()) {
  943. MethodDefUnit = getOrCreateFile(Method->getLocation());
  944. MethodLine = getLineNumber(Method->getLocation());
  945. }
  946. // Collect virtual method info.
  947. llvm::DIType *ContainingType = nullptr;
  948. unsigned Virtuality = 0;
  949. unsigned VIndex = 0;
  950. if (Method->isVirtual()) {
  951. if (Method->isPure())
  952. Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
  953. else
  954. Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
  955. // It doesn't make sense to give a virtual destructor a vtable index,
  956. // since a single destructor has two entries in the vtable.
  957. // FIXME: Add proper support for debug info for virtual calls in
  958. // the Microsoft ABI, where we may use multiple vptrs to make a vftable
  959. // lookup if we have multiple or virtual inheritance.
  960. if (!isa<CXXDestructorDecl>(Method) &&
  961. !CGM.getTarget().getCXXABI().isMicrosoft())
  962. VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
  963. ContainingType = RecordTy;
  964. }
  965. unsigned Flags = 0;
  966. if (Method->isImplicit())
  967. Flags |= llvm::DINode::FlagArtificial;
  968. Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
  969. if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
  970. if (CXXC->isExplicit())
  971. Flags |= llvm::DINode::FlagExplicit;
  972. } else if (const CXXConversionDecl *CXXC =
  973. dyn_cast<CXXConversionDecl>(Method)) {
  974. if (CXXC->isExplicit())
  975. Flags |= llvm::DINode::FlagExplicit;
  976. }
  977. if (Method->hasPrototype())
  978. Flags |= llvm::DINode::FlagPrototyped;
  979. if (Method->getRefQualifier() == RQ_LValue)
  980. Flags |= llvm::DINode::FlagLValueReference;
  981. if (Method->getRefQualifier() == RQ_RValue)
  982. Flags |= llvm::DINode::FlagRValueReference;
  983. llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
  984. llvm::DISubprogram *SP = DBuilder.createMethod(
  985. RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
  986. MethodTy, /*isLocalToUnit=*/false,
  987. /* isDefinition=*/false, Virtuality, VIndex, ContainingType, Flags,
  988. CGM.getLangOpts().Optimize, nullptr, TParamsArray.get());
  989. SPCache[Method->getCanonicalDecl()].reset(SP);
  990. return SP;
  991. }
  992. void CGDebugInfo::CollectCXXMemberFunctions(
  993. const CXXRecordDecl *RD, llvm::DIFile *Unit,
  994. SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
  995. // Since we want more than just the individual member decls if we
  996. // have templated functions iterate over every declaration to gather
  997. // the functions.
  998. for (const auto *I : RD->decls()) {
  999. const auto *Method = dyn_cast<CXXMethodDecl>(I);
  1000. // If the member is implicit, don't add it to the member list. This avoids
  1001. // the member being added to type units by LLVM, while still allowing it
  1002. // to be emitted into the type declaration/reference inside the compile
  1003. // unit.
  1004. // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
  1005. // FIXME: Handle Using(Shadow?)Decls here to create
  1006. // DW_TAG_imported_declarations inside the class for base decls brought into
  1007. // derived classes. GDB doesn't seem to notice/leverage these when I tried
  1008. // it, so I'm not rushing to fix this. (GCC seems to produce them, if
  1009. // referenced)
  1010. if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
  1011. continue;
  1012. if (Method->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
  1013. continue;
  1014. // Reuse the existing member function declaration if it exists.
  1015. // It may be associated with the declaration of the type & should be
  1016. // reused as we're building the definition.
  1017. //
  1018. // This situation can arise in the vtable-based debug info reduction where
  1019. // implicit members are emitted in a non-vtable TU.
  1020. auto MI = SPCache.find(Method->getCanonicalDecl());
  1021. EltTys.push_back(MI == SPCache.end()
  1022. ? CreateCXXMemberFunction(Method, Unit, RecordTy)
  1023. : static_cast<llvm::Metadata *>(MI->second));
  1024. }
  1025. }
  1026. void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
  1027. SmallVectorImpl<llvm::Metadata *> &EltTys,
  1028. llvm::DIType *RecordTy) {
  1029. const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
  1030. for (const auto &BI : RD->bases()) {
  1031. unsigned BFlags = 0;
  1032. uint64_t BaseOffset;
  1033. const CXXRecordDecl *Base =
  1034. cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl());
  1035. if (BI.isVirtual()) {
  1036. if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
  1037. // virtual base offset offset is -ve. The code generator emits dwarf
  1038. // expression where it expects +ve number.
  1039. BaseOffset = 0 - CGM.getItaniumVTableContext()
  1040. .getVirtualBaseOffsetOffset(RD, Base)
  1041. .getQuantity();
  1042. } else {
  1043. // In the MS ABI, store the vbtable offset, which is analogous to the
  1044. // vbase offset offset in Itanium.
  1045. BaseOffset =
  1046. 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
  1047. }
  1048. BFlags = llvm::DINode::FlagVirtual;
  1049. } else
  1050. BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
  1051. // FIXME: Inconsistent units for BaseOffset. It is in bytes when
  1052. // BI->isVirtual() and bits when not.
  1053. BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
  1054. llvm::DIType *DTy = DBuilder.createInheritance(
  1055. RecordTy, getOrCreateType(BI.getType(), Unit), BaseOffset, BFlags);
  1056. EltTys.push_back(DTy);
  1057. }
  1058. }
  1059. llvm::DINodeArray
  1060. CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
  1061. ArrayRef<TemplateArgument> TAList,
  1062. llvm::DIFile *Unit) {
  1063. SmallVector<llvm::Metadata *, 16> TemplateParams;
  1064. for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
  1065. const TemplateArgument &TA = TAList[i];
  1066. StringRef Name;
  1067. if (TPList)
  1068. Name = TPList->getParam(i)->getName();
  1069. switch (TA.getKind()) {
  1070. case TemplateArgument::Type: {
  1071. llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
  1072. TemplateParams.push_back(
  1073. DBuilder.createTemplateTypeParameter(TheCU, Name, TTy));
  1074. } break;
  1075. case TemplateArgument::Integral: {
  1076. llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
  1077. TemplateParams.push_back(DBuilder.createTemplateValueParameter(
  1078. TheCU, Name, TTy,
  1079. llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
  1080. } break;
  1081. case TemplateArgument::Declaration: {
  1082. const ValueDecl *D = TA.getAsDecl();
  1083. QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
  1084. llvm::DIType *TTy = getOrCreateType(T, Unit);
  1085. llvm::Constant *V = nullptr;
  1086. const CXXMethodDecl *MD;
  1087. // Variable pointer template parameters have a value that is the address
  1088. // of the variable.
  1089. if (const auto *VD = dyn_cast<VarDecl>(D))
  1090. V = CGM.GetAddrOfGlobalVar(VD);
  1091. // Member function pointers have special support for building them, though
  1092. // this is currently unsupported in LLVM CodeGen.
  1093. else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
  1094. V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
  1095. else if (const auto *FD = dyn_cast<FunctionDecl>(D))
  1096. V = CGM.GetAddrOfFunction(FD);
  1097. // Member data pointers have special handling too to compute the fixed
  1098. // offset within the object.
  1099. else if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr())) {
  1100. // These five lines (& possibly the above member function pointer
  1101. // handling) might be able to be refactored to use similar code in
  1102. // CodeGenModule::getMemberPointerConstant
  1103. uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
  1104. CharUnits chars =
  1105. CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
  1106. V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
  1107. }
  1108. TemplateParams.push_back(DBuilder.createTemplateValueParameter(
  1109. TheCU, Name, TTy,
  1110. cast_or_null<llvm::Constant>(V->stripPointerCasts())));
  1111. } break;
  1112. case TemplateArgument::NullPtr: {
  1113. QualType T = TA.getNullPtrType();
  1114. llvm::DIType *TTy = getOrCreateType(T, Unit);
  1115. llvm::Constant *V = nullptr;
  1116. // Special case member data pointer null values since they're actually -1
  1117. // instead of zero.
  1118. if (const MemberPointerType *MPT =
  1119. dyn_cast<MemberPointerType>(T.getTypePtr()))
  1120. // But treat member function pointers as simple zero integers because
  1121. // it's easier than having a special case in LLVM's CodeGen. If LLVM
  1122. // CodeGen grows handling for values of non-null member function
  1123. // pointers then perhaps we could remove this special case and rely on
  1124. // EmitNullMemberPointer for member function pointers.
  1125. if (MPT->isMemberDataPointer())
  1126. V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
  1127. if (!V)
  1128. V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
  1129. TemplateParams.push_back(DBuilder.createTemplateValueParameter(
  1130. TheCU, Name, TTy, cast<llvm::Constant>(V)));
  1131. } break;
  1132. case TemplateArgument::Template:
  1133. TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
  1134. TheCU, Name, nullptr,
  1135. TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
  1136. break;
  1137. case TemplateArgument::Pack:
  1138. TemplateParams.push_back(DBuilder.createTemplateParameterPack(
  1139. TheCU, Name, nullptr,
  1140. CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
  1141. break;
  1142. case TemplateArgument::Expression: {
  1143. const Expr *E = TA.getAsExpr();
  1144. QualType T = E->getType();
  1145. if (E->isGLValue())
  1146. T = CGM.getContext().getLValueReferenceType(T);
  1147. llvm::Constant *V = CGM.EmitConstantExpr(E, T);
  1148. assert(V && "Expression in template argument isn't constant");
  1149. llvm::DIType *TTy = getOrCreateType(T, Unit);
  1150. TemplateParams.push_back(DBuilder.createTemplateValueParameter(
  1151. TheCU, Name, TTy, cast<llvm::Constant>(V->stripPointerCasts())));
  1152. } break;
  1153. // And the following should never occur:
  1154. case TemplateArgument::TemplateExpansion:
  1155. case TemplateArgument::Null:
  1156. llvm_unreachable(
  1157. "These argument types shouldn't exist in concrete types");
  1158. }
  1159. }
  1160. return DBuilder.getOrCreateArray(TemplateParams);
  1161. }
  1162. llvm::DINodeArray
  1163. CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
  1164. llvm::DIFile *Unit) {
  1165. if (FD->getTemplatedKind() ==
  1166. FunctionDecl::TK_FunctionTemplateSpecialization) {
  1167. const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
  1168. ->getTemplate()
  1169. ->getTemplateParameters();
  1170. return CollectTemplateParams(
  1171. TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
  1172. }
  1173. return llvm::DINodeArray();
  1174. }
  1175. llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
  1176. const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
  1177. // Always get the full list of parameters, not just the ones from
  1178. // the specialization.
  1179. TemplateParameterList *TPList =
  1180. TSpecial->getSpecializedTemplate()->getTemplateParameters();
  1181. const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
  1182. return CollectTemplateParams(TPList, TAList.asArray(), Unit);
  1183. }
  1184. llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
  1185. if (VTablePtrType)
  1186. return VTablePtrType;
  1187. ASTContext &Context = CGM.getContext();
  1188. /* Function type */
  1189. llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
  1190. llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
  1191. llvm::DIType *SubTy = DBuilder.createSubroutineType(Unit, SElements);
  1192. unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
  1193. llvm::DIType *vtbl_ptr_type =
  1194. DBuilder.createPointerType(SubTy, Size, 0, "__vtbl_ptr_type");
  1195. VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
  1196. return VTablePtrType;
  1197. }
  1198. StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
  1199. // Copy the gdb compatible name on the side and use its reference.
  1200. return internString("_vptr$", RD->getNameAsString());
  1201. }
  1202. void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
  1203. SmallVectorImpl<llvm::Metadata *> &EltTys) {
  1204. const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
  1205. // If there is a primary base then it will hold vtable info.
  1206. if (RL.getPrimaryBase())
  1207. return;
  1208. // If this class is not dynamic then there is not any vtable info to collect.
  1209. if (!RD->isDynamicClass())
  1210. return;
  1211. unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
  1212. llvm::DIType *VPTR = DBuilder.createMemberType(
  1213. Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
  1214. llvm::DINode::FlagArtificial, getOrCreateVTablePtrType(Unit));
  1215. EltTys.push_back(VPTR);
  1216. }
  1217. llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
  1218. SourceLocation Loc) {
  1219. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  1220. llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
  1221. return T;
  1222. }
  1223. llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
  1224. SourceLocation Loc) {
  1225. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  1226. llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
  1227. RetainedTypes.push_back(D.getAsOpaquePtr());
  1228. return T;
  1229. }
  1230. void CGDebugInfo::completeType(const EnumDecl *ED) {
  1231. if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  1232. return;
  1233. QualType Ty = CGM.getContext().getEnumType(ED);
  1234. void *TyPtr = Ty.getAsOpaquePtr();
  1235. auto I = TypeCache.find(TyPtr);
  1236. if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
  1237. return;
  1238. llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
  1239. assert(!Res->isForwardDecl());
  1240. TypeCache[TyPtr].reset(Res);
  1241. }
  1242. void CGDebugInfo::completeType(const RecordDecl *RD) {
  1243. if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
  1244. !CGM.getLangOpts().CPlusPlus)
  1245. completeRequiredType(RD);
  1246. }
  1247. void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
  1248. if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  1249. return;
  1250. if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
  1251. if (CXXDecl->isDynamicClass())
  1252. return;
  1253. QualType Ty = CGM.getContext().getRecordType(RD);
  1254. llvm::DIType *T = getTypeOrNull(Ty);
  1255. if (T && T->isForwardDecl())
  1256. completeClassData(RD);
  1257. }
  1258. void CGDebugInfo::completeClassData(const RecordDecl *RD) {
  1259. if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  1260. return;
  1261. QualType Ty = CGM.getContext().getRecordType(RD);
  1262. void *TyPtr = Ty.getAsOpaquePtr();
  1263. auto I = TypeCache.find(TyPtr);
  1264. if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
  1265. return;
  1266. llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
  1267. assert(!Res->isForwardDecl());
  1268. TypeCache[TyPtr].reset(Res);
  1269. }
  1270. static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
  1271. CXXRecordDecl::method_iterator End) {
  1272. for (; I != End; ++I)
  1273. if (FunctionDecl *Tmpl = I->getInstantiatedFromMemberFunction())
  1274. if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
  1275. !I->getMemberSpecializationInfo()->isExplicitSpecialization())
  1276. return true;
  1277. return false;
  1278. }
  1279. static bool shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind,
  1280. const RecordDecl *RD,
  1281. const LangOptions &LangOpts) {
  1282. if (DebugKind > CodeGenOptions::LimitedDebugInfo)
  1283. return false;
  1284. if (!LangOpts.CPlusPlus)
  1285. return false;
  1286. if (!RD->isCompleteDefinitionRequired())
  1287. return true;
  1288. const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
  1289. if (!CXXDecl)
  1290. return false;
  1291. if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())
  1292. return true;
  1293. TemplateSpecializationKind Spec = TSK_Undeclared;
  1294. if (const ClassTemplateSpecializationDecl *SD =
  1295. dyn_cast<ClassTemplateSpecializationDecl>(RD))
  1296. Spec = SD->getSpecializationKind();
  1297. if (Spec == TSK_ExplicitInstantiationDeclaration &&
  1298. hasExplicitMemberDefinition(CXXDecl->method_begin(),
  1299. CXXDecl->method_end()))
  1300. return true;
  1301. return false;
  1302. }
  1303. llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
  1304. RecordDecl *RD = Ty->getDecl();
  1305. llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
  1306. if (T || shouldOmitDefinition(DebugKind, RD, CGM.getLangOpts())) {
  1307. if (!T)
  1308. T = getOrCreateRecordFwdDecl(
  1309. Ty, getContextDescriptor(cast<Decl>(RD->getDeclContext())));
  1310. return T;
  1311. }
  1312. return CreateTypeDefinition(Ty);
  1313. }
  1314. llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
  1315. RecordDecl *RD = Ty->getDecl();
  1316. // Get overall information about the record type for the debug info.
  1317. llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
  1318. // Records and classes and unions can all be recursive. To handle them, we
  1319. // first generate a debug descriptor for the struct as a forward declaration.
  1320. // Then (if it is a definition) we go through and get debug info for all of
  1321. // its members. Finally, we create a descriptor for the complete type (which
  1322. // may refer to the forward decl if the struct is recursive) and replace all
  1323. // uses of the forward declaration with the final definition.
  1324. auto *FwdDecl =
  1325. cast<llvm::DICompositeType>(getOrCreateLimitedType(Ty, DefUnit));
  1326. const RecordDecl *D = RD->getDefinition();
  1327. if (!D || !D->isCompleteDefinition())
  1328. return FwdDecl;
  1329. if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
  1330. CollectContainingType(CXXDecl, FwdDecl);
  1331. // Push the struct on region stack.
  1332. LexicalBlockStack.emplace_back(&*FwdDecl);
  1333. RegionMap[Ty->getDecl()].reset(FwdDecl);
  1334. // Convert all the elements.
  1335. SmallVector<llvm::Metadata *, 16> EltTys;
  1336. // what about nested types?
  1337. // Note: The split of CXXDecl information here is intentional, the
  1338. // gdb tests will depend on a certain ordering at printout. The debug
  1339. // information offsets are still correct if we merge them all together
  1340. // though.
  1341. const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
  1342. if (CXXDecl) {
  1343. CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
  1344. CollectVTableInfo(CXXDecl, DefUnit, EltTys);
  1345. }
  1346. // Collect data fields (including static variables and any initializers).
  1347. CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
  1348. if (CXXDecl)
  1349. CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
  1350. LexicalBlockStack.pop_back();
  1351. RegionMap.erase(Ty->getDecl());
  1352. llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
  1353. DBuilder.replaceArrays(FwdDecl, Elements);
  1354. if (FwdDecl->isTemporary())
  1355. FwdDecl =
  1356. llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
  1357. RegionMap[Ty->getDecl()].reset(FwdDecl);
  1358. return FwdDecl;
  1359. }
  1360. #if 0 // HLSL Change - no ObjC support
  1361. llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
  1362. llvm::DIFile *Unit) {
  1363. // Ignore protocols.
  1364. return getOrCreateType(Ty->getBaseType(), Unit);
  1365. }
  1366. /// \return true if Getter has the default name for the property PD.
  1367. static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
  1368. const ObjCMethodDecl *Getter) {
  1369. assert(PD);
  1370. if (!Getter)
  1371. return true;
  1372. assert(Getter->getDeclName().isObjCZeroArgSelector());
  1373. return PD->getName() ==
  1374. Getter->getDeclName().getObjCSelector().getNameForSlot(0);
  1375. }
  1376. /// \return true if Setter has the default name for the property PD.
  1377. static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
  1378. const ObjCMethodDecl *Setter) {
  1379. assert(PD);
  1380. if (!Setter)
  1381. return true;
  1382. assert(Setter->getDeclName().isObjCOneArgSelector());
  1383. return SelectorTable::constructSetterName(PD->getName()) ==
  1384. Setter->getDeclName().getObjCSelector().getNameForSlot(0);
  1385. }
  1386. llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
  1387. llvm::DIFile *Unit) {
  1388. ObjCInterfaceDecl *ID = Ty->getDecl();
  1389. if (!ID)
  1390. return nullptr;
  1391. // Get overall information about the record type for the debug info.
  1392. llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
  1393. unsigned Line = getLineNumber(ID->getLocation());
  1394. auto RuntimeLang =
  1395. static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
  1396. // If this is just a forward declaration return a special forward-declaration
  1397. // debug type since we won't be able to lay out the entire type.
  1398. ObjCInterfaceDecl *Def = ID->getDefinition();
  1399. if (!Def || !Def->getImplementation()) {
  1400. llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
  1401. llvm::dwarf::DW_TAG_structure_type, ID->getName(), TheCU, DefUnit, Line,
  1402. RuntimeLang);
  1403. ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
  1404. return FwdDecl;
  1405. }
  1406. return CreateTypeDefinition(Ty, Unit);
  1407. }
  1408. #endif // HLSL Change - no ObjC support
  1409. llvm::DIModule *
  1410. CGDebugInfo::getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod) {
  1411. auto it = ModuleRefCache.find(Mod.Signature);
  1412. if (it != ModuleRefCache.end())
  1413. return it->second;
  1414. // Macro definitions that were defined with "-D" on the command line.
  1415. SmallString<128> ConfigMacros;
  1416. {
  1417. llvm::raw_svector_ostream OS(ConfigMacros);
  1418. const auto &PPOpts = CGM.getPreprocessorOpts();
  1419. unsigned I = 0;
  1420. // Translate the macro definitions back into a commmand line.
  1421. for (auto &M : PPOpts.Macros) {
  1422. if (++I > 1)
  1423. OS << " ";
  1424. const std::string &Macro = M.first;
  1425. bool Undef = M.second;
  1426. OS << "\"-" << (Undef ? 'U' : 'D');
  1427. for (char c : Macro)
  1428. switch (c) {
  1429. case '\\' : OS << "\\\\"; break;
  1430. case '"' : OS << "\\\""; break;
  1431. default: OS << c;
  1432. }
  1433. OS << '\"';
  1434. }
  1435. }
  1436. llvm::DIBuilder DIB(CGM.getModule());
  1437. auto *CU = DIB.createCompileUnit(
  1438. TheCU->getSourceLanguage(), internString(Mod.ModuleName),
  1439. internString(Mod.Path), TheCU->getProducer(), true, StringRef(), 0,
  1440. internString(Mod.ASTFile), llvm::DIBuilder::FullDebug, Mod.Signature);
  1441. llvm::DIModule *ModuleRef =
  1442. DIB.createModule(CU, Mod.ModuleName, ConfigMacros, internString(Mod.Path),
  1443. internString(CGM.getHeaderSearchOpts().Sysroot));
  1444. DIB.finalize();
  1445. ModuleRefCache.insert(std::make_pair(Mod.Signature, ModuleRef));
  1446. return ModuleRef;
  1447. }
  1448. #if 0 // HLSL Change - no ObjC support
  1449. llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
  1450. llvm::DIFile *Unit) {
  1451. ObjCInterfaceDecl *ID = Ty->getDecl();
  1452. llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
  1453. unsigned Line = getLineNumber(ID->getLocation());
  1454. unsigned RuntimeLang = TheCU->getSourceLanguage();
  1455. // Bit size, align and offset of the type.
  1456. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  1457. uint64_t Align = CGM.getContext().getTypeAlign(Ty);
  1458. unsigned Flags = 0;
  1459. if (ID->getImplementation())
  1460. Flags |= llvm::DINode::FlagObjcClassComplete;
  1461. llvm::DICompositeType *RealDecl = DBuilder.createStructType(
  1462. Unit, ID->getName(), DefUnit, Line, Size, Align, Flags, nullptr,
  1463. llvm::DINodeArray(), RuntimeLang);
  1464. QualType QTy(Ty, 0);
  1465. TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
  1466. // Push the struct on region stack.
  1467. LexicalBlockStack.emplace_back(RealDecl);
  1468. RegionMap[Ty->getDecl()].reset(RealDecl);
  1469. // Convert all the elements.
  1470. SmallVector<llvm::Metadata *, 16> EltTys;
  1471. ObjCInterfaceDecl *SClass = ID->getSuperClass();
  1472. if (SClass) {
  1473. llvm::DIType *SClassTy =
  1474. getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
  1475. if (!SClassTy)
  1476. return nullptr;
  1477. llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
  1478. EltTys.push_back(InhTag);
  1479. }
  1480. // Create entries for all of the properties.
  1481. for (const auto *PD : ID->properties()) {
  1482. SourceLocation Loc = PD->getLocation();
  1483. llvm::DIFile *PUnit = getOrCreateFile(Loc);
  1484. unsigned PLine = getLineNumber(Loc);
  1485. ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
  1486. ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
  1487. llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
  1488. PD->getName(), PUnit, PLine,
  1489. hasDefaultGetterName(PD, Getter) ? ""
  1490. : getSelectorName(PD->getGetterName()),
  1491. hasDefaultSetterName(PD, Setter) ? ""
  1492. : getSelectorName(PD->getSetterName()),
  1493. PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
  1494. EltTys.push_back(PropertyNode);
  1495. }
  1496. const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
  1497. unsigned FieldNo = 0;
  1498. for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
  1499. Field = Field->getNextIvar(), ++FieldNo) {
  1500. llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
  1501. if (!FieldTy)
  1502. return nullptr;
  1503. StringRef FieldName = Field->getName();
  1504. // Ignore unnamed fields.
  1505. if (FieldName.empty())
  1506. continue;
  1507. // Get the location for the field.
  1508. llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
  1509. unsigned FieldLine = getLineNumber(Field->getLocation());
  1510. QualType FType = Field->getType();
  1511. uint64_t FieldSize = 0;
  1512. unsigned FieldAlign = 0;
  1513. if (!FType->isIncompleteArrayType()) {
  1514. // Bit size, align and offset of the type.
  1515. FieldSize = Field->isBitField()
  1516. ? Field->getBitWidthValue(CGM.getContext())
  1517. : CGM.getContext().getTypeSize(FType);
  1518. FieldAlign = CGM.getContext().getTypeAlign(FType);
  1519. }
  1520. uint64_t FieldOffset;
  1521. if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
  1522. // We don't know the runtime offset of an ivar if we're using the
  1523. // non-fragile ABI. For bitfields, use the bit offset into the first
  1524. // byte of storage of the bitfield. For other fields, use zero.
  1525. if (Field->isBitField()) {
  1526. FieldOffset =
  1527. CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
  1528. FieldOffset %= CGM.getContext().getCharWidth();
  1529. } else {
  1530. FieldOffset = 0;
  1531. }
  1532. } else {
  1533. FieldOffset = RL.getFieldOffset(FieldNo);
  1534. }
  1535. unsigned Flags = 0;
  1536. if (Field->getAccessControl() == ObjCIvarDecl::Protected)
  1537. Flags = llvm::DINode::FlagProtected;
  1538. else if (Field->getAccessControl() == ObjCIvarDecl::Private)
  1539. Flags = llvm::DINode::FlagPrivate;
  1540. else if (Field->getAccessControl() == ObjCIvarDecl::Public)
  1541. Flags = llvm::DINode::FlagPublic;
  1542. llvm::MDNode *PropertyNode = nullptr;
  1543. if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
  1544. if (ObjCPropertyImplDecl *PImpD =
  1545. ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
  1546. if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
  1547. SourceLocation Loc = PD->getLocation();
  1548. llvm::DIFile *PUnit = getOrCreateFile(Loc);
  1549. unsigned PLine = getLineNumber(Loc);
  1550. ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
  1551. ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
  1552. PropertyNode = DBuilder.createObjCProperty(
  1553. PD->getName(), PUnit, PLine,
  1554. hasDefaultGetterName(PD, Getter) ? "" : getSelectorName(
  1555. PD->getGetterName()),
  1556. hasDefaultSetterName(PD, Setter) ? "" : getSelectorName(
  1557. PD->getSetterName()),
  1558. PD->getPropertyAttributes(),
  1559. getOrCreateType(PD->getType(), PUnit));
  1560. }
  1561. }
  1562. }
  1563. FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
  1564. FieldSize, FieldAlign, FieldOffset, Flags,
  1565. FieldTy, PropertyNode);
  1566. EltTys.push_back(FieldTy);
  1567. }
  1568. llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
  1569. DBuilder.replaceArrays(RealDecl, Elements);
  1570. LexicalBlockStack.pop_back();
  1571. return RealDecl;
  1572. }
  1573. #endif // HLSL Change - no ObjC support
  1574. llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
  1575. llvm::DIFile *Unit) {
  1576. llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
  1577. int64_t Count = Ty->getNumElements();
  1578. if (Count == 0)
  1579. // If number of elements are not known then this is an unbounded array.
  1580. // Use Count == -1 to express such arrays.
  1581. Count = -1;
  1582. llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(0, Count);
  1583. llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
  1584. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  1585. uint64_t Align = CGM.getContext().getTypeAlign(Ty);
  1586. return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
  1587. }
  1588. llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
  1589. uint64_t Size;
  1590. uint64_t Align;
  1591. // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
  1592. if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
  1593. Size = 0;
  1594. Align =
  1595. CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
  1596. } else if (Ty->isIncompleteArrayType()) {
  1597. Size = 0;
  1598. if (Ty->getElementType()->isIncompleteType())
  1599. Align = 0;
  1600. else
  1601. Align = CGM.getContext().getTypeAlign(Ty->getElementType());
  1602. } else if (Ty->isIncompleteType()) {
  1603. Size = 0;
  1604. Align = 0;
  1605. } else {
  1606. // Size and align of the whole array, not the element type.
  1607. Size = CGM.getContext().getTypeSize(Ty);
  1608. Align = CGM.getContext().getTypeAlign(Ty);
  1609. }
  1610. // Add the dimensions of the array. FIXME: This loses CV qualifiers from
  1611. // interior arrays, do we care? Why aren't nested arrays represented the
  1612. // obvious/recursive way?
  1613. SmallVector<llvm::Metadata *, 8> Subscripts;
  1614. QualType EltTy(Ty, 0);
  1615. while ((Ty = dyn_cast<ArrayType>(EltTy))) {
  1616. // If the number of elements is known, then count is that number. Otherwise,
  1617. // it's -1. This allows us to represent a subrange with an array of 0
  1618. // elements, like this:
  1619. //
  1620. // struct foo {
  1621. // int x[0];
  1622. // };
  1623. int64_t Count = -1; // Count == -1 is an unbounded array.
  1624. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
  1625. Count = CAT->getSize().getZExtValue();
  1626. // FIXME: Verify this is right for VLAs.
  1627. Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
  1628. EltTy = Ty->getElementType();
  1629. }
  1630. llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
  1631. return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
  1632. SubscriptArray);
  1633. }
  1634. llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
  1635. llvm::DIFile *Unit) {
  1636. return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
  1637. Ty->getPointeeType(), Unit);
  1638. }
  1639. llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
  1640. llvm::DIFile *Unit) {
  1641. return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
  1642. Ty->getPointeeType(), Unit);
  1643. }
  1644. llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
  1645. llvm::DIFile *U) {
  1646. uint64_t Size = CGM.getCXXABI().isTypeInfoCalculable(QualType(Ty, 0))
  1647. ? CGM.getContext().getTypeSize(Ty)
  1648. : 0;
  1649. llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
  1650. if (Ty->isMemberDataPointerType())
  1651. return DBuilder.createMemberPointerType(
  1652. getOrCreateType(Ty->getPointeeType(), U), ClassType, Size);
  1653. const FunctionProtoType *FPT =
  1654. Ty->getPointeeType()->getAs<FunctionProtoType>();
  1655. return DBuilder.createMemberPointerType(
  1656. getOrCreateInstanceMethodType(CGM.getContext().getPointerType(QualType(
  1657. Ty->getClass(), FPT->getTypeQuals())),
  1658. FPT, U),
  1659. ClassType, Size);
  1660. }
  1661. llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
  1662. // Ignore the atomic wrapping
  1663. // FIXME: What is the correct representation?
  1664. return getOrCreateType(Ty->getValueType(), U);
  1665. }
  1666. llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
  1667. const EnumDecl *ED = Ty->getDecl();
  1668. uint64_t Size = 0;
  1669. uint64_t Align = 0;
  1670. if (!ED->getTypeForDecl()->isIncompleteType()) {
  1671. Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
  1672. Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
  1673. }
  1674. SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
  1675. // If this is just a forward declaration, construct an appropriately
  1676. // marked node and just return it.
  1677. if (!ED->getDefinition()) {
  1678. llvm::DIScope *EDContext =
  1679. getContextDescriptor(cast<Decl>(ED->getDeclContext()));
  1680. llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
  1681. unsigned Line = getLineNumber(ED->getLocation());
  1682. StringRef EDName = ED->getName();
  1683. llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
  1684. llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
  1685. 0, Size, Align, llvm::DINode::FlagFwdDecl, FullName);
  1686. ReplaceMap.emplace_back(
  1687. std::piecewise_construct, std::make_tuple(Ty),
  1688. std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
  1689. return RetTy;
  1690. }
  1691. return CreateTypeDefinition(Ty);
  1692. }
  1693. llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
  1694. const EnumDecl *ED = Ty->getDecl();
  1695. uint64_t Size = 0;
  1696. uint64_t Align = 0;
  1697. if (!ED->getTypeForDecl()->isIncompleteType()) {
  1698. Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
  1699. Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
  1700. }
  1701. SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
  1702. // Create elements for each enumerator.
  1703. SmallVector<llvm::Metadata *, 16> Enumerators;
  1704. ED = ED->getDefinition();
  1705. for (const auto *Enum : ED->enumerators()) {
  1706. Enumerators.push_back(DBuilder.createEnumerator(
  1707. Enum->getName(), Enum->getInitVal().getSExtValue()));
  1708. }
  1709. // Return a CompositeType for the enum itself.
  1710. llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
  1711. llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
  1712. unsigned Line = getLineNumber(ED->getLocation());
  1713. llvm::DIScope *EnumContext =
  1714. getContextDescriptor(cast<Decl>(ED->getDeclContext()));
  1715. llvm::DIType *ClassTy =
  1716. ED->isFixed() ? getOrCreateType(ED->getIntegerType(), DefUnit) : nullptr;
  1717. return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
  1718. Line, Size, Align, EltArray, ClassTy,
  1719. FullName);
  1720. }
  1721. static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
  1722. Qualifiers Quals;
  1723. do {
  1724. Qualifiers InnerQuals = T.getLocalQualifiers();
  1725. // Qualifiers::operator+() doesn't like it if you add a Qualifier
  1726. // that is already there.
  1727. Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
  1728. Quals += InnerQuals;
  1729. QualType LastT = T;
  1730. switch (T->getTypeClass()) {
  1731. default:
  1732. return C.getQualifiedType(T.getTypePtr(), Quals);
  1733. case Type::TemplateSpecialization: {
  1734. const auto *Spec = cast<TemplateSpecializationType>(T);
  1735. if (Spec->isTypeAlias())
  1736. return C.getQualifiedType(T.getTypePtr(), Quals);
  1737. T = Spec->desugar();
  1738. break;
  1739. }
  1740. case Type::TypeOfExpr:
  1741. T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
  1742. break;
  1743. case Type::TypeOf:
  1744. T = cast<TypeOfType>(T)->getUnderlyingType();
  1745. break;
  1746. case Type::Decltype:
  1747. T = cast<DecltypeType>(T)->getUnderlyingType();
  1748. break;
  1749. case Type::UnaryTransform:
  1750. T = cast<UnaryTransformType>(T)->getUnderlyingType();
  1751. break;
  1752. case Type::Attributed:
  1753. T = cast<AttributedType>(T)->getEquivalentType();
  1754. break;
  1755. case Type::Elaborated:
  1756. T = cast<ElaboratedType>(T)->getNamedType();
  1757. break;
  1758. case Type::Paren:
  1759. T = cast<ParenType>(T)->getInnerType();
  1760. break;
  1761. case Type::SubstTemplateTypeParm:
  1762. T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
  1763. break;
  1764. case Type::Auto:
  1765. QualType DT = cast<AutoType>(T)->getDeducedType();
  1766. assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
  1767. T = DT;
  1768. break;
  1769. }
  1770. assert(T != LastT && "Type unwrapping failed to unwrap!");
  1771. (void)LastT;
  1772. } while (true);
  1773. }
  1774. llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
  1775. // Unwrap the type as needed for debug information.
  1776. Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
  1777. auto it = TypeCache.find(Ty.getAsOpaquePtr());
  1778. if (it != TypeCache.end()) {
  1779. // Verify that the debug info still exists.
  1780. if (llvm::Metadata *V = it->second)
  1781. return cast<llvm::DIType>(V);
  1782. }
  1783. return nullptr;
  1784. }
  1785. void CGDebugInfo::completeTemplateDefinition(
  1786. const ClassTemplateSpecializationDecl &SD) {
  1787. if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  1788. return;
  1789. completeClassData(&SD);
  1790. // In case this type has no member function definitions being emitted, ensure
  1791. // it is retained
  1792. RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr());
  1793. }
  1794. llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
  1795. if (Ty.isNull())
  1796. return nullptr;
  1797. // Unwrap the type as needed for debug information.
  1798. Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
  1799. if (auto *T = getTypeOrNull(Ty))
  1800. return T;
  1801. // Otherwise create the type.
  1802. llvm::DIType *Res = CreateTypeNode(Ty, Unit);
  1803. void *TyPtr = Ty.getAsOpaquePtr();
  1804. // And update the type cache.
  1805. TypeCache[TyPtr].reset(Res);
  1806. return Res;
  1807. }
  1808. #if 0 // HLSL Change - no ObjC support
  1809. unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
  1810. // The assumption is that the number of ivars can only increase
  1811. // monotonically, so it is safe to just use their current number as
  1812. // a checksum.
  1813. unsigned Sum = 0;
  1814. for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
  1815. Ivar != nullptr; Ivar = Ivar->getNextIvar())
  1816. ++Sum;
  1817. return Sum;
  1818. }
  1819. ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
  1820. switch (Ty->getTypeClass()) {
  1821. case Type::ObjCObjectPointer:
  1822. return getObjCInterfaceDecl(
  1823. cast<ObjCObjectPointerType>(Ty)->getPointeeType());
  1824. case Type::ObjCInterface:
  1825. return cast<ObjCInterfaceType>(Ty)->getDecl();
  1826. default:
  1827. return nullptr;
  1828. }
  1829. }
  1830. #endif // HLSL Change - no ObjC support
  1831. llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
  1832. // Handle qualifiers, which recursively handles what they refer to.
  1833. if (Ty.hasLocalQualifiers())
  1834. return CreateQualifiedType(Ty, Unit);
  1835. // Work out details of type.
  1836. switch (Ty->getTypeClass()) {
  1837. #define TYPE(Class, Base)
  1838. #define ABSTRACT_TYPE(Class, Base)
  1839. #define NON_CANONICAL_TYPE(Class, Base)
  1840. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1841. #include "clang/AST/TypeNodes.def"
  1842. llvm_unreachable("Dependent types cannot show up in debug information");
  1843. case Type::ExtVector:
  1844. case Type::Vector:
  1845. return CreateType(cast<VectorType>(Ty), Unit);
  1846. #if 0 // HLSL Change - no ObjC support
  1847. case Type::ObjCObjectPointer:
  1848. return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
  1849. case Type::ObjCObject:
  1850. return CreateType(cast<ObjCObjectType>(Ty), Unit);
  1851. case Type::ObjCInterface:
  1852. return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
  1853. #endif // HLSL Change - no ObjC support
  1854. case Type::Builtin:
  1855. return CreateType(cast<BuiltinType>(Ty));
  1856. case Type::Complex:
  1857. return CreateType(cast<ComplexType>(Ty));
  1858. case Type::Pointer:
  1859. return CreateType(cast<PointerType>(Ty), Unit);
  1860. case Type::Adjusted:
  1861. case Type::Decayed:
  1862. // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
  1863. return CreateType(
  1864. cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
  1865. #if 0 // HLSL Change - no block support
  1866. case Type::BlockPointer:
  1867. return CreateType(cast<BlockPointerType>(Ty), Unit);
  1868. #endif // HLSL Change - no block support
  1869. case Type::Typedef:
  1870. return CreateType(cast<TypedefType>(Ty), Unit);
  1871. case Type::Record:
  1872. return CreateType(cast<RecordType>(Ty));
  1873. case Type::Enum:
  1874. return CreateEnumType(cast<EnumType>(Ty));
  1875. case Type::FunctionProto:
  1876. case Type::FunctionNoProto:
  1877. return CreateType(cast<FunctionType>(Ty), Unit);
  1878. case Type::ConstantArray:
  1879. case Type::VariableArray:
  1880. case Type::IncompleteArray:
  1881. return CreateType(cast<ArrayType>(Ty), Unit);
  1882. case Type::LValueReference:
  1883. return CreateType(cast<LValueReferenceType>(Ty), Unit);
  1884. case Type::RValueReference:
  1885. return CreateType(cast<RValueReferenceType>(Ty), Unit);
  1886. case Type::MemberPointer:
  1887. return CreateType(cast<MemberPointerType>(Ty), Unit);
  1888. case Type::Atomic:
  1889. return CreateType(cast<AtomicType>(Ty), Unit);
  1890. case Type::TemplateSpecialization:
  1891. return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
  1892. case Type::Auto:
  1893. case Type::Attributed:
  1894. case Type::Elaborated:
  1895. case Type::Paren:
  1896. case Type::SubstTemplateTypeParm:
  1897. case Type::TypeOfExpr:
  1898. case Type::TypeOf:
  1899. case Type::Decltype:
  1900. case Type::UnaryTransform:
  1901. case Type::PackExpansion:
  1902. break;
  1903. }
  1904. llvm_unreachable("type should have been unwrapped!");
  1905. }
  1906. llvm::DIType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
  1907. llvm::DIFile *Unit) {
  1908. QualType QTy(Ty, 0);
  1909. auto *T = cast_or_null<llvm::DICompositeTypeBase>(getTypeOrNull(QTy));
  1910. // We may have cached a forward decl when we could have created
  1911. // a non-forward decl. Go ahead and create a non-forward decl
  1912. // now.
  1913. if (T && !T->isForwardDecl())
  1914. return T;
  1915. // Otherwise create the type.
  1916. llvm::DICompositeType *Res = CreateLimitedType(Ty);
  1917. // Propagate members from the declaration to the definition
  1918. // CreateType(const RecordType*) will overwrite this with the members in the
  1919. // correct order if the full type is needed.
  1920. DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
  1921. // And update the type cache.
  1922. TypeCache[QTy.getAsOpaquePtr()].reset(Res);
  1923. return Res;
  1924. }
  1925. // TODO: Currently used for context chains when limiting debug info.
  1926. llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
  1927. RecordDecl *RD = Ty->getDecl();
  1928. // Get overall information about the record type for the debug info.
  1929. llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
  1930. unsigned Line = getLineNumber(RD->getLocation());
  1931. StringRef RDName = getClassName(RD);
  1932. llvm::DIScope *RDContext =
  1933. getContextDescriptor(cast<Decl>(RD->getDeclContext()));
  1934. // If we ended up creating the type during the context chain construction,
  1935. // just return that.
  1936. auto *T = cast_or_null<llvm::DICompositeType>(
  1937. getTypeOrNull(CGM.getContext().getRecordType(RD)));
  1938. if (T && (!T->isForwardDecl() || !RD->getDefinition()))
  1939. return T;
  1940. // If this is just a forward or incomplete declaration, construct an
  1941. // appropriately marked node and just return it.
  1942. const RecordDecl *D = RD->getDefinition();
  1943. if (!D || !D->isCompleteDefinition())
  1944. return getOrCreateRecordFwdDecl(Ty, RDContext);
  1945. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  1946. uint64_t Align = CGM.getContext().getTypeAlign(Ty);
  1947. SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
  1948. llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
  1949. getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align, 0,
  1950. FullName);
  1951. RegionMap[Ty->getDecl()].reset(RealDecl);
  1952. TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
  1953. if (const ClassTemplateSpecializationDecl *TSpecial =
  1954. dyn_cast<ClassTemplateSpecializationDecl>(RD))
  1955. DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
  1956. CollectCXXTemplateParams(TSpecial, DefUnit));
  1957. return RealDecl;
  1958. }
  1959. void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
  1960. llvm::DICompositeType *RealDecl) {
  1961. // A class's primary base or the class itself contains the vtable.
  1962. llvm::DICompositeType *ContainingType = nullptr;
  1963. const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
  1964. if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
  1965. // Seek non-virtual primary base root.
  1966. while (1) {
  1967. const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
  1968. const CXXRecordDecl *PBT = BRL.getPrimaryBase();
  1969. if (PBT && !BRL.isPrimaryBaseVirtual())
  1970. PBase = PBT;
  1971. else
  1972. break;
  1973. }
  1974. ContainingType = cast<llvm::DICompositeType>(
  1975. getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
  1976. getOrCreateFile(RD->getLocation())));
  1977. } else if (RD->isDynamicClass())
  1978. ContainingType = RealDecl;
  1979. DBuilder.replaceVTableHolder(RealDecl, ContainingType);
  1980. }
  1981. llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
  1982. StringRef Name, uint64_t *Offset) {
  1983. llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
  1984. uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
  1985. unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
  1986. llvm::DIType *Ty = DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize,
  1987. FieldAlign, *Offset, 0, FieldTy);
  1988. *Offset += FieldSize;
  1989. return Ty;
  1990. }
  1991. void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
  1992. StringRef &Name,
  1993. StringRef &LinkageName,
  1994. llvm::DIScope *&FDContext,
  1995. llvm::DINodeArray &TParamsArray,
  1996. unsigned &Flags) {
  1997. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  1998. Name = getFunctionName(FD);
  1999. // Use mangled name as linkage name for C/C++ functions.
  2000. if (FD->hasPrototype()) {
  2001. LinkageName = CGM.getMangledName(GD);
  2002. Flags |= llvm::DINode::FlagPrototyped;
  2003. }
  2004. // No need to replicate the linkage name if it isn't different from the
  2005. // subprogram name, no need to have it at all unless coverage is enabled or
  2006. // debug is set to more than just line tables.
  2007. if (LinkageName == Name ||
  2008. (!CGM.getCodeGenOpts().EmitGcovArcs &&
  2009. !CGM.getCodeGenOpts().EmitGcovNotes &&
  2010. DebugKind <= CodeGenOptions::DebugLineTablesOnly))
  2011. LinkageName = StringRef();
  2012. if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
  2013. if (const NamespaceDecl *NSDecl =
  2014. dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
  2015. FDContext = getOrCreateNameSpace(NSDecl);
  2016. else if (const RecordDecl *RDecl =
  2017. dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
  2018. FDContext = getContextDescriptor(cast<Decl>(RDecl));
  2019. // Collect template parameters.
  2020. TParamsArray = CollectFunctionTemplateParams(FD, Unit);
  2021. }
  2022. }
  2023. void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
  2024. unsigned &LineNo, QualType &T,
  2025. StringRef &Name, StringRef &LinkageName,
  2026. llvm::DIScope *&VDContext) {
  2027. Unit = getOrCreateFile(VD->getLocation());
  2028. LineNo = getLineNumber(VD->getLocation());
  2029. setLocation(VD->getLocation());
  2030. T = VD->getType();
  2031. if (T->isIncompleteArrayType()) {
  2032. // CodeGen turns int[] into int[1] so we'll do the same here.
  2033. llvm::APInt ConstVal(32, 1);
  2034. QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
  2035. T = CGM.getContext().getConstantArrayType(ET, ConstVal,
  2036. ArrayType::Normal, 0);
  2037. }
  2038. Name = VD->getName();
  2039. if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
  2040. !isa<ObjCMethodDecl>(VD->getDeclContext()))
  2041. LinkageName = CGM.getMangledName(VD);
  2042. if (LinkageName == Name)
  2043. LinkageName = StringRef();
  2044. // Since we emit declarations (DW_AT_members) for static members, place the
  2045. // definition of those static members in the namespace they were declared in
  2046. // in the source code (the lexical decl context).
  2047. // FIXME: Generalize this for even non-member global variables where the
  2048. // declaration and definition may have different lexical decl contexts, once
  2049. // we have support for emitting declarations of (non-member) global variables.
  2050. const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
  2051. : VD->getDeclContext();
  2052. // When a record type contains an in-line initialization of a static data
  2053. // member, and the record type is marked as __declspec(dllexport), an implicit
  2054. // definition of the member will be created in the record context. DWARF
  2055. // doesn't seem to have a nice way to describe this in a form that consumers
  2056. // are likely to understand, so fake the "normal" situation of a definition
  2057. // outside the class by putting it in the global scope.
  2058. if (DC->isRecord())
  2059. DC = CGM.getContext().getTranslationUnitDecl();
  2060. VDContext = getContextDescriptor(dyn_cast<Decl>(DC));
  2061. }
  2062. llvm::DISubprogram *
  2063. CGDebugInfo::getFunctionForwardDeclaration(const FunctionDecl *FD) {
  2064. llvm::DINodeArray TParamsArray;
  2065. StringRef Name, LinkageName;
  2066. unsigned Flags = 0;
  2067. SourceLocation Loc = FD->getLocation();
  2068. llvm::DIFile *Unit = getOrCreateFile(Loc);
  2069. llvm::DIScope *DContext = Unit;
  2070. unsigned Line = getLineNumber(Loc);
  2071. collectFunctionDeclProps(FD, Unit, Name, LinkageName, DContext,
  2072. TParamsArray, Flags);
  2073. // Build function type.
  2074. SmallVector<QualType, 16> ArgTypes;
  2075. for (const ParmVarDecl *Parm: FD->parameters())
  2076. ArgTypes.push_back(Parm->getType());
  2077. QualType FnType = CGM.getContext().getFunctionType(
  2078. FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(),
  2079. ArrayRef<hlsl::ParameterModifier>()); // HLSL Change - parameter modifiers
  2080. llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
  2081. DContext, Name, LinkageName, Unit, Line,
  2082. getOrCreateFunctionType(FD, FnType, Unit), !FD->isExternallyVisible(),
  2083. false /*declaration*/, 0, Flags, CGM.getLangOpts().Optimize, nullptr,
  2084. TParamsArray.get(), getFunctionDeclaration(FD));
  2085. const FunctionDecl *CanonDecl = cast<FunctionDecl>(FD->getCanonicalDecl());
  2086. FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
  2087. std::make_tuple(CanonDecl),
  2088. std::make_tuple(SP));
  2089. return SP;
  2090. }
  2091. llvm::DIGlobalVariable *
  2092. CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
  2093. QualType T;
  2094. StringRef Name, LinkageName;
  2095. SourceLocation Loc = VD->getLocation();
  2096. llvm::DIFile *Unit = getOrCreateFile(Loc);
  2097. llvm::DIScope *DContext = Unit;
  2098. unsigned Line = getLineNumber(Loc);
  2099. collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, DContext);
  2100. auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
  2101. DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
  2102. !VD->isExternallyVisible(), nullptr, nullptr);
  2103. FwdDeclReplaceMap.emplace_back(
  2104. std::piecewise_construct,
  2105. std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
  2106. std::make_tuple(static_cast<llvm::Metadata *>(GV)));
  2107. return GV;
  2108. }
  2109. llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
  2110. // We only need a declaration (not a definition) of the type - so use whatever
  2111. // we would otherwise do to get a type for a pointee. (forward declarations in
  2112. // limited debug info, full definitions (if the type definition is available)
  2113. // in unlimited debug info)
  2114. if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
  2115. return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
  2116. getOrCreateFile(TD->getLocation()));
  2117. auto I = DeclCache.find(D->getCanonicalDecl());
  2118. if (I != DeclCache.end())
  2119. return dyn_cast_or_null<llvm::DINode>(I->second);
  2120. // No definition for now. Emit a forward definition that might be
  2121. // merged with a potential upcoming definition.
  2122. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  2123. return getFunctionForwardDeclaration(FD);
  2124. else if (const auto *VD = dyn_cast<VarDecl>(D))
  2125. return getGlobalVariableForwardDeclaration(VD);
  2126. return nullptr;
  2127. }
  2128. llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
  2129. if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  2130. return nullptr;
  2131. const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
  2132. if (!FD)
  2133. return nullptr;
  2134. // Setup context.
  2135. auto *S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
  2136. auto MI = SPCache.find(FD->getCanonicalDecl());
  2137. if (MI == SPCache.end()) {
  2138. if (const CXXMethodDecl *MD =
  2139. dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
  2140. return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
  2141. cast<llvm::DICompositeType>(S));
  2142. }
  2143. }
  2144. if (MI != SPCache.end()) {
  2145. auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
  2146. if (SP && !SP->isDefinition())
  2147. return SP;
  2148. }
  2149. for (auto NextFD : FD->redecls()) {
  2150. auto MI = SPCache.find(NextFD->getCanonicalDecl());
  2151. if (MI != SPCache.end()) {
  2152. auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
  2153. if (SP && !SP->isDefinition())
  2154. return SP;
  2155. }
  2156. }
  2157. return nullptr;
  2158. }
  2159. // getOrCreateFunctionType - Construct type. If it is a c++ method, include
  2160. // implicit parameter "this".
  2161. llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
  2162. QualType FnType,
  2163. llvm::DIFile *F) {
  2164. if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  2165. // Create fake but valid subroutine type. Otherwise -verify would fail, and
  2166. // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
  2167. return DBuilder.createSubroutineType(F,
  2168. DBuilder.getOrCreateTypeArray(None));
  2169. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  2170. return getOrCreateMethodType(Method, F);
  2171. #if 0 // HLSL Change - no ObjC support
  2172. if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
  2173. // Add "self" and "_cmd"
  2174. SmallVector<llvm::Metadata *, 16> Elts;
  2175. // First element is always return type. For 'void' functions it is NULL.
  2176. QualType ResultTy = OMethod->getReturnType();
  2177. // Replace the instancetype keyword with the actual type.
  2178. if (ResultTy == CGM.getContext().getObjCInstanceType())
  2179. ResultTy = CGM.getContext().getPointerType(
  2180. QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
  2181. Elts.push_back(getOrCreateType(ResultTy, F));
  2182. // "self" pointer is always first argument.
  2183. QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
  2184. Elts.push_back(CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
  2185. // "_cmd" pointer is always second argument.
  2186. Elts.push_back(DBuilder.createArtificialType(
  2187. getOrCreateType(OMethod->getCmdDecl()->getType(), F)));
  2188. // Get rest of the arguments.
  2189. for (const auto *PI : OMethod->params())
  2190. Elts.push_back(getOrCreateType(PI->getType(), F));
  2191. // Variadic methods need a special marker at the end of the type list.
  2192. if (OMethod->isVariadic())
  2193. Elts.push_back(DBuilder.createUnspecifiedParameter());
  2194. llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
  2195. return DBuilder.createSubroutineType(F, EltTypeArray);
  2196. }
  2197. #endif // HLSL Change - no ObjC support
  2198. // Handle variadic function types; they need an additional
  2199. // unspecified parameter.
  2200. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  2201. if (FD->isVariadic()) {
  2202. SmallVector<llvm::Metadata *, 16> EltTys;
  2203. EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
  2204. if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
  2205. for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
  2206. EltTys.push_back(getOrCreateType(FPT->getParamType(i), F));
  2207. EltTys.push_back(DBuilder.createUnspecifiedParameter());
  2208. llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
  2209. return DBuilder.createSubroutineType(F, EltTypeArray);
  2210. }
  2211. return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
  2212. }
  2213. void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
  2214. SourceLocation ScopeLoc, QualType FnType,
  2215. llvm::Function *Fn, CGBuilderTy &Builder) {
  2216. StringRef Name;
  2217. StringRef LinkageName;
  2218. FnBeginRegionCount.push_back(LexicalBlockStack.size());
  2219. const Decl *D = GD.getDecl();
  2220. bool HasDecl = (D != nullptr);
  2221. unsigned Flags = 0;
  2222. llvm::DIFile *Unit = getOrCreateFile(Loc);
  2223. llvm::DIScope *FDContext = Unit;
  2224. llvm::DINodeArray TParamsArray;
  2225. if (!HasDecl) {
  2226. // Use llvm function name.
  2227. LinkageName = Fn->getName();
  2228. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  2229. // If there is a subprogram for this function available then use it.
  2230. auto FI = SPCache.find(FD->getCanonicalDecl());
  2231. if (FI != SPCache.end()) {
  2232. auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
  2233. if (SP && SP->isDefinition()) {
  2234. LexicalBlockStack.emplace_back(SP);
  2235. RegionMap[D].reset(SP);
  2236. return;
  2237. }
  2238. }
  2239. collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
  2240. TParamsArray, Flags);
  2241. #if 0 // HLSL Change - no ObjC support
  2242. } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
  2243. Name = getObjCMethodName(OMD);
  2244. Flags |= llvm::DINode::FlagPrototyped;
  2245. #endif // HLSL Change - no ObjC support
  2246. } else {
  2247. // Use llvm function name.
  2248. Name = Fn->getName();
  2249. Flags |= llvm::DINode::FlagPrototyped;
  2250. }
  2251. if (!Name.empty() && Name[0] == '\01')
  2252. Name = Name.substr(1);
  2253. if (!HasDecl || D->isImplicit()) {
  2254. Flags |= llvm::DINode::FlagArtificial;
  2255. // Artificial functions without a location should not silently reuse CurLoc.
  2256. if (Loc.isInvalid())
  2257. CurLoc = SourceLocation();
  2258. }
  2259. unsigned LineNo = getLineNumber(Loc);
  2260. unsigned ScopeLine = getLineNumber(ScopeLoc);
  2261. // FIXME: The function declaration we're constructing here is mostly reusing
  2262. // declarations from CXXMethodDecl and not constructing new ones for arbitrary
  2263. // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
  2264. // all subprograms instead of the actual context since subprogram definitions
  2265. // are emitted as CU level entities by the backend.
  2266. llvm::DISubprogram *SP = DBuilder.createFunction(
  2267. FDContext, Name, LinkageName, Unit, LineNo,
  2268. getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
  2269. true /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize, Fn,
  2270. TParamsArray.get(), getFunctionDeclaration(D));
  2271. // We might get here with a VarDecl in the case we're generating
  2272. // code for the initialization of globals. Do not record these decls
  2273. // as they will overwrite the actual VarDecl Decl in the cache.
  2274. if (HasDecl && isa<FunctionDecl>(D))
  2275. DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(SP));
  2276. // Push the function onto the lexical block stack.
  2277. LexicalBlockStack.emplace_back(SP);
  2278. if (HasDecl)
  2279. RegionMap[D].reset(SP);
  2280. }
  2281. void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
  2282. // Update our current location
  2283. setLocation(Loc);
  2284. if (CurLoc.isInvalid() || CurLoc.isMacroID())
  2285. return;
  2286. llvm::MDNode *Scope = LexicalBlockStack.back();
  2287. Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
  2288. getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope));
  2289. }
  2290. void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
  2291. llvm::MDNode *Back = nullptr;
  2292. if (!LexicalBlockStack.empty())
  2293. Back = LexicalBlockStack.back().get();
  2294. LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
  2295. cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
  2296. getColumnNumber(CurLoc)));
  2297. }
  2298. void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
  2299. SourceLocation Loc) {
  2300. // Set our current location.
  2301. setLocation(Loc);
  2302. // Emit a line table change for the current location inside the new scope.
  2303. Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
  2304. getLineNumber(Loc), getColumnNumber(Loc), LexicalBlockStack.back()));
  2305. if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  2306. return;
  2307. // Create a new lexical block and push it on the stack.
  2308. CreateLexicalBlock(Loc);
  2309. }
  2310. void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
  2311. SourceLocation Loc) {
  2312. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  2313. // Provide an entry in the line table for the end of the block.
  2314. EmitLocation(Builder, Loc);
  2315. if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  2316. return;
  2317. LexicalBlockStack.pop_back();
  2318. }
  2319. void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
  2320. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  2321. unsigned RCount = FnBeginRegionCount.back();
  2322. assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
  2323. // Pop all regions for this function.
  2324. while (LexicalBlockStack.size() != RCount) {
  2325. // Provide an entry in the line table for the end of the block.
  2326. EmitLocation(Builder, CurLoc);
  2327. LexicalBlockStack.pop_back();
  2328. }
  2329. FnBeginRegionCount.pop_back();
  2330. }
  2331. llvm::DIType *CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
  2332. uint64_t *XOffset) {
  2333. SmallVector<llvm::Metadata *, 5> EltTys;
  2334. QualType FType;
  2335. uint64_t FieldSize, FieldOffset;
  2336. unsigned FieldAlign;
  2337. llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
  2338. QualType Type = VD->getType();
  2339. FieldOffset = 0;
  2340. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  2341. EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
  2342. EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
  2343. FType = CGM.getContext().IntTy;
  2344. EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
  2345. EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
  2346. #if 0 // HLSL Change - no ObjC or block support
  2347. bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
  2348. if (HasCopyAndDispose) {
  2349. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  2350. EltTys.push_back(
  2351. CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
  2352. EltTys.push_back(
  2353. CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
  2354. }
  2355. bool HasByrefExtendedLayout;
  2356. Qualifiers::ObjCLifetime Lifetime;
  2357. if (CGM.getContext().getByrefLifetime(Type, Lifetime,
  2358. HasByrefExtendedLayout) &&
  2359. HasByrefExtendedLayout) {
  2360. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  2361. EltTys.push_back(
  2362. CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
  2363. }
  2364. #endif // HLSL Change - no ObjC or block support
  2365. CharUnits Align = CGM.getContext().getDeclAlign(VD);
  2366. if (Align > CGM.getContext().toCharUnitsFromBits(
  2367. CGM.getTarget().getPointerAlign(0))) {
  2368. CharUnits FieldOffsetInBytes =
  2369. CGM.getContext().toCharUnitsFromBits(FieldOffset);
  2370. CharUnits AlignedOffsetInBytes =
  2371. FieldOffsetInBytes.RoundUpToAlignment(Align);
  2372. CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
  2373. if (NumPaddingBytes.isPositive()) {
  2374. llvm::APInt pad(32, NumPaddingBytes.getQuantity());
  2375. FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
  2376. pad, ArrayType::Normal, 0);
  2377. EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
  2378. }
  2379. }
  2380. FType = Type;
  2381. llvm::DIType *FieldTy = getOrCreateType(FType, Unit);
  2382. FieldSize = CGM.getContext().getTypeSize(FType);
  2383. FieldAlign = CGM.getContext().toBits(Align);
  2384. *XOffset = FieldOffset;
  2385. FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 0, FieldSize,
  2386. FieldAlign, FieldOffset, 0, FieldTy);
  2387. EltTys.push_back(FieldTy);
  2388. FieldOffset += FieldSize;
  2389. llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
  2390. unsigned Flags = llvm::DINode::FlagBlockByrefStruct;
  2391. return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
  2392. nullptr, Elements);
  2393. }
  2394. void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::dwarf::Tag Tag,
  2395. llvm::Value *Storage, unsigned ArgNo,
  2396. CGBuilderTy &Builder) {
  2397. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2398. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  2399. bool Unwritten =
  2400. VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
  2401. cast<Decl>(VD->getDeclContext())->isImplicit());
  2402. llvm::DIFile *Unit = nullptr;
  2403. if (!Unwritten)
  2404. Unit = getOrCreateFile(VD->getLocation());
  2405. llvm::DIType *Ty;
  2406. uint64_t XOffset = 0;
  2407. if (VD->hasAttr<BlocksAttr>())
  2408. Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
  2409. else
  2410. Ty = getOrCreateType(VD->getType(), Unit);
  2411. // If there is no debug info for this type then do not emit debug info
  2412. // for this variable.
  2413. if (!Ty)
  2414. return;
  2415. // Get location information.
  2416. unsigned Line = 0;
  2417. unsigned Column = 0;
  2418. if (!Unwritten) {
  2419. Line = getLineNumber(VD->getLocation());
  2420. Column = getColumnNumber(VD->getLocation());
  2421. }
  2422. SmallVector<int64_t, 9> Expr;
  2423. unsigned Flags = 0;
  2424. if (VD->isImplicit())
  2425. Flags |= llvm::DINode::FlagArtificial;
  2426. // If this is the first argument and it is implicit then
  2427. // give it an object pointer flag.
  2428. // FIXME: There has to be a better way to do this, but for static
  2429. // functions there won't be an implicit param at arg1 and
  2430. // otherwise it is 'self' or 'this'.
  2431. if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
  2432. Flags |= llvm::DINode::FlagObjectPointer;
  2433. if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
  2434. if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
  2435. !VD->getType()->isPointerType())
  2436. Expr.push_back(llvm::dwarf::DW_OP_deref);
  2437. auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
  2438. StringRef Name = VD->getName();
  2439. if (!Name.empty()) {
  2440. if (VD->hasAttr<BlocksAttr>()) {
  2441. CharUnits offset = CharUnits::fromQuantity(32);
  2442. Expr.push_back(llvm::dwarf::DW_OP_plus);
  2443. // offset of __forwarding field
  2444. offset = CGM.getContext().toCharUnitsFromBits(
  2445. CGM.getTarget().getPointerWidth(0));
  2446. Expr.push_back(offset.getQuantity());
  2447. Expr.push_back(llvm::dwarf::DW_OP_deref);
  2448. Expr.push_back(llvm::dwarf::DW_OP_plus);
  2449. // offset of x field
  2450. offset = CGM.getContext().toCharUnitsFromBits(XOffset);
  2451. Expr.push_back(offset.getQuantity());
  2452. // Create the descriptor for the variable.
  2453. auto *D = DBuilder.createLocalVariable(Tag, Scope, VD->getName(), Unit,
  2454. Line, Ty, ArgNo);
  2455. // Insert an llvm.dbg.declare into the current block.
  2456. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
  2457. llvm::DebugLoc::get(Line, Column, Scope),
  2458. Builder.GetInsertBlock());
  2459. return;
  2460. } else if (isa<VariableArrayType>(VD->getType()))
  2461. Expr.push_back(llvm::dwarf::DW_OP_deref);
  2462. } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
  2463. // If VD is an anonymous union then Storage represents value for
  2464. // all union fields.
  2465. const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
  2466. if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
  2467. // GDB has trouble finding local variables in anonymous unions, so we emit
  2468. // artifical local variables for each of the members.
  2469. //
  2470. // FIXME: Remove this code as soon as GDB supports this.
  2471. // The debug info verifier in LLVM operates based on the assumption that a
  2472. // variable has the same size as its storage and we had to disable the check
  2473. // for artificial variables.
  2474. for (const auto *Field : RD->fields()) {
  2475. llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
  2476. StringRef FieldName = Field->getName();
  2477. // Ignore unnamed fields. Do not ignore unnamed records.
  2478. if (FieldName.empty() && !isa<RecordType>(Field->getType()))
  2479. continue;
  2480. // Use VarDecl's Tag, Scope and Line number.
  2481. auto *D = DBuilder.createLocalVariable(
  2482. Tag, Scope, FieldName, Unit, Line, FieldTy,
  2483. CGM.getLangOpts().Optimize, Flags | llvm::DINode::FlagArtificial,
  2484. ArgNo);
  2485. // Insert an llvm.dbg.declare into the current block.
  2486. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
  2487. llvm::DebugLoc::get(Line, Column, Scope),
  2488. Builder.GetInsertBlock());
  2489. }
  2490. }
  2491. }
  2492. // Create the descriptor for the variable.
  2493. auto *D =
  2494. DBuilder.createLocalVariable(Tag, Scope, Name, Unit, Line, Ty,
  2495. CGM.getLangOpts().Optimize, Flags, ArgNo);
  2496. // Insert an llvm.dbg.declare into the current block.
  2497. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
  2498. llvm::DebugLoc::get(Line, Column, Scope),
  2499. Builder.GetInsertBlock());
  2500. }
  2501. void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
  2502. llvm::Value *Storage,
  2503. CGBuilderTy &Builder) {
  2504. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2505. EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
  2506. }
  2507. llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
  2508. llvm::DIType *Ty) {
  2509. llvm::DIType *CachedTy = getTypeOrNull(QualTy);
  2510. if (CachedTy)
  2511. Ty = CachedTy;
  2512. return DBuilder.createObjectPointerType(Ty);
  2513. }
  2514. void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
  2515. const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
  2516. const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
  2517. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2518. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  2519. if (Builder.GetInsertBlock() == nullptr)
  2520. return;
  2521. bool isByRef = VD->hasAttr<BlocksAttr>();
  2522. uint64_t XOffset = 0;
  2523. llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
  2524. llvm::DIType *Ty;
  2525. if (isByRef)
  2526. Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
  2527. else
  2528. Ty = getOrCreateType(VD->getType(), Unit);
  2529. // Self is passed along as an implicit non-arg variable in a
  2530. // block. Mark it as the object pointer.
  2531. if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
  2532. Ty = CreateSelfType(VD->getType(), Ty);
  2533. // Get location information.
  2534. unsigned Line = getLineNumber(VD->getLocation());
  2535. unsigned Column = getColumnNumber(VD->getLocation());
  2536. const llvm::DataLayout &target = CGM.getDataLayout();
  2537. CharUnits offset = CharUnits::fromQuantity(
  2538. target.getStructLayout(blockInfo.StructureType)
  2539. ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
  2540. SmallVector<int64_t, 9> addr;
  2541. if (isa<llvm::AllocaInst>(Storage))
  2542. addr.push_back(llvm::dwarf::DW_OP_deref);
  2543. addr.push_back(llvm::dwarf::DW_OP_plus);
  2544. addr.push_back(offset.getQuantity());
  2545. if (isByRef) {
  2546. addr.push_back(llvm::dwarf::DW_OP_deref);
  2547. addr.push_back(llvm::dwarf::DW_OP_plus);
  2548. // offset of __forwarding field
  2549. offset =
  2550. CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
  2551. addr.push_back(offset.getQuantity());
  2552. addr.push_back(llvm::dwarf::DW_OP_deref);
  2553. addr.push_back(llvm::dwarf::DW_OP_plus);
  2554. // offset of x field
  2555. offset = CGM.getContext().toCharUnitsFromBits(XOffset);
  2556. addr.push_back(offset.getQuantity());
  2557. }
  2558. // Create the descriptor for the variable.
  2559. auto *D = DBuilder.createLocalVariable(
  2560. llvm::dwarf::DW_TAG_auto_variable,
  2561. cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
  2562. Line, Ty);
  2563. // Insert an llvm.dbg.declare into the current block.
  2564. auto DL = llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back());
  2565. if (InsertPoint)
  2566. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
  2567. InsertPoint);
  2568. else
  2569. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
  2570. Builder.GetInsertBlock());
  2571. }
  2572. void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
  2573. unsigned ArgNo,
  2574. CGBuilderTy &Builder) {
  2575. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2576. EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
  2577. }
  2578. #if 0 // HLSL Change - no block support
  2579. namespace {
  2580. struct BlockLayoutChunk {
  2581. uint64_t OffsetInBits;
  2582. const BlockDecl::Capture *Capture;
  2583. };
  2584. bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
  2585. return l.OffsetInBits < r.OffsetInBits;
  2586. }
  2587. }
  2588. void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
  2589. llvm::Value *Arg,
  2590. unsigned ArgNo,
  2591. llvm::Value *LocalAddr,
  2592. CGBuilderTy &Builder) {
  2593. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2594. ASTContext &C = CGM.getContext();
  2595. const BlockDecl *blockDecl = block.getBlockDecl();
  2596. // Collect some general information about the block's location.
  2597. SourceLocation loc = blockDecl->getCaretLocation();
  2598. llvm::DIFile *tunit = getOrCreateFile(loc);
  2599. unsigned line = getLineNumber(loc);
  2600. unsigned column = getColumnNumber(loc);
  2601. // Build the debug-info type for the block literal.
  2602. getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
  2603. const llvm::StructLayout *blockLayout =
  2604. CGM.getDataLayout().getStructLayout(block.StructureType);
  2605. SmallVector<llvm::Metadata *, 16> fields;
  2606. fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
  2607. blockLayout->getElementOffsetInBits(0),
  2608. tunit, tunit));
  2609. fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
  2610. blockLayout->getElementOffsetInBits(1),
  2611. tunit, tunit));
  2612. fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
  2613. blockLayout->getElementOffsetInBits(2),
  2614. tunit, tunit));
  2615. auto *FnTy = block.getBlockExpr()->getFunctionType();
  2616. auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
  2617. fields.push_back(createFieldType("__FuncPtr", FnPtrType, 0, loc, AS_public,
  2618. blockLayout->getElementOffsetInBits(3),
  2619. tunit, tunit));
  2620. fields.push_back(createFieldType(
  2621. "__descriptor", C.getPointerType(block.NeedsCopyDispose
  2622. ? C.getBlockDescriptorExtendedType()
  2623. : C.getBlockDescriptorType()),
  2624. 0, loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit));
  2625. // We want to sort the captures by offset, not because DWARF
  2626. // requires this, but because we're paranoid about debuggers.
  2627. SmallVector<BlockLayoutChunk, 8> chunks;
  2628. // 'this' capture.
  2629. if (blockDecl->capturesCXXThis()) {
  2630. BlockLayoutChunk chunk;
  2631. chunk.OffsetInBits =
  2632. blockLayout->getElementOffsetInBits(block.CXXThisIndex);
  2633. chunk.Capture = nullptr;
  2634. chunks.push_back(chunk);
  2635. }
  2636. // Variable captures.
  2637. for (const auto &capture : blockDecl->captures()) {
  2638. const VarDecl *variable = capture.getVariable();
  2639. const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
  2640. // Ignore constant captures.
  2641. if (captureInfo.isConstant())
  2642. continue;
  2643. BlockLayoutChunk chunk;
  2644. chunk.OffsetInBits =
  2645. blockLayout->getElementOffsetInBits(captureInfo.getIndex());
  2646. chunk.Capture = &capture;
  2647. chunks.push_back(chunk);
  2648. }
  2649. // Sort by offset.
  2650. llvm::array_pod_sort(chunks.begin(), chunks.end());
  2651. for (SmallVectorImpl<BlockLayoutChunk>::iterator i = chunks.begin(),
  2652. e = chunks.end();
  2653. i != e; ++i) {
  2654. uint64_t offsetInBits = i->OffsetInBits;
  2655. const BlockDecl::Capture *capture = i->Capture;
  2656. // If we have a null capture, this must be the C++ 'this' capture.
  2657. if (!capture) {
  2658. const CXXMethodDecl *method =
  2659. cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
  2660. QualType type = method->getThisType(C);
  2661. fields.push_back(createFieldType("this", type, 0, loc, AS_public,
  2662. offsetInBits, tunit, tunit));
  2663. continue;
  2664. }
  2665. const VarDecl *variable = capture->getVariable();
  2666. StringRef name = variable->getName();
  2667. llvm::DIType *fieldType;
  2668. if (capture->isByRef()) {
  2669. TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
  2670. // FIXME: this creates a second copy of this type!
  2671. uint64_t xoffset;
  2672. fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
  2673. fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
  2674. fieldType =
  2675. DBuilder.createMemberType(tunit, name, tunit, line, PtrInfo.Width,
  2676. PtrInfo.Align, offsetInBits, 0, fieldType);
  2677. } else {
  2678. fieldType = createFieldType(name, variable->getType(), 0, loc, AS_public,
  2679. offsetInBits, tunit, tunit);
  2680. }
  2681. fields.push_back(fieldType);
  2682. }
  2683. SmallString<36> typeName;
  2684. llvm::raw_svector_ostream(typeName) << "__block_literal_"
  2685. << CGM.getUniqueBlockCount();
  2686. llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
  2687. llvm::DIType *type = DBuilder.createStructType(
  2688. tunit, typeName.str(), tunit, line,
  2689. CGM.getContext().toBits(block.BlockSize),
  2690. CGM.getContext().toBits(block.BlockAlign), 0, nullptr, fieldsArray);
  2691. type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
  2692. // Get overall information about the block.
  2693. unsigned flags = llvm::DINode::FlagArtificial;
  2694. auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
  2695. // Create the descriptor for the parameter.
  2696. auto *debugVar = DBuilder.createLocalVariable(
  2697. llvm::dwarf::DW_TAG_arg_variable, scope, Arg->getName(), tunit, line,
  2698. type, CGM.getLangOpts().Optimize, flags, ArgNo);
  2699. if (LocalAddr) {
  2700. // Insert an llvm.dbg.value into the current block.
  2701. DBuilder.insertDbgValueIntrinsic(
  2702. LocalAddr, 0, debugVar, DBuilder.createExpression(),
  2703. llvm::DebugLoc::get(line, column, scope), Builder.GetInsertBlock());
  2704. }
  2705. // Insert an llvm.dbg.declare into the current block.
  2706. DBuilder.insertDeclare(Arg, debugVar, DBuilder.createExpression(),
  2707. llvm::DebugLoc::get(line, column, scope),
  2708. Builder.GetInsertBlock());
  2709. }
  2710. #endif // HLSL Change - no block support
  2711. llvm::DIDerivedType *
  2712. CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
  2713. if (!D->isStaticDataMember())
  2714. return nullptr;
  2715. auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
  2716. if (MI != StaticDataMemberCache.end()) {
  2717. assert(MI->second && "Static data member declaration should still exist");
  2718. return cast<llvm::DIDerivedType>(MI->second);
  2719. }
  2720. // If the member wasn't found in the cache, lazily construct and add it to the
  2721. // type (used when a limited form of the type is emitted).
  2722. auto DC = D->getDeclContext();
  2723. auto *Ctxt =
  2724. cast<llvm::DICompositeType>(getContextDescriptor(cast<Decl>(DC)));
  2725. return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
  2726. }
  2727. llvm::DIGlobalVariable *CGDebugInfo::CollectAnonRecordDecls(
  2728. const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
  2729. StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
  2730. llvm::DIGlobalVariable *GV = nullptr;
  2731. for (const auto *Field : RD->fields()) {
  2732. llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
  2733. StringRef FieldName = Field->getName();
  2734. // Ignore unnamed fields, but recurse into anonymous records.
  2735. if (FieldName.empty()) {
  2736. const RecordType *RT = dyn_cast<RecordType>(Field->getType());
  2737. if (RT)
  2738. GV = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
  2739. Var, DContext);
  2740. continue;
  2741. }
  2742. // Use VarDecl's Tag, Scope and Line number.
  2743. GV = DBuilder.createGlobalVariable(DContext, FieldName, LinkageName, Unit,
  2744. LineNo, FieldTy,
  2745. Var->hasInternalLinkage(), Var, nullptr);
  2746. }
  2747. return GV;
  2748. }
  2749. void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
  2750. const VarDecl *D) {
  2751. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2752. // Create global variable debug descriptor.
  2753. llvm::DIFile *Unit = nullptr;
  2754. llvm::DIScope *DContext = nullptr;
  2755. unsigned LineNo;
  2756. StringRef DeclName, LinkageName;
  2757. QualType T;
  2758. collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, DContext);
  2759. // Attempt to store one global variable for the declaration - even if we
  2760. // emit a lot of fields.
  2761. llvm::DIGlobalVariable *GV = nullptr;
  2762. // If this is an anonymous union then we'll want to emit a global
  2763. // variable for each member of the anonymous union so that it's possible
  2764. // to find the name of any field in the union.
  2765. if (T->isUnionType() && DeclName.empty()) {
  2766. const RecordDecl *RD = cast<RecordType>(T)->getDecl();
  2767. assert(RD->isAnonymousStructOrUnion() &&
  2768. "unnamed non-anonymous struct or union?");
  2769. GV = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
  2770. } else {
  2771. GV = DBuilder.createGlobalVariable(
  2772. DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
  2773. Var->hasInternalLinkage(), Var,
  2774. getOrCreateStaticDataMemberDeclarationOrNull(D));
  2775. }
  2776. DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(GV));
  2777. }
  2778. void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
  2779. llvm::Constant *Init) {
  2780. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2781. // Create the descriptor for the variable.
  2782. llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
  2783. StringRef Name = VD->getName();
  2784. llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
  2785. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
  2786. const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
  2787. assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
  2788. Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
  2789. }
  2790. // Do not use global variables for enums.
  2791. //
  2792. // FIXME: why not?
  2793. if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
  2794. return;
  2795. // Do not emit separate definitions for function local const/statics.
  2796. if (isa<FunctionDecl>(VD->getDeclContext()))
  2797. return;
  2798. VD = cast<ValueDecl>(VD->getCanonicalDecl());
  2799. auto *VarD = cast<VarDecl>(VD);
  2800. if (VarD->isStaticDataMember()) {
  2801. auto *RD = cast<RecordDecl>(VarD->getDeclContext());
  2802. getContextDescriptor(RD);
  2803. // Ensure that the type is retained even though it's otherwise unreferenced.
  2804. RetainedTypes.push_back(
  2805. CGM.getContext().getRecordType(RD).getAsOpaquePtr());
  2806. return;
  2807. }
  2808. llvm::DIScope *DContext =
  2809. getContextDescriptor(dyn_cast<Decl>(VD->getDeclContext()));
  2810. auto &GV = DeclCache[VD];
  2811. if (GV)
  2812. return;
  2813. GV.reset(DBuilder.createGlobalVariable(
  2814. DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
  2815. true, Init, getOrCreateStaticDataMemberDeclarationOrNull(VarD)));
  2816. }
  2817. llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
  2818. if (!LexicalBlockStack.empty())
  2819. return LexicalBlockStack.back();
  2820. return getContextDescriptor(D);
  2821. }
  2822. void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
  2823. if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
  2824. return;
  2825. DBuilder.createImportedModule(
  2826. getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
  2827. getOrCreateNameSpace(UD.getNominatedNamespace()),
  2828. getLineNumber(UD.getLocation()));
  2829. }
  2830. void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
  2831. if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
  2832. return;
  2833. assert(UD.shadow_size() &&
  2834. "We shouldn't be codegening an invalid UsingDecl containing no decls");
  2835. // Emitting one decl is sufficient - debuggers can detect that this is an
  2836. // overloaded name & provide lookup for all the overloads.
  2837. const UsingShadowDecl &USD = **UD.shadow_begin();
  2838. if (llvm::DINode *Target =
  2839. getDeclarationOrDefinition(USD.getUnderlyingDecl()))
  2840. DBuilder.createImportedDeclaration(
  2841. getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
  2842. getLineNumber(USD.getLocation()));
  2843. }
  2844. void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
  2845. auto *Reader = CGM.getContext().getExternalSource();
  2846. auto Info = Reader->getSourceDescriptor(*ID.getImportedModule());
  2847. DBuilder.createImportedDeclaration(
  2848. getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
  2849. getOrCreateModuleRef(Info),
  2850. getLineNumber(ID.getLocation()));
  2851. }
  2852. llvm::DIImportedEntity *
  2853. CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
  2854. if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
  2855. return nullptr;
  2856. auto &VH = NamespaceAliasCache[&NA];
  2857. if (VH)
  2858. return cast<llvm::DIImportedEntity>(VH);
  2859. llvm::DIImportedEntity *R;
  2860. if (const NamespaceAliasDecl *Underlying =
  2861. dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
  2862. // This could cache & dedup here rather than relying on metadata deduping.
  2863. R = DBuilder.createImportedDeclaration(
  2864. getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
  2865. EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
  2866. NA.getName());
  2867. else
  2868. R = DBuilder.createImportedDeclaration(
  2869. getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
  2870. getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
  2871. getLineNumber(NA.getLocation()), NA.getName());
  2872. VH.reset(R);
  2873. return R;
  2874. }
  2875. llvm::DINamespace *
  2876. CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
  2877. NSDecl = NSDecl->getCanonicalDecl();
  2878. auto I = NameSpaceCache.find(NSDecl);
  2879. if (I != NameSpaceCache.end())
  2880. return cast<llvm::DINamespace>(I->second);
  2881. unsigned LineNo = getLineNumber(NSDecl->getLocation());
  2882. llvm::DIFile *FileD = getOrCreateFile(NSDecl->getLocation());
  2883. llvm::DIScope *Context =
  2884. getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
  2885. llvm::DINamespace *NS =
  2886. DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
  2887. NameSpaceCache[NSDecl].reset(NS);
  2888. return NS;
  2889. }
  2890. void CGDebugInfo::finalize() {
  2891. // Creating types might create further types - invalidating the current
  2892. // element and the size(), so don't cache/reference them.
  2893. #if 1 // HLSL Change - no ObjC support
  2894. assert(ObjCInterfaceCache.size() == 0);
  2895. #else
  2896. for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
  2897. ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
  2898. llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
  2899. ? CreateTypeDefinition(E.Type, E.Unit)
  2900. : E.Decl;
  2901. DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
  2902. }
  2903. #endif // HLSL Change - no ObjC support
  2904. for (auto p : ReplaceMap) {
  2905. assert(p.second);
  2906. auto *Ty = cast<llvm::DIType>(p.second);
  2907. assert(Ty->isForwardDecl());
  2908. auto it = TypeCache.find(p.first);
  2909. assert(it != TypeCache.end());
  2910. assert(it->second);
  2911. DBuilder.replaceTemporary(llvm::TempDIType(Ty),
  2912. cast<llvm::DIType>(it->second));
  2913. }
  2914. for (const auto &p : FwdDeclReplaceMap) {
  2915. assert(p.second);
  2916. llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(p.second));
  2917. llvm::Metadata *Repl;
  2918. auto it = DeclCache.find(p.first);
  2919. // If there has been no definition for the declaration, call RAUW
  2920. // with ourselves, that will destroy the temporary MDNode and
  2921. // replace it with a standard one, avoiding leaking memory.
  2922. if (it == DeclCache.end())
  2923. Repl = p.second;
  2924. else
  2925. Repl = it->second;
  2926. DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
  2927. }
  2928. // We keep our own list of retained types, because we need to look
  2929. // up the final type in the type cache.
  2930. for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
  2931. RE = RetainedTypes.end(); RI != RE; ++RI)
  2932. DBuilder.retainType(cast<llvm::DIType>(TypeCache[*RI]));
  2933. DBuilder.finalize();
  2934. }
  2935. void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
  2936. if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
  2937. return;
  2938. if (auto *DieTy = getOrCreateType(Ty, getOrCreateMainFile()))
  2939. // Don't ignore in case of explicit cast where it is referenced indirectly.
  2940. DBuilder.retainType(DieTy);
  2941. }