CGDebugInfo.cpp 177 KB

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