CGDebugInfo.cpp 183 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779
  1. //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This coordinates the debug information generation while generating code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CGDebugInfo.h"
  13. #include "CGBlocks.h"
  14. #include "CGCXXABI.h"
  15. #include "CGObjCRuntime.h"
  16. #include "CGRecordLayout.h"
  17. #include "CodeGenFunction.h"
  18. #include "CodeGenModule.h"
  19. #include "ConstantEmitter.h"
  20. #include "clang/Analysis/Analyses/ExprMutationAnalyzer.h"
  21. #include "clang/AST/ASTContext.h"
  22. #include "clang/AST/DeclFriend.h"
  23. #include "clang/AST/DeclObjC.h"
  24. #include "clang/AST/DeclTemplate.h"
  25. #include "clang/AST/Expr.h"
  26. #include "clang/AST/RecordLayout.h"
  27. #include "clang/Basic/CodeGenOptions.h"
  28. #include "clang/Basic/FileManager.h"
  29. #include "clang/Basic/SourceManager.h"
  30. #include "clang/Basic/Version.h"
  31. #include "clang/Frontend/FrontendOptions.h"
  32. #include "clang/Lex/HeaderSearchOptions.h"
  33. #include "clang/Lex/ModuleMap.h"
  34. #include "clang/Lex/PreprocessorOptions.h"
  35. #include "llvm/ADT/DenseSet.h"
  36. #include "llvm/ADT/SmallVector.h"
  37. #include "llvm/ADT/StringExtras.h"
  38. #include "llvm/IR/Constants.h"
  39. #include "llvm/IR/DataLayout.h"
  40. #include "llvm/IR/DerivedTypes.h"
  41. #include "llvm/IR/Instructions.h"
  42. #include "llvm/IR/Intrinsics.h"
  43. #include "llvm/IR/Metadata.h"
  44. #include "llvm/IR/Module.h"
  45. #include "llvm/Support/FileSystem.h"
  46. #include "llvm/Support/MD5.h"
  47. #include "llvm/Support/Path.h"
  48. using namespace clang;
  49. using namespace clang::CodeGen;
  50. static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
  51. auto TI = Ctx.getTypeInfo(Ty);
  52. return TI.AlignIsRequired ? TI.Align : 0;
  53. }
  54. static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
  55. return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
  56. }
  57. static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
  58. return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0;
  59. }
  60. CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
  61. : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
  62. DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
  63. DBuilder(CGM.getModule()) {
  64. for (const auto &KV : CGM.getCodeGenOpts().DebugPrefixMap)
  65. DebugPrefixMap[KV.first] = KV.second;
  66. CreateCompileUnit();
  67. }
  68. CGDebugInfo::~CGDebugInfo() {
  69. assert(LexicalBlockStack.empty() &&
  70. "Region stack mismatch, stack not empty!");
  71. }
  72. ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
  73. SourceLocation TemporaryLocation)
  74. : CGF(&CGF) {
  75. init(TemporaryLocation);
  76. }
  77. ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
  78. bool DefaultToEmpty,
  79. SourceLocation TemporaryLocation)
  80. : CGF(&CGF) {
  81. init(TemporaryLocation, DefaultToEmpty);
  82. }
  83. void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
  84. bool DefaultToEmpty) {
  85. auto *DI = CGF->getDebugInfo();
  86. if (!DI) {
  87. CGF = nullptr;
  88. return;
  89. }
  90. OriginalLocation = CGF->Builder.getCurrentDebugLocation();
  91. if (OriginalLocation && !DI->CGM.getExpressionLocationsEnabled())
  92. return;
  93. if (TemporaryLocation.isValid()) {
  94. DI->EmitLocation(CGF->Builder, TemporaryLocation);
  95. return;
  96. }
  97. if (DefaultToEmpty) {
  98. CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
  99. return;
  100. }
  101. // Construct a location that has a valid scope, but no line info.
  102. assert(!DI->LexicalBlockStack.empty());
  103. CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
  104. 0, 0, DI->LexicalBlockStack.back(), DI->getInlinedAt()));
  105. }
  106. ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
  107. : CGF(&CGF) {
  108. init(E->getExprLoc());
  109. }
  110. ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
  111. : CGF(&CGF) {
  112. if (!CGF.getDebugInfo()) {
  113. this->CGF = nullptr;
  114. return;
  115. }
  116. OriginalLocation = CGF.Builder.getCurrentDebugLocation();
  117. if (Loc)
  118. CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
  119. }
  120. ApplyDebugLocation::~ApplyDebugLocation() {
  121. // Query CGF so the location isn't overwritten when location updates are
  122. // temporarily disabled (for C++ default function arguments)
  123. if (CGF)
  124. CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
  125. }
  126. ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction &CGF,
  127. GlobalDecl InlinedFn)
  128. : CGF(&CGF) {
  129. if (!CGF.getDebugInfo()) {
  130. this->CGF = nullptr;
  131. return;
  132. }
  133. auto &DI = *CGF.getDebugInfo();
  134. SavedLocation = DI.getLocation();
  135. assert((DI.getInlinedAt() ==
  136. CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) &&
  137. "CGDebugInfo and IRBuilder are out of sync");
  138. DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn);
  139. }
  140. ApplyInlineDebugLocation::~ApplyInlineDebugLocation() {
  141. if (!CGF)
  142. return;
  143. auto &DI = *CGF->getDebugInfo();
  144. DI.EmitInlineFunctionEnd(CGF->Builder);
  145. DI.EmitLocation(CGF->Builder, SavedLocation);
  146. }
  147. void CGDebugInfo::setLocation(SourceLocation Loc) {
  148. // If the new location isn't valid return.
  149. if (Loc.isInvalid())
  150. return;
  151. CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
  152. // If we've changed files in the middle of a lexical scope go ahead
  153. // and create a new lexical scope with file node if it's different
  154. // from the one in the scope.
  155. if (LexicalBlockStack.empty())
  156. return;
  157. SourceManager &SM = CGM.getContext().getSourceManager();
  158. auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
  159. PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
  160. if (PCLoc.isInvalid() || Scope->getFile() == getOrCreateFile(CurLoc))
  161. return;
  162. if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
  163. LexicalBlockStack.pop_back();
  164. LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
  165. LBF->getScope(), getOrCreateFile(CurLoc)));
  166. } else if (isa<llvm::DILexicalBlock>(Scope) ||
  167. isa<llvm::DISubprogram>(Scope)) {
  168. LexicalBlockStack.pop_back();
  169. LexicalBlockStack.emplace_back(
  170. DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
  171. }
  172. }
  173. llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
  174. llvm::DIScope *Mod = getParentModuleOrNull(D);
  175. return getContextDescriptor(cast<Decl>(D->getDeclContext()),
  176. Mod ? Mod : TheCU);
  177. }
  178. llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
  179. llvm::DIScope *Default) {
  180. if (!Context)
  181. return Default;
  182. auto I = RegionMap.find(Context);
  183. if (I != RegionMap.end()) {
  184. llvm::Metadata *V = I->second;
  185. return dyn_cast_or_null<llvm::DIScope>(V);
  186. }
  187. // Check namespace.
  188. if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
  189. return getOrCreateNamespace(NSDecl);
  190. if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
  191. if (!RDecl->isDependentType())
  192. return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
  193. TheCU->getFile());
  194. return Default;
  195. }
  196. PrintingPolicy CGDebugInfo::getPrintingPolicy() const {
  197. PrintingPolicy PP = CGM.getContext().getPrintingPolicy();
  198. // If we're emitting codeview, it's important to try to match MSVC's naming so
  199. // that visualizers written for MSVC will trigger for our class names. In
  200. // particular, we can't have spaces between arguments of standard templates
  201. // like basic_string and vector.
  202. if (CGM.getCodeGenOpts().EmitCodeView)
  203. PP.MSVCFormatting = true;
  204. // Apply -fdebug-prefix-map.
  205. PP.RemapFilePaths = true;
  206. PP.remapPath = [this](StringRef Path) { return remapDIPath(Path); };
  207. return PP;
  208. }
  209. StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
  210. assert(FD && "Invalid FunctionDecl!");
  211. IdentifierInfo *FII = FD->getIdentifier();
  212. FunctionTemplateSpecializationInfo *Info =
  213. FD->getTemplateSpecializationInfo();
  214. // Emit the unqualified name in normal operation. LLVM and the debugger can
  215. // compute the fully qualified name from the scope chain. If we're only
  216. // emitting line table info, there won't be any scope chains, so emit the
  217. // fully qualified name here so that stack traces are more accurate.
  218. // FIXME: Do this when emitting DWARF as well as when emitting CodeView after
  219. // evaluating the size impact.
  220. bool UseQualifiedName = DebugKind == codegenoptions::DebugLineTablesOnly &&
  221. CGM.getCodeGenOpts().EmitCodeView;
  222. if (!Info && FII && !UseQualifiedName)
  223. return FII->getName();
  224. SmallString<128> NS;
  225. llvm::raw_svector_ostream OS(NS);
  226. if (!UseQualifiedName)
  227. FD->printName(OS);
  228. else
  229. FD->printQualifiedName(OS, getPrintingPolicy());
  230. // Add any template specialization args.
  231. if (Info) {
  232. const TemplateArgumentList *TArgs = Info->TemplateArguments;
  233. printTemplateArgumentList(OS, TArgs->asArray(), getPrintingPolicy());
  234. }
  235. // Copy this name on the side and use its reference.
  236. return internString(OS.str());
  237. }
  238. StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
  239. SmallString<256> MethodName;
  240. llvm::raw_svector_ostream OS(MethodName);
  241. OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
  242. const DeclContext *DC = OMD->getDeclContext();
  243. if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
  244. OS << OID->getName();
  245. } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
  246. OS << OID->getName();
  247. } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
  248. if (OC->IsClassExtension()) {
  249. OS << OC->getClassInterface()->getName();
  250. } else {
  251. OS << OC->getIdentifier()->getNameStart() << '('
  252. << OC->getIdentifier()->getNameStart() << ')';
  253. }
  254. } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
  255. OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')';
  256. } else if (isa<ObjCProtocolDecl>(DC)) {
  257. // We can extract the type of the class from the self pointer.
  258. if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
  259. QualType ClassTy =
  260. cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
  261. ClassTy.print(OS, PrintingPolicy(LangOptions()));
  262. }
  263. }
  264. OS << ' ' << OMD->getSelector().getAsString() << ']';
  265. return internString(OS.str());
  266. }
  267. StringRef CGDebugInfo::getSelectorName(Selector S) {
  268. return internString(S.getAsString());
  269. }
  270. StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
  271. if (isa<ClassTemplateSpecializationDecl>(RD)) {
  272. SmallString<128> Name;
  273. llvm::raw_svector_ostream OS(Name);
  274. PrintingPolicy PP = getPrintingPolicy();
  275. PP.PrintCanonicalTypes = true;
  276. RD->getNameForDiagnostic(OS, PP,
  277. /*Qualified*/ false);
  278. // Copy this name on the side and use its reference.
  279. return internString(Name);
  280. }
  281. // quick optimization to avoid having to intern strings that are already
  282. // stored reliably elsewhere
  283. if (const IdentifierInfo *II = RD->getIdentifier())
  284. return II->getName();
  285. // The CodeView printer in LLVM wants to see the names of unnamed types: it is
  286. // used to reconstruct the fully qualified type names.
  287. if (CGM.getCodeGenOpts().EmitCodeView) {
  288. if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
  289. assert(RD->getDeclContext() == D->getDeclContext() &&
  290. "Typedef should not be in another decl context!");
  291. assert(D->getDeclName().getAsIdentifierInfo() &&
  292. "Typedef was not named!");
  293. return D->getDeclName().getAsIdentifierInfo()->getName();
  294. }
  295. if (CGM.getLangOpts().CPlusPlus) {
  296. StringRef Name;
  297. ASTContext &Context = CGM.getContext();
  298. if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
  299. // Anonymous types without a name for linkage purposes have their
  300. // declarator mangled in if they have one.
  301. Name = DD->getName();
  302. else if (const TypedefNameDecl *TND =
  303. Context.getTypedefNameForUnnamedTagDecl(RD))
  304. // Anonymous types without a name for linkage purposes have their
  305. // associate typedef mangled in if they have one.
  306. Name = TND->getName();
  307. if (!Name.empty()) {
  308. SmallString<256> UnnamedType("<unnamed-type-");
  309. UnnamedType += Name;
  310. UnnamedType += '>';
  311. return internString(UnnamedType);
  312. }
  313. }
  314. }
  315. return StringRef();
  316. }
  317. Optional<llvm::DIFile::ChecksumKind>
  318. CGDebugInfo::computeChecksum(FileID FID, SmallString<32> &Checksum) const {
  319. Checksum.clear();
  320. if (!CGM.getCodeGenOpts().EmitCodeView &&
  321. CGM.getCodeGenOpts().DwarfVersion < 5)
  322. return None;
  323. SourceManager &SM = CGM.getContext().getSourceManager();
  324. bool Invalid;
  325. const llvm::MemoryBuffer *MemBuffer = SM.getBuffer(FID, &Invalid);
  326. if (Invalid)
  327. return None;
  328. llvm::MD5 Hash;
  329. llvm::MD5::MD5Result Result;
  330. Hash.update(MemBuffer->getBuffer());
  331. Hash.final(Result);
  332. Hash.stringifyResult(Result, Checksum);
  333. return llvm::DIFile::CSK_MD5;
  334. }
  335. Optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM,
  336. FileID FID) {
  337. if (!CGM.getCodeGenOpts().EmbedSource)
  338. return None;
  339. bool SourceInvalid = false;
  340. StringRef Source = SM.getBufferData(FID, &SourceInvalid);
  341. if (SourceInvalid)
  342. return None;
  343. return Source;
  344. }
  345. llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
  346. if (!Loc.isValid())
  347. // If Location is not valid then use main input file.
  348. return TheCU->getFile();
  349. SourceManager &SM = CGM.getContext().getSourceManager();
  350. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  351. StringRef FileName = PLoc.getFilename();
  352. if (PLoc.isInvalid() || FileName.empty())
  353. // If the location is not valid then use main input file.
  354. return TheCU->getFile();
  355. // Cache the results.
  356. auto It = DIFileCache.find(FileName.data());
  357. if (It != DIFileCache.end()) {
  358. // Verify that the information still exists.
  359. if (llvm::Metadata *V = It->second)
  360. return cast<llvm::DIFile>(V);
  361. }
  362. SmallString<32> Checksum;
  363. // Compute the checksum if possible. If the location is affected by a #line
  364. // directive that refers to a file, PLoc will have an invalid FileID, and we
  365. // will correctly get no checksum.
  366. Optional<llvm::DIFile::ChecksumKind> CSKind =
  367. computeChecksum(PLoc.getFileID(), Checksum);
  368. Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
  369. if (CSKind)
  370. CSInfo.emplace(*CSKind, Checksum);
  371. return createFile(FileName, CSInfo, getSource(SM, SM.getFileID(Loc)));
  372. }
  373. llvm::DIFile *
  374. CGDebugInfo::createFile(StringRef FileName,
  375. Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
  376. Optional<StringRef> Source) {
  377. StringRef Dir;
  378. StringRef File;
  379. std::string RemappedFile = remapDIPath(FileName);
  380. std::string CurDir = remapDIPath(getCurrentDirname());
  381. SmallString<128> DirBuf;
  382. SmallString<128> FileBuf;
  383. if (llvm::sys::path::is_absolute(RemappedFile)) {
  384. // Strip the common prefix (if it is more than just "/") from current
  385. // directory and FileName for a more space-efficient encoding.
  386. auto FileIt = llvm::sys::path::begin(RemappedFile);
  387. auto FileE = llvm::sys::path::end(RemappedFile);
  388. auto CurDirIt = llvm::sys::path::begin(CurDir);
  389. auto CurDirE = llvm::sys::path::end(CurDir);
  390. for (; CurDirIt != CurDirE && *CurDirIt == *FileIt; ++CurDirIt, ++FileIt)
  391. llvm::sys::path::append(DirBuf, *CurDirIt);
  392. if (std::distance(llvm::sys::path::begin(CurDir), CurDirIt) == 1) {
  393. // Don't strip the common prefix if it is only the root "/"
  394. // since that would make LLVM diagnostic locations confusing.
  395. Dir = {};
  396. File = RemappedFile;
  397. } else {
  398. for (; FileIt != FileE; ++FileIt)
  399. llvm::sys::path::append(FileBuf, *FileIt);
  400. Dir = DirBuf;
  401. File = FileBuf;
  402. }
  403. } else {
  404. Dir = CurDir;
  405. File = RemappedFile;
  406. }
  407. llvm::DIFile *F = DBuilder.createFile(File, Dir, CSInfo, Source);
  408. DIFileCache[FileName.data()].reset(F);
  409. return F;
  410. }
  411. std::string CGDebugInfo::remapDIPath(StringRef Path) const {
  412. for (const auto &Entry : DebugPrefixMap)
  413. if (Path.startswith(Entry.first))
  414. return (Twine(Entry.second) + Path.substr(Entry.first.size())).str();
  415. return Path.str();
  416. }
  417. unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
  418. if (Loc.isInvalid() && CurLoc.isInvalid())
  419. return 0;
  420. SourceManager &SM = CGM.getContext().getSourceManager();
  421. PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
  422. return PLoc.isValid() ? PLoc.getLine() : 0;
  423. }
  424. unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
  425. // We may not want column information at all.
  426. if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
  427. return 0;
  428. // If the location is invalid then use the current column.
  429. if (Loc.isInvalid() && CurLoc.isInvalid())
  430. return 0;
  431. SourceManager &SM = CGM.getContext().getSourceManager();
  432. PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
  433. return PLoc.isValid() ? PLoc.getColumn() : 0;
  434. }
  435. StringRef CGDebugInfo::getCurrentDirname() {
  436. if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
  437. return CGM.getCodeGenOpts().DebugCompilationDir;
  438. if (!CWDName.empty())
  439. return CWDName;
  440. SmallString<256> CWD;
  441. llvm::sys::fs::current_path(CWD);
  442. return CWDName = internString(CWD);
  443. }
  444. void CGDebugInfo::CreateCompileUnit() {
  445. SmallString<32> Checksum;
  446. Optional<llvm::DIFile::ChecksumKind> CSKind;
  447. Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
  448. // Should we be asking the SourceManager for the main file name, instead of
  449. // accepting it as an argument? This just causes the main file name to
  450. // mismatch with source locations and create extra lexical scopes or
  451. // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
  452. // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
  453. // because that's what the SourceManager says)
  454. // Get absolute path name.
  455. SourceManager &SM = CGM.getContext().getSourceManager();
  456. std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
  457. if (MainFileName.empty())
  458. MainFileName = "<stdin>";
  459. // The main file name provided via the "-main-file-name" option contains just
  460. // the file name itself with no path information. This file name may have had
  461. // a relative path, so we look into the actual file entry for the main
  462. // file to determine the real absolute path for the file.
  463. std::string MainFileDir;
  464. if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  465. MainFileDir = MainFile->getDir()->getName();
  466. if (!llvm::sys::path::is_absolute(MainFileName)) {
  467. llvm::SmallString<1024> MainFileDirSS(MainFileDir);
  468. llvm::sys::path::append(MainFileDirSS, MainFileName);
  469. MainFileName = llvm::sys::path::remove_leading_dotslash(MainFileDirSS);
  470. }
  471. // If the main file name provided is identical to the input file name, and
  472. // if the input file is a preprocessed source, use the module name for
  473. // debug info. The module name comes from the name specified in the first
  474. // linemarker if the input is a preprocessed source.
  475. if (MainFile->getName() == MainFileName &&
  476. FrontendOptions::getInputKindForExtension(
  477. MainFile->getName().rsplit('.').second)
  478. .isPreprocessed())
  479. MainFileName = CGM.getModule().getName().str();
  480. CSKind = computeChecksum(SM.getMainFileID(), Checksum);
  481. }
  482. llvm::dwarf::SourceLanguage LangTag;
  483. const LangOptions &LO = CGM.getLangOpts();
  484. if (LO.CPlusPlus) {
  485. if (LO.ObjC)
  486. LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
  487. else if (LO.CPlusPlus14)
  488. LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14;
  489. else if (LO.CPlusPlus11)
  490. LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11;
  491. else
  492. LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
  493. } else if (LO.ObjC) {
  494. LangTag = llvm::dwarf::DW_LANG_ObjC;
  495. } else if (LO.RenderScript) {
  496. LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
  497. } else if (LO.C99) {
  498. LangTag = llvm::dwarf::DW_LANG_C99;
  499. } else {
  500. LangTag = llvm::dwarf::DW_LANG_C89;
  501. }
  502. std::string Producer = getClangFullVersion();
  503. // Figure out which version of the ObjC runtime we have.
  504. unsigned RuntimeVers = 0;
  505. if (LO.ObjC)
  506. RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
  507. llvm::DICompileUnit::DebugEmissionKind EmissionKind;
  508. switch (DebugKind) {
  509. case codegenoptions::NoDebugInfo:
  510. case codegenoptions::LocTrackingOnly:
  511. EmissionKind = llvm::DICompileUnit::NoDebug;
  512. break;
  513. case codegenoptions::DebugLineTablesOnly:
  514. EmissionKind = llvm::DICompileUnit::LineTablesOnly;
  515. break;
  516. case codegenoptions::DebugDirectivesOnly:
  517. EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly;
  518. break;
  519. case codegenoptions::LimitedDebugInfo:
  520. case codegenoptions::FullDebugInfo:
  521. EmissionKind = llvm::DICompileUnit::FullDebug;
  522. break;
  523. }
  524. uint64_t DwoId = 0;
  525. auto &CGOpts = CGM.getCodeGenOpts();
  526. // The DIFile used by the CU is distinct from the main source
  527. // file. Its directory part specifies what becomes the
  528. // DW_AT_comp_dir (the compilation directory), even if the source
  529. // file was specified with an absolute path.
  530. if (CSKind)
  531. CSInfo.emplace(*CSKind, Checksum);
  532. llvm::DIFile *CUFile = DBuilder.createFile(
  533. remapDIPath(MainFileName), remapDIPath(getCurrentDirname()), CSInfo,
  534. getSource(SM, SM.getMainFileID()));
  535. // Create new compile unit.
  536. TheCU = DBuilder.createCompileUnit(
  537. LangTag, CUFile, CGOpts.EmitVersionIdentMetadata ? Producer : "",
  538. LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO,
  539. CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,
  540. DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
  541. CGM.getTarget().getTriple().isNVPTX()
  542. ? llvm::DICompileUnit::DebugNameTableKind::None
  543. : static_cast<llvm::DICompileUnit::DebugNameTableKind>(
  544. CGOpts.DebugNameTable),
  545. CGOpts.DebugRangesBaseAddress);
  546. }
  547. llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
  548. llvm::dwarf::TypeKind Encoding;
  549. StringRef BTName;
  550. switch (BT->getKind()) {
  551. #define BUILTIN_TYPE(Id, SingletonId)
  552. #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
  553. #include "clang/AST/BuiltinTypes.def"
  554. case BuiltinType::Dependent:
  555. llvm_unreachable("Unexpected builtin type");
  556. case BuiltinType::NullPtr:
  557. return DBuilder.createNullPtrType();
  558. case BuiltinType::Void:
  559. return nullptr;
  560. case BuiltinType::ObjCClass:
  561. if (!ClassTy)
  562. ClassTy =
  563. DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
  564. "objc_class", TheCU, TheCU->getFile(), 0);
  565. return ClassTy;
  566. case BuiltinType::ObjCId: {
  567. // typedef struct objc_class *Class;
  568. // typedef struct objc_object {
  569. // Class isa;
  570. // } *id;
  571. if (ObjTy)
  572. return ObjTy;
  573. if (!ClassTy)
  574. ClassTy =
  575. DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
  576. "objc_class", TheCU, TheCU->getFile(), 0);
  577. unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
  578. auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
  579. ObjTy = DBuilder.createStructType(TheCU, "objc_object", TheCU->getFile(), 0,
  580. 0, 0, llvm::DINode::FlagZero, nullptr,
  581. llvm::DINodeArray());
  582. DBuilder.replaceArrays(
  583. ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
  584. ObjTy, "isa", TheCU->getFile(), 0, Size, 0, 0,
  585. llvm::DINode::FlagZero, ISATy)));
  586. return ObjTy;
  587. }
  588. case BuiltinType::ObjCSel: {
  589. if (!SelTy)
  590. SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
  591. "objc_selector", TheCU,
  592. TheCU->getFile(), 0);
  593. return SelTy;
  594. }
  595. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  596. case BuiltinType::Id: \
  597. return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
  598. SingletonId);
  599. #include "clang/Basic/OpenCLImageTypes.def"
  600. case BuiltinType::OCLSampler:
  601. return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);
  602. case BuiltinType::OCLEvent:
  603. return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
  604. case BuiltinType::OCLClkEvent:
  605. return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
  606. case BuiltinType::OCLQueue:
  607. return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
  608. case BuiltinType::OCLReserveID:
  609. return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
  610. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  611. case BuiltinType::Id: \
  612. return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
  613. #include "clang/Basic/OpenCLExtensionTypes.def"
  614. // TODO: real support for SVE types requires more infrastructure
  615. // to be added first. The types have a variable length and are
  616. // represented in debug info as types whose length depends on a
  617. // target-specific pseudo register.
  618. #define SVE_TYPE(Name, Id, SingletonId) \
  619. case BuiltinType::Id:
  620. #include "clang/Basic/AArch64SVEACLETypes.def"
  621. {
  622. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  623. DiagnosticsEngine::Error,
  624. "cannot yet generate debug info for SVE type '%0'");
  625. auto Name = BT->getName(CGM.getContext().getPrintingPolicy());
  626. CGM.getDiags().Report(DiagID) << Name;
  627. // Return something safe.
  628. return CreateType(cast<const BuiltinType>(CGM.getContext().IntTy));
  629. }
  630. case BuiltinType::UChar:
  631. case BuiltinType::Char_U:
  632. Encoding = llvm::dwarf::DW_ATE_unsigned_char;
  633. break;
  634. case BuiltinType::Char_S:
  635. case BuiltinType::SChar:
  636. Encoding = llvm::dwarf::DW_ATE_signed_char;
  637. break;
  638. case BuiltinType::Char8:
  639. case BuiltinType::Char16:
  640. case BuiltinType::Char32:
  641. Encoding = llvm::dwarf::DW_ATE_UTF;
  642. break;
  643. case BuiltinType::UShort:
  644. case BuiltinType::UInt:
  645. case BuiltinType::UInt128:
  646. case BuiltinType::ULong:
  647. case BuiltinType::WChar_U:
  648. case BuiltinType::ULongLong:
  649. Encoding = llvm::dwarf::DW_ATE_unsigned;
  650. break;
  651. case BuiltinType::Short:
  652. case BuiltinType::Int:
  653. case BuiltinType::Int128:
  654. case BuiltinType::Long:
  655. case BuiltinType::WChar_S:
  656. case BuiltinType::LongLong:
  657. Encoding = llvm::dwarf::DW_ATE_signed;
  658. break;
  659. case BuiltinType::Bool:
  660. Encoding = llvm::dwarf::DW_ATE_boolean;
  661. break;
  662. case BuiltinType::Half:
  663. case BuiltinType::Float:
  664. case BuiltinType::LongDouble:
  665. case BuiltinType::Float16:
  666. case BuiltinType::Float128:
  667. case BuiltinType::Double:
  668. // FIXME: For targets where long double and __float128 have the same size,
  669. // they are currently indistinguishable in the debugger without some
  670. // special treatment. However, there is currently no consensus on encoding
  671. // and this should be updated once a DWARF encoding exists for distinct
  672. // floating point types of the same size.
  673. Encoding = llvm::dwarf::DW_ATE_float;
  674. break;
  675. case BuiltinType::ShortAccum:
  676. case BuiltinType::Accum:
  677. case BuiltinType::LongAccum:
  678. case BuiltinType::ShortFract:
  679. case BuiltinType::Fract:
  680. case BuiltinType::LongFract:
  681. case BuiltinType::SatShortFract:
  682. case BuiltinType::SatFract:
  683. case BuiltinType::SatLongFract:
  684. case BuiltinType::SatShortAccum:
  685. case BuiltinType::SatAccum:
  686. case BuiltinType::SatLongAccum:
  687. Encoding = llvm::dwarf::DW_ATE_signed_fixed;
  688. break;
  689. case BuiltinType::UShortAccum:
  690. case BuiltinType::UAccum:
  691. case BuiltinType::ULongAccum:
  692. case BuiltinType::UShortFract:
  693. case BuiltinType::UFract:
  694. case BuiltinType::ULongFract:
  695. case BuiltinType::SatUShortAccum:
  696. case BuiltinType::SatUAccum:
  697. case BuiltinType::SatULongAccum:
  698. case BuiltinType::SatUShortFract:
  699. case BuiltinType::SatUFract:
  700. case BuiltinType::SatULongFract:
  701. Encoding = llvm::dwarf::DW_ATE_unsigned_fixed;
  702. break;
  703. }
  704. switch (BT->getKind()) {
  705. case BuiltinType::Long:
  706. BTName = "long int";
  707. break;
  708. case BuiltinType::LongLong:
  709. BTName = "long long int";
  710. break;
  711. case BuiltinType::ULong:
  712. BTName = "long unsigned int";
  713. break;
  714. case BuiltinType::ULongLong:
  715. BTName = "long long unsigned int";
  716. break;
  717. default:
  718. BTName = BT->getName(CGM.getLangOpts());
  719. break;
  720. }
  721. // Bit size and offset of the type.
  722. uint64_t Size = CGM.getContext().getTypeSize(BT);
  723. return DBuilder.createBasicType(BTName, Size, Encoding);
  724. }
  725. llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
  726. // Bit size and offset of the type.
  727. llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
  728. if (Ty->isComplexIntegerType())
  729. Encoding = llvm::dwarf::DW_ATE_lo_user;
  730. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  731. return DBuilder.createBasicType("complex", Size, Encoding);
  732. }
  733. llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
  734. llvm::DIFile *Unit) {
  735. QualifierCollector Qc;
  736. const Type *T = Qc.strip(Ty);
  737. // Ignore these qualifiers for now.
  738. Qc.removeObjCGCAttr();
  739. Qc.removeAddressSpace();
  740. Qc.removeObjCLifetime();
  741. // We will create one Derived type for one qualifier and recurse to handle any
  742. // additional ones.
  743. llvm::dwarf::Tag Tag;
  744. if (Qc.hasConst()) {
  745. Tag = llvm::dwarf::DW_TAG_const_type;
  746. Qc.removeConst();
  747. } else if (Qc.hasVolatile()) {
  748. Tag = llvm::dwarf::DW_TAG_volatile_type;
  749. Qc.removeVolatile();
  750. } else if (Qc.hasRestrict()) {
  751. Tag = llvm::dwarf::DW_TAG_restrict_type;
  752. Qc.removeRestrict();
  753. } else {
  754. assert(Qc.empty() && "Unknown type qualifier for debug info");
  755. return getOrCreateType(QualType(T, 0), Unit);
  756. }
  757. auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
  758. // No need to fill in the Name, Line, Size, Alignment, Offset in case of
  759. // CVR derived types.
  760. return DBuilder.createQualifiedType(Tag, FromTy);
  761. }
  762. llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
  763. llvm::DIFile *Unit) {
  764. // The frontend treats 'id' as a typedef to an ObjCObjectType,
  765. // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
  766. // debug info, we want to emit 'id' in both cases.
  767. if (Ty->isObjCQualifiedIdType())
  768. return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
  769. return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
  770. Ty->getPointeeType(), Unit);
  771. }
  772. llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
  773. llvm::DIFile *Unit) {
  774. return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
  775. Ty->getPointeeType(), Unit);
  776. }
  777. /// \return whether a C++ mangling exists for the type defined by TD.
  778. static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
  779. switch (TheCU->getSourceLanguage()) {
  780. case llvm::dwarf::DW_LANG_C_plus_plus:
  781. case llvm::dwarf::DW_LANG_C_plus_plus_11:
  782. case llvm::dwarf::DW_LANG_C_plus_plus_14:
  783. return true;
  784. case llvm::dwarf::DW_LANG_ObjC_plus_plus:
  785. return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
  786. default:
  787. return false;
  788. }
  789. }
  790. // Determines if the debug info for this tag declaration needs a type
  791. // identifier. The purpose of the unique identifier is to deduplicate type
  792. // information for identical types across TUs. Because of the C++ one definition
  793. // rule (ODR), it is valid to assume that the type is defined the same way in
  794. // every TU and its debug info is equivalent.
  795. //
  796. // C does not have the ODR, and it is common for codebases to contain multiple
  797. // different definitions of a struct with the same name in different TUs.
  798. // Therefore, if the type doesn't have a C++ mangling, don't give it an
  799. // identifer. Type information in C is smaller and simpler than C++ type
  800. // information, so the increase in debug info size is negligible.
  801. //
  802. // If the type is not externally visible, it should be unique to the current TU,
  803. // and should not need an identifier to participate in type deduplication.
  804. // However, when emitting CodeView, the format internally uses these
  805. // unique type name identifers for references between debug info. For example,
  806. // the method of a class in an anonymous namespace uses the identifer to refer
  807. // to its parent class. The Microsoft C++ ABI attempts to provide unique names
  808. // for such types, so when emitting CodeView, always use identifiers for C++
  809. // types. This may create problems when attempting to emit CodeView when the MS
  810. // C++ ABI is not in use.
  811. static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
  812. llvm::DICompileUnit *TheCU) {
  813. // We only add a type identifier for types with C++ name mangling.
  814. if (!hasCXXMangling(TD, TheCU))
  815. return false;
  816. // Externally visible types with C++ mangling need a type identifier.
  817. if (TD->isExternallyVisible())
  818. return true;
  819. // CodeView types with C++ mangling need a type identifier.
  820. if (CGM.getCodeGenOpts().EmitCodeView)
  821. return true;
  822. return false;
  823. }
  824. // Returns a unique type identifier string if one exists, or an empty string.
  825. static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM,
  826. llvm::DICompileUnit *TheCU) {
  827. SmallString<256> Identifier;
  828. const TagDecl *TD = Ty->getDecl();
  829. if (!needsTypeIdentifier(TD, CGM, TheCU))
  830. return Identifier;
  831. if (const auto *RD = dyn_cast<CXXRecordDecl>(TD))
  832. if (RD->getDefinition())
  833. if (RD->isDynamicClass() &&
  834. CGM.getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage)
  835. return Identifier;
  836. // TODO: This is using the RTTI name. Is there a better way to get
  837. // a unique string for a type?
  838. llvm::raw_svector_ostream Out(Identifier);
  839. CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
  840. return Identifier;
  841. }
  842. /// \return the appropriate DWARF tag for a composite type.
  843. static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
  844. llvm::dwarf::Tag Tag;
  845. if (RD->isStruct() || RD->isInterface())
  846. Tag = llvm::dwarf::DW_TAG_structure_type;
  847. else if (RD->isUnion())
  848. Tag = llvm::dwarf::DW_TAG_union_type;
  849. else {
  850. // FIXME: This could be a struct type giving a default visibility different
  851. // than C++ class type, but needs llvm metadata changes first.
  852. assert(RD->isClass());
  853. Tag = llvm::dwarf::DW_TAG_class_type;
  854. }
  855. return Tag;
  856. }
  857. llvm::DICompositeType *
  858. CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
  859. llvm::DIScope *Ctx) {
  860. const RecordDecl *RD = Ty->getDecl();
  861. if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
  862. return cast<llvm::DICompositeType>(T);
  863. llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
  864. unsigned Line = getLineNumber(RD->getLocation());
  865. StringRef RDName = getClassName(RD);
  866. uint64_t Size = 0;
  867. uint32_t Align = 0;
  868. // Create the type.
  869. SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
  870. llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
  871. getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align,
  872. llvm::DINode::FlagFwdDecl, Identifier);
  873. if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
  874. if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
  875. DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
  876. CollectCXXTemplateParams(TSpecial, DefUnit));
  877. ReplaceMap.emplace_back(
  878. std::piecewise_construct, std::make_tuple(Ty),
  879. std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
  880. return RetTy;
  881. }
  882. llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
  883. const Type *Ty,
  884. QualType PointeeTy,
  885. llvm::DIFile *Unit) {
  886. // Bit size, align and offset of the type.
  887. // Size is always the size of a pointer. We can't use getTypeSize here
  888. // because that does not return the correct value for references.
  889. unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(PointeeTy);
  890. uint64_t Size = CGM.getTarget().getPointerWidth(AddressSpace);
  891. auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
  892. Optional<unsigned> DWARFAddressSpace =
  893. CGM.getTarget().getDWARFAddressSpace(AddressSpace);
  894. if (Tag == llvm::dwarf::DW_TAG_reference_type ||
  895. Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
  896. return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
  897. Size, Align, DWARFAddressSpace);
  898. else
  899. return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
  900. Align, DWARFAddressSpace);
  901. }
  902. llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
  903. llvm::DIType *&Cache) {
  904. if (Cache)
  905. return Cache;
  906. Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
  907. TheCU, TheCU->getFile(), 0);
  908. unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
  909. Cache = DBuilder.createPointerType(Cache, Size);
  910. return Cache;
  911. }
  912. uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
  913. const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,
  914. unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {
  915. QualType FType;
  916. // Advanced by calls to CreateMemberType in increments of FType, then
  917. // returned as the overall size of the default elements.
  918. uint64_t FieldOffset = 0;
  919. // Blocks in OpenCL have unique constraints which make the standard fields
  920. // redundant while requiring size and align fields for enqueue_kernel. See
  921. // initializeForBlockHeader in CGBlocks.cpp
  922. if (CGM.getLangOpts().OpenCL) {
  923. FType = CGM.getContext().IntTy;
  924. EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
  925. EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
  926. } else {
  927. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  928. EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
  929. FType = CGM.getContext().IntTy;
  930. EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
  931. EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
  932. FType = CGM.getContext().getPointerType(Ty->getPointeeType());
  933. EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
  934. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  935. uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);
  936. uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);
  937. EltTys.push_back(DBuilder.createMemberType(
  938. Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,
  939. FieldOffset, llvm::DINode::FlagZero, DescTy));
  940. FieldOffset += FieldSize;
  941. }
  942. return FieldOffset;
  943. }
  944. llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
  945. llvm::DIFile *Unit) {
  946. SmallVector<llvm::Metadata *, 8> EltTys;
  947. QualType FType;
  948. uint64_t FieldOffset;
  949. llvm::DINodeArray Elements;
  950. FieldOffset = 0;
  951. FType = CGM.getContext().UnsignedLongTy;
  952. EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
  953. EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
  954. Elements = DBuilder.getOrCreateArray(EltTys);
  955. EltTys.clear();
  956. llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
  957. auto *EltTy =
  958. DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,
  959. FieldOffset, 0, Flags, nullptr, Elements);
  960. // Bit size, align and offset of the type.
  961. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  962. auto *DescTy = DBuilder.createPointerType(EltTy, Size);
  963. FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,
  964. 0, EltTys);
  965. Elements = DBuilder.getOrCreateArray(EltTys);
  966. // The __block_literal_generic structs are marked with a special
  967. // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
  968. // the debugger needs to know about. To allow type uniquing, emit
  969. // them without a name or a location.
  970. EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,
  971. Flags, nullptr, Elements);
  972. return DBuilder.createPointerType(EltTy, Size);
  973. }
  974. llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
  975. llvm::DIFile *Unit) {
  976. assert(Ty->isTypeAlias());
  977. llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
  978. auto *AliasDecl =
  979. cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl())
  980. ->getTemplatedDecl();
  981. if (AliasDecl->hasAttr<NoDebugAttr>())
  982. return Src;
  983. SmallString<128> NS;
  984. llvm::raw_svector_ostream OS(NS);
  985. Ty->getTemplateName().print(OS, getPrintingPolicy(), /*qualified*/ false);
  986. printTemplateArgumentList(OS, Ty->template_arguments(), getPrintingPolicy());
  987. SourceLocation Loc = AliasDecl->getLocation();
  988. return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
  989. getLineNumber(Loc),
  990. getDeclContextDescriptor(AliasDecl));
  991. }
  992. llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
  993. llvm::DIFile *Unit) {
  994. llvm::DIType *Underlying =
  995. getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
  996. if (Ty->getDecl()->hasAttr<NoDebugAttr>())
  997. return Underlying;
  998. // We don't set size information, but do specify where the typedef was
  999. // declared.
  1000. SourceLocation Loc = Ty->getDecl()->getLocation();
  1001. // Typedefs are derived from some other type.
  1002. return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
  1003. getOrCreateFile(Loc), getLineNumber(Loc),
  1004. getDeclContextDescriptor(Ty->getDecl()));
  1005. }
  1006. static unsigned getDwarfCC(CallingConv CC) {
  1007. switch (CC) {
  1008. case CC_C:
  1009. // Avoid emitting DW_AT_calling_convention if the C convention was used.
  1010. return 0;
  1011. case CC_X86StdCall:
  1012. return llvm::dwarf::DW_CC_BORLAND_stdcall;
  1013. case CC_X86FastCall:
  1014. return llvm::dwarf::DW_CC_BORLAND_msfastcall;
  1015. case CC_X86ThisCall:
  1016. return llvm::dwarf::DW_CC_BORLAND_thiscall;
  1017. case CC_X86VectorCall:
  1018. return llvm::dwarf::DW_CC_LLVM_vectorcall;
  1019. case CC_X86Pascal:
  1020. return llvm::dwarf::DW_CC_BORLAND_pascal;
  1021. case CC_Win64:
  1022. return llvm::dwarf::DW_CC_LLVM_Win64;
  1023. case CC_X86_64SysV:
  1024. return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
  1025. case CC_AAPCS:
  1026. case CC_AArch64VectorCall:
  1027. return llvm::dwarf::DW_CC_LLVM_AAPCS;
  1028. case CC_AAPCS_VFP:
  1029. return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
  1030. case CC_IntelOclBicc:
  1031. return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
  1032. case CC_SpirFunction:
  1033. return llvm::dwarf::DW_CC_LLVM_SpirFunction;
  1034. case CC_OpenCLKernel:
  1035. return llvm::dwarf::DW_CC_LLVM_OpenCLKernel;
  1036. case CC_Swift:
  1037. return llvm::dwarf::DW_CC_LLVM_Swift;
  1038. case CC_PreserveMost:
  1039. return llvm::dwarf::DW_CC_LLVM_PreserveMost;
  1040. case CC_PreserveAll:
  1041. return llvm::dwarf::DW_CC_LLVM_PreserveAll;
  1042. case CC_X86RegCall:
  1043. return llvm::dwarf::DW_CC_LLVM_X86RegCall;
  1044. }
  1045. return 0;
  1046. }
  1047. llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
  1048. llvm::DIFile *Unit) {
  1049. SmallVector<llvm::Metadata *, 16> EltTys;
  1050. // Add the result type at least.
  1051. EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
  1052. // Set up remainder of arguments if there is a prototype.
  1053. // otherwise emit it as a variadic function.
  1054. if (isa<FunctionNoProtoType>(Ty))
  1055. EltTys.push_back(DBuilder.createUnspecifiedParameter());
  1056. else if (const auto *FPT = dyn_cast<FunctionProtoType>(Ty)) {
  1057. for (const QualType &ParamType : FPT->param_types())
  1058. EltTys.push_back(getOrCreateType(ParamType, Unit));
  1059. if (FPT->isVariadic())
  1060. EltTys.push_back(DBuilder.createUnspecifiedParameter());
  1061. }
  1062. llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
  1063. return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
  1064. getDwarfCC(Ty->getCallConv()));
  1065. }
  1066. /// Convert an AccessSpecifier into the corresponding DINode flag.
  1067. /// As an optimization, return 0 if the access specifier equals the
  1068. /// default for the containing type.
  1069. static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
  1070. const RecordDecl *RD) {
  1071. AccessSpecifier Default = clang::AS_none;
  1072. if (RD && RD->isClass())
  1073. Default = clang::AS_private;
  1074. else if (RD && (RD->isStruct() || RD->isUnion()))
  1075. Default = clang::AS_public;
  1076. if (Access == Default)
  1077. return llvm::DINode::FlagZero;
  1078. switch (Access) {
  1079. case clang::AS_private:
  1080. return llvm::DINode::FlagPrivate;
  1081. case clang::AS_protected:
  1082. return llvm::DINode::FlagProtected;
  1083. case clang::AS_public:
  1084. return llvm::DINode::FlagPublic;
  1085. case clang::AS_none:
  1086. return llvm::DINode::FlagZero;
  1087. }
  1088. llvm_unreachable("unexpected access enumerator");
  1089. }
  1090. llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
  1091. llvm::DIScope *RecordTy,
  1092. const RecordDecl *RD) {
  1093. StringRef Name = BitFieldDecl->getName();
  1094. QualType Ty = BitFieldDecl->getType();
  1095. SourceLocation Loc = BitFieldDecl->getLocation();
  1096. llvm::DIFile *VUnit = getOrCreateFile(Loc);
  1097. llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
  1098. // Get the location for the field.
  1099. llvm::DIFile *File = getOrCreateFile(Loc);
  1100. unsigned Line = getLineNumber(Loc);
  1101. const CGBitFieldInfo &BitFieldInfo =
  1102. CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
  1103. uint64_t SizeInBits = BitFieldInfo.Size;
  1104. assert(SizeInBits > 0 && "found named 0-width bitfield");
  1105. uint64_t StorageOffsetInBits =
  1106. CGM.getContext().toBits(BitFieldInfo.StorageOffset);
  1107. uint64_t Offset = BitFieldInfo.Offset;
  1108. // The bit offsets for big endian machines are reversed for big
  1109. // endian target, compensate for that as the DIDerivedType requires
  1110. // un-reversed offsets.
  1111. if (CGM.getDataLayout().isBigEndian())
  1112. Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
  1113. uint64_t OffsetInBits = StorageOffsetInBits + Offset;
  1114. llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
  1115. return DBuilder.createBitFieldMemberType(
  1116. RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
  1117. Flags, DebugType);
  1118. }
  1119. llvm::DIType *
  1120. CGDebugInfo::createFieldType(StringRef name, QualType type, SourceLocation loc,
  1121. AccessSpecifier AS, uint64_t offsetInBits,
  1122. uint32_t AlignInBits, llvm::DIFile *tunit,
  1123. llvm::DIScope *scope, const RecordDecl *RD) {
  1124. llvm::DIType *debugType = getOrCreateType(type, tunit);
  1125. // Get the location for the field.
  1126. llvm::DIFile *file = getOrCreateFile(loc);
  1127. unsigned line = getLineNumber(loc);
  1128. uint64_t SizeInBits = 0;
  1129. auto Align = AlignInBits;
  1130. if (!type->isIncompleteArrayType()) {
  1131. TypeInfo TI = CGM.getContext().getTypeInfo(type);
  1132. SizeInBits = TI.Width;
  1133. if (!Align)
  1134. Align = getTypeAlignIfRequired(type, CGM.getContext());
  1135. }
  1136. llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
  1137. return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
  1138. offsetInBits, flags, debugType);
  1139. }
  1140. void CGDebugInfo::CollectRecordLambdaFields(
  1141. const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
  1142. llvm::DIType *RecordTy) {
  1143. // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
  1144. // has the name and the location of the variable so we should iterate over
  1145. // both concurrently.
  1146. const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
  1147. RecordDecl::field_iterator Field = CXXDecl->field_begin();
  1148. unsigned fieldno = 0;
  1149. for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
  1150. E = CXXDecl->captures_end();
  1151. I != E; ++I, ++Field, ++fieldno) {
  1152. const LambdaCapture &C = *I;
  1153. if (C.capturesVariable()) {
  1154. SourceLocation Loc = C.getLocation();
  1155. assert(!Field->isBitField() && "lambdas don't have bitfield members!");
  1156. VarDecl *V = C.getCapturedVar();
  1157. StringRef VName = V->getName();
  1158. llvm::DIFile *VUnit = getOrCreateFile(Loc);
  1159. auto Align = getDeclAlignIfRequired(V, CGM.getContext());
  1160. llvm::DIType *FieldType = createFieldType(
  1161. VName, Field->getType(), Loc, Field->getAccess(),
  1162. layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
  1163. elements.push_back(FieldType);
  1164. } else if (C.capturesThis()) {
  1165. // TODO: Need to handle 'this' in some way by probably renaming the
  1166. // this of the lambda class and having a field member of 'this' or
  1167. // by using AT_object_pointer for the function and having that be
  1168. // used as 'this' for semantic references.
  1169. FieldDecl *f = *Field;
  1170. llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
  1171. QualType type = f->getType();
  1172. llvm::DIType *fieldType = createFieldType(
  1173. "this", type, f->getLocation(), f->getAccess(),
  1174. layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
  1175. elements.push_back(fieldType);
  1176. }
  1177. }
  1178. }
  1179. llvm::DIDerivedType *
  1180. CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
  1181. const RecordDecl *RD) {
  1182. // Create the descriptor for the static variable, with or without
  1183. // constant initializers.
  1184. Var = Var->getCanonicalDecl();
  1185. llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
  1186. llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
  1187. unsigned LineNumber = getLineNumber(Var->getLocation());
  1188. StringRef VName = Var->getName();
  1189. llvm::Constant *C = nullptr;
  1190. if (Var->getInit()) {
  1191. const APValue *Value = Var->evaluateValue();
  1192. if (Value) {
  1193. if (Value->isInt())
  1194. C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
  1195. if (Value->isFloat())
  1196. C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
  1197. }
  1198. }
  1199. llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
  1200. auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
  1201. llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
  1202. RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
  1203. StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
  1204. return GV;
  1205. }
  1206. void CGDebugInfo::CollectRecordNormalField(
  1207. const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
  1208. SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
  1209. const RecordDecl *RD) {
  1210. StringRef name = field->getName();
  1211. QualType type = field->getType();
  1212. // Ignore unnamed fields unless they're anonymous structs/unions.
  1213. if (name.empty() && !type->isRecordType())
  1214. return;
  1215. llvm::DIType *FieldType;
  1216. if (field->isBitField()) {
  1217. FieldType = createBitFieldType(field, RecordTy, RD);
  1218. } else {
  1219. auto Align = getDeclAlignIfRequired(field, CGM.getContext());
  1220. FieldType =
  1221. createFieldType(name, type, field->getLocation(), field->getAccess(),
  1222. OffsetInBits, Align, tunit, RecordTy, RD);
  1223. }
  1224. elements.push_back(FieldType);
  1225. }
  1226. void CGDebugInfo::CollectRecordNestedType(
  1227. const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
  1228. QualType Ty = CGM.getContext().getTypeDeclType(TD);
  1229. // Injected class names are not considered nested records.
  1230. if (isa<InjectedClassNameType>(Ty))
  1231. return;
  1232. SourceLocation Loc = TD->getLocation();
  1233. llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
  1234. elements.push_back(nestedType);
  1235. }
  1236. void CGDebugInfo::CollectRecordFields(
  1237. const RecordDecl *record, llvm::DIFile *tunit,
  1238. SmallVectorImpl<llvm::Metadata *> &elements,
  1239. llvm::DICompositeType *RecordTy) {
  1240. const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
  1241. if (CXXDecl && CXXDecl->isLambda())
  1242. CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
  1243. else {
  1244. const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
  1245. // Field number for non-static fields.
  1246. unsigned fieldNo = 0;
  1247. // Static and non-static members should appear in the same order as
  1248. // the corresponding declarations in the source program.
  1249. for (const auto *I : record->decls())
  1250. if (const auto *V = dyn_cast<VarDecl>(I)) {
  1251. if (V->hasAttr<NoDebugAttr>())
  1252. continue;
  1253. // Skip variable template specializations when emitting CodeView. MSVC
  1254. // doesn't emit them.
  1255. if (CGM.getCodeGenOpts().EmitCodeView &&
  1256. isa<VarTemplateSpecializationDecl>(V))
  1257. continue;
  1258. if (isa<VarTemplatePartialSpecializationDecl>(V))
  1259. continue;
  1260. // Reuse the existing static member declaration if one exists
  1261. auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
  1262. if (MI != StaticDataMemberCache.end()) {
  1263. assert(MI->second &&
  1264. "Static data member declaration should still exist");
  1265. elements.push_back(MI->second);
  1266. } else {
  1267. auto Field = CreateRecordStaticField(V, RecordTy, record);
  1268. elements.push_back(Field);
  1269. }
  1270. } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
  1271. CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
  1272. elements, RecordTy, record);
  1273. // Bump field number for next field.
  1274. ++fieldNo;
  1275. } else if (CGM.getCodeGenOpts().EmitCodeView) {
  1276. // Debug info for nested types is included in the member list only for
  1277. // CodeView.
  1278. if (const auto *nestedType = dyn_cast<TypeDecl>(I))
  1279. if (!nestedType->isImplicit() &&
  1280. nestedType->getDeclContext() == record)
  1281. CollectRecordNestedType(nestedType, elements);
  1282. }
  1283. }
  1284. }
  1285. llvm::DISubroutineType *
  1286. CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
  1287. llvm::DIFile *Unit) {
  1288. const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
  1289. if (Method->isStatic())
  1290. return cast_or_null<llvm::DISubroutineType>(
  1291. getOrCreateType(QualType(Func, 0), Unit));
  1292. return getOrCreateInstanceMethodType(Method->getThisType(), Func, Unit);
  1293. }
  1294. llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
  1295. QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
  1296. // Add "this" pointer.
  1297. llvm::DITypeRefArray Args(
  1298. cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
  1299. ->getTypeArray());
  1300. assert(Args.size() && "Invalid number of arguments!");
  1301. SmallVector<llvm::Metadata *, 16> Elts;
  1302. // First element is always return type. For 'void' functions it is NULL.
  1303. Elts.push_back(Args[0]);
  1304. // "this" pointer is always first argument.
  1305. const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
  1306. if (isa<ClassTemplateSpecializationDecl>(RD)) {
  1307. // Create pointer type directly in this case.
  1308. const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
  1309. QualType PointeeTy = ThisPtrTy->getPointeeType();
  1310. unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
  1311. uint64_t Size = CGM.getTarget().getPointerWidth(AS);
  1312. auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
  1313. llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
  1314. llvm::DIType *ThisPtrType =
  1315. DBuilder.createPointerType(PointeeType, Size, Align);
  1316. TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
  1317. // TODO: This and the artificial type below are misleading, the
  1318. // types aren't artificial the argument is, but the current
  1319. // metadata doesn't represent that.
  1320. ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
  1321. Elts.push_back(ThisPtrType);
  1322. } else {
  1323. llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
  1324. TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
  1325. ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
  1326. Elts.push_back(ThisPtrType);
  1327. }
  1328. // Copy rest of the arguments.
  1329. for (unsigned i = 1, e = Args.size(); i != e; ++i)
  1330. Elts.push_back(Args[i]);
  1331. llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
  1332. llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
  1333. if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
  1334. Flags |= llvm::DINode::FlagLValueReference;
  1335. if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
  1336. Flags |= llvm::DINode::FlagRValueReference;
  1337. return DBuilder.createSubroutineType(EltTypeArray, Flags,
  1338. getDwarfCC(Func->getCallConv()));
  1339. }
  1340. /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
  1341. /// inside a function.
  1342. static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
  1343. if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
  1344. return isFunctionLocalClass(NRD);
  1345. if (isa<FunctionDecl>(RD->getDeclContext()))
  1346. return true;
  1347. return false;
  1348. }
  1349. llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
  1350. const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
  1351. bool IsCtorOrDtor =
  1352. isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
  1353. StringRef MethodName = getFunctionName(Method);
  1354. llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
  1355. // Since a single ctor/dtor corresponds to multiple functions, it doesn't
  1356. // make sense to give a single ctor/dtor a linkage name.
  1357. StringRef MethodLinkageName;
  1358. // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
  1359. // property to use here. It may've been intended to model "is non-external
  1360. // type" but misses cases of non-function-local but non-external classes such
  1361. // as those in anonymous namespaces as well as the reverse - external types
  1362. // that are function local, such as those in (non-local) inline functions.
  1363. if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
  1364. MethodLinkageName = CGM.getMangledName(Method);
  1365. // Get the location for the method.
  1366. llvm::DIFile *MethodDefUnit = nullptr;
  1367. unsigned MethodLine = 0;
  1368. if (!Method->isImplicit()) {
  1369. MethodDefUnit = getOrCreateFile(Method->getLocation());
  1370. MethodLine = getLineNumber(Method->getLocation());
  1371. }
  1372. // Collect virtual method info.
  1373. llvm::DIType *ContainingType = nullptr;
  1374. unsigned VIndex = 0;
  1375. llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
  1376. llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
  1377. int ThisAdjustment = 0;
  1378. if (Method->isVirtual()) {
  1379. if (Method->isPure())
  1380. SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;
  1381. else
  1382. SPFlags |= llvm::DISubprogram::SPFlagVirtual;
  1383. if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
  1384. // It doesn't make sense to give a virtual destructor a vtable index,
  1385. // since a single destructor has two entries in the vtable.
  1386. if (!isa<CXXDestructorDecl>(Method))
  1387. VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
  1388. } else {
  1389. // Emit MS ABI vftable information. There is only one entry for the
  1390. // deleting dtor.
  1391. const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
  1392. GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
  1393. MethodVFTableLocation ML =
  1394. CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
  1395. VIndex = ML.Index;
  1396. // CodeView only records the vftable offset in the class that introduces
  1397. // the virtual method. This is possible because, unlike Itanium, the MS
  1398. // C++ ABI does not include all virtual methods from non-primary bases in
  1399. // the vtable for the most derived class. For example, if C inherits from
  1400. // A and B, C's primary vftable will not include B's virtual methods.
  1401. if (Method->size_overridden_methods() == 0)
  1402. Flags |= llvm::DINode::FlagIntroducedVirtual;
  1403. // The 'this' adjustment accounts for both the virtual and non-virtual
  1404. // portions of the adjustment. Presumably the debugger only uses it when
  1405. // it knows the dynamic type of an object.
  1406. ThisAdjustment = CGM.getCXXABI()
  1407. .getVirtualFunctionPrologueThisAdjustment(GD)
  1408. .getQuantity();
  1409. }
  1410. ContainingType = RecordTy;
  1411. }
  1412. if (Method->isNoReturn())
  1413. Flags |= llvm::DINode::FlagNoReturn;
  1414. if (Method->isStatic())
  1415. Flags |= llvm::DINode::FlagStaticMember;
  1416. if (Method->isImplicit())
  1417. Flags |= llvm::DINode::FlagArtificial;
  1418. Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
  1419. if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
  1420. if (CXXC->isExplicit())
  1421. Flags |= llvm::DINode::FlagExplicit;
  1422. } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
  1423. if (CXXC->isExplicit())
  1424. Flags |= llvm::DINode::FlagExplicit;
  1425. }
  1426. if (Method->hasPrototype())
  1427. Flags |= llvm::DINode::FlagPrototyped;
  1428. if (Method->getRefQualifier() == RQ_LValue)
  1429. Flags |= llvm::DINode::FlagLValueReference;
  1430. if (Method->getRefQualifier() == RQ_RValue)
  1431. Flags |= llvm::DINode::FlagRValueReference;
  1432. if (CGM.getLangOpts().Optimize)
  1433. SPFlags |= llvm::DISubprogram::SPFlagOptimized;
  1434. llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
  1435. llvm::DISubprogram *SP = DBuilder.createMethod(
  1436. RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
  1437. MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
  1438. TParamsArray.get());
  1439. SPCache[Method->getCanonicalDecl()].reset(SP);
  1440. return SP;
  1441. }
  1442. void CGDebugInfo::CollectCXXMemberFunctions(
  1443. const CXXRecordDecl *RD, llvm::DIFile *Unit,
  1444. SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
  1445. // Since we want more than just the individual member decls if we
  1446. // have templated functions iterate over every declaration to gather
  1447. // the functions.
  1448. for (const auto *I : RD->decls()) {
  1449. const auto *Method = dyn_cast<CXXMethodDecl>(I);
  1450. // If the member is implicit, don't add it to the member list. This avoids
  1451. // the member being added to type units by LLVM, while still allowing it
  1452. // to be emitted into the type declaration/reference inside the compile
  1453. // unit.
  1454. // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
  1455. // FIXME: Handle Using(Shadow?)Decls here to create
  1456. // DW_TAG_imported_declarations inside the class for base decls brought into
  1457. // derived classes. GDB doesn't seem to notice/leverage these when I tried
  1458. // it, so I'm not rushing to fix this. (GCC seems to produce them, if
  1459. // referenced)
  1460. if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
  1461. continue;
  1462. if (Method->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
  1463. continue;
  1464. // Reuse the existing member function declaration if it exists.
  1465. // It may be associated with the declaration of the type & should be
  1466. // reused as we're building the definition.
  1467. //
  1468. // This situation can arise in the vtable-based debug info reduction where
  1469. // implicit members are emitted in a non-vtable TU.
  1470. auto MI = SPCache.find(Method->getCanonicalDecl());
  1471. EltTys.push_back(MI == SPCache.end()
  1472. ? CreateCXXMemberFunction(Method, Unit, RecordTy)
  1473. : static_cast<llvm::Metadata *>(MI->second));
  1474. }
  1475. }
  1476. void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
  1477. SmallVectorImpl<llvm::Metadata *> &EltTys,
  1478. llvm::DIType *RecordTy) {
  1479. llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
  1480. CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
  1481. llvm::DINode::FlagZero);
  1482. // If we are generating CodeView debug info, we also need to emit records for
  1483. // indirect virtual base classes.
  1484. if (CGM.getCodeGenOpts().EmitCodeView) {
  1485. CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
  1486. llvm::DINode::FlagIndirectVirtualBase);
  1487. }
  1488. }
  1489. void CGDebugInfo::CollectCXXBasesAux(
  1490. const CXXRecordDecl *RD, llvm::DIFile *Unit,
  1491. SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
  1492. const CXXRecordDecl::base_class_const_range &Bases,
  1493. llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
  1494. llvm::DINode::DIFlags StartingFlags) {
  1495. const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
  1496. for (const auto &BI : Bases) {
  1497. const auto *Base =
  1498. cast<CXXRecordDecl>(BI.getType()->castAs<RecordType>()->getDecl());
  1499. if (!SeenTypes.insert(Base).second)
  1500. continue;
  1501. auto *BaseTy = getOrCreateType(BI.getType(), Unit);
  1502. llvm::DINode::DIFlags BFlags = StartingFlags;
  1503. uint64_t BaseOffset;
  1504. uint32_t VBPtrOffset = 0;
  1505. if (BI.isVirtual()) {
  1506. if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
  1507. // virtual base offset offset is -ve. The code generator emits dwarf
  1508. // expression where it expects +ve number.
  1509. BaseOffset = 0 - CGM.getItaniumVTableContext()
  1510. .getVirtualBaseOffsetOffset(RD, Base)
  1511. .getQuantity();
  1512. } else {
  1513. // In the MS ABI, store the vbtable offset, which is analogous to the
  1514. // vbase offset offset in Itanium.
  1515. BaseOffset =
  1516. 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
  1517. VBPtrOffset = CGM.getContext()
  1518. .getASTRecordLayout(RD)
  1519. .getVBPtrOffset()
  1520. .getQuantity();
  1521. }
  1522. BFlags |= llvm::DINode::FlagVirtual;
  1523. } else
  1524. BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
  1525. // FIXME: Inconsistent units for BaseOffset. It is in bytes when
  1526. // BI->isVirtual() and bits when not.
  1527. BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
  1528. llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
  1529. VBPtrOffset, BFlags);
  1530. EltTys.push_back(DTy);
  1531. }
  1532. }
  1533. llvm::DINodeArray
  1534. CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
  1535. ArrayRef<TemplateArgument> TAList,
  1536. llvm::DIFile *Unit) {
  1537. SmallVector<llvm::Metadata *, 16> TemplateParams;
  1538. for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
  1539. const TemplateArgument &TA = TAList[i];
  1540. StringRef Name;
  1541. if (TPList)
  1542. Name = TPList->getParam(i)->getName();
  1543. switch (TA.getKind()) {
  1544. case TemplateArgument::Type: {
  1545. llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
  1546. TemplateParams.push_back(
  1547. DBuilder.createTemplateTypeParameter(TheCU, Name, TTy));
  1548. } break;
  1549. case TemplateArgument::Integral: {
  1550. llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
  1551. TemplateParams.push_back(DBuilder.createTemplateValueParameter(
  1552. TheCU, Name, TTy,
  1553. llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
  1554. } break;
  1555. case TemplateArgument::Declaration: {
  1556. const ValueDecl *D = TA.getAsDecl();
  1557. QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
  1558. llvm::DIType *TTy = getOrCreateType(T, Unit);
  1559. llvm::Constant *V = nullptr;
  1560. // Skip retrieve the value if that template parameter has cuda device
  1561. // attribute, i.e. that value is not available at the host side.
  1562. if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice ||
  1563. !D->hasAttr<CUDADeviceAttr>()) {
  1564. const CXXMethodDecl *MD;
  1565. // Variable pointer template parameters have a value that is the address
  1566. // of the variable.
  1567. if (const auto *VD = dyn_cast<VarDecl>(D))
  1568. V = CGM.GetAddrOfGlobalVar(VD);
  1569. // Member function pointers have special support for building them,
  1570. // though this is currently unsupported in LLVM CodeGen.
  1571. else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
  1572. V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
  1573. else if (const auto *FD = dyn_cast<FunctionDecl>(D))
  1574. V = CGM.GetAddrOfFunction(FD);
  1575. // Member data pointers have special handling too to compute the fixed
  1576. // offset within the object.
  1577. else if (const auto *MPT =
  1578. dyn_cast<MemberPointerType>(T.getTypePtr())) {
  1579. // These five lines (& possibly the above member function pointer
  1580. // handling) might be able to be refactored to use similar code in
  1581. // CodeGenModule::getMemberPointerConstant
  1582. uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
  1583. CharUnits chars =
  1584. CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
  1585. V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
  1586. }
  1587. assert(V && "Failed to find template parameter pointer");
  1588. V = V->stripPointerCasts();
  1589. }
  1590. TemplateParams.push_back(DBuilder.createTemplateValueParameter(
  1591. TheCU, Name, TTy, cast_or_null<llvm::Constant>(V)));
  1592. } break;
  1593. case TemplateArgument::NullPtr: {
  1594. QualType T = TA.getNullPtrType();
  1595. llvm::DIType *TTy = getOrCreateType(T, Unit);
  1596. llvm::Constant *V = nullptr;
  1597. // Special case member data pointer null values since they're actually -1
  1598. // instead of zero.
  1599. if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
  1600. // But treat member function pointers as simple zero integers because
  1601. // it's easier than having a special case in LLVM's CodeGen. If LLVM
  1602. // CodeGen grows handling for values of non-null member function
  1603. // pointers then perhaps we could remove this special case and rely on
  1604. // EmitNullMemberPointer for member function pointers.
  1605. if (MPT->isMemberDataPointer())
  1606. V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
  1607. if (!V)
  1608. V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
  1609. TemplateParams.push_back(
  1610. DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V));
  1611. } break;
  1612. case TemplateArgument::Template:
  1613. TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
  1614. TheCU, Name, nullptr,
  1615. TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
  1616. break;
  1617. case TemplateArgument::Pack:
  1618. TemplateParams.push_back(DBuilder.createTemplateParameterPack(
  1619. TheCU, Name, nullptr,
  1620. CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
  1621. break;
  1622. case TemplateArgument::Expression: {
  1623. const Expr *E = TA.getAsExpr();
  1624. QualType T = E->getType();
  1625. if (E->isGLValue())
  1626. T = CGM.getContext().getLValueReferenceType(T);
  1627. llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
  1628. assert(V && "Expression in template argument isn't constant");
  1629. llvm::DIType *TTy = getOrCreateType(T, Unit);
  1630. TemplateParams.push_back(DBuilder.createTemplateValueParameter(
  1631. TheCU, Name, TTy, V->stripPointerCasts()));
  1632. } break;
  1633. // And the following should never occur:
  1634. case TemplateArgument::TemplateExpansion:
  1635. case TemplateArgument::Null:
  1636. llvm_unreachable(
  1637. "These argument types shouldn't exist in concrete types");
  1638. }
  1639. }
  1640. return DBuilder.getOrCreateArray(TemplateParams);
  1641. }
  1642. llvm::DINodeArray
  1643. CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
  1644. llvm::DIFile *Unit) {
  1645. if (FD->getTemplatedKind() ==
  1646. FunctionDecl::TK_FunctionTemplateSpecialization) {
  1647. const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
  1648. ->getTemplate()
  1649. ->getTemplateParameters();
  1650. return CollectTemplateParams(
  1651. TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
  1652. }
  1653. return llvm::DINodeArray();
  1654. }
  1655. llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
  1656. llvm::DIFile *Unit) {
  1657. // Always get the full list of parameters, not just the ones from the
  1658. // specialization. A partial specialization may have fewer parameters than
  1659. // there are arguments.
  1660. auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VL);
  1661. if (!TS)
  1662. return llvm::DINodeArray();
  1663. VarTemplateDecl *T = TS->getSpecializedTemplate();
  1664. const TemplateParameterList *TList = T->getTemplateParameters();
  1665. auto TA = TS->getTemplateArgs().asArray();
  1666. return CollectTemplateParams(TList, TA, Unit);
  1667. }
  1668. llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
  1669. const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
  1670. // Always get the full list of parameters, not just the ones from the
  1671. // specialization. A partial specialization may have fewer parameters than
  1672. // there are arguments.
  1673. TemplateParameterList *TPList =
  1674. TSpecial->getSpecializedTemplate()->getTemplateParameters();
  1675. const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
  1676. return CollectTemplateParams(TPList, TAList.asArray(), Unit);
  1677. }
  1678. llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
  1679. if (VTablePtrType)
  1680. return VTablePtrType;
  1681. ASTContext &Context = CGM.getContext();
  1682. /* Function type */
  1683. llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
  1684. llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
  1685. llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
  1686. unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
  1687. unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
  1688. Optional<unsigned> DWARFAddressSpace =
  1689. CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
  1690. llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
  1691. SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
  1692. VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
  1693. return VTablePtrType;
  1694. }
  1695. StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
  1696. // Copy the gdb compatible name on the side and use its reference.
  1697. return internString("_vptr$", RD->getNameAsString());
  1698. }
  1699. StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
  1700. DynamicInitKind StubKind,
  1701. llvm::Function *InitFn) {
  1702. // If we're not emitting codeview, use the mangled name. For Itanium, this is
  1703. // arbitrary.
  1704. if (!CGM.getCodeGenOpts().EmitCodeView)
  1705. return InitFn->getName();
  1706. // Print the normal qualified name for the variable, then break off the last
  1707. // NNS, and add the appropriate other text. Clang always prints the global
  1708. // variable name without template arguments, so we can use rsplit("::") and
  1709. // then recombine the pieces.
  1710. SmallString<128> QualifiedGV;
  1711. StringRef Quals;
  1712. StringRef GVName;
  1713. {
  1714. llvm::raw_svector_ostream OS(QualifiedGV);
  1715. VD->printQualifiedName(OS, getPrintingPolicy());
  1716. std::tie(Quals, GVName) = OS.str().rsplit("::");
  1717. if (GVName.empty())
  1718. std::swap(Quals, GVName);
  1719. }
  1720. SmallString<128> InitName;
  1721. llvm::raw_svector_ostream OS(InitName);
  1722. if (!Quals.empty())
  1723. OS << Quals << "::";
  1724. switch (StubKind) {
  1725. case DynamicInitKind::NoStub:
  1726. llvm_unreachable("not an initializer");
  1727. case DynamicInitKind::Initializer:
  1728. OS << "`dynamic initializer for '";
  1729. break;
  1730. case DynamicInitKind::AtExit:
  1731. OS << "`dynamic atexit destructor for '";
  1732. break;
  1733. }
  1734. OS << GVName;
  1735. // Add any template specialization args.
  1736. if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
  1737. printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),
  1738. getPrintingPolicy());
  1739. }
  1740. OS << '\'';
  1741. return internString(OS.str());
  1742. }
  1743. void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
  1744. SmallVectorImpl<llvm::Metadata *> &EltTys,
  1745. llvm::DICompositeType *RecordTy) {
  1746. // If this class is not dynamic then there is not any vtable info to collect.
  1747. if (!RD->isDynamicClass())
  1748. return;
  1749. // Don't emit any vtable shape or vptr info if this class doesn't have an
  1750. // extendable vfptr. This can happen if the class doesn't have virtual
  1751. // methods, or in the MS ABI if those virtual methods only come from virtually
  1752. // inherited bases.
  1753. const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
  1754. if (!RL.hasExtendableVFPtr())
  1755. return;
  1756. // CodeView needs to know how large the vtable of every dynamic class is, so
  1757. // emit a special named pointer type into the element list. The vptr type
  1758. // points to this type as well.
  1759. llvm::DIType *VPtrTy = nullptr;
  1760. bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
  1761. CGM.getTarget().getCXXABI().isMicrosoft();
  1762. if (NeedVTableShape) {
  1763. uint64_t PtrWidth =
  1764. CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
  1765. const VTableLayout &VFTLayout =
  1766. CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
  1767. unsigned VSlotCount =
  1768. VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
  1769. unsigned VTableWidth = PtrWidth * VSlotCount;
  1770. unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
  1771. Optional<unsigned> DWARFAddressSpace =
  1772. CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
  1773. // Create a very wide void* type and insert it directly in the element list.
  1774. llvm::DIType *VTableType = DBuilder.createPointerType(
  1775. nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
  1776. EltTys.push_back(VTableType);
  1777. // The vptr is a pointer to this special vtable type.
  1778. VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
  1779. }
  1780. // If there is a primary base then the artificial vptr member lives there.
  1781. if (RL.getPrimaryBase())
  1782. return;
  1783. if (!VPtrTy)
  1784. VPtrTy = getOrCreateVTablePtrType(Unit);
  1785. unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
  1786. llvm::DIType *VPtrMember =
  1787. DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
  1788. llvm::DINode::FlagArtificial, VPtrTy);
  1789. EltTys.push_back(VPtrMember);
  1790. }
  1791. llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
  1792. SourceLocation Loc) {
  1793. assert(DebugKind >= codegenoptions::LimitedDebugInfo);
  1794. llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
  1795. return T;
  1796. }
  1797. llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
  1798. SourceLocation Loc) {
  1799. return getOrCreateStandaloneType(D, Loc);
  1800. }
  1801. llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
  1802. SourceLocation Loc) {
  1803. assert(DebugKind >= codegenoptions::LimitedDebugInfo);
  1804. assert(!D.isNull() && "null type");
  1805. llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
  1806. assert(T && "could not create debug info for type");
  1807. RetainedTypes.push_back(D.getAsOpaquePtr());
  1808. return T;
  1809. }
  1810. void CGDebugInfo::addHeapAllocSiteMetadata(llvm::Instruction *CI,
  1811. QualType D,
  1812. SourceLocation Loc) {
  1813. llvm::MDNode *node;
  1814. if (D.getTypePtr()->isVoidPointerType()) {
  1815. node = llvm::MDNode::get(CGM.getLLVMContext(), None);
  1816. } else {
  1817. QualType PointeeTy = D.getTypePtr()->getPointeeType();
  1818. node = getOrCreateType(PointeeTy, getOrCreateFile(Loc));
  1819. }
  1820. CI->setMetadata("heapallocsite", node);
  1821. }
  1822. void CGDebugInfo::completeType(const EnumDecl *ED) {
  1823. if (DebugKind <= codegenoptions::DebugLineTablesOnly)
  1824. return;
  1825. QualType Ty = CGM.getContext().getEnumType(ED);
  1826. void *TyPtr = Ty.getAsOpaquePtr();
  1827. auto I = TypeCache.find(TyPtr);
  1828. if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
  1829. return;
  1830. llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
  1831. assert(!Res->isForwardDecl());
  1832. TypeCache[TyPtr].reset(Res);
  1833. }
  1834. void CGDebugInfo::completeType(const RecordDecl *RD) {
  1835. if (DebugKind > codegenoptions::LimitedDebugInfo ||
  1836. !CGM.getLangOpts().CPlusPlus)
  1837. completeRequiredType(RD);
  1838. }
  1839. /// Return true if the class or any of its methods are marked dllimport.
  1840. static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
  1841. if (RD->hasAttr<DLLImportAttr>())
  1842. return true;
  1843. for (const CXXMethodDecl *MD : RD->methods())
  1844. if (MD->hasAttr<DLLImportAttr>())
  1845. return true;
  1846. return false;
  1847. }
  1848. /// Does a type definition exist in an imported clang module?
  1849. static bool isDefinedInClangModule(const RecordDecl *RD) {
  1850. // Only definitions that where imported from an AST file come from a module.
  1851. if (!RD || !RD->isFromASTFile())
  1852. return false;
  1853. // Anonymous entities cannot be addressed. Treat them as not from module.
  1854. if (!RD->isExternallyVisible() && RD->getName().empty())
  1855. return false;
  1856. if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
  1857. if (!CXXDecl->isCompleteDefinition())
  1858. return false;
  1859. // Check wether RD is a template.
  1860. auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
  1861. if (TemplateKind != TSK_Undeclared) {
  1862. // Unfortunately getOwningModule() isn't accurate enough to find the
  1863. // owning module of a ClassTemplateSpecializationDecl that is inside a
  1864. // namespace spanning multiple modules.
  1865. bool Explicit = false;
  1866. if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
  1867. Explicit = TD->isExplicitInstantiationOrSpecialization();
  1868. if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
  1869. return false;
  1870. // This is a template, check the origin of the first member.
  1871. if (CXXDecl->field_begin() == CXXDecl->field_end())
  1872. return TemplateKind == TSK_ExplicitInstantiationDeclaration;
  1873. if (!CXXDecl->field_begin()->isFromASTFile())
  1874. return false;
  1875. }
  1876. }
  1877. return true;
  1878. }
  1879. void CGDebugInfo::completeClassData(const RecordDecl *RD) {
  1880. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  1881. if (CXXRD->isDynamicClass() &&
  1882. CGM.getVTableLinkage(CXXRD) ==
  1883. llvm::GlobalValue::AvailableExternallyLinkage &&
  1884. !isClassOrMethodDLLImport(CXXRD))
  1885. return;
  1886. if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
  1887. return;
  1888. completeClass(RD);
  1889. }
  1890. void CGDebugInfo::completeClass(const RecordDecl *RD) {
  1891. if (DebugKind <= codegenoptions::DebugLineTablesOnly)
  1892. return;
  1893. QualType Ty = CGM.getContext().getRecordType(RD);
  1894. void *TyPtr = Ty.getAsOpaquePtr();
  1895. auto I = TypeCache.find(TyPtr);
  1896. if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
  1897. return;
  1898. llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
  1899. assert(!Res->isForwardDecl());
  1900. TypeCache[TyPtr].reset(Res);
  1901. }
  1902. static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
  1903. CXXRecordDecl::method_iterator End) {
  1904. for (CXXMethodDecl *MD : llvm::make_range(I, End))
  1905. if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())
  1906. if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
  1907. !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
  1908. return true;
  1909. return false;
  1910. }
  1911. static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind,
  1912. bool DebugTypeExtRefs, const RecordDecl *RD,
  1913. const LangOptions &LangOpts) {
  1914. if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
  1915. return true;
  1916. if (auto *ES = RD->getASTContext().getExternalSource())
  1917. if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
  1918. return true;
  1919. if (DebugKind > codegenoptions::LimitedDebugInfo)
  1920. return false;
  1921. if (!LangOpts.CPlusPlus)
  1922. return false;
  1923. if (!RD->isCompleteDefinitionRequired())
  1924. return true;
  1925. const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
  1926. if (!CXXDecl)
  1927. return false;
  1928. // Only emit complete debug info for a dynamic class when its vtable is
  1929. // emitted. However, Microsoft debuggers don't resolve type information
  1930. // across DLL boundaries, so skip this optimization if the class or any of its
  1931. // methods are marked dllimport. This isn't a complete solution, since objects
  1932. // without any dllimport methods can be used in one DLL and constructed in
  1933. // another, but it is the current behavior of LimitedDebugInfo.
  1934. if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
  1935. !isClassOrMethodDLLImport(CXXDecl))
  1936. return true;
  1937. TemplateSpecializationKind Spec = TSK_Undeclared;
  1938. if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
  1939. Spec = SD->getSpecializationKind();
  1940. if (Spec == TSK_ExplicitInstantiationDeclaration &&
  1941. hasExplicitMemberDefinition(CXXDecl->method_begin(),
  1942. CXXDecl->method_end()))
  1943. return true;
  1944. return false;
  1945. }
  1946. void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
  1947. if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
  1948. return;
  1949. QualType Ty = CGM.getContext().getRecordType(RD);
  1950. llvm::DIType *T = getTypeOrNull(Ty);
  1951. if (T && T->isForwardDecl())
  1952. completeClassData(RD);
  1953. }
  1954. llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
  1955. RecordDecl *RD = Ty->getDecl();
  1956. llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
  1957. if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
  1958. CGM.getLangOpts())) {
  1959. if (!T)
  1960. T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
  1961. return T;
  1962. }
  1963. return CreateTypeDefinition(Ty);
  1964. }
  1965. llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
  1966. RecordDecl *RD = Ty->getDecl();
  1967. // Get overall information about the record type for the debug info.
  1968. llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
  1969. // Records and classes and unions can all be recursive. To handle them, we
  1970. // first generate a debug descriptor for the struct as a forward declaration.
  1971. // Then (if it is a definition) we go through and get debug info for all of
  1972. // its members. Finally, we create a descriptor for the complete type (which
  1973. // may refer to the forward decl if the struct is recursive) and replace all
  1974. // uses of the forward declaration with the final definition.
  1975. llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
  1976. const RecordDecl *D = RD->getDefinition();
  1977. if (!D || !D->isCompleteDefinition())
  1978. return FwdDecl;
  1979. if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
  1980. CollectContainingType(CXXDecl, FwdDecl);
  1981. // Push the struct on region stack.
  1982. LexicalBlockStack.emplace_back(&*FwdDecl);
  1983. RegionMap[Ty->getDecl()].reset(FwdDecl);
  1984. // Convert all the elements.
  1985. SmallVector<llvm::Metadata *, 16> EltTys;
  1986. // what about nested types?
  1987. // Note: The split of CXXDecl information here is intentional, the
  1988. // gdb tests will depend on a certain ordering at printout. The debug
  1989. // information offsets are still correct if we merge them all together
  1990. // though.
  1991. const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
  1992. if (CXXDecl) {
  1993. CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
  1994. CollectVTableInfo(CXXDecl, DefUnit, EltTys, FwdDecl);
  1995. }
  1996. // Collect data fields (including static variables and any initializers).
  1997. CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
  1998. if (CXXDecl)
  1999. CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
  2000. LexicalBlockStack.pop_back();
  2001. RegionMap.erase(Ty->getDecl());
  2002. llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
  2003. DBuilder.replaceArrays(FwdDecl, Elements);
  2004. if (FwdDecl->isTemporary())
  2005. FwdDecl =
  2006. llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
  2007. RegionMap[Ty->getDecl()].reset(FwdDecl);
  2008. return FwdDecl;
  2009. }
  2010. llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
  2011. llvm::DIFile *Unit) {
  2012. // Ignore protocols.
  2013. return getOrCreateType(Ty->getBaseType(), Unit);
  2014. }
  2015. llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
  2016. llvm::DIFile *Unit) {
  2017. // Ignore protocols.
  2018. SourceLocation Loc = Ty->getDecl()->getLocation();
  2019. // Use Typedefs to represent ObjCTypeParamType.
  2020. return DBuilder.createTypedef(
  2021. getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
  2022. Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
  2023. getDeclContextDescriptor(Ty->getDecl()));
  2024. }
  2025. /// \return true if Getter has the default name for the property PD.
  2026. static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
  2027. const ObjCMethodDecl *Getter) {
  2028. assert(PD);
  2029. if (!Getter)
  2030. return true;
  2031. assert(Getter->getDeclName().isObjCZeroArgSelector());
  2032. return PD->getName() ==
  2033. Getter->getDeclName().getObjCSelector().getNameForSlot(0);
  2034. }
  2035. /// \return true if Setter has the default name for the property PD.
  2036. static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
  2037. const ObjCMethodDecl *Setter) {
  2038. assert(PD);
  2039. if (!Setter)
  2040. return true;
  2041. assert(Setter->getDeclName().isObjCOneArgSelector());
  2042. return SelectorTable::constructSetterName(PD->getName()) ==
  2043. Setter->getDeclName().getObjCSelector().getNameForSlot(0);
  2044. }
  2045. llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
  2046. llvm::DIFile *Unit) {
  2047. ObjCInterfaceDecl *ID = Ty->getDecl();
  2048. if (!ID)
  2049. return nullptr;
  2050. // Return a forward declaration if this type was imported from a clang module,
  2051. // and this is not the compile unit with the implementation of the type (which
  2052. // may contain hidden ivars).
  2053. if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
  2054. !ID->getImplementation())
  2055. return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
  2056. ID->getName(),
  2057. getDeclContextDescriptor(ID), Unit, 0);
  2058. // Get overall information about the record type for the debug info.
  2059. llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
  2060. unsigned Line = getLineNumber(ID->getLocation());
  2061. auto RuntimeLang =
  2062. static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
  2063. // If this is just a forward declaration return a special forward-declaration
  2064. // debug type since we won't be able to lay out the entire type.
  2065. ObjCInterfaceDecl *Def = ID->getDefinition();
  2066. if (!Def || !Def->getImplementation()) {
  2067. llvm::DIScope *Mod = getParentModuleOrNull(ID);
  2068. llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
  2069. llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
  2070. DefUnit, Line, RuntimeLang);
  2071. ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
  2072. return FwdDecl;
  2073. }
  2074. return CreateTypeDefinition(Ty, Unit);
  2075. }
  2076. llvm::DIModule *
  2077. CGDebugInfo::getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod,
  2078. bool CreateSkeletonCU) {
  2079. // Use the Module pointer as the key into the cache. This is a
  2080. // nullptr if the "Module" is a PCH, which is safe because we don't
  2081. // support chained PCH debug info, so there can only be a single PCH.
  2082. const Module *M = Mod.getModuleOrNull();
  2083. auto ModRef = ModuleCache.find(M);
  2084. if (ModRef != ModuleCache.end())
  2085. return cast<llvm::DIModule>(ModRef->second);
  2086. // Macro definitions that were defined with "-D" on the command line.
  2087. SmallString<128> ConfigMacros;
  2088. {
  2089. llvm::raw_svector_ostream OS(ConfigMacros);
  2090. const auto &PPOpts = CGM.getPreprocessorOpts();
  2091. unsigned I = 0;
  2092. // Translate the macro definitions back into a command line.
  2093. for (auto &M : PPOpts.Macros) {
  2094. if (++I > 1)
  2095. OS << " ";
  2096. const std::string &Macro = M.first;
  2097. bool Undef = M.second;
  2098. OS << "\"-" << (Undef ? 'U' : 'D');
  2099. for (char c : Macro)
  2100. switch (c) {
  2101. case '\\':
  2102. OS << "\\\\";
  2103. break;
  2104. case '"':
  2105. OS << "\\\"";
  2106. break;
  2107. default:
  2108. OS << c;
  2109. }
  2110. OS << '\"';
  2111. }
  2112. }
  2113. bool IsRootModule = M ? !M->Parent : true;
  2114. // When a module name is specified as -fmodule-name, that module gets a
  2115. // clang::Module object, but it won't actually be built or imported; it will
  2116. // be textual.
  2117. if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)
  2118. assert(StringRef(M->Name).startswith(CGM.getLangOpts().ModuleName) &&
  2119. "clang module without ASTFile must be specified by -fmodule-name");
  2120. if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {
  2121. // PCH files don't have a signature field in the control block,
  2122. // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
  2123. // We use the lower 64 bits for debug info.
  2124. uint64_t Signature =
  2125. Mod.getSignature()
  2126. ? (uint64_t)Mod.getSignature()[1] << 32 | Mod.getSignature()[0]
  2127. : ~1ULL;
  2128. llvm::DIBuilder DIB(CGM.getModule());
  2129. DIB.createCompileUnit(TheCU->getSourceLanguage(),
  2130. // TODO: Support "Source" from external AST providers?
  2131. DIB.createFile(Mod.getModuleName(), Mod.getPath()),
  2132. TheCU->getProducer(), true, StringRef(), 0,
  2133. Mod.getASTFile(), llvm::DICompileUnit::FullDebug,
  2134. Signature);
  2135. DIB.finalize();
  2136. }
  2137. llvm::DIModule *Parent =
  2138. IsRootModule ? nullptr
  2139. : getOrCreateModuleRef(
  2140. ExternalASTSource::ASTSourceDescriptor(*M->Parent),
  2141. CreateSkeletonCU);
  2142. llvm::DIModule *DIMod =
  2143. DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
  2144. Mod.getPath(), CGM.getHeaderSearchOpts().Sysroot);
  2145. ModuleCache[M].reset(DIMod);
  2146. return DIMod;
  2147. }
  2148. llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
  2149. llvm::DIFile *Unit) {
  2150. ObjCInterfaceDecl *ID = Ty->getDecl();
  2151. llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
  2152. unsigned Line = getLineNumber(ID->getLocation());
  2153. unsigned RuntimeLang = TheCU->getSourceLanguage();
  2154. // Bit size, align and offset of the type.
  2155. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  2156. auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
  2157. llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
  2158. if (ID->getImplementation())
  2159. Flags |= llvm::DINode::FlagObjcClassComplete;
  2160. llvm::DIScope *Mod = getParentModuleOrNull(ID);
  2161. llvm::DICompositeType *RealDecl = DBuilder.createStructType(
  2162. Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
  2163. nullptr, llvm::DINodeArray(), RuntimeLang);
  2164. QualType QTy(Ty, 0);
  2165. TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
  2166. // Push the struct on region stack.
  2167. LexicalBlockStack.emplace_back(RealDecl);
  2168. RegionMap[Ty->getDecl()].reset(RealDecl);
  2169. // Convert all the elements.
  2170. SmallVector<llvm::Metadata *, 16> EltTys;
  2171. ObjCInterfaceDecl *SClass = ID->getSuperClass();
  2172. if (SClass) {
  2173. llvm::DIType *SClassTy =
  2174. getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
  2175. if (!SClassTy)
  2176. return nullptr;
  2177. llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
  2178. llvm::DINode::FlagZero);
  2179. EltTys.push_back(InhTag);
  2180. }
  2181. // Create entries for all of the properties.
  2182. auto AddProperty = [&](const ObjCPropertyDecl *PD) {
  2183. SourceLocation Loc = PD->getLocation();
  2184. llvm::DIFile *PUnit = getOrCreateFile(Loc);
  2185. unsigned PLine = getLineNumber(Loc);
  2186. ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
  2187. ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
  2188. llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
  2189. PD->getName(), PUnit, PLine,
  2190. hasDefaultGetterName(PD, Getter) ? ""
  2191. : getSelectorName(PD->getGetterName()),
  2192. hasDefaultSetterName(PD, Setter) ? ""
  2193. : getSelectorName(PD->getSetterName()),
  2194. PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
  2195. EltTys.push_back(PropertyNode);
  2196. };
  2197. {
  2198. llvm::SmallPtrSet<const IdentifierInfo *, 16> PropertySet;
  2199. for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
  2200. for (auto *PD : ClassExt->properties()) {
  2201. PropertySet.insert(PD->getIdentifier());
  2202. AddProperty(PD);
  2203. }
  2204. for (const auto *PD : ID->properties()) {
  2205. // Don't emit duplicate metadata for properties that were already in a
  2206. // class extension.
  2207. if (!PropertySet.insert(PD->getIdentifier()).second)
  2208. continue;
  2209. AddProperty(PD);
  2210. }
  2211. }
  2212. const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
  2213. unsigned FieldNo = 0;
  2214. for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
  2215. Field = Field->getNextIvar(), ++FieldNo) {
  2216. llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
  2217. if (!FieldTy)
  2218. return nullptr;
  2219. StringRef FieldName = Field->getName();
  2220. // Ignore unnamed fields.
  2221. if (FieldName.empty())
  2222. continue;
  2223. // Get the location for the field.
  2224. llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
  2225. unsigned FieldLine = getLineNumber(Field->getLocation());
  2226. QualType FType = Field->getType();
  2227. uint64_t FieldSize = 0;
  2228. uint32_t FieldAlign = 0;
  2229. if (!FType->isIncompleteArrayType()) {
  2230. // Bit size, align and offset of the type.
  2231. FieldSize = Field->isBitField()
  2232. ? Field->getBitWidthValue(CGM.getContext())
  2233. : CGM.getContext().getTypeSize(FType);
  2234. FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
  2235. }
  2236. uint64_t FieldOffset;
  2237. if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
  2238. // We don't know the runtime offset of an ivar if we're using the
  2239. // non-fragile ABI. For bitfields, use the bit offset into the first
  2240. // byte of storage of the bitfield. For other fields, use zero.
  2241. if (Field->isBitField()) {
  2242. FieldOffset =
  2243. CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
  2244. FieldOffset %= CGM.getContext().getCharWidth();
  2245. } else {
  2246. FieldOffset = 0;
  2247. }
  2248. } else {
  2249. FieldOffset = RL.getFieldOffset(FieldNo);
  2250. }
  2251. llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
  2252. if (Field->getAccessControl() == ObjCIvarDecl::Protected)
  2253. Flags = llvm::DINode::FlagProtected;
  2254. else if (Field->getAccessControl() == ObjCIvarDecl::Private)
  2255. Flags = llvm::DINode::FlagPrivate;
  2256. else if (Field->getAccessControl() == ObjCIvarDecl::Public)
  2257. Flags = llvm::DINode::FlagPublic;
  2258. llvm::MDNode *PropertyNode = nullptr;
  2259. if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
  2260. if (ObjCPropertyImplDecl *PImpD =
  2261. ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
  2262. if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
  2263. SourceLocation Loc = PD->getLocation();
  2264. llvm::DIFile *PUnit = getOrCreateFile(Loc);
  2265. unsigned PLine = getLineNumber(Loc);
  2266. ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
  2267. ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
  2268. PropertyNode = DBuilder.createObjCProperty(
  2269. PD->getName(), PUnit, PLine,
  2270. hasDefaultGetterName(PD, Getter)
  2271. ? ""
  2272. : getSelectorName(PD->getGetterName()),
  2273. hasDefaultSetterName(PD, Setter)
  2274. ? ""
  2275. : getSelectorName(PD->getSetterName()),
  2276. PD->getPropertyAttributes(),
  2277. getOrCreateType(PD->getType(), PUnit));
  2278. }
  2279. }
  2280. }
  2281. FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
  2282. FieldSize, FieldAlign, FieldOffset, Flags,
  2283. FieldTy, PropertyNode);
  2284. EltTys.push_back(FieldTy);
  2285. }
  2286. llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
  2287. DBuilder.replaceArrays(RealDecl, Elements);
  2288. LexicalBlockStack.pop_back();
  2289. return RealDecl;
  2290. }
  2291. llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
  2292. llvm::DIFile *Unit) {
  2293. llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
  2294. int64_t Count = Ty->getNumElements();
  2295. llvm::Metadata *Subscript;
  2296. QualType QTy(Ty, 0);
  2297. auto SizeExpr = SizeExprCache.find(QTy);
  2298. if (SizeExpr != SizeExprCache.end())
  2299. Subscript = DBuilder.getOrCreateSubrange(0, SizeExpr->getSecond());
  2300. else
  2301. Subscript = DBuilder.getOrCreateSubrange(0, Count ? Count : -1);
  2302. llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
  2303. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  2304. auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
  2305. return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
  2306. }
  2307. llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
  2308. uint64_t Size;
  2309. uint32_t Align;
  2310. // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
  2311. if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
  2312. Size = 0;
  2313. Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
  2314. CGM.getContext());
  2315. } else if (Ty->isIncompleteArrayType()) {
  2316. Size = 0;
  2317. if (Ty->getElementType()->isIncompleteType())
  2318. Align = 0;
  2319. else
  2320. Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
  2321. } else if (Ty->isIncompleteType()) {
  2322. Size = 0;
  2323. Align = 0;
  2324. } else {
  2325. // Size and align of the whole array, not the element type.
  2326. Size = CGM.getContext().getTypeSize(Ty);
  2327. Align = getTypeAlignIfRequired(Ty, CGM.getContext());
  2328. }
  2329. // Add the dimensions of the array. FIXME: This loses CV qualifiers from
  2330. // interior arrays, do we care? Why aren't nested arrays represented the
  2331. // obvious/recursive way?
  2332. SmallVector<llvm::Metadata *, 8> Subscripts;
  2333. QualType EltTy(Ty, 0);
  2334. while ((Ty = dyn_cast<ArrayType>(EltTy))) {
  2335. // If the number of elements is known, then count is that number. Otherwise,
  2336. // it's -1. This allows us to represent a subrange with an array of 0
  2337. // elements, like this:
  2338. //
  2339. // struct foo {
  2340. // int x[0];
  2341. // };
  2342. int64_t Count = -1; // Count == -1 is an unbounded array.
  2343. if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
  2344. Count = CAT->getSize().getZExtValue();
  2345. else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
  2346. if (Expr *Size = VAT->getSizeExpr()) {
  2347. Expr::EvalResult Result;
  2348. if (Size->EvaluateAsInt(Result, CGM.getContext()))
  2349. Count = Result.Val.getInt().getExtValue();
  2350. }
  2351. }
  2352. auto SizeNode = SizeExprCache.find(EltTy);
  2353. if (SizeNode != SizeExprCache.end())
  2354. Subscripts.push_back(
  2355. DBuilder.getOrCreateSubrange(0, SizeNode->getSecond()));
  2356. else
  2357. Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
  2358. EltTy = Ty->getElementType();
  2359. }
  2360. llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
  2361. return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
  2362. SubscriptArray);
  2363. }
  2364. llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
  2365. llvm::DIFile *Unit) {
  2366. return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
  2367. Ty->getPointeeType(), Unit);
  2368. }
  2369. llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
  2370. llvm::DIFile *Unit) {
  2371. return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
  2372. Ty->getPointeeType(), Unit);
  2373. }
  2374. llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
  2375. llvm::DIFile *U) {
  2376. llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
  2377. uint64_t Size = 0;
  2378. if (!Ty->isIncompleteType()) {
  2379. Size = CGM.getContext().getTypeSize(Ty);
  2380. // Set the MS inheritance model. There is no flag for the unspecified model.
  2381. if (CGM.getTarget().getCXXABI().isMicrosoft()) {
  2382. switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
  2383. case MSInheritanceAttr::Keyword_single_inheritance:
  2384. Flags |= llvm::DINode::FlagSingleInheritance;
  2385. break;
  2386. case MSInheritanceAttr::Keyword_multiple_inheritance:
  2387. Flags |= llvm::DINode::FlagMultipleInheritance;
  2388. break;
  2389. case MSInheritanceAttr::Keyword_virtual_inheritance:
  2390. Flags |= llvm::DINode::FlagVirtualInheritance;
  2391. break;
  2392. case MSInheritanceAttr::Keyword_unspecified_inheritance:
  2393. break;
  2394. case MSInheritanceAttr::SpellingNotCalculated:
  2395. llvm_unreachable("Spelling not yet calculated");
  2396. }
  2397. }
  2398. }
  2399. llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
  2400. if (Ty->isMemberDataPointerType())
  2401. return DBuilder.createMemberPointerType(
  2402. getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
  2403. Flags);
  2404. const FunctionProtoType *FPT =
  2405. Ty->getPointeeType()->getAs<FunctionProtoType>();
  2406. return DBuilder.createMemberPointerType(
  2407. getOrCreateInstanceMethodType(
  2408. CXXMethodDecl::getThisType(FPT, Ty->getMostRecentCXXRecordDecl()),
  2409. FPT, U),
  2410. ClassType, Size, /*Align=*/0, Flags);
  2411. }
  2412. llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
  2413. auto *FromTy = getOrCreateType(Ty->getValueType(), U);
  2414. return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
  2415. }
  2416. llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
  2417. return getOrCreateType(Ty->getElementType(), U);
  2418. }
  2419. llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
  2420. const EnumDecl *ED = Ty->getDecl();
  2421. uint64_t Size = 0;
  2422. uint32_t Align = 0;
  2423. if (!ED->getTypeForDecl()->isIncompleteType()) {
  2424. Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
  2425. Align = getDeclAlignIfRequired(ED, CGM.getContext());
  2426. }
  2427. SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
  2428. bool isImportedFromModule =
  2429. DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
  2430. // If this is just a forward declaration, construct an appropriately
  2431. // marked node and just return it.
  2432. if (isImportedFromModule || !ED->getDefinition()) {
  2433. // Note that it is possible for enums to be created as part of
  2434. // their own declcontext. In this case a FwdDecl will be created
  2435. // twice. This doesn't cause a problem because both FwdDecls are
  2436. // entered into the ReplaceMap: finalize() will replace the first
  2437. // FwdDecl with the second and then replace the second with
  2438. // complete type.
  2439. llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
  2440. llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
  2441. llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
  2442. llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
  2443. unsigned Line = getLineNumber(ED->getLocation());
  2444. StringRef EDName = ED->getName();
  2445. llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
  2446. llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
  2447. 0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
  2448. ReplaceMap.emplace_back(
  2449. std::piecewise_construct, std::make_tuple(Ty),
  2450. std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
  2451. return RetTy;
  2452. }
  2453. return CreateTypeDefinition(Ty);
  2454. }
  2455. llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
  2456. const EnumDecl *ED = Ty->getDecl();
  2457. uint64_t Size = 0;
  2458. uint32_t Align = 0;
  2459. if (!ED->getTypeForDecl()->isIncompleteType()) {
  2460. Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
  2461. Align = getDeclAlignIfRequired(ED, CGM.getContext());
  2462. }
  2463. SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
  2464. // Create elements for each enumerator.
  2465. SmallVector<llvm::Metadata *, 16> Enumerators;
  2466. ED = ED->getDefinition();
  2467. bool IsSigned = ED->getIntegerType()->isSignedIntegerType();
  2468. for (const auto *Enum : ED->enumerators()) {
  2469. const auto &InitVal = Enum->getInitVal();
  2470. auto Value = IsSigned ? InitVal.getSExtValue() : InitVal.getZExtValue();
  2471. Enumerators.push_back(
  2472. DBuilder.createEnumerator(Enum->getName(), Value, !IsSigned));
  2473. }
  2474. // Return a CompositeType for the enum itself.
  2475. llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
  2476. llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
  2477. unsigned Line = getLineNumber(ED->getLocation());
  2478. llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
  2479. llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
  2480. return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
  2481. Line, Size, Align, EltArray, ClassTy,
  2482. Identifier, ED->isScoped());
  2483. }
  2484. llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
  2485. unsigned MType, SourceLocation LineLoc,
  2486. StringRef Name, StringRef Value) {
  2487. unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
  2488. return DBuilder.createMacro(Parent, Line, MType, Name, Value);
  2489. }
  2490. llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
  2491. SourceLocation LineLoc,
  2492. SourceLocation FileLoc) {
  2493. llvm::DIFile *FName = getOrCreateFile(FileLoc);
  2494. unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
  2495. return DBuilder.createTempMacroFile(Parent, Line, FName);
  2496. }
  2497. static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
  2498. Qualifiers Quals;
  2499. do {
  2500. Qualifiers InnerQuals = T.getLocalQualifiers();
  2501. // Qualifiers::operator+() doesn't like it if you add a Qualifier
  2502. // that is already there.
  2503. Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
  2504. Quals += InnerQuals;
  2505. QualType LastT = T;
  2506. switch (T->getTypeClass()) {
  2507. default:
  2508. return C.getQualifiedType(T.getTypePtr(), Quals);
  2509. case Type::TemplateSpecialization: {
  2510. const auto *Spec = cast<TemplateSpecializationType>(T);
  2511. if (Spec->isTypeAlias())
  2512. return C.getQualifiedType(T.getTypePtr(), Quals);
  2513. T = Spec->desugar();
  2514. break;
  2515. }
  2516. case Type::TypeOfExpr:
  2517. T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
  2518. break;
  2519. case Type::TypeOf:
  2520. T = cast<TypeOfType>(T)->getUnderlyingType();
  2521. break;
  2522. case Type::Decltype:
  2523. T = cast<DecltypeType>(T)->getUnderlyingType();
  2524. break;
  2525. case Type::UnaryTransform:
  2526. T = cast<UnaryTransformType>(T)->getUnderlyingType();
  2527. break;
  2528. case Type::Attributed:
  2529. T = cast<AttributedType>(T)->getEquivalentType();
  2530. break;
  2531. case Type::Elaborated:
  2532. T = cast<ElaboratedType>(T)->getNamedType();
  2533. break;
  2534. case Type::Paren:
  2535. T = cast<ParenType>(T)->getInnerType();
  2536. break;
  2537. case Type::MacroQualified:
  2538. T = cast<MacroQualifiedType>(T)->getUnderlyingType();
  2539. break;
  2540. case Type::SubstTemplateTypeParm:
  2541. T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
  2542. break;
  2543. case Type::Auto:
  2544. case Type::DeducedTemplateSpecialization: {
  2545. QualType DT = cast<DeducedType>(T)->getDeducedType();
  2546. assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
  2547. T = DT;
  2548. break;
  2549. }
  2550. case Type::Adjusted:
  2551. case Type::Decayed:
  2552. // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
  2553. T = cast<AdjustedType>(T)->getAdjustedType();
  2554. break;
  2555. }
  2556. assert(T != LastT && "Type unwrapping failed to unwrap!");
  2557. (void)LastT;
  2558. } while (true);
  2559. }
  2560. llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
  2561. // Unwrap the type as needed for debug information.
  2562. Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
  2563. auto It = TypeCache.find(Ty.getAsOpaquePtr());
  2564. if (It != TypeCache.end()) {
  2565. // Verify that the debug info still exists.
  2566. if (llvm::Metadata *V = It->second)
  2567. return cast<llvm::DIType>(V);
  2568. }
  2569. return nullptr;
  2570. }
  2571. void CGDebugInfo::completeTemplateDefinition(
  2572. const ClassTemplateSpecializationDecl &SD) {
  2573. if (DebugKind <= codegenoptions::DebugLineTablesOnly)
  2574. return;
  2575. completeUnusedClass(SD);
  2576. }
  2577. void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
  2578. if (DebugKind <= codegenoptions::DebugLineTablesOnly)
  2579. return;
  2580. completeClassData(&D);
  2581. // In case this type has no member function definitions being emitted, ensure
  2582. // it is retained
  2583. RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
  2584. }
  2585. llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
  2586. if (Ty.isNull())
  2587. return nullptr;
  2588. // Unwrap the type as needed for debug information.
  2589. Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
  2590. if (auto *T = getTypeOrNull(Ty))
  2591. return T;
  2592. llvm::DIType *Res = CreateTypeNode(Ty, Unit);
  2593. void *TyPtr = Ty.getAsOpaquePtr();
  2594. // And update the type cache.
  2595. TypeCache[TyPtr].reset(Res);
  2596. return Res;
  2597. }
  2598. llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
  2599. // A forward declaration inside a module header does not belong to the module.
  2600. if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
  2601. return nullptr;
  2602. if (DebugTypeExtRefs && D->isFromASTFile()) {
  2603. // Record a reference to an imported clang module or precompiled header.
  2604. auto *Reader = CGM.getContext().getExternalSource();
  2605. auto Idx = D->getOwningModuleID();
  2606. auto Info = Reader->getSourceDescriptor(Idx);
  2607. if (Info)
  2608. return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
  2609. } else if (ClangModuleMap) {
  2610. // We are building a clang module or a precompiled header.
  2611. //
  2612. // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
  2613. // and it wouldn't be necessary to specify the parent scope
  2614. // because the type is already unique by definition (it would look
  2615. // like the output of -fno-standalone-debug). On the other hand,
  2616. // the parent scope helps a consumer to quickly locate the object
  2617. // file where the type's definition is located, so it might be
  2618. // best to make this behavior a command line or debugger tuning
  2619. // option.
  2620. if (Module *M = D->getOwningModule()) {
  2621. // This is a (sub-)module.
  2622. auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
  2623. return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
  2624. } else {
  2625. // This the precompiled header being built.
  2626. return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
  2627. }
  2628. }
  2629. return nullptr;
  2630. }
  2631. llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
  2632. // Handle qualifiers, which recursively handles what they refer to.
  2633. if (Ty.hasLocalQualifiers())
  2634. return CreateQualifiedType(Ty, Unit);
  2635. // Work out details of type.
  2636. switch (Ty->getTypeClass()) {
  2637. #define TYPE(Class, Base)
  2638. #define ABSTRACT_TYPE(Class, Base)
  2639. #define NON_CANONICAL_TYPE(Class, Base)
  2640. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  2641. #include "clang/AST/TypeNodes.inc"
  2642. llvm_unreachable("Dependent types cannot show up in debug information");
  2643. case Type::ExtVector:
  2644. case Type::Vector:
  2645. return CreateType(cast<VectorType>(Ty), Unit);
  2646. case Type::ObjCObjectPointer:
  2647. return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
  2648. case Type::ObjCObject:
  2649. return CreateType(cast<ObjCObjectType>(Ty), Unit);
  2650. case Type::ObjCTypeParam:
  2651. return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
  2652. case Type::ObjCInterface:
  2653. return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
  2654. case Type::Builtin:
  2655. return CreateType(cast<BuiltinType>(Ty));
  2656. case Type::Complex:
  2657. return CreateType(cast<ComplexType>(Ty));
  2658. case Type::Pointer:
  2659. return CreateType(cast<PointerType>(Ty), Unit);
  2660. case Type::BlockPointer:
  2661. return CreateType(cast<BlockPointerType>(Ty), Unit);
  2662. case Type::Typedef:
  2663. return CreateType(cast<TypedefType>(Ty), Unit);
  2664. case Type::Record:
  2665. return CreateType(cast<RecordType>(Ty));
  2666. case Type::Enum:
  2667. return CreateEnumType(cast<EnumType>(Ty));
  2668. case Type::FunctionProto:
  2669. case Type::FunctionNoProto:
  2670. return CreateType(cast<FunctionType>(Ty), Unit);
  2671. case Type::ConstantArray:
  2672. case Type::VariableArray:
  2673. case Type::IncompleteArray:
  2674. return CreateType(cast<ArrayType>(Ty), Unit);
  2675. case Type::LValueReference:
  2676. return CreateType(cast<LValueReferenceType>(Ty), Unit);
  2677. case Type::RValueReference:
  2678. return CreateType(cast<RValueReferenceType>(Ty), Unit);
  2679. case Type::MemberPointer:
  2680. return CreateType(cast<MemberPointerType>(Ty), Unit);
  2681. case Type::Atomic:
  2682. return CreateType(cast<AtomicType>(Ty), Unit);
  2683. case Type::Pipe:
  2684. return CreateType(cast<PipeType>(Ty), Unit);
  2685. case Type::TemplateSpecialization:
  2686. return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
  2687. case Type::Auto:
  2688. case Type::Attributed:
  2689. case Type::Adjusted:
  2690. case Type::Decayed:
  2691. case Type::DeducedTemplateSpecialization:
  2692. case Type::Elaborated:
  2693. case Type::Paren:
  2694. case Type::MacroQualified:
  2695. case Type::SubstTemplateTypeParm:
  2696. case Type::TypeOfExpr:
  2697. case Type::TypeOf:
  2698. case Type::Decltype:
  2699. case Type::UnaryTransform:
  2700. case Type::PackExpansion:
  2701. break;
  2702. }
  2703. llvm_unreachable("type should have been unwrapped!");
  2704. }
  2705. llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
  2706. llvm::DIFile *Unit) {
  2707. QualType QTy(Ty, 0);
  2708. auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
  2709. // We may have cached a forward decl when we could have created
  2710. // a non-forward decl. Go ahead and create a non-forward decl
  2711. // now.
  2712. if (T && !T->isForwardDecl())
  2713. return T;
  2714. // Otherwise create the type.
  2715. llvm::DICompositeType *Res = CreateLimitedType(Ty);
  2716. // Propagate members from the declaration to the definition
  2717. // CreateType(const RecordType*) will overwrite this with the members in the
  2718. // correct order if the full type is needed.
  2719. DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
  2720. // And update the type cache.
  2721. TypeCache[QTy.getAsOpaquePtr()].reset(Res);
  2722. return Res;
  2723. }
  2724. // TODO: Currently used for context chains when limiting debug info.
  2725. llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
  2726. RecordDecl *RD = Ty->getDecl();
  2727. // Get overall information about the record type for the debug info.
  2728. llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
  2729. unsigned Line = getLineNumber(RD->getLocation());
  2730. StringRef RDName = getClassName(RD);
  2731. llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
  2732. // If we ended up creating the type during the context chain construction,
  2733. // just return that.
  2734. auto *T = cast_or_null<llvm::DICompositeType>(
  2735. getTypeOrNull(CGM.getContext().getRecordType(RD)));
  2736. if (T && (!T->isForwardDecl() || !RD->getDefinition()))
  2737. return T;
  2738. // If this is just a forward or incomplete declaration, construct an
  2739. // appropriately marked node and just return it.
  2740. const RecordDecl *D = RD->getDefinition();
  2741. if (!D || !D->isCompleteDefinition())
  2742. return getOrCreateRecordFwdDecl(Ty, RDContext);
  2743. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  2744. auto Align = getDeclAlignIfRequired(D, CGM.getContext());
  2745. SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
  2746. // Explicitly record the calling convention and export symbols for C++
  2747. // records.
  2748. auto Flags = llvm::DINode::FlagZero;
  2749. if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  2750. if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
  2751. Flags |= llvm::DINode::FlagTypePassByReference;
  2752. else
  2753. Flags |= llvm::DINode::FlagTypePassByValue;
  2754. // Record if a C++ record is non-trivial type.
  2755. if (!CXXRD->isTrivial())
  2756. Flags |= llvm::DINode::FlagNonTrivial;
  2757. // Record exports it symbols to the containing structure.
  2758. if (CXXRD->isAnonymousStructOrUnion())
  2759. Flags |= llvm::DINode::FlagExportSymbols;
  2760. }
  2761. llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
  2762. getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
  2763. Flags, Identifier);
  2764. // Elements of composite types usually have back to the type, creating
  2765. // uniquing cycles. Distinct nodes are more efficient.
  2766. switch (RealDecl->getTag()) {
  2767. default:
  2768. llvm_unreachable("invalid composite type tag");
  2769. case llvm::dwarf::DW_TAG_array_type:
  2770. case llvm::dwarf::DW_TAG_enumeration_type:
  2771. // Array elements and most enumeration elements don't have back references,
  2772. // so they don't tend to be involved in uniquing cycles and there is some
  2773. // chance of merging them when linking together two modules. Only make
  2774. // them distinct if they are ODR-uniqued.
  2775. if (Identifier.empty())
  2776. break;
  2777. LLVM_FALLTHROUGH;
  2778. case llvm::dwarf::DW_TAG_structure_type:
  2779. case llvm::dwarf::DW_TAG_union_type:
  2780. case llvm::dwarf::DW_TAG_class_type:
  2781. // Immediately resolve to a distinct node.
  2782. RealDecl =
  2783. llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
  2784. break;
  2785. }
  2786. RegionMap[Ty->getDecl()].reset(RealDecl);
  2787. TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
  2788. if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
  2789. DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
  2790. CollectCXXTemplateParams(TSpecial, DefUnit));
  2791. return RealDecl;
  2792. }
  2793. void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
  2794. llvm::DICompositeType *RealDecl) {
  2795. // A class's primary base or the class itself contains the vtable.
  2796. llvm::DICompositeType *ContainingType = nullptr;
  2797. const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
  2798. if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
  2799. // Seek non-virtual primary base root.
  2800. while (1) {
  2801. const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
  2802. const CXXRecordDecl *PBT = BRL.getPrimaryBase();
  2803. if (PBT && !BRL.isPrimaryBaseVirtual())
  2804. PBase = PBT;
  2805. else
  2806. break;
  2807. }
  2808. ContainingType = cast<llvm::DICompositeType>(
  2809. getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
  2810. getOrCreateFile(RD->getLocation())));
  2811. } else if (RD->isDynamicClass())
  2812. ContainingType = RealDecl;
  2813. DBuilder.replaceVTableHolder(RealDecl, ContainingType);
  2814. }
  2815. llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
  2816. StringRef Name, uint64_t *Offset) {
  2817. llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
  2818. uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
  2819. auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
  2820. llvm::DIType *Ty =
  2821. DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
  2822. *Offset, llvm::DINode::FlagZero, FieldTy);
  2823. *Offset += FieldSize;
  2824. return Ty;
  2825. }
  2826. void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
  2827. StringRef &Name,
  2828. StringRef &LinkageName,
  2829. llvm::DIScope *&FDContext,
  2830. llvm::DINodeArray &TParamsArray,
  2831. llvm::DINode::DIFlags &Flags) {
  2832. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  2833. Name = getFunctionName(FD);
  2834. // Use mangled name as linkage name for C/C++ functions.
  2835. if (FD->hasPrototype()) {
  2836. LinkageName = CGM.getMangledName(GD);
  2837. Flags |= llvm::DINode::FlagPrototyped;
  2838. }
  2839. // No need to replicate the linkage name if it isn't different from the
  2840. // subprogram name, no need to have it at all unless coverage is enabled or
  2841. // debug is set to more than just line tables or extra debug info is needed.
  2842. if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs &&
  2843. !CGM.getCodeGenOpts().EmitGcovNotes &&
  2844. !CGM.getCodeGenOpts().DebugInfoForProfiling &&
  2845. DebugKind <= codegenoptions::DebugLineTablesOnly))
  2846. LinkageName = StringRef();
  2847. if (DebugKind >= codegenoptions::LimitedDebugInfo) {
  2848. if (const NamespaceDecl *NSDecl =
  2849. dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
  2850. FDContext = getOrCreateNamespace(NSDecl);
  2851. else if (const RecordDecl *RDecl =
  2852. dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
  2853. llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
  2854. FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
  2855. }
  2856. // Check if it is a noreturn-marked function
  2857. if (FD->isNoReturn())
  2858. Flags |= llvm::DINode::FlagNoReturn;
  2859. // Collect template parameters.
  2860. TParamsArray = CollectFunctionTemplateParams(FD, Unit);
  2861. }
  2862. }
  2863. void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
  2864. unsigned &LineNo, QualType &T,
  2865. StringRef &Name, StringRef &LinkageName,
  2866. llvm::MDTuple *&TemplateParameters,
  2867. llvm::DIScope *&VDContext) {
  2868. Unit = getOrCreateFile(VD->getLocation());
  2869. LineNo = getLineNumber(VD->getLocation());
  2870. setLocation(VD->getLocation());
  2871. T = VD->getType();
  2872. if (T->isIncompleteArrayType()) {
  2873. // CodeGen turns int[] into int[1] so we'll do the same here.
  2874. llvm::APInt ConstVal(32, 1);
  2875. QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
  2876. T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
  2877. ArrayType::Normal, 0);
  2878. }
  2879. Name = VD->getName();
  2880. if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
  2881. !isa<ObjCMethodDecl>(VD->getDeclContext()))
  2882. LinkageName = CGM.getMangledName(VD);
  2883. if (LinkageName == Name)
  2884. LinkageName = StringRef();
  2885. if (isa<VarTemplateSpecializationDecl>(VD)) {
  2886. llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
  2887. TemplateParameters = parameterNodes.get();
  2888. } else {
  2889. TemplateParameters = nullptr;
  2890. }
  2891. // Since we emit declarations (DW_AT_members) for static members, place the
  2892. // definition of those static members in the namespace they were declared in
  2893. // in the source code (the lexical decl context).
  2894. // FIXME: Generalize this for even non-member global variables where the
  2895. // declaration and definition may have different lexical decl contexts, once
  2896. // we have support for emitting declarations of (non-member) global variables.
  2897. const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
  2898. : VD->getDeclContext();
  2899. // When a record type contains an in-line initialization of a static data
  2900. // member, and the record type is marked as __declspec(dllexport), an implicit
  2901. // definition of the member will be created in the record context. DWARF
  2902. // doesn't seem to have a nice way to describe this in a form that consumers
  2903. // are likely to understand, so fake the "normal" situation of a definition
  2904. // outside the class by putting it in the global scope.
  2905. if (DC->isRecord())
  2906. DC = CGM.getContext().getTranslationUnitDecl();
  2907. llvm::DIScope *Mod = getParentModuleOrNull(VD);
  2908. VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
  2909. }
  2910. llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
  2911. bool Stub) {
  2912. llvm::DINodeArray TParamsArray;
  2913. StringRef Name, LinkageName;
  2914. llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
  2915. llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
  2916. SourceLocation Loc = GD.getDecl()->getLocation();
  2917. llvm::DIFile *Unit = getOrCreateFile(Loc);
  2918. llvm::DIScope *DContext = Unit;
  2919. unsigned Line = getLineNumber(Loc);
  2920. collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
  2921. Flags);
  2922. auto *FD = cast<FunctionDecl>(GD.getDecl());
  2923. // Build function type.
  2924. SmallVector<QualType, 16> ArgTypes;
  2925. for (const ParmVarDecl *Parm : FD->parameters())
  2926. ArgTypes.push_back(Parm->getType());
  2927. CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
  2928. QualType FnType = CGM.getContext().getFunctionType(
  2929. FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
  2930. if (!FD->isExternallyVisible())
  2931. SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
  2932. if (CGM.getLangOpts().Optimize)
  2933. SPFlags |= llvm::DISubprogram::SPFlagOptimized;
  2934. if (Stub) {
  2935. Flags |= getCallSiteRelatedAttrs();
  2936. SPFlags |= llvm::DISubprogram::SPFlagDefinition;
  2937. return DBuilder.createFunction(
  2938. DContext, Name, LinkageName, Unit, Line,
  2939. getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
  2940. TParamsArray.get(), getFunctionDeclaration(FD));
  2941. }
  2942. llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
  2943. DContext, Name, LinkageName, Unit, Line,
  2944. getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
  2945. TParamsArray.get(), getFunctionDeclaration(FD));
  2946. const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
  2947. FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
  2948. std::make_tuple(CanonDecl),
  2949. std::make_tuple(SP));
  2950. return SP;
  2951. }
  2952. llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
  2953. return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
  2954. }
  2955. llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
  2956. return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
  2957. }
  2958. llvm::DIGlobalVariable *
  2959. CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
  2960. QualType T;
  2961. StringRef Name, LinkageName;
  2962. SourceLocation Loc = VD->getLocation();
  2963. llvm::DIFile *Unit = getOrCreateFile(Loc);
  2964. llvm::DIScope *DContext = Unit;
  2965. unsigned Line = getLineNumber(Loc);
  2966. llvm::MDTuple *TemplateParameters = nullptr;
  2967. collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
  2968. DContext);
  2969. auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
  2970. auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
  2971. DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
  2972. !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
  2973. FwdDeclReplaceMap.emplace_back(
  2974. std::piecewise_construct,
  2975. std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
  2976. std::make_tuple(static_cast<llvm::Metadata *>(GV)));
  2977. return GV;
  2978. }
  2979. llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
  2980. // We only need a declaration (not a definition) of the type - so use whatever
  2981. // we would otherwise do to get a type for a pointee. (forward declarations in
  2982. // limited debug info, full definitions (if the type definition is available)
  2983. // in unlimited debug info)
  2984. if (const auto *TD = dyn_cast<TypeDecl>(D))
  2985. return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
  2986. getOrCreateFile(TD->getLocation()));
  2987. auto I = DeclCache.find(D->getCanonicalDecl());
  2988. if (I != DeclCache.end()) {
  2989. auto N = I->second;
  2990. if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
  2991. return GVE->getVariable();
  2992. return dyn_cast_or_null<llvm::DINode>(N);
  2993. }
  2994. // No definition for now. Emit a forward definition that might be
  2995. // merged with a potential upcoming definition.
  2996. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  2997. return getFunctionForwardDeclaration(FD);
  2998. else if (const auto *VD = dyn_cast<VarDecl>(D))
  2999. return getGlobalVariableForwardDeclaration(VD);
  3000. return nullptr;
  3001. }
  3002. llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
  3003. if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
  3004. return nullptr;
  3005. const auto *FD = dyn_cast<FunctionDecl>(D);
  3006. if (!FD)
  3007. return nullptr;
  3008. // Setup context.
  3009. auto *S = getDeclContextDescriptor(D);
  3010. auto MI = SPCache.find(FD->getCanonicalDecl());
  3011. if (MI == SPCache.end()) {
  3012. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
  3013. return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
  3014. cast<llvm::DICompositeType>(S));
  3015. }
  3016. }
  3017. if (MI != SPCache.end()) {
  3018. auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
  3019. if (SP && !SP->isDefinition())
  3020. return SP;
  3021. }
  3022. for (auto NextFD : FD->redecls()) {
  3023. auto MI = SPCache.find(NextFD->getCanonicalDecl());
  3024. if (MI != SPCache.end()) {
  3025. auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
  3026. if (SP && !SP->isDefinition())
  3027. return SP;
  3028. }
  3029. }
  3030. return nullptr;
  3031. }
  3032. // getOrCreateFunctionType - Construct type. If it is a c++ method, include
  3033. // implicit parameter "this".
  3034. llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
  3035. QualType FnType,
  3036. llvm::DIFile *F) {
  3037. if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
  3038. // Create fake but valid subroutine type. Otherwise -verify would fail, and
  3039. // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
  3040. return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
  3041. if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
  3042. return getOrCreateMethodType(Method, F);
  3043. const auto *FTy = FnType->getAs<FunctionType>();
  3044. CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
  3045. if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
  3046. // Add "self" and "_cmd"
  3047. SmallVector<llvm::Metadata *, 16> Elts;
  3048. // First element is always return type. For 'void' functions it is NULL.
  3049. QualType ResultTy = OMethod->getReturnType();
  3050. // Replace the instancetype keyword with the actual type.
  3051. if (ResultTy == CGM.getContext().getObjCInstanceType())
  3052. ResultTy = CGM.getContext().getPointerType(
  3053. QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
  3054. Elts.push_back(getOrCreateType(ResultTy, F));
  3055. // "self" pointer is always first argument.
  3056. QualType SelfDeclTy;
  3057. if (auto *SelfDecl = OMethod->getSelfDecl())
  3058. SelfDeclTy = SelfDecl->getType();
  3059. else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
  3060. if (FPT->getNumParams() > 1)
  3061. SelfDeclTy = FPT->getParamType(0);
  3062. if (!SelfDeclTy.isNull())
  3063. Elts.push_back(
  3064. CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
  3065. // "_cmd" pointer is always second argument.
  3066. Elts.push_back(DBuilder.createArtificialType(
  3067. getOrCreateType(CGM.getContext().getObjCSelType(), F)));
  3068. // Get rest of the arguments.
  3069. for (const auto *PI : OMethod->parameters())
  3070. Elts.push_back(getOrCreateType(PI->getType(), F));
  3071. // Variadic methods need a special marker at the end of the type list.
  3072. if (OMethod->isVariadic())
  3073. Elts.push_back(DBuilder.createUnspecifiedParameter());
  3074. llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
  3075. return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
  3076. getDwarfCC(CC));
  3077. }
  3078. // Handle variadic function types; they need an additional
  3079. // unspecified parameter.
  3080. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  3081. if (FD->isVariadic()) {
  3082. SmallVector<llvm::Metadata *, 16> EltTys;
  3083. EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
  3084. if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
  3085. for (QualType ParamType : FPT->param_types())
  3086. EltTys.push_back(getOrCreateType(ParamType, F));
  3087. EltTys.push_back(DBuilder.createUnspecifiedParameter());
  3088. llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
  3089. return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
  3090. getDwarfCC(CC));
  3091. }
  3092. return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
  3093. }
  3094. void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
  3095. SourceLocation ScopeLoc, QualType FnType,
  3096. llvm::Function *Fn, bool CurFuncIsThunk,
  3097. CGBuilderTy &Builder) {
  3098. StringRef Name;
  3099. StringRef LinkageName;
  3100. FnBeginRegionCount.push_back(LexicalBlockStack.size());
  3101. const Decl *D = GD.getDecl();
  3102. bool HasDecl = (D != nullptr);
  3103. llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
  3104. llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
  3105. llvm::DIFile *Unit = getOrCreateFile(Loc);
  3106. llvm::DIScope *FDContext = Unit;
  3107. llvm::DINodeArray TParamsArray;
  3108. if (!HasDecl) {
  3109. // Use llvm function name.
  3110. LinkageName = Fn->getName();
  3111. } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  3112. // If there is a subprogram for this function available then use it.
  3113. auto FI = SPCache.find(FD->getCanonicalDecl());
  3114. if (FI != SPCache.end()) {
  3115. auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
  3116. if (SP && SP->isDefinition()) {
  3117. LexicalBlockStack.emplace_back(SP);
  3118. RegionMap[D].reset(SP);
  3119. return;
  3120. }
  3121. }
  3122. collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
  3123. TParamsArray, Flags);
  3124. } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
  3125. Name = getObjCMethodName(OMD);
  3126. Flags |= llvm::DINode::FlagPrototyped;
  3127. } else if (isa<VarDecl>(D) &&
  3128. GD.getDynamicInitKind() != DynamicInitKind::NoStub) {
  3129. // This is a global initializer or atexit destructor for a global variable.
  3130. Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
  3131. Fn);
  3132. } else {
  3133. // Use llvm function name.
  3134. Name = Fn->getName();
  3135. Flags |= llvm::DINode::FlagPrototyped;
  3136. }
  3137. if (Name.startswith("\01"))
  3138. Name = Name.substr(1);
  3139. if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>()) {
  3140. Flags |= llvm::DINode::FlagArtificial;
  3141. // Artificial functions should not silently reuse CurLoc.
  3142. CurLoc = SourceLocation();
  3143. }
  3144. if (CurFuncIsThunk)
  3145. Flags |= llvm::DINode::FlagThunk;
  3146. if (Fn->hasLocalLinkage())
  3147. SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
  3148. if (CGM.getLangOpts().Optimize)
  3149. SPFlags |= llvm::DISubprogram::SPFlagOptimized;
  3150. llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
  3151. llvm::DISubprogram::DISPFlags SPFlagsForDef =
  3152. SPFlags | llvm::DISubprogram::SPFlagDefinition;
  3153. unsigned LineNo = getLineNumber(Loc);
  3154. unsigned ScopeLine = getLineNumber(ScopeLoc);
  3155. // FIXME: The function declaration we're constructing here is mostly reusing
  3156. // declarations from CXXMethodDecl and not constructing new ones for arbitrary
  3157. // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
  3158. // all subprograms instead of the actual context since subprogram definitions
  3159. // are emitted as CU level entities by the backend.
  3160. llvm::DISubprogram *SP = DBuilder.createFunction(
  3161. FDContext, Name, LinkageName, Unit, LineNo,
  3162. getOrCreateFunctionType(D, FnType, Unit), ScopeLine, FlagsForDef,
  3163. SPFlagsForDef, TParamsArray.get(), getFunctionDeclaration(D));
  3164. Fn->setSubprogram(SP);
  3165. // We might get here with a VarDecl in the case we're generating
  3166. // code for the initialization of globals. Do not record these decls
  3167. // as they will overwrite the actual VarDecl Decl in the cache.
  3168. if (HasDecl && isa<FunctionDecl>(D))
  3169. DeclCache[D->getCanonicalDecl()].reset(SP);
  3170. // We use the SPDefCache only in the case when the debug entry values option
  3171. // is set, in order to speed up parameters modification analysis.
  3172. //
  3173. // FIXME: Use AbstractCallee here to support ObjCMethodDecl.
  3174. if (CGM.getCodeGenOpts().EnableDebugEntryValues && HasDecl)
  3175. if (auto *FD = dyn_cast<FunctionDecl>(D))
  3176. if (FD->hasBody() && !FD->param_empty())
  3177. SPDefCache[FD].reset(SP);
  3178. if (CGM.getCodeGenOpts().DwarfVersion >= 5) {
  3179. // Starting with DWARF V5 method declarations are emitted as children of
  3180. // the interface type.
  3181. if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
  3182. const ObjCInterfaceDecl *ID = OMD->getClassInterface();
  3183. QualType QTy(ID->getTypeForDecl(), 0);
  3184. auto It = TypeCache.find(QTy.getAsOpaquePtr());
  3185. if (It != TypeCache.end()) {
  3186. llvm::DICompositeType *InterfaceDecl =
  3187. cast<llvm::DICompositeType>(It->second);
  3188. llvm::DISubprogram *FD = DBuilder.createFunction(
  3189. InterfaceDecl, Name, LinkageName, Unit, LineNo,
  3190. getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
  3191. TParamsArray.get());
  3192. DBuilder.finalizeSubprogram(FD);
  3193. ObjCMethodCache[ID].push_back(FD);
  3194. }
  3195. }
  3196. }
  3197. // Push the function onto the lexical block stack.
  3198. LexicalBlockStack.emplace_back(SP);
  3199. if (HasDecl)
  3200. RegionMap[D].reset(SP);
  3201. }
  3202. void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
  3203. QualType FnType, llvm::Function *Fn) {
  3204. StringRef Name;
  3205. StringRef LinkageName;
  3206. const Decl *D = GD.getDecl();
  3207. if (!D)
  3208. return;
  3209. llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
  3210. llvm::DIFile *Unit = getOrCreateFile(Loc);
  3211. bool IsDeclForCallSite = Fn ? true : false;
  3212. llvm::DIScope *FDContext =
  3213. IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
  3214. llvm::DINodeArray TParamsArray;
  3215. if (isa<FunctionDecl>(D)) {
  3216. // If there is a DISubprogram for this function available then use it.
  3217. collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
  3218. TParamsArray, Flags);
  3219. } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
  3220. Name = getObjCMethodName(OMD);
  3221. Flags |= llvm::DINode::FlagPrototyped;
  3222. } else {
  3223. llvm_unreachable("not a function or ObjC method");
  3224. }
  3225. if (!Name.empty() && Name[0] == '\01')
  3226. Name = Name.substr(1);
  3227. if (D->isImplicit()) {
  3228. Flags |= llvm::DINode::FlagArtificial;
  3229. // Artificial functions without a location should not silently reuse CurLoc.
  3230. if (Loc.isInvalid())
  3231. CurLoc = SourceLocation();
  3232. }
  3233. unsigned LineNo = getLineNumber(Loc);
  3234. unsigned ScopeLine = 0;
  3235. llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
  3236. if (CGM.getLangOpts().Optimize)
  3237. SPFlags |= llvm::DISubprogram::SPFlagOptimized;
  3238. llvm::DISubprogram *SP = DBuilder.createFunction(
  3239. FDContext, Name, LinkageName, Unit, LineNo,
  3240. getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
  3241. TParamsArray.get(), getFunctionDeclaration(D));
  3242. if (IsDeclForCallSite)
  3243. Fn->setSubprogram(SP);
  3244. DBuilder.retainType(SP);
  3245. }
  3246. void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
  3247. QualType CalleeType,
  3248. const FunctionDecl *CalleeDecl) {
  3249. auto &CGOpts = CGM.getCodeGenOpts();
  3250. if (!CGOpts.EnableDebugEntryValues || !CGM.getLangOpts().Optimize ||
  3251. !CallOrInvoke)
  3252. return;
  3253. auto *Func = CallOrInvoke->getCalledFunction();
  3254. if (!Func)
  3255. return;
  3256. // If there is no DISubprogram attached to the function being called,
  3257. // create the one describing the function in order to have complete
  3258. // call site debug info.
  3259. if (Func->getSubprogram())
  3260. return;
  3261. if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
  3262. EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
  3263. }
  3264. void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {
  3265. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  3266. // If there is a subprogram for this function available then use it.
  3267. auto FI = SPCache.find(FD->getCanonicalDecl());
  3268. llvm::DISubprogram *SP = nullptr;
  3269. if (FI != SPCache.end())
  3270. SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
  3271. if (!SP || !SP->isDefinition())
  3272. SP = getFunctionStub(GD);
  3273. FnBeginRegionCount.push_back(LexicalBlockStack.size());
  3274. LexicalBlockStack.emplace_back(SP);
  3275. setInlinedAt(Builder.getCurrentDebugLocation());
  3276. EmitLocation(Builder, FD->getLocation());
  3277. }
  3278. void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {
  3279. assert(CurInlinedAt && "unbalanced inline scope stack");
  3280. EmitFunctionEnd(Builder, nullptr);
  3281. setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
  3282. }
  3283. void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
  3284. // Update our current location
  3285. setLocation(Loc);
  3286. if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
  3287. return;
  3288. llvm::MDNode *Scope = LexicalBlockStack.back();
  3289. Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
  3290. getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope, CurInlinedAt));
  3291. }
  3292. void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
  3293. llvm::MDNode *Back = nullptr;
  3294. if (!LexicalBlockStack.empty())
  3295. Back = LexicalBlockStack.back().get();
  3296. LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
  3297. cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
  3298. getColumnNumber(CurLoc)));
  3299. }
  3300. void CGDebugInfo::AppendAddressSpaceXDeref(
  3301. unsigned AddressSpace, SmallVectorImpl<int64_t> &Expr) const {
  3302. Optional<unsigned> DWARFAddressSpace =
  3303. CGM.getTarget().getDWARFAddressSpace(AddressSpace);
  3304. if (!DWARFAddressSpace)
  3305. return;
  3306. Expr.push_back(llvm::dwarf::DW_OP_constu);
  3307. Expr.push_back(DWARFAddressSpace.getValue());
  3308. Expr.push_back(llvm::dwarf::DW_OP_swap);
  3309. Expr.push_back(llvm::dwarf::DW_OP_xderef);
  3310. }
  3311. void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
  3312. SourceLocation Loc) {
  3313. // Set our current location.
  3314. setLocation(Loc);
  3315. // Emit a line table change for the current location inside the new scope.
  3316. Builder.SetCurrentDebugLocation(
  3317. llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc),
  3318. LexicalBlockStack.back(), CurInlinedAt));
  3319. if (DebugKind <= codegenoptions::DebugLineTablesOnly)
  3320. return;
  3321. // Create a new lexical block and push it on the stack.
  3322. CreateLexicalBlock(Loc);
  3323. }
  3324. void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
  3325. SourceLocation Loc) {
  3326. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  3327. // Provide an entry in the line table for the end of the block.
  3328. EmitLocation(Builder, Loc);
  3329. if (DebugKind <= codegenoptions::DebugLineTablesOnly)
  3330. return;
  3331. LexicalBlockStack.pop_back();
  3332. }
  3333. void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
  3334. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  3335. unsigned RCount = FnBeginRegionCount.back();
  3336. assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
  3337. // Pop all regions for this function.
  3338. while (LexicalBlockStack.size() != RCount) {
  3339. // Provide an entry in the line table for the end of the block.
  3340. EmitLocation(Builder, CurLoc);
  3341. LexicalBlockStack.pop_back();
  3342. }
  3343. FnBeginRegionCount.pop_back();
  3344. if (Fn && Fn->getSubprogram())
  3345. DBuilder.finalizeSubprogram(Fn->getSubprogram());
  3346. }
  3347. CGDebugInfo::BlockByRefType
  3348. CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
  3349. uint64_t *XOffset) {
  3350. SmallVector<llvm::Metadata *, 5> EltTys;
  3351. QualType FType;
  3352. uint64_t FieldSize, FieldOffset;
  3353. uint32_t FieldAlign;
  3354. llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
  3355. QualType Type = VD->getType();
  3356. FieldOffset = 0;
  3357. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  3358. EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
  3359. EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
  3360. FType = CGM.getContext().IntTy;
  3361. EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
  3362. EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
  3363. bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
  3364. if (HasCopyAndDispose) {
  3365. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  3366. EltTys.push_back(
  3367. CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
  3368. EltTys.push_back(
  3369. CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
  3370. }
  3371. bool HasByrefExtendedLayout;
  3372. Qualifiers::ObjCLifetime Lifetime;
  3373. if (CGM.getContext().getByrefLifetime(Type, Lifetime,
  3374. HasByrefExtendedLayout) &&
  3375. HasByrefExtendedLayout) {
  3376. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  3377. EltTys.push_back(
  3378. CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
  3379. }
  3380. CharUnits Align = CGM.getContext().getDeclAlign(VD);
  3381. if (Align > CGM.getContext().toCharUnitsFromBits(
  3382. CGM.getTarget().getPointerAlign(0))) {
  3383. CharUnits FieldOffsetInBytes =
  3384. CGM.getContext().toCharUnitsFromBits(FieldOffset);
  3385. CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
  3386. CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
  3387. if (NumPaddingBytes.isPositive()) {
  3388. llvm::APInt pad(32, NumPaddingBytes.getQuantity());
  3389. FType = CGM.getContext().getConstantArrayType(
  3390. CGM.getContext().CharTy, pad, nullptr, ArrayType::Normal, 0);
  3391. EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
  3392. }
  3393. }
  3394. FType = Type;
  3395. llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
  3396. FieldSize = CGM.getContext().getTypeSize(FType);
  3397. FieldAlign = CGM.getContext().toBits(Align);
  3398. *XOffset = FieldOffset;
  3399. llvm::DIType *FieldTy = DBuilder.createMemberType(
  3400. Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
  3401. llvm::DINode::FlagZero, WrappedTy);
  3402. EltTys.push_back(FieldTy);
  3403. FieldOffset += FieldSize;
  3404. llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
  3405. return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
  3406. llvm::DINode::FlagZero, nullptr, Elements),
  3407. WrappedTy};
  3408. }
  3409. llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
  3410. llvm::Value *Storage,
  3411. llvm::Optional<unsigned> ArgNo,
  3412. CGBuilderTy &Builder,
  3413. const bool UsePointerValue) {
  3414. assert(DebugKind >= codegenoptions::LimitedDebugInfo);
  3415. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  3416. if (VD->hasAttr<NoDebugAttr>())
  3417. return nullptr;
  3418. bool Unwritten =
  3419. VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
  3420. cast<Decl>(VD->getDeclContext())->isImplicit());
  3421. llvm::DIFile *Unit = nullptr;
  3422. if (!Unwritten)
  3423. Unit = getOrCreateFile(VD->getLocation());
  3424. llvm::DIType *Ty;
  3425. uint64_t XOffset = 0;
  3426. if (VD->hasAttr<BlocksAttr>())
  3427. Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
  3428. else
  3429. Ty = getOrCreateType(VD->getType(), Unit);
  3430. // If there is no debug info for this type then do not emit debug info
  3431. // for this variable.
  3432. if (!Ty)
  3433. return nullptr;
  3434. // Get location information.
  3435. unsigned Line = 0;
  3436. unsigned Column = 0;
  3437. if (!Unwritten) {
  3438. Line = getLineNumber(VD->getLocation());
  3439. Column = getColumnNumber(VD->getLocation());
  3440. }
  3441. SmallVector<int64_t, 13> Expr;
  3442. llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
  3443. if (VD->isImplicit())
  3444. Flags |= llvm::DINode::FlagArtificial;
  3445. auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
  3446. unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType());
  3447. AppendAddressSpaceXDeref(AddressSpace, Expr);
  3448. // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
  3449. // object pointer flag.
  3450. if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
  3451. if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis ||
  3452. IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
  3453. Flags |= llvm::DINode::FlagObjectPointer;
  3454. }
  3455. // Note: Older versions of clang used to emit byval references with an extra
  3456. // DW_OP_deref, because they referenced the IR arg directly instead of
  3457. // referencing an alloca. Newer versions of LLVM don't treat allocas
  3458. // differently from other function arguments when used in a dbg.declare.
  3459. auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
  3460. StringRef Name = VD->getName();
  3461. if (!Name.empty()) {
  3462. if (VD->hasAttr<BlocksAttr>()) {
  3463. // Here, we need an offset *into* the alloca.
  3464. CharUnits offset = CharUnits::fromQuantity(32);
  3465. Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
  3466. // offset of __forwarding field
  3467. offset = CGM.getContext().toCharUnitsFromBits(
  3468. CGM.getTarget().getPointerWidth(0));
  3469. Expr.push_back(offset.getQuantity());
  3470. Expr.push_back(llvm::dwarf::DW_OP_deref);
  3471. Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
  3472. // offset of x field
  3473. offset = CGM.getContext().toCharUnitsFromBits(XOffset);
  3474. Expr.push_back(offset.getQuantity());
  3475. }
  3476. } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
  3477. // If VD is an anonymous union then Storage represents value for
  3478. // all union fields.
  3479. const RecordDecl *RD = RT->getDecl();
  3480. if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
  3481. // GDB has trouble finding local variables in anonymous unions, so we emit
  3482. // artificial local variables for each of the members.
  3483. //
  3484. // FIXME: Remove this code as soon as GDB supports this.
  3485. // The debug info verifier in LLVM operates based on the assumption that a
  3486. // variable has the same size as its storage and we had to disable the
  3487. // check for artificial variables.
  3488. for (const auto *Field : RD->fields()) {
  3489. llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
  3490. StringRef FieldName = Field->getName();
  3491. // Ignore unnamed fields. Do not ignore unnamed records.
  3492. if (FieldName.empty() && !isa<RecordType>(Field->getType()))
  3493. continue;
  3494. // Use VarDecl's Tag, Scope and Line number.
  3495. auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
  3496. auto *D = DBuilder.createAutoVariable(
  3497. Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
  3498. Flags | llvm::DINode::FlagArtificial, FieldAlign);
  3499. // Insert an llvm.dbg.declare into the current block.
  3500. DBuilder.insertDeclare(
  3501. Storage, D, DBuilder.createExpression(Expr),
  3502. llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
  3503. Builder.GetInsertBlock());
  3504. }
  3505. }
  3506. }
  3507. // Clang stores the sret pointer provided by the caller in a static alloca.
  3508. // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
  3509. // the address of the variable.
  3510. if (UsePointerValue) {
  3511. assert(std::find(Expr.begin(), Expr.end(), llvm::dwarf::DW_OP_deref) ==
  3512. Expr.end() &&
  3513. "Debug info already contains DW_OP_deref.");
  3514. Expr.push_back(llvm::dwarf::DW_OP_deref);
  3515. }
  3516. // Create the descriptor for the variable.
  3517. auto *D = ArgNo ? DBuilder.createParameterVariable(
  3518. Scope, Name, *ArgNo, Unit, Line, Ty,
  3519. CGM.getLangOpts().Optimize, Flags)
  3520. : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
  3521. CGM.getLangOpts().Optimize,
  3522. Flags, Align);
  3523. // Insert an llvm.dbg.declare into the current block.
  3524. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
  3525. llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
  3526. Builder.GetInsertBlock());
  3527. if (CGM.getCodeGenOpts().EnableDebugEntryValues && ArgNo) {
  3528. if (auto *PD = dyn_cast<ParmVarDecl>(VD))
  3529. ParamCache[PD].reset(D);
  3530. }
  3531. return D;
  3532. }
  3533. llvm::DILocalVariable *
  3534. CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
  3535. CGBuilderTy &Builder,
  3536. const bool UsePointerValue) {
  3537. assert(DebugKind >= codegenoptions::LimitedDebugInfo);
  3538. return EmitDeclare(VD, Storage, llvm::None, Builder, UsePointerValue);
  3539. }
  3540. void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) {
  3541. assert(DebugKind >= codegenoptions::LimitedDebugInfo);
  3542. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  3543. if (D->hasAttr<NoDebugAttr>())
  3544. return;
  3545. auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
  3546. llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
  3547. // Get location information.
  3548. unsigned Line = getLineNumber(D->getLocation());
  3549. unsigned Column = getColumnNumber(D->getLocation());
  3550. StringRef Name = D->getName();
  3551. // Create the descriptor for the label.
  3552. auto *L =
  3553. DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);
  3554. // Insert an llvm.dbg.label into the current block.
  3555. DBuilder.insertLabel(L,
  3556. llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
  3557. Builder.GetInsertBlock());
  3558. }
  3559. llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
  3560. llvm::DIType *Ty) {
  3561. llvm::DIType *CachedTy = getTypeOrNull(QualTy);
  3562. if (CachedTy)
  3563. Ty = CachedTy;
  3564. return DBuilder.createObjectPointerType(Ty);
  3565. }
  3566. void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
  3567. const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
  3568. const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
  3569. assert(DebugKind >= codegenoptions::LimitedDebugInfo);
  3570. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  3571. if (Builder.GetInsertBlock() == nullptr)
  3572. return;
  3573. if (VD->hasAttr<NoDebugAttr>())
  3574. return;
  3575. bool isByRef = VD->hasAttr<BlocksAttr>();
  3576. uint64_t XOffset = 0;
  3577. llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
  3578. llvm::DIType *Ty;
  3579. if (isByRef)
  3580. Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
  3581. else
  3582. Ty = getOrCreateType(VD->getType(), Unit);
  3583. // Self is passed along as an implicit non-arg variable in a
  3584. // block. Mark it as the object pointer.
  3585. if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
  3586. if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
  3587. Ty = CreateSelfType(VD->getType(), Ty);
  3588. // Get location information.
  3589. unsigned Line = getLineNumber(VD->getLocation());
  3590. unsigned Column = getColumnNumber(VD->getLocation());
  3591. const llvm::DataLayout &target = CGM.getDataLayout();
  3592. CharUnits offset = CharUnits::fromQuantity(
  3593. target.getStructLayout(blockInfo.StructureType)
  3594. ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
  3595. SmallVector<int64_t, 9> addr;
  3596. addr.push_back(llvm::dwarf::DW_OP_deref);
  3597. addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
  3598. addr.push_back(offset.getQuantity());
  3599. if (isByRef) {
  3600. addr.push_back(llvm::dwarf::DW_OP_deref);
  3601. addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
  3602. // offset of __forwarding field
  3603. offset =
  3604. CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
  3605. addr.push_back(offset.getQuantity());
  3606. addr.push_back(llvm::dwarf::DW_OP_deref);
  3607. addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
  3608. // offset of x field
  3609. offset = CGM.getContext().toCharUnitsFromBits(XOffset);
  3610. addr.push_back(offset.getQuantity());
  3611. }
  3612. // Create the descriptor for the variable.
  3613. auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
  3614. auto *D = DBuilder.createAutoVariable(
  3615. cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
  3616. Line, Ty, false, llvm::DINode::FlagZero, Align);
  3617. // Insert an llvm.dbg.declare into the current block.
  3618. auto DL =
  3619. llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back(), CurInlinedAt);
  3620. auto *Expr = DBuilder.createExpression(addr);
  3621. if (InsertPoint)
  3622. DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
  3623. else
  3624. DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
  3625. }
  3626. void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
  3627. unsigned ArgNo,
  3628. CGBuilderTy &Builder) {
  3629. assert(DebugKind >= codegenoptions::LimitedDebugInfo);
  3630. EmitDeclare(VD, AI, ArgNo, Builder);
  3631. }
  3632. namespace {
  3633. struct BlockLayoutChunk {
  3634. uint64_t OffsetInBits;
  3635. const BlockDecl::Capture *Capture;
  3636. };
  3637. bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
  3638. return l.OffsetInBits < r.OffsetInBits;
  3639. }
  3640. } // namespace
  3641. void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
  3642. const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
  3643. const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
  3644. SmallVectorImpl<llvm::Metadata *> &Fields) {
  3645. // Blocks in OpenCL have unique constraints which make the standard fields
  3646. // redundant while requiring size and align fields for enqueue_kernel. See
  3647. // initializeForBlockHeader in CGBlocks.cpp
  3648. if (CGM.getLangOpts().OpenCL) {
  3649. Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
  3650. BlockLayout.getElementOffsetInBits(0),
  3651. Unit, Unit));
  3652. Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
  3653. BlockLayout.getElementOffsetInBits(1),
  3654. Unit, Unit));
  3655. } else {
  3656. Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
  3657. BlockLayout.getElementOffsetInBits(0),
  3658. Unit, Unit));
  3659. Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
  3660. BlockLayout.getElementOffsetInBits(1),
  3661. Unit, Unit));
  3662. Fields.push_back(
  3663. createFieldType("__reserved", Context.IntTy, Loc, AS_public,
  3664. BlockLayout.getElementOffsetInBits(2), Unit, Unit));
  3665. auto *FnTy = Block.getBlockExpr()->getFunctionType();
  3666. auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
  3667. Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
  3668. BlockLayout.getElementOffsetInBits(3),
  3669. Unit, Unit));
  3670. Fields.push_back(createFieldType(
  3671. "__descriptor",
  3672. Context.getPointerType(Block.NeedsCopyDispose
  3673. ? Context.getBlockDescriptorExtendedType()
  3674. : Context.getBlockDescriptorType()),
  3675. Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
  3676. }
  3677. }
  3678. void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
  3679. StringRef Name,
  3680. unsigned ArgNo,
  3681. llvm::AllocaInst *Alloca,
  3682. CGBuilderTy &Builder) {
  3683. assert(DebugKind >= codegenoptions::LimitedDebugInfo);
  3684. ASTContext &C = CGM.getContext();
  3685. const BlockDecl *blockDecl = block.getBlockDecl();
  3686. // Collect some general information about the block's location.
  3687. SourceLocation loc = blockDecl->getCaretLocation();
  3688. llvm::DIFile *tunit = getOrCreateFile(loc);
  3689. unsigned line = getLineNumber(loc);
  3690. unsigned column = getColumnNumber(loc);
  3691. // Build the debug-info type for the block literal.
  3692. getDeclContextDescriptor(blockDecl);
  3693. const llvm::StructLayout *blockLayout =
  3694. CGM.getDataLayout().getStructLayout(block.StructureType);
  3695. SmallVector<llvm::Metadata *, 16> fields;
  3696. collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
  3697. fields);
  3698. // We want to sort the captures by offset, not because DWARF
  3699. // requires this, but because we're paranoid about debuggers.
  3700. SmallVector<BlockLayoutChunk, 8> chunks;
  3701. // 'this' capture.
  3702. if (blockDecl->capturesCXXThis()) {
  3703. BlockLayoutChunk chunk;
  3704. chunk.OffsetInBits =
  3705. blockLayout->getElementOffsetInBits(block.CXXThisIndex);
  3706. chunk.Capture = nullptr;
  3707. chunks.push_back(chunk);
  3708. }
  3709. // Variable captures.
  3710. for (const auto &capture : blockDecl->captures()) {
  3711. const VarDecl *variable = capture.getVariable();
  3712. const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
  3713. // Ignore constant captures.
  3714. if (captureInfo.isConstant())
  3715. continue;
  3716. BlockLayoutChunk chunk;
  3717. chunk.OffsetInBits =
  3718. blockLayout->getElementOffsetInBits(captureInfo.getIndex());
  3719. chunk.Capture = &capture;
  3720. chunks.push_back(chunk);
  3721. }
  3722. // Sort by offset.
  3723. llvm::array_pod_sort(chunks.begin(), chunks.end());
  3724. for (const BlockLayoutChunk &Chunk : chunks) {
  3725. uint64_t offsetInBits = Chunk.OffsetInBits;
  3726. const BlockDecl::Capture *capture = Chunk.Capture;
  3727. // If we have a null capture, this must be the C++ 'this' capture.
  3728. if (!capture) {
  3729. QualType type;
  3730. if (auto *Method =
  3731. cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
  3732. type = Method->getThisType();
  3733. else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
  3734. type = QualType(RDecl->getTypeForDecl(), 0);
  3735. else
  3736. llvm_unreachable("unexpected block declcontext");
  3737. fields.push_back(createFieldType("this", type, loc, AS_public,
  3738. offsetInBits, tunit, tunit));
  3739. continue;
  3740. }
  3741. const VarDecl *variable = capture->getVariable();
  3742. StringRef name = variable->getName();
  3743. llvm::DIType *fieldType;
  3744. if (capture->isByRef()) {
  3745. TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
  3746. auto Align = PtrInfo.AlignIsRequired ? PtrInfo.Align : 0;
  3747. // FIXME: This recomputes the layout of the BlockByRefWrapper.
  3748. uint64_t xoffset;
  3749. fieldType =
  3750. EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
  3751. fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
  3752. fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
  3753. PtrInfo.Width, Align, offsetInBits,
  3754. llvm::DINode::FlagZero, fieldType);
  3755. } else {
  3756. auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
  3757. fieldType = createFieldType(name, variable->getType(), loc, AS_public,
  3758. offsetInBits, Align, tunit, tunit);
  3759. }
  3760. fields.push_back(fieldType);
  3761. }
  3762. SmallString<36> typeName;
  3763. llvm::raw_svector_ostream(typeName)
  3764. << "__block_literal_" << CGM.getUniqueBlockCount();
  3765. llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
  3766. llvm::DIType *type =
  3767. DBuilder.createStructType(tunit, typeName.str(), tunit, line,
  3768. CGM.getContext().toBits(block.BlockSize), 0,
  3769. llvm::DINode::FlagZero, nullptr, fieldsArray);
  3770. type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
  3771. // Get overall information about the block.
  3772. llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
  3773. auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
  3774. // Create the descriptor for the parameter.
  3775. auto *debugVar = DBuilder.createParameterVariable(
  3776. scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
  3777. // Insert an llvm.dbg.declare into the current block.
  3778. DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
  3779. llvm::DebugLoc::get(line, column, scope, CurInlinedAt),
  3780. Builder.GetInsertBlock());
  3781. }
  3782. llvm::DIDerivedType *
  3783. CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
  3784. if (!D || !D->isStaticDataMember())
  3785. return nullptr;
  3786. auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
  3787. if (MI != StaticDataMemberCache.end()) {
  3788. assert(MI->second && "Static data member declaration should still exist");
  3789. return MI->second;
  3790. }
  3791. // If the member wasn't found in the cache, lazily construct and add it to the
  3792. // type (used when a limited form of the type is emitted).
  3793. auto DC = D->getDeclContext();
  3794. auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
  3795. return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
  3796. }
  3797. llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
  3798. const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
  3799. StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
  3800. llvm::DIGlobalVariableExpression *GVE = nullptr;
  3801. for (const auto *Field : RD->fields()) {
  3802. llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
  3803. StringRef FieldName = Field->getName();
  3804. // Ignore unnamed fields, but recurse into anonymous records.
  3805. if (FieldName.empty()) {
  3806. if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
  3807. GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
  3808. Var, DContext);
  3809. continue;
  3810. }
  3811. // Use VarDecl's Tag, Scope and Line number.
  3812. GVE = DBuilder.createGlobalVariableExpression(
  3813. DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
  3814. Var->hasLocalLinkage());
  3815. Var->addDebugInfo(GVE);
  3816. }
  3817. return GVE;
  3818. }
  3819. void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
  3820. const VarDecl *D) {
  3821. assert(DebugKind >= codegenoptions::LimitedDebugInfo);
  3822. if (D->hasAttr<NoDebugAttr>())
  3823. return;
  3824. // If we already created a DIGlobalVariable for this declaration, just attach
  3825. // it to the llvm::GlobalVariable.
  3826. auto Cached = DeclCache.find(D->getCanonicalDecl());
  3827. if (Cached != DeclCache.end())
  3828. return Var->addDebugInfo(
  3829. cast<llvm::DIGlobalVariableExpression>(Cached->second));
  3830. // Create global variable debug descriptor.
  3831. llvm::DIFile *Unit = nullptr;
  3832. llvm::DIScope *DContext = nullptr;
  3833. unsigned LineNo;
  3834. StringRef DeclName, LinkageName;
  3835. QualType T;
  3836. llvm::MDTuple *TemplateParameters = nullptr;
  3837. collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
  3838. TemplateParameters, DContext);
  3839. // Attempt to store one global variable for the declaration - even if we
  3840. // emit a lot of fields.
  3841. llvm::DIGlobalVariableExpression *GVE = nullptr;
  3842. // If this is an anonymous union then we'll want to emit a global
  3843. // variable for each member of the anonymous union so that it's possible
  3844. // to find the name of any field in the union.
  3845. if (T->isUnionType() && DeclName.empty()) {
  3846. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  3847. assert(RD->isAnonymousStructOrUnion() &&
  3848. "unnamed non-anonymous struct or union?");
  3849. GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
  3850. } else {
  3851. auto Align = getDeclAlignIfRequired(D, CGM.getContext());
  3852. SmallVector<int64_t, 4> Expr;
  3853. unsigned AddressSpace =
  3854. CGM.getContext().getTargetAddressSpace(D->getType());
  3855. if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {
  3856. if (D->hasAttr<CUDASharedAttr>())
  3857. AddressSpace =
  3858. CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared);
  3859. else if (D->hasAttr<CUDAConstantAttr>())
  3860. AddressSpace =
  3861. CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
  3862. }
  3863. AppendAddressSpaceXDeref(AddressSpace, Expr);
  3864. GVE = DBuilder.createGlobalVariableExpression(
  3865. DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
  3866. Var->hasLocalLinkage(),
  3867. Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
  3868. getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
  3869. Align);
  3870. Var->addDebugInfo(GVE);
  3871. }
  3872. DeclCache[D->getCanonicalDecl()].reset(GVE);
  3873. }
  3874. void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
  3875. assert(DebugKind >= codegenoptions::LimitedDebugInfo);
  3876. if (VD->hasAttr<NoDebugAttr>())
  3877. return;
  3878. auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
  3879. // Create the descriptor for the variable.
  3880. llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
  3881. StringRef Name = VD->getName();
  3882. llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
  3883. if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
  3884. const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
  3885. assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
  3886. if (CGM.getCodeGenOpts().EmitCodeView) {
  3887. // If CodeView, emit enums as global variables, unless they are defined
  3888. // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
  3889. // enums in classes, and because it is difficult to attach this scope
  3890. // information to the global variable.
  3891. if (isa<RecordDecl>(ED->getDeclContext()))
  3892. return;
  3893. } else {
  3894. // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
  3895. // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
  3896. // first time `ZERO` is referenced in a function.
  3897. llvm::DIType *EDTy =
  3898. getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
  3899. assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
  3900. (void)EDTy;
  3901. return;
  3902. }
  3903. }
  3904. llvm::DIScope *DContext = nullptr;
  3905. // Do not emit separate definitions for function local consts.
  3906. if (isa<FunctionDecl>(VD->getDeclContext()))
  3907. return;
  3908. // Emit definition for static members in CodeView.
  3909. VD = cast<ValueDecl>(VD->getCanonicalDecl());
  3910. auto *VarD = dyn_cast<VarDecl>(VD);
  3911. if (VarD && VarD->isStaticDataMember()) {
  3912. auto *RD = cast<RecordDecl>(VarD->getDeclContext());
  3913. getDeclContextDescriptor(VarD);
  3914. // Ensure that the type is retained even though it's otherwise unreferenced.
  3915. //
  3916. // FIXME: This is probably unnecessary, since Ty should reference RD
  3917. // through its scope.
  3918. RetainedTypes.push_back(
  3919. CGM.getContext().getRecordType(RD).getAsOpaquePtr());
  3920. if (!CGM.getCodeGenOpts().EmitCodeView)
  3921. return;
  3922. // Use the global scope for static members.
  3923. DContext = getContextDescriptor(
  3924. cast<Decl>(CGM.getContext().getTranslationUnitDecl()), TheCU);
  3925. } else {
  3926. DContext = getDeclContextDescriptor(VD);
  3927. }
  3928. auto &GV = DeclCache[VD];
  3929. if (GV)
  3930. return;
  3931. llvm::DIExpression *InitExpr = nullptr;
  3932. if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
  3933. // FIXME: Add a representation for integer constants wider than 64 bits.
  3934. if (Init.isInt())
  3935. InitExpr =
  3936. DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
  3937. else if (Init.isFloat())
  3938. InitExpr = DBuilder.createConstantValueExpression(
  3939. Init.getFloat().bitcastToAPInt().getZExtValue());
  3940. }
  3941. llvm::MDTuple *TemplateParameters = nullptr;
  3942. if (isa<VarTemplateSpecializationDecl>(VD))
  3943. if (VarD) {
  3944. llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
  3945. TemplateParameters = parameterNodes.get();
  3946. }
  3947. GV.reset(DBuilder.createGlobalVariableExpression(
  3948. DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
  3949. true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
  3950. TemplateParameters, Align));
  3951. }
  3952. llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
  3953. if (!LexicalBlockStack.empty())
  3954. return LexicalBlockStack.back();
  3955. llvm::DIScope *Mod = getParentModuleOrNull(D);
  3956. return getContextDescriptor(D, Mod ? Mod : TheCU);
  3957. }
  3958. void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
  3959. if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
  3960. return;
  3961. const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
  3962. if (!NSDecl->isAnonymousNamespace() ||
  3963. CGM.getCodeGenOpts().DebugExplicitImport) {
  3964. auto Loc = UD.getLocation();
  3965. DBuilder.createImportedModule(
  3966. getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
  3967. getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
  3968. }
  3969. }
  3970. void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
  3971. if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
  3972. return;
  3973. assert(UD.shadow_size() &&
  3974. "We shouldn't be codegening an invalid UsingDecl containing no decls");
  3975. // Emitting one decl is sufficient - debuggers can detect that this is an
  3976. // overloaded name & provide lookup for all the overloads.
  3977. const UsingShadowDecl &USD = **UD.shadow_begin();
  3978. // FIXME: Skip functions with undeduced auto return type for now since we
  3979. // don't currently have the plumbing for separate declarations & definitions
  3980. // of free functions and mismatched types (auto in the declaration, concrete
  3981. // return type in the definition)
  3982. if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl()))
  3983. if (const auto *AT =
  3984. FD->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
  3985. if (AT->getDeducedType().isNull())
  3986. return;
  3987. if (llvm::DINode *Target =
  3988. getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
  3989. auto Loc = USD.getLocation();
  3990. DBuilder.createImportedDeclaration(
  3991. getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
  3992. getOrCreateFile(Loc), getLineNumber(Loc));
  3993. }
  3994. }
  3995. void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
  3996. if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
  3997. return;
  3998. if (Module *M = ID.getImportedModule()) {
  3999. auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
  4000. auto Loc = ID.getLocation();
  4001. DBuilder.createImportedDeclaration(
  4002. getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
  4003. getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
  4004. getLineNumber(Loc));
  4005. }
  4006. }
  4007. llvm::DIImportedEntity *
  4008. CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
  4009. if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
  4010. return nullptr;
  4011. auto &VH = NamespaceAliasCache[&NA];
  4012. if (VH)
  4013. return cast<llvm::DIImportedEntity>(VH);
  4014. llvm::DIImportedEntity *R;
  4015. auto Loc = NA.getLocation();
  4016. if (const auto *Underlying =
  4017. dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
  4018. // This could cache & dedup here rather than relying on metadata deduping.
  4019. R = DBuilder.createImportedDeclaration(
  4020. getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
  4021. EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
  4022. getLineNumber(Loc), NA.getName());
  4023. else
  4024. R = DBuilder.createImportedDeclaration(
  4025. getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
  4026. getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
  4027. getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
  4028. VH.reset(R);
  4029. return R;
  4030. }
  4031. llvm::DINamespace *
  4032. CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
  4033. // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
  4034. // if necessary, and this way multiple declarations of the same namespace in
  4035. // different parent modules stay distinct.
  4036. auto I = NamespaceCache.find(NSDecl);
  4037. if (I != NamespaceCache.end())
  4038. return cast<llvm::DINamespace>(I->second);
  4039. llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
  4040. // Don't trust the context if it is a DIModule (see comment above).
  4041. llvm::DINamespace *NS =
  4042. DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
  4043. NamespaceCache[NSDecl].reset(NS);
  4044. return NS;
  4045. }
  4046. void CGDebugInfo::setDwoId(uint64_t Signature) {
  4047. assert(TheCU && "no main compile unit");
  4048. TheCU->setDWOId(Signature);
  4049. }
  4050. /// Analyzes each function parameter to determine whether it is constant
  4051. /// throughout the function body.
  4052. static void analyzeParametersModification(
  4053. ASTContext &Ctx,
  4054. llvm::DenseMap<const FunctionDecl *, llvm::TrackingMDRef> &SPDefCache,
  4055. llvm::DenseMap<const ParmVarDecl *, llvm::TrackingMDRef> &ParamCache) {
  4056. for (auto &SP : SPDefCache) {
  4057. auto *FD = SP.first;
  4058. assert(FD->hasBody() && "Functions must have body here");
  4059. const Stmt *FuncBody = (*FD).getBody();
  4060. for (auto Parm : FD->parameters()) {
  4061. ExprMutationAnalyzer FuncAnalyzer(*FuncBody, Ctx);
  4062. if (FuncAnalyzer.isMutated(Parm))
  4063. continue;
  4064. auto I = ParamCache.find(Parm);
  4065. assert(I != ParamCache.end() && "Parameters should be already cached");
  4066. auto *DIParm = cast<llvm::DILocalVariable>(I->second);
  4067. DIParm->setIsNotModified();
  4068. }
  4069. }
  4070. }
  4071. void CGDebugInfo::finalize() {
  4072. // Creating types might create further types - invalidating the current
  4073. // element and the size(), so don't cache/reference them.
  4074. for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
  4075. ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
  4076. llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
  4077. ? CreateTypeDefinition(E.Type, E.Unit)
  4078. : E.Decl;
  4079. DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
  4080. }
  4081. if (CGM.getCodeGenOpts().DwarfVersion >= 5) {
  4082. // Add methods to interface.
  4083. for (const auto &P : ObjCMethodCache) {
  4084. if (P.second.empty())
  4085. continue;
  4086. QualType QTy(P.first->getTypeForDecl(), 0);
  4087. auto It = TypeCache.find(QTy.getAsOpaquePtr());
  4088. assert(It != TypeCache.end());
  4089. llvm::DICompositeType *InterfaceDecl =
  4090. cast<llvm::DICompositeType>(It->second);
  4091. SmallVector<llvm::Metadata *, 16> EltTys;
  4092. auto CurrenetElts = InterfaceDecl->getElements();
  4093. EltTys.append(CurrenetElts.begin(), CurrenetElts.end());
  4094. for (auto &MD : P.second)
  4095. EltTys.push_back(MD);
  4096. llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
  4097. DBuilder.replaceArrays(InterfaceDecl, Elements);
  4098. }
  4099. }
  4100. for (const auto &P : ReplaceMap) {
  4101. assert(P.second);
  4102. auto *Ty = cast<llvm::DIType>(P.second);
  4103. assert(Ty->isForwardDecl());
  4104. auto It = TypeCache.find(P.first);
  4105. assert(It != TypeCache.end());
  4106. assert(It->second);
  4107. DBuilder.replaceTemporary(llvm::TempDIType(Ty),
  4108. cast<llvm::DIType>(It->second));
  4109. }
  4110. for (const auto &P : FwdDeclReplaceMap) {
  4111. assert(P.second);
  4112. llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
  4113. llvm::Metadata *Repl;
  4114. auto It = DeclCache.find(P.first);
  4115. // If there has been no definition for the declaration, call RAUW
  4116. // with ourselves, that will destroy the temporary MDNode and
  4117. // replace it with a standard one, avoiding leaking memory.
  4118. if (It == DeclCache.end())
  4119. Repl = P.second;
  4120. else
  4121. Repl = It->second;
  4122. if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
  4123. Repl = GVE->getVariable();
  4124. DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
  4125. }
  4126. // We keep our own list of retained types, because we need to look
  4127. // up the final type in the type cache.
  4128. for (auto &RT : RetainedTypes)
  4129. if (auto MD = TypeCache[RT])
  4130. DBuilder.retainType(cast<llvm::DIType>(MD));
  4131. if (CGM.getCodeGenOpts().EnableDebugEntryValues)
  4132. // This will be used to emit debug entry values.
  4133. analyzeParametersModification(CGM.getContext(), SPDefCache, ParamCache);
  4134. DBuilder.finalize();
  4135. }
  4136. void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
  4137. if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
  4138. return;
  4139. if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
  4140. // Don't ignore in case of explicit cast where it is referenced indirectly.
  4141. DBuilder.retainType(DieTy);
  4142. }
  4143. llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
  4144. if (LexicalBlockStack.empty())
  4145. return llvm::DebugLoc();
  4146. llvm::MDNode *Scope = LexicalBlockStack.back();
  4147. return llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc), Scope);
  4148. }
  4149. llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
  4150. // Call site-related attributes are only useful in optimized programs, and
  4151. // when there's a possibility of debugging backtraces.
  4152. if (!CGM.getLangOpts().Optimize || DebugKind == codegenoptions::NoDebugInfo ||
  4153. DebugKind == codegenoptions::LocTrackingOnly)
  4154. return llvm::DINode::FlagZero;
  4155. // Call site-related attributes are available in DWARF v5. Some debuggers,
  4156. // while not fully DWARF v5-compliant, may accept these attributes as if they
  4157. // were part of DWARF v4.
  4158. bool SupportsDWARFv4Ext =
  4159. CGM.getCodeGenOpts().DwarfVersion == 4 &&
  4160. (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
  4161. (CGM.getCodeGenOpts().EnableDebugEntryValues &&
  4162. CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB));
  4163. if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
  4164. return llvm::DINode::FlagZero;
  4165. return llvm::DINode::FlagAllCallsDescribed;
  4166. }