CGDebugInfo.cpp 214 KB

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