CGDebugInfo.cpp 168 KB

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