CGDebugInfo.cpp 132 KB

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