CGDebugInfo.cpp 181 KB

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