CGDebugInfo.cpp 132 KB

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