AsmWriter.cpp 160 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980
  1. //===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===//
  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 library implements `print` family of functions in classes like
  10. // Module, Function, Value, etc. In-memory representation of those classes is
  11. // converted to IR strings.
  12. //
  13. // Note that these routines must be extremely tolerant of various errors in the
  14. // LLVM code, because it can be used for debugging transformations.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/ADT/APFloat.h"
  18. #include "llvm/ADT/APInt.h"
  19. #include "llvm/ADT/ArrayRef.h"
  20. #include "llvm/ADT/DenseMap.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ADT/SetVector.h"
  23. #include "llvm/ADT/SmallPtrSet.h"
  24. #include "llvm/ADT/SmallString.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/StringExtras.h"
  27. #include "llvm/ADT/StringRef.h"
  28. #include "llvm/ADT/iterator_range.h"
  29. #include "llvm/BinaryFormat/Dwarf.h"
  30. #include "llvm/Config/llvm-config.h"
  31. #include "llvm/IR/Argument.h"
  32. #include "llvm/IR/AssemblyAnnotationWriter.h"
  33. #include "llvm/IR/Attributes.h"
  34. #include "llvm/IR/BasicBlock.h"
  35. #include "llvm/IR/CFG.h"
  36. #include "llvm/IR/CallingConv.h"
  37. #include "llvm/IR/Comdat.h"
  38. #include "llvm/IR/Constant.h"
  39. #include "llvm/IR/Constants.h"
  40. #include "llvm/IR/DebugInfoMetadata.h"
  41. #include "llvm/IR/DerivedTypes.h"
  42. #include "llvm/IR/Function.h"
  43. #include "llvm/IR/GlobalAlias.h"
  44. #include "llvm/IR/GlobalIFunc.h"
  45. #include "llvm/IR/GlobalObject.h"
  46. #include "llvm/IR/GlobalValue.h"
  47. #include "llvm/IR/GlobalVariable.h"
  48. #include "llvm/IR/IRPrintingPasses.h"
  49. #include "llvm/IR/InlineAsm.h"
  50. #include "llvm/IR/InstrTypes.h"
  51. #include "llvm/IR/Instruction.h"
  52. #include "llvm/IR/Instructions.h"
  53. #include "llvm/IR/IntrinsicInst.h"
  54. #include "llvm/IR/LLVMContext.h"
  55. #include "llvm/IR/Metadata.h"
  56. #include "llvm/IR/Module.h"
  57. #include "llvm/IR/ModuleSlotTracker.h"
  58. #include "llvm/IR/ModuleSummaryIndex.h"
  59. #include "llvm/IR/Operator.h"
  60. #include "llvm/IR/Type.h"
  61. #include "llvm/IR/TypeFinder.h"
  62. #include "llvm/IR/TypedPointerType.h"
  63. #include "llvm/IR/Use.h"
  64. #include "llvm/IR/User.h"
  65. #include "llvm/IR/Value.h"
  66. #include "llvm/Support/AtomicOrdering.h"
  67. #include "llvm/Support/Casting.h"
  68. #include "llvm/Support/Compiler.h"
  69. #include "llvm/Support/Debug.h"
  70. #include "llvm/Support/ErrorHandling.h"
  71. #include "llvm/Support/Format.h"
  72. #include "llvm/Support/FormattedStream.h"
  73. #include "llvm/Support/SaveAndRestore.h"
  74. #include "llvm/Support/raw_ostream.h"
  75. #include <algorithm>
  76. #include <cassert>
  77. #include <cctype>
  78. #include <cstddef>
  79. #include <cstdint>
  80. #include <iterator>
  81. #include <memory>
  82. #include <optional>
  83. #include <string>
  84. #include <tuple>
  85. #include <utility>
  86. #include <vector>
  87. using namespace llvm;
  88. // Make virtual table appear in this compilation unit.
  89. AssemblyAnnotationWriter::~AssemblyAnnotationWriter() = default;
  90. //===----------------------------------------------------------------------===//
  91. // Helper Functions
  92. //===----------------------------------------------------------------------===//
  93. using OrderMap = MapVector<const Value *, unsigned>;
  94. using UseListOrderMap =
  95. DenseMap<const Function *, MapVector<const Value *, std::vector<unsigned>>>;
  96. /// Look for a value that might be wrapped as metadata, e.g. a value in a
  97. /// metadata operand. Returns the input value as-is if it is not wrapped.
  98. static const Value *skipMetadataWrapper(const Value *V) {
  99. if (const auto *MAV = dyn_cast<MetadataAsValue>(V))
  100. if (const auto *VAM = dyn_cast<ValueAsMetadata>(MAV->getMetadata()))
  101. return VAM->getValue();
  102. return V;
  103. }
  104. static void orderValue(const Value *V, OrderMap &OM) {
  105. if (OM.lookup(V))
  106. return;
  107. if (const Constant *C = dyn_cast<Constant>(V))
  108. if (C->getNumOperands() && !isa<GlobalValue>(C))
  109. for (const Value *Op : C->operands())
  110. if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
  111. orderValue(Op, OM);
  112. // Note: we cannot cache this lookup above, since inserting into the map
  113. // changes the map's size, and thus affects the other IDs.
  114. unsigned ID = OM.size() + 1;
  115. OM[V] = ID;
  116. }
  117. static OrderMap orderModule(const Module *M) {
  118. OrderMap OM;
  119. for (const GlobalVariable &G : M->globals()) {
  120. if (G.hasInitializer())
  121. if (!isa<GlobalValue>(G.getInitializer()))
  122. orderValue(G.getInitializer(), OM);
  123. orderValue(&G, OM);
  124. }
  125. for (const GlobalAlias &A : M->aliases()) {
  126. if (!isa<GlobalValue>(A.getAliasee()))
  127. orderValue(A.getAliasee(), OM);
  128. orderValue(&A, OM);
  129. }
  130. for (const GlobalIFunc &I : M->ifuncs()) {
  131. if (!isa<GlobalValue>(I.getResolver()))
  132. orderValue(I.getResolver(), OM);
  133. orderValue(&I, OM);
  134. }
  135. for (const Function &F : *M) {
  136. for (const Use &U : F.operands())
  137. if (!isa<GlobalValue>(U.get()))
  138. orderValue(U.get(), OM);
  139. orderValue(&F, OM);
  140. if (F.isDeclaration())
  141. continue;
  142. for (const Argument &A : F.args())
  143. orderValue(&A, OM);
  144. for (const BasicBlock &BB : F) {
  145. orderValue(&BB, OM);
  146. for (const Instruction &I : BB) {
  147. for (const Value *Op : I.operands()) {
  148. Op = skipMetadataWrapper(Op);
  149. if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
  150. isa<InlineAsm>(*Op))
  151. orderValue(Op, OM);
  152. }
  153. orderValue(&I, OM);
  154. }
  155. }
  156. }
  157. return OM;
  158. }
  159. static std::vector<unsigned>
  160. predictValueUseListOrder(const Value *V, unsigned ID, const OrderMap &OM) {
  161. // Predict use-list order for this one.
  162. using Entry = std::pair<const Use *, unsigned>;
  163. SmallVector<Entry, 64> List;
  164. for (const Use &U : V->uses())
  165. // Check if this user will be serialized.
  166. if (OM.lookup(U.getUser()))
  167. List.push_back(std::make_pair(&U, List.size()));
  168. if (List.size() < 2)
  169. // We may have lost some users.
  170. return {};
  171. // When referencing a value before its declaration, a temporary value is
  172. // created, which will later be RAUWed with the actual value. This reverses
  173. // the use list. This happens for all values apart from basic blocks.
  174. bool GetsReversed = !isa<BasicBlock>(V);
  175. if (auto *BA = dyn_cast<BlockAddress>(V))
  176. ID = OM.lookup(BA->getBasicBlock());
  177. llvm::sort(List, [&](const Entry &L, const Entry &R) {
  178. const Use *LU = L.first;
  179. const Use *RU = R.first;
  180. if (LU == RU)
  181. return false;
  182. auto LID = OM.lookup(LU->getUser());
  183. auto RID = OM.lookup(RU->getUser());
  184. // If ID is 4, then expect: 7 6 5 1 2 3.
  185. if (LID < RID) {
  186. if (GetsReversed)
  187. if (RID <= ID)
  188. return true;
  189. return false;
  190. }
  191. if (RID < LID) {
  192. if (GetsReversed)
  193. if (LID <= ID)
  194. return false;
  195. return true;
  196. }
  197. // LID and RID are equal, so we have different operands of the same user.
  198. // Assume operands are added in order for all instructions.
  199. if (GetsReversed)
  200. if (LID <= ID)
  201. return LU->getOperandNo() < RU->getOperandNo();
  202. return LU->getOperandNo() > RU->getOperandNo();
  203. });
  204. if (llvm::is_sorted(List, llvm::less_second()))
  205. // Order is already correct.
  206. return {};
  207. // Store the shuffle.
  208. std::vector<unsigned> Shuffle(List.size());
  209. for (size_t I = 0, E = List.size(); I != E; ++I)
  210. Shuffle[I] = List[I].second;
  211. return Shuffle;
  212. }
  213. static UseListOrderMap predictUseListOrder(const Module *M) {
  214. OrderMap OM = orderModule(M);
  215. UseListOrderMap ULOM;
  216. for (const auto &Pair : OM) {
  217. const Value *V = Pair.first;
  218. if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
  219. continue;
  220. std::vector<unsigned> Shuffle =
  221. predictValueUseListOrder(V, Pair.second, OM);
  222. if (Shuffle.empty())
  223. continue;
  224. const Function *F = nullptr;
  225. if (auto *I = dyn_cast<Instruction>(V))
  226. F = I->getFunction();
  227. if (auto *A = dyn_cast<Argument>(V))
  228. F = A->getParent();
  229. if (auto *BB = dyn_cast<BasicBlock>(V))
  230. F = BB->getParent();
  231. ULOM[F][V] = std::move(Shuffle);
  232. }
  233. return ULOM;
  234. }
  235. static const Module *getModuleFromVal(const Value *V) {
  236. if (const Argument *MA = dyn_cast<Argument>(V))
  237. return MA->getParent() ? MA->getParent()->getParent() : nullptr;
  238. if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
  239. return BB->getParent() ? BB->getParent()->getParent() : nullptr;
  240. if (const Instruction *I = dyn_cast<Instruction>(V)) {
  241. const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
  242. return M ? M->getParent() : nullptr;
  243. }
  244. if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
  245. return GV->getParent();
  246. if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
  247. for (const User *U : MAV->users())
  248. if (isa<Instruction>(U))
  249. if (const Module *M = getModuleFromVal(U))
  250. return M;
  251. return nullptr;
  252. }
  253. return nullptr;
  254. }
  255. static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
  256. switch (cc) {
  257. default: Out << "cc" << cc; break;
  258. case CallingConv::Fast: Out << "fastcc"; break;
  259. case CallingConv::Cold: Out << "coldcc"; break;
  260. case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
  261. case CallingConv::AnyReg: Out << "anyregcc"; break;
  262. case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
  263. case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
  264. case CallingConv::CXX_FAST_TLS: Out << "cxx_fast_tlscc"; break;
  265. case CallingConv::GHC: Out << "ghccc"; break;
  266. case CallingConv::Tail: Out << "tailcc"; break;
  267. case CallingConv::CFGuard_Check: Out << "cfguard_checkcc"; break;
  268. case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
  269. case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
  270. case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
  271. case CallingConv::X86_RegCall: Out << "x86_regcallcc"; break;
  272. case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
  273. case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
  274. case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
  275. case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
  276. case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
  277. case CallingConv::AArch64_VectorCall: Out << "aarch64_vector_pcs"; break;
  278. case CallingConv::AArch64_SVE_VectorCall:
  279. Out << "aarch64_sve_vector_pcs";
  280. break;
  281. case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0:
  282. Out << "aarch64_sme_preservemost_from_x0";
  283. break;
  284. case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2:
  285. Out << "aarch64_sme_preservemost_from_x2";
  286. break;
  287. case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
  288. case CallingConv::AVR_INTR: Out << "avr_intrcc "; break;
  289. case CallingConv::AVR_SIGNAL: Out << "avr_signalcc "; break;
  290. case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
  291. case CallingConv::PTX_Device: Out << "ptx_device"; break;
  292. case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
  293. case CallingConv::Win64: Out << "win64cc"; break;
  294. case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
  295. case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
  296. case CallingConv::Swift: Out << "swiftcc"; break;
  297. case CallingConv::SwiftTail: Out << "swifttailcc"; break;
  298. case CallingConv::X86_INTR: Out << "x86_intrcc"; break;
  299. case CallingConv::HHVM: Out << "hhvmcc"; break;
  300. case CallingConv::HHVM_C: Out << "hhvm_ccc"; break;
  301. case CallingConv::AMDGPU_VS: Out << "amdgpu_vs"; break;
  302. case CallingConv::AMDGPU_LS: Out << "amdgpu_ls"; break;
  303. case CallingConv::AMDGPU_HS: Out << "amdgpu_hs"; break;
  304. case CallingConv::AMDGPU_ES: Out << "amdgpu_es"; break;
  305. case CallingConv::AMDGPU_GS: Out << "amdgpu_gs"; break;
  306. case CallingConv::AMDGPU_PS: Out << "amdgpu_ps"; break;
  307. case CallingConv::AMDGPU_CS: Out << "amdgpu_cs"; break;
  308. case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
  309. case CallingConv::AMDGPU_Gfx: Out << "amdgpu_gfx"; break;
  310. }
  311. }
  312. enum PrefixType {
  313. GlobalPrefix,
  314. ComdatPrefix,
  315. LabelPrefix,
  316. LocalPrefix,
  317. NoPrefix
  318. };
  319. void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
  320. assert(!Name.empty() && "Cannot get empty name!");
  321. // Scan the name to see if it needs quotes first.
  322. bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
  323. if (!NeedsQuotes) {
  324. for (unsigned char C : Name) {
  325. // By making this unsigned, the value passed in to isalnum will always be
  326. // in the range 0-255. This is important when building with MSVC because
  327. // its implementation will assert. This situation can arise when dealing
  328. // with UTF-8 multibyte characters.
  329. if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
  330. C != '_') {
  331. NeedsQuotes = true;
  332. break;
  333. }
  334. }
  335. }
  336. // If we didn't need any quotes, just write out the name in one blast.
  337. if (!NeedsQuotes) {
  338. OS << Name;
  339. return;
  340. }
  341. // Okay, we need quotes. Output the quotes and escape any scary characters as
  342. // needed.
  343. OS << '"';
  344. printEscapedString(Name, OS);
  345. OS << '"';
  346. }
  347. /// Turn the specified name into an 'LLVM name', which is either prefixed with %
  348. /// (if the string only contains simple characters) or is surrounded with ""'s
  349. /// (if it has special chars in it). Print it out.
  350. static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
  351. switch (Prefix) {
  352. case NoPrefix:
  353. break;
  354. case GlobalPrefix:
  355. OS << '@';
  356. break;
  357. case ComdatPrefix:
  358. OS << '$';
  359. break;
  360. case LabelPrefix:
  361. break;
  362. case LocalPrefix:
  363. OS << '%';
  364. break;
  365. }
  366. printLLVMNameWithoutPrefix(OS, Name);
  367. }
  368. /// Turn the specified name into an 'LLVM name', which is either prefixed with %
  369. /// (if the string only contains simple characters) or is surrounded with ""'s
  370. /// (if it has special chars in it). Print it out.
  371. static void PrintLLVMName(raw_ostream &OS, const Value *V) {
  372. PrintLLVMName(OS, V->getName(),
  373. isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
  374. }
  375. static void PrintShuffleMask(raw_ostream &Out, Type *Ty, ArrayRef<int> Mask) {
  376. Out << ", <";
  377. if (isa<ScalableVectorType>(Ty))
  378. Out << "vscale x ";
  379. Out << Mask.size() << " x i32> ";
  380. bool FirstElt = true;
  381. if (all_of(Mask, [](int Elt) { return Elt == 0; })) {
  382. Out << "zeroinitializer";
  383. } else if (all_of(Mask, [](int Elt) { return Elt == UndefMaskElem; })) {
  384. Out << "undef";
  385. } else {
  386. Out << "<";
  387. for (int Elt : Mask) {
  388. if (FirstElt)
  389. FirstElt = false;
  390. else
  391. Out << ", ";
  392. Out << "i32 ";
  393. if (Elt == UndefMaskElem)
  394. Out << "undef";
  395. else
  396. Out << Elt;
  397. }
  398. Out << ">";
  399. }
  400. }
  401. namespace {
  402. class TypePrinting {
  403. public:
  404. TypePrinting(const Module *M = nullptr) : DeferredM(M) {}
  405. TypePrinting(const TypePrinting &) = delete;
  406. TypePrinting &operator=(const TypePrinting &) = delete;
  407. /// The named types that are used by the current module.
  408. TypeFinder &getNamedTypes();
  409. /// The numbered types, number to type mapping.
  410. std::vector<StructType *> &getNumberedTypes();
  411. bool empty();
  412. void print(Type *Ty, raw_ostream &OS);
  413. void printStructBody(StructType *Ty, raw_ostream &OS);
  414. private:
  415. void incorporateTypes();
  416. /// A module to process lazily when needed. Set to nullptr as soon as used.
  417. const Module *DeferredM;
  418. TypeFinder NamedTypes;
  419. // The numbered types, along with their value.
  420. DenseMap<StructType *, unsigned> Type2Number;
  421. std::vector<StructType *> NumberedTypes;
  422. };
  423. } // end anonymous namespace
  424. TypeFinder &TypePrinting::getNamedTypes() {
  425. incorporateTypes();
  426. return NamedTypes;
  427. }
  428. std::vector<StructType *> &TypePrinting::getNumberedTypes() {
  429. incorporateTypes();
  430. // We know all the numbers that each type is used and we know that it is a
  431. // dense assignment. Convert the map to an index table, if it's not done
  432. // already (judging from the sizes):
  433. if (NumberedTypes.size() == Type2Number.size())
  434. return NumberedTypes;
  435. NumberedTypes.resize(Type2Number.size());
  436. for (const auto &P : Type2Number) {
  437. assert(P.second < NumberedTypes.size() && "Didn't get a dense numbering?");
  438. assert(!NumberedTypes[P.second] && "Didn't get a unique numbering?");
  439. NumberedTypes[P.second] = P.first;
  440. }
  441. return NumberedTypes;
  442. }
  443. bool TypePrinting::empty() {
  444. incorporateTypes();
  445. return NamedTypes.empty() && Type2Number.empty();
  446. }
  447. void TypePrinting::incorporateTypes() {
  448. if (!DeferredM)
  449. return;
  450. NamedTypes.run(*DeferredM, false);
  451. DeferredM = nullptr;
  452. // The list of struct types we got back includes all the struct types, split
  453. // the unnamed ones out to a numbering and remove the anonymous structs.
  454. unsigned NextNumber = 0;
  455. std::vector<StructType *>::iterator NextToUse = NamedTypes.begin();
  456. for (StructType *STy : NamedTypes) {
  457. // Ignore anonymous types.
  458. if (STy->isLiteral())
  459. continue;
  460. if (STy->getName().empty())
  461. Type2Number[STy] = NextNumber++;
  462. else
  463. *NextToUse++ = STy;
  464. }
  465. NamedTypes.erase(NextToUse, NamedTypes.end());
  466. }
  467. /// Write the specified type to the specified raw_ostream, making use of type
  468. /// names or up references to shorten the type name where possible.
  469. void TypePrinting::print(Type *Ty, raw_ostream &OS) {
  470. switch (Ty->getTypeID()) {
  471. case Type::VoidTyID: OS << "void"; return;
  472. case Type::HalfTyID: OS << "half"; return;
  473. case Type::BFloatTyID: OS << "bfloat"; return;
  474. case Type::FloatTyID: OS << "float"; return;
  475. case Type::DoubleTyID: OS << "double"; return;
  476. case Type::X86_FP80TyID: OS << "x86_fp80"; return;
  477. case Type::FP128TyID: OS << "fp128"; return;
  478. case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
  479. case Type::LabelTyID: OS << "label"; return;
  480. case Type::MetadataTyID: OS << "metadata"; return;
  481. case Type::X86_MMXTyID: OS << "x86_mmx"; return;
  482. case Type::X86_AMXTyID: OS << "x86_amx"; return;
  483. case Type::TokenTyID: OS << "token"; return;
  484. case Type::IntegerTyID:
  485. OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
  486. return;
  487. case Type::FunctionTyID: {
  488. FunctionType *FTy = cast<FunctionType>(Ty);
  489. print(FTy->getReturnType(), OS);
  490. OS << " (";
  491. ListSeparator LS;
  492. for (Type *Ty : FTy->params()) {
  493. OS << LS;
  494. print(Ty, OS);
  495. }
  496. if (FTy->isVarArg())
  497. OS << LS << "...";
  498. OS << ')';
  499. return;
  500. }
  501. case Type::StructTyID: {
  502. StructType *STy = cast<StructType>(Ty);
  503. if (STy->isLiteral())
  504. return printStructBody(STy, OS);
  505. if (!STy->getName().empty())
  506. return PrintLLVMName(OS, STy->getName(), LocalPrefix);
  507. incorporateTypes();
  508. const auto I = Type2Number.find(STy);
  509. if (I != Type2Number.end())
  510. OS << '%' << I->second;
  511. else // Not enumerated, print the hex address.
  512. OS << "%\"type " << STy << '\"';
  513. return;
  514. }
  515. case Type::PointerTyID: {
  516. PointerType *PTy = cast<PointerType>(Ty);
  517. if (PTy->isOpaque()) {
  518. OS << "ptr";
  519. if (unsigned AddressSpace = PTy->getAddressSpace())
  520. OS << " addrspace(" << AddressSpace << ')';
  521. return;
  522. }
  523. print(PTy->getNonOpaquePointerElementType(), OS);
  524. if (unsigned AddressSpace = PTy->getAddressSpace())
  525. OS << " addrspace(" << AddressSpace << ')';
  526. OS << '*';
  527. return;
  528. }
  529. case Type::ArrayTyID: {
  530. ArrayType *ATy = cast<ArrayType>(Ty);
  531. OS << '[' << ATy->getNumElements() << " x ";
  532. print(ATy->getElementType(), OS);
  533. OS << ']';
  534. return;
  535. }
  536. case Type::FixedVectorTyID:
  537. case Type::ScalableVectorTyID: {
  538. VectorType *PTy = cast<VectorType>(Ty);
  539. ElementCount EC = PTy->getElementCount();
  540. OS << "<";
  541. if (EC.isScalable())
  542. OS << "vscale x ";
  543. OS << EC.getKnownMinValue() << " x ";
  544. print(PTy->getElementType(), OS);
  545. OS << '>';
  546. return;
  547. }
  548. case Type::TypedPointerTyID: {
  549. TypedPointerType *TPTy = cast<TypedPointerType>(Ty);
  550. OS << "typedptr(" << *TPTy->getElementType() << ", "
  551. << TPTy->getAddressSpace() << ")";
  552. return;
  553. }
  554. case Type::TargetExtTyID:
  555. TargetExtType *TETy = cast<TargetExtType>(Ty);
  556. OS << "target(\"";
  557. printEscapedString(Ty->getTargetExtName(), OS);
  558. OS << "\"";
  559. for (Type *Inner : TETy->type_params())
  560. OS << ", " << *Inner;
  561. for (unsigned IntParam : TETy->int_params())
  562. OS << ", " << IntParam;
  563. OS << ")";
  564. return;
  565. }
  566. llvm_unreachable("Invalid TypeID");
  567. }
  568. void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
  569. if (STy->isOpaque()) {
  570. OS << "opaque";
  571. return;
  572. }
  573. if (STy->isPacked())
  574. OS << '<';
  575. if (STy->getNumElements() == 0) {
  576. OS << "{}";
  577. } else {
  578. OS << "{ ";
  579. ListSeparator LS;
  580. for (Type *Ty : STy->elements()) {
  581. OS << LS;
  582. print(Ty, OS);
  583. }
  584. OS << " }";
  585. }
  586. if (STy->isPacked())
  587. OS << '>';
  588. }
  589. AbstractSlotTrackerStorage::~AbstractSlotTrackerStorage() = default;
  590. namespace llvm {
  591. //===----------------------------------------------------------------------===//
  592. // SlotTracker Class: Enumerate slot numbers for unnamed values
  593. //===----------------------------------------------------------------------===//
  594. /// This class provides computation of slot numbers for LLVM Assembly writing.
  595. ///
  596. class SlotTracker : public AbstractSlotTrackerStorage {
  597. public:
  598. /// ValueMap - A mapping of Values to slot numbers.
  599. using ValueMap = DenseMap<const Value *, unsigned>;
  600. private:
  601. /// TheModule - The module for which we are holding slot numbers.
  602. const Module* TheModule;
  603. /// TheFunction - The function for which we are holding slot numbers.
  604. const Function* TheFunction = nullptr;
  605. bool FunctionProcessed = false;
  606. bool ShouldInitializeAllMetadata;
  607. std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
  608. ProcessModuleHookFn;
  609. std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
  610. ProcessFunctionHookFn;
  611. /// The summary index for which we are holding slot numbers.
  612. const ModuleSummaryIndex *TheIndex = nullptr;
  613. /// mMap - The slot map for the module level data.
  614. ValueMap mMap;
  615. unsigned mNext = 0;
  616. /// fMap - The slot map for the function level data.
  617. ValueMap fMap;
  618. unsigned fNext = 0;
  619. /// mdnMap - Map for MDNodes.
  620. DenseMap<const MDNode*, unsigned> mdnMap;
  621. unsigned mdnNext = 0;
  622. /// asMap - The slot map for attribute sets.
  623. DenseMap<AttributeSet, unsigned> asMap;
  624. unsigned asNext = 0;
  625. /// ModulePathMap - The slot map for Module paths used in the summary index.
  626. StringMap<unsigned> ModulePathMap;
  627. unsigned ModulePathNext = 0;
  628. /// GUIDMap - The slot map for GUIDs used in the summary index.
  629. DenseMap<GlobalValue::GUID, unsigned> GUIDMap;
  630. unsigned GUIDNext = 0;
  631. /// TypeIdMap - The slot map for type ids used in the summary index.
  632. StringMap<unsigned> TypeIdMap;
  633. unsigned TypeIdNext = 0;
  634. public:
  635. /// Construct from a module.
  636. ///
  637. /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
  638. /// functions, giving correct numbering for metadata referenced only from
  639. /// within a function (even if no functions have been initialized).
  640. explicit SlotTracker(const Module *M,
  641. bool ShouldInitializeAllMetadata = false);
  642. /// Construct from a function, starting out in incorp state.
  643. ///
  644. /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
  645. /// functions, giving correct numbering for metadata referenced only from
  646. /// within a function (even if no functions have been initialized).
  647. explicit SlotTracker(const Function *F,
  648. bool ShouldInitializeAllMetadata = false);
  649. /// Construct from a module summary index.
  650. explicit SlotTracker(const ModuleSummaryIndex *Index);
  651. SlotTracker(const SlotTracker &) = delete;
  652. SlotTracker &operator=(const SlotTracker &) = delete;
  653. ~SlotTracker() = default;
  654. void setProcessHook(
  655. std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>);
  656. void setProcessHook(std::function<void(AbstractSlotTrackerStorage *,
  657. const Function *, bool)>);
  658. unsigned getNextMetadataSlot() override { return mdnNext; }
  659. void createMetadataSlot(const MDNode *N) override;
  660. /// Return the slot number of the specified value in it's type
  661. /// plane. If something is not in the SlotTracker, return -1.
  662. int getLocalSlot(const Value *V);
  663. int getGlobalSlot(const GlobalValue *V);
  664. int getMetadataSlot(const MDNode *N) override;
  665. int getAttributeGroupSlot(AttributeSet AS);
  666. int getModulePathSlot(StringRef Path);
  667. int getGUIDSlot(GlobalValue::GUID GUID);
  668. int getTypeIdSlot(StringRef Id);
  669. /// If you'd like to deal with a function instead of just a module, use
  670. /// this method to get its data into the SlotTracker.
  671. void incorporateFunction(const Function *F) {
  672. TheFunction = F;
  673. FunctionProcessed = false;
  674. }
  675. const Function *getFunction() const { return TheFunction; }
  676. /// After calling incorporateFunction, use this method to remove the
  677. /// most recently incorporated function from the SlotTracker. This
  678. /// will reset the state of the machine back to just the module contents.
  679. void purgeFunction();
  680. /// MDNode map iterators.
  681. using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
  682. mdn_iterator mdn_begin() { return mdnMap.begin(); }
  683. mdn_iterator mdn_end() { return mdnMap.end(); }
  684. unsigned mdn_size() const { return mdnMap.size(); }
  685. bool mdn_empty() const { return mdnMap.empty(); }
  686. /// AttributeSet map iterators.
  687. using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
  688. as_iterator as_begin() { return asMap.begin(); }
  689. as_iterator as_end() { return asMap.end(); }
  690. unsigned as_size() const { return asMap.size(); }
  691. bool as_empty() const { return asMap.empty(); }
  692. /// GUID map iterators.
  693. using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator;
  694. /// These functions do the actual initialization.
  695. inline void initializeIfNeeded();
  696. int initializeIndexIfNeeded();
  697. // Implementation Details
  698. private:
  699. /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
  700. void CreateModuleSlot(const GlobalValue *V);
  701. /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
  702. void CreateMetadataSlot(const MDNode *N);
  703. /// CreateFunctionSlot - Insert the specified Value* into the slot table.
  704. void CreateFunctionSlot(const Value *V);
  705. /// Insert the specified AttributeSet into the slot table.
  706. void CreateAttributeSetSlot(AttributeSet AS);
  707. inline void CreateModulePathSlot(StringRef Path);
  708. void CreateGUIDSlot(GlobalValue::GUID GUID);
  709. void CreateTypeIdSlot(StringRef Id);
  710. /// Add all of the module level global variables (and their initializers)
  711. /// and function declarations, but not the contents of those functions.
  712. void processModule();
  713. // Returns number of allocated slots
  714. int processIndex();
  715. /// Add all of the functions arguments, basic blocks, and instructions.
  716. void processFunction();
  717. /// Add the metadata directly attached to a GlobalObject.
  718. void processGlobalObjectMetadata(const GlobalObject &GO);
  719. /// Add all of the metadata from a function.
  720. void processFunctionMetadata(const Function &F);
  721. /// Add all of the metadata from an instruction.
  722. void processInstructionMetadata(const Instruction &I);
  723. };
  724. } // end namespace llvm
  725. ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
  726. const Function *F)
  727. : M(M), F(F), Machine(&Machine) {}
  728. ModuleSlotTracker::ModuleSlotTracker(const Module *M,
  729. bool ShouldInitializeAllMetadata)
  730. : ShouldCreateStorage(M),
  731. ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
  732. ModuleSlotTracker::~ModuleSlotTracker() = default;
  733. SlotTracker *ModuleSlotTracker::getMachine() {
  734. if (!ShouldCreateStorage)
  735. return Machine;
  736. ShouldCreateStorage = false;
  737. MachineStorage =
  738. std::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
  739. Machine = MachineStorage.get();
  740. if (ProcessModuleHookFn)
  741. Machine->setProcessHook(ProcessModuleHookFn);
  742. if (ProcessFunctionHookFn)
  743. Machine->setProcessHook(ProcessFunctionHookFn);
  744. return Machine;
  745. }
  746. void ModuleSlotTracker::incorporateFunction(const Function &F) {
  747. // Using getMachine() may lazily create the slot tracker.
  748. if (!getMachine())
  749. return;
  750. // Nothing to do if this is the right function already.
  751. if (this->F == &F)
  752. return;
  753. if (this->F)
  754. Machine->purgeFunction();
  755. Machine->incorporateFunction(&F);
  756. this->F = &F;
  757. }
  758. int ModuleSlotTracker::getLocalSlot(const Value *V) {
  759. assert(F && "No function incorporated");
  760. return Machine->getLocalSlot(V);
  761. }
  762. void ModuleSlotTracker::setProcessHook(
  763. std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
  764. Fn) {
  765. ProcessModuleHookFn = Fn;
  766. }
  767. void ModuleSlotTracker::setProcessHook(
  768. std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
  769. Fn) {
  770. ProcessFunctionHookFn = Fn;
  771. }
  772. static SlotTracker *createSlotTracker(const Value *V) {
  773. if (const Argument *FA = dyn_cast<Argument>(V))
  774. return new SlotTracker(FA->getParent());
  775. if (const Instruction *I = dyn_cast<Instruction>(V))
  776. if (I->getParent())
  777. return new SlotTracker(I->getParent()->getParent());
  778. if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
  779. return new SlotTracker(BB->getParent());
  780. if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
  781. return new SlotTracker(GV->getParent());
  782. if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
  783. return new SlotTracker(GA->getParent());
  784. if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
  785. return new SlotTracker(GIF->getParent());
  786. if (const Function *Func = dyn_cast<Function>(V))
  787. return new SlotTracker(Func);
  788. return nullptr;
  789. }
  790. #if 0
  791. #define ST_DEBUG(X) dbgs() << X
  792. #else
  793. #define ST_DEBUG(X)
  794. #endif
  795. // Module level constructor. Causes the contents of the Module (sans functions)
  796. // to be added to the slot table.
  797. SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
  798. : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
  799. // Function level constructor. Causes the contents of the Module and the one
  800. // function provided to be added to the slot table.
  801. SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
  802. : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
  803. ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
  804. SlotTracker::SlotTracker(const ModuleSummaryIndex *Index)
  805. : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {}
  806. inline void SlotTracker::initializeIfNeeded() {
  807. if (TheModule) {
  808. processModule();
  809. TheModule = nullptr; ///< Prevent re-processing next time we're called.
  810. }
  811. if (TheFunction && !FunctionProcessed)
  812. processFunction();
  813. }
  814. int SlotTracker::initializeIndexIfNeeded() {
  815. if (!TheIndex)
  816. return 0;
  817. int NumSlots = processIndex();
  818. TheIndex = nullptr; ///< Prevent re-processing next time we're called.
  819. return NumSlots;
  820. }
  821. // Iterate through all the global variables, functions, and global
  822. // variable initializers and create slots for them.
  823. void SlotTracker::processModule() {
  824. ST_DEBUG("begin processModule!\n");
  825. // Add all of the unnamed global variables to the value table.
  826. for (const GlobalVariable &Var : TheModule->globals()) {
  827. if (!Var.hasName())
  828. CreateModuleSlot(&Var);
  829. processGlobalObjectMetadata(Var);
  830. auto Attrs = Var.getAttributes();
  831. if (Attrs.hasAttributes())
  832. CreateAttributeSetSlot(Attrs);
  833. }
  834. for (const GlobalAlias &A : TheModule->aliases()) {
  835. if (!A.hasName())
  836. CreateModuleSlot(&A);
  837. }
  838. for (const GlobalIFunc &I : TheModule->ifuncs()) {
  839. if (!I.hasName())
  840. CreateModuleSlot(&I);
  841. }
  842. // Add metadata used by named metadata.
  843. for (const NamedMDNode &NMD : TheModule->named_metadata()) {
  844. for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
  845. CreateMetadataSlot(NMD.getOperand(i));
  846. }
  847. for (const Function &F : *TheModule) {
  848. if (!F.hasName())
  849. // Add all the unnamed functions to the table.
  850. CreateModuleSlot(&F);
  851. if (ShouldInitializeAllMetadata)
  852. processFunctionMetadata(F);
  853. // Add all the function attributes to the table.
  854. // FIXME: Add attributes of other objects?
  855. AttributeSet FnAttrs = F.getAttributes().getFnAttrs();
  856. if (FnAttrs.hasAttributes())
  857. CreateAttributeSetSlot(FnAttrs);
  858. }
  859. if (ProcessModuleHookFn)
  860. ProcessModuleHookFn(this, TheModule, ShouldInitializeAllMetadata);
  861. ST_DEBUG("end processModule!\n");
  862. }
  863. // Process the arguments, basic blocks, and instructions of a function.
  864. void SlotTracker::processFunction() {
  865. ST_DEBUG("begin processFunction!\n");
  866. fNext = 0;
  867. // Process function metadata if it wasn't hit at the module-level.
  868. if (!ShouldInitializeAllMetadata)
  869. processFunctionMetadata(*TheFunction);
  870. // Add all the function arguments with no names.
  871. for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
  872. AE = TheFunction->arg_end(); AI != AE; ++AI)
  873. if (!AI->hasName())
  874. CreateFunctionSlot(&*AI);
  875. ST_DEBUG("Inserting Instructions:\n");
  876. // Add all of the basic blocks and instructions with no names.
  877. for (auto &BB : *TheFunction) {
  878. if (!BB.hasName())
  879. CreateFunctionSlot(&BB);
  880. for (auto &I : BB) {
  881. if (!I.getType()->isVoidTy() && !I.hasName())
  882. CreateFunctionSlot(&I);
  883. // We allow direct calls to any llvm.foo function here, because the
  884. // target may not be linked into the optimizer.
  885. if (const auto *Call = dyn_cast<CallBase>(&I)) {
  886. // Add all the call attributes to the table.
  887. AttributeSet Attrs = Call->getAttributes().getFnAttrs();
  888. if (Attrs.hasAttributes())
  889. CreateAttributeSetSlot(Attrs);
  890. }
  891. }
  892. }
  893. if (ProcessFunctionHookFn)
  894. ProcessFunctionHookFn(this, TheFunction, ShouldInitializeAllMetadata);
  895. FunctionProcessed = true;
  896. ST_DEBUG("end processFunction!\n");
  897. }
  898. // Iterate through all the GUID in the index and create slots for them.
  899. int SlotTracker::processIndex() {
  900. ST_DEBUG("begin processIndex!\n");
  901. assert(TheIndex);
  902. // The first block of slots are just the module ids, which start at 0 and are
  903. // assigned consecutively. Since the StringMap iteration order isn't
  904. // guaranteed, use a std::map to order by module ID before assigning slots.
  905. std::map<uint64_t, StringRef> ModuleIdToPathMap;
  906. for (auto &[ModPath, ModId] : TheIndex->modulePaths())
  907. ModuleIdToPathMap[ModId.first] = ModPath;
  908. for (auto &ModPair : ModuleIdToPathMap)
  909. CreateModulePathSlot(ModPair.second);
  910. // Start numbering the GUIDs after the module ids.
  911. GUIDNext = ModulePathNext;
  912. for (auto &GlobalList : *TheIndex)
  913. CreateGUIDSlot(GlobalList.first);
  914. for (auto &TId : TheIndex->typeIdCompatibleVtableMap())
  915. CreateGUIDSlot(GlobalValue::getGUID(TId.first));
  916. // Start numbering the TypeIds after the GUIDs.
  917. TypeIdNext = GUIDNext;
  918. for (const auto &TID : TheIndex->typeIds())
  919. CreateTypeIdSlot(TID.second.first);
  920. ST_DEBUG("end processIndex!\n");
  921. return TypeIdNext;
  922. }
  923. void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {
  924. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  925. GO.getAllMetadata(MDs);
  926. for (auto &MD : MDs)
  927. CreateMetadataSlot(MD.second);
  928. }
  929. void SlotTracker::processFunctionMetadata(const Function &F) {
  930. processGlobalObjectMetadata(F);
  931. for (auto &BB : F) {
  932. for (auto &I : BB)
  933. processInstructionMetadata(I);
  934. }
  935. }
  936. void SlotTracker::processInstructionMetadata(const Instruction &I) {
  937. // Process metadata used directly by intrinsics.
  938. if (const CallInst *CI = dyn_cast<CallInst>(&I))
  939. if (Function *F = CI->getCalledFunction())
  940. if (F->isIntrinsic())
  941. for (auto &Op : I.operands())
  942. if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
  943. if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
  944. CreateMetadataSlot(N);
  945. // Process metadata attached to this instruction.
  946. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  947. I.getAllMetadata(MDs);
  948. for (auto &MD : MDs)
  949. CreateMetadataSlot(MD.second);
  950. }
  951. /// Clean up after incorporating a function. This is the only way to get out of
  952. /// the function incorporation state that affects get*Slot/Create*Slot. Function
  953. /// incorporation state is indicated by TheFunction != 0.
  954. void SlotTracker::purgeFunction() {
  955. ST_DEBUG("begin purgeFunction!\n");
  956. fMap.clear(); // Simply discard the function level map
  957. TheFunction = nullptr;
  958. FunctionProcessed = false;
  959. ST_DEBUG("end purgeFunction!\n");
  960. }
  961. /// getGlobalSlot - Get the slot number of a global value.
  962. int SlotTracker::getGlobalSlot(const GlobalValue *V) {
  963. // Check for uninitialized state and do lazy initialization.
  964. initializeIfNeeded();
  965. // Find the value in the module map
  966. ValueMap::iterator MI = mMap.find(V);
  967. return MI == mMap.end() ? -1 : (int)MI->second;
  968. }
  969. void SlotTracker::setProcessHook(
  970. std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
  971. Fn) {
  972. ProcessModuleHookFn = Fn;
  973. }
  974. void SlotTracker::setProcessHook(
  975. std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
  976. Fn) {
  977. ProcessFunctionHookFn = Fn;
  978. }
  979. /// getMetadataSlot - Get the slot number of a MDNode.
  980. void SlotTracker::createMetadataSlot(const MDNode *N) { CreateMetadataSlot(N); }
  981. /// getMetadataSlot - Get the slot number of a MDNode.
  982. int SlotTracker::getMetadataSlot(const MDNode *N) {
  983. // Check for uninitialized state and do lazy initialization.
  984. initializeIfNeeded();
  985. // Find the MDNode in the module map
  986. mdn_iterator MI = mdnMap.find(N);
  987. return MI == mdnMap.end() ? -1 : (int)MI->second;
  988. }
  989. /// getLocalSlot - Get the slot number for a value that is local to a function.
  990. int SlotTracker::getLocalSlot(const Value *V) {
  991. assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
  992. // Check for uninitialized state and do lazy initialization.
  993. initializeIfNeeded();
  994. ValueMap::iterator FI = fMap.find(V);
  995. return FI == fMap.end() ? -1 : (int)FI->second;
  996. }
  997. int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
  998. // Check for uninitialized state and do lazy initialization.
  999. initializeIfNeeded();
  1000. // Find the AttributeSet in the module map.
  1001. as_iterator AI = asMap.find(AS);
  1002. return AI == asMap.end() ? -1 : (int)AI->second;
  1003. }
  1004. int SlotTracker::getModulePathSlot(StringRef Path) {
  1005. // Check for uninitialized state and do lazy initialization.
  1006. initializeIndexIfNeeded();
  1007. // Find the Module path in the map
  1008. auto I = ModulePathMap.find(Path);
  1009. return I == ModulePathMap.end() ? -1 : (int)I->second;
  1010. }
  1011. int SlotTracker::getGUIDSlot(GlobalValue::GUID GUID) {
  1012. // Check for uninitialized state and do lazy initialization.
  1013. initializeIndexIfNeeded();
  1014. // Find the GUID in the map
  1015. guid_iterator I = GUIDMap.find(GUID);
  1016. return I == GUIDMap.end() ? -1 : (int)I->second;
  1017. }
  1018. int SlotTracker::getTypeIdSlot(StringRef Id) {
  1019. // Check for uninitialized state and do lazy initialization.
  1020. initializeIndexIfNeeded();
  1021. // Find the TypeId string in the map
  1022. auto I = TypeIdMap.find(Id);
  1023. return I == TypeIdMap.end() ? -1 : (int)I->second;
  1024. }
  1025. /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
  1026. void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
  1027. assert(V && "Can't insert a null Value into SlotTracker!");
  1028. assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
  1029. assert(!V->hasName() && "Doesn't need a slot!");
  1030. unsigned DestSlot = mNext++;
  1031. mMap[V] = DestSlot;
  1032. ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
  1033. DestSlot << " [");
  1034. // G = Global, F = Function, A = Alias, I = IFunc, o = other
  1035. ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
  1036. (isa<Function>(V) ? 'F' :
  1037. (isa<GlobalAlias>(V) ? 'A' :
  1038. (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
  1039. }
  1040. /// CreateSlot - Create a new slot for the specified value if it has no name.
  1041. void SlotTracker::CreateFunctionSlot(const Value *V) {
  1042. assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
  1043. unsigned DestSlot = fNext++;
  1044. fMap[V] = DestSlot;
  1045. // G = Global, F = Function, o = other
  1046. ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
  1047. DestSlot << " [o]\n");
  1048. }
  1049. /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
  1050. void SlotTracker::CreateMetadataSlot(const MDNode *N) {
  1051. assert(N && "Can't insert a null Value into SlotTracker!");
  1052. // Don't make slots for DIExpressions or DIArgLists. We just print them inline
  1053. // everywhere.
  1054. if (isa<DIExpression>(N) || isa<DIArgList>(N))
  1055. return;
  1056. unsigned DestSlot = mdnNext;
  1057. if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
  1058. return;
  1059. ++mdnNext;
  1060. // Recursively add any MDNodes referenced by operands.
  1061. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
  1062. if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
  1063. CreateMetadataSlot(Op);
  1064. }
  1065. void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
  1066. assert(AS.hasAttributes() && "Doesn't need a slot!");
  1067. as_iterator I = asMap.find(AS);
  1068. if (I != asMap.end())
  1069. return;
  1070. unsigned DestSlot = asNext++;
  1071. asMap[AS] = DestSlot;
  1072. }
  1073. /// Create a new slot for the specified Module
  1074. void SlotTracker::CreateModulePathSlot(StringRef Path) {
  1075. ModulePathMap[Path] = ModulePathNext++;
  1076. }
  1077. /// Create a new slot for the specified GUID
  1078. void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID) {
  1079. GUIDMap[GUID] = GUIDNext++;
  1080. }
  1081. /// Create a new slot for the specified Id
  1082. void SlotTracker::CreateTypeIdSlot(StringRef Id) {
  1083. TypeIdMap[Id] = TypeIdNext++;
  1084. }
  1085. namespace {
  1086. /// Common instances used by most of the printer functions.
  1087. struct AsmWriterContext {
  1088. TypePrinting *TypePrinter = nullptr;
  1089. SlotTracker *Machine = nullptr;
  1090. const Module *Context = nullptr;
  1091. AsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M = nullptr)
  1092. : TypePrinter(TP), Machine(ST), Context(M) {}
  1093. static AsmWriterContext &getEmpty() {
  1094. static AsmWriterContext EmptyCtx(nullptr, nullptr);
  1095. return EmptyCtx;
  1096. }
  1097. /// A callback that will be triggered when the underlying printer
  1098. /// prints a Metadata as operand.
  1099. virtual void onWriteMetadataAsOperand(const Metadata *) {}
  1100. virtual ~AsmWriterContext() = default;
  1101. };
  1102. } // end anonymous namespace
  1103. //===----------------------------------------------------------------------===//
  1104. // AsmWriter Implementation
  1105. //===----------------------------------------------------------------------===//
  1106. static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
  1107. AsmWriterContext &WriterCtx);
  1108. static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
  1109. AsmWriterContext &WriterCtx,
  1110. bool FromValue = false);
  1111. static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
  1112. if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U))
  1113. Out << FPO->getFastMathFlags();
  1114. if (const OverflowingBinaryOperator *OBO =
  1115. dyn_cast<OverflowingBinaryOperator>(U)) {
  1116. if (OBO->hasNoUnsignedWrap())
  1117. Out << " nuw";
  1118. if (OBO->hasNoSignedWrap())
  1119. Out << " nsw";
  1120. } else if (const PossiblyExactOperator *Div =
  1121. dyn_cast<PossiblyExactOperator>(U)) {
  1122. if (Div->isExact())
  1123. Out << " exact";
  1124. } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  1125. if (GEP->isInBounds())
  1126. Out << " inbounds";
  1127. }
  1128. }
  1129. static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
  1130. AsmWriterContext &WriterCtx) {
  1131. if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
  1132. if (CI->getType()->isIntegerTy(1)) {
  1133. Out << (CI->getZExtValue() ? "true" : "false");
  1134. return;
  1135. }
  1136. Out << CI->getValue();
  1137. return;
  1138. }
  1139. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
  1140. const APFloat &APF = CFP->getValueAPF();
  1141. if (&APF.getSemantics() == &APFloat::IEEEsingle() ||
  1142. &APF.getSemantics() == &APFloat::IEEEdouble()) {
  1143. // We would like to output the FP constant value in exponential notation,
  1144. // but we cannot do this if doing so will lose precision. Check here to
  1145. // make sure that we only output it in exponential format if we can parse
  1146. // the value back and get the same value.
  1147. //
  1148. bool ignored;
  1149. bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble();
  1150. bool isInf = APF.isInfinity();
  1151. bool isNaN = APF.isNaN();
  1152. if (!isInf && !isNaN) {
  1153. double Val = APF.convertToDouble();
  1154. SmallString<128> StrVal;
  1155. APF.toString(StrVal, 6, 0, false);
  1156. // Check to make sure that the stringized number is not some string like
  1157. // "Inf" or NaN, that atof will accept, but the lexer will not. Check
  1158. // that the string matches the "[-+]?[0-9]" regex.
  1159. //
  1160. assert((isDigit(StrVal[0]) || ((StrVal[0] == '-' || StrVal[0] == '+') &&
  1161. isDigit(StrVal[1]))) &&
  1162. "[-+]?[0-9] regex does not match!");
  1163. // Reparse stringized version!
  1164. if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
  1165. Out << StrVal;
  1166. return;
  1167. }
  1168. }
  1169. // Otherwise we could not reparse it to exactly the same value, so we must
  1170. // output the string in hexadecimal format! Note that loading and storing
  1171. // floating point types changes the bits of NaNs on some hosts, notably
  1172. // x86, so we must not use these types.
  1173. static_assert(sizeof(double) == sizeof(uint64_t),
  1174. "assuming that double is 64 bits!");
  1175. APFloat apf = APF;
  1176. // Floats are represented in ASCII IR as double, convert.
  1177. // FIXME: We should allow 32-bit hex float and remove this.
  1178. if (!isDouble) {
  1179. // A signaling NaN is quieted on conversion, so we need to recreate the
  1180. // expected value after convert (quiet bit of the payload is clear).
  1181. bool IsSNAN = apf.isSignaling();
  1182. apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
  1183. &ignored);
  1184. if (IsSNAN) {
  1185. APInt Payload = apf.bitcastToAPInt();
  1186. apf = APFloat::getSNaN(APFloat::IEEEdouble(), apf.isNegative(),
  1187. &Payload);
  1188. }
  1189. }
  1190. Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
  1191. return;
  1192. }
  1193. // Either half, bfloat or some form of long double.
  1194. // These appear as a magic letter identifying the type, then a
  1195. // fixed number of hex digits.
  1196. Out << "0x";
  1197. APInt API = APF.bitcastToAPInt();
  1198. if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {
  1199. Out << 'K';
  1200. Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
  1201. /*Upper=*/true);
  1202. Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
  1203. /*Upper=*/true);
  1204. return;
  1205. } else if (&APF.getSemantics() == &APFloat::IEEEquad()) {
  1206. Out << 'L';
  1207. Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
  1208. /*Upper=*/true);
  1209. Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
  1210. /*Upper=*/true);
  1211. } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
  1212. Out << 'M';
  1213. Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
  1214. /*Upper=*/true);
  1215. Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
  1216. /*Upper=*/true);
  1217. } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {
  1218. Out << 'H';
  1219. Out << format_hex_no_prefix(API.getZExtValue(), 4,
  1220. /*Upper=*/true);
  1221. } else if (&APF.getSemantics() == &APFloat::BFloat()) {
  1222. Out << 'R';
  1223. Out << format_hex_no_prefix(API.getZExtValue(), 4,
  1224. /*Upper=*/true);
  1225. } else
  1226. llvm_unreachable("Unsupported floating point type");
  1227. return;
  1228. }
  1229. if (isa<ConstantAggregateZero>(CV) || isa<ConstantTargetNone>(CV)) {
  1230. Out << "zeroinitializer";
  1231. return;
  1232. }
  1233. if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
  1234. Out << "blockaddress(";
  1235. WriteAsOperandInternal(Out, BA->getFunction(), WriterCtx);
  1236. Out << ", ";
  1237. WriteAsOperandInternal(Out, BA->getBasicBlock(), WriterCtx);
  1238. Out << ")";
  1239. return;
  1240. }
  1241. if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV)) {
  1242. Out << "dso_local_equivalent ";
  1243. WriteAsOperandInternal(Out, Equiv->getGlobalValue(), WriterCtx);
  1244. return;
  1245. }
  1246. if (const auto *NC = dyn_cast<NoCFIValue>(CV)) {
  1247. Out << "no_cfi ";
  1248. WriteAsOperandInternal(Out, NC->getGlobalValue(), WriterCtx);
  1249. return;
  1250. }
  1251. if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
  1252. Type *ETy = CA->getType()->getElementType();
  1253. Out << '[';
  1254. WriterCtx.TypePrinter->print(ETy, Out);
  1255. Out << ' ';
  1256. WriteAsOperandInternal(Out, CA->getOperand(0), WriterCtx);
  1257. for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
  1258. Out << ", ";
  1259. WriterCtx.TypePrinter->print(ETy, Out);
  1260. Out << ' ';
  1261. WriteAsOperandInternal(Out, CA->getOperand(i), WriterCtx);
  1262. }
  1263. Out << ']';
  1264. return;
  1265. }
  1266. if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
  1267. // As a special case, print the array as a string if it is an array of
  1268. // i8 with ConstantInt values.
  1269. if (CA->isString()) {
  1270. Out << "c\"";
  1271. printEscapedString(CA->getAsString(), Out);
  1272. Out << '"';
  1273. return;
  1274. }
  1275. Type *ETy = CA->getType()->getElementType();
  1276. Out << '[';
  1277. WriterCtx.TypePrinter->print(ETy, Out);
  1278. Out << ' ';
  1279. WriteAsOperandInternal(Out, CA->getElementAsConstant(0), WriterCtx);
  1280. for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
  1281. Out << ", ";
  1282. WriterCtx.TypePrinter->print(ETy, Out);
  1283. Out << ' ';
  1284. WriteAsOperandInternal(Out, CA->getElementAsConstant(i), WriterCtx);
  1285. }
  1286. Out << ']';
  1287. return;
  1288. }
  1289. if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
  1290. if (CS->getType()->isPacked())
  1291. Out << '<';
  1292. Out << '{';
  1293. unsigned N = CS->getNumOperands();
  1294. if (N) {
  1295. Out << ' ';
  1296. WriterCtx.TypePrinter->print(CS->getOperand(0)->getType(), Out);
  1297. Out << ' ';
  1298. WriteAsOperandInternal(Out, CS->getOperand(0), WriterCtx);
  1299. for (unsigned i = 1; i < N; i++) {
  1300. Out << ", ";
  1301. WriterCtx.TypePrinter->print(CS->getOperand(i)->getType(), Out);
  1302. Out << ' ';
  1303. WriteAsOperandInternal(Out, CS->getOperand(i), WriterCtx);
  1304. }
  1305. Out << ' ';
  1306. }
  1307. Out << '}';
  1308. if (CS->getType()->isPacked())
  1309. Out << '>';
  1310. return;
  1311. }
  1312. if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
  1313. auto *CVVTy = cast<FixedVectorType>(CV->getType());
  1314. Type *ETy = CVVTy->getElementType();
  1315. Out << '<';
  1316. WriterCtx.TypePrinter->print(ETy, Out);
  1317. Out << ' ';
  1318. WriteAsOperandInternal(Out, CV->getAggregateElement(0U), WriterCtx);
  1319. for (unsigned i = 1, e = CVVTy->getNumElements(); i != e; ++i) {
  1320. Out << ", ";
  1321. WriterCtx.TypePrinter->print(ETy, Out);
  1322. Out << ' ';
  1323. WriteAsOperandInternal(Out, CV->getAggregateElement(i), WriterCtx);
  1324. }
  1325. Out << '>';
  1326. return;
  1327. }
  1328. if (isa<ConstantPointerNull>(CV)) {
  1329. Out << "null";
  1330. return;
  1331. }
  1332. if (isa<ConstantTokenNone>(CV)) {
  1333. Out << "none";
  1334. return;
  1335. }
  1336. if (isa<PoisonValue>(CV)) {
  1337. Out << "poison";
  1338. return;
  1339. }
  1340. if (isa<UndefValue>(CV)) {
  1341. Out << "undef";
  1342. return;
  1343. }
  1344. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
  1345. Out << CE->getOpcodeName();
  1346. WriteOptimizationInfo(Out, CE);
  1347. if (CE->isCompare())
  1348. Out << ' ' << CmpInst::getPredicateName(
  1349. static_cast<CmpInst::Predicate>(CE->getPredicate()));
  1350. Out << " (";
  1351. std::optional<unsigned> InRangeOp;
  1352. if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
  1353. WriterCtx.TypePrinter->print(GEP->getSourceElementType(), Out);
  1354. Out << ", ";
  1355. InRangeOp = GEP->getInRangeIndex();
  1356. if (InRangeOp)
  1357. ++*InRangeOp;
  1358. }
  1359. for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
  1360. if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp)
  1361. Out << "inrange ";
  1362. WriterCtx.TypePrinter->print((*OI)->getType(), Out);
  1363. Out << ' ';
  1364. WriteAsOperandInternal(Out, *OI, WriterCtx);
  1365. if (OI+1 != CE->op_end())
  1366. Out << ", ";
  1367. }
  1368. if (CE->isCast()) {
  1369. Out << " to ";
  1370. WriterCtx.TypePrinter->print(CE->getType(), Out);
  1371. }
  1372. if (CE->getOpcode() == Instruction::ShuffleVector)
  1373. PrintShuffleMask(Out, CE->getType(), CE->getShuffleMask());
  1374. Out << ')';
  1375. return;
  1376. }
  1377. Out << "<placeholder or erroneous Constant>";
  1378. }
  1379. static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
  1380. AsmWriterContext &WriterCtx) {
  1381. Out << "!{";
  1382. for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
  1383. const Metadata *MD = Node->getOperand(mi);
  1384. if (!MD)
  1385. Out << "null";
  1386. else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
  1387. Value *V = MDV->getValue();
  1388. WriterCtx.TypePrinter->print(V->getType(), Out);
  1389. Out << ' ';
  1390. WriteAsOperandInternal(Out, V, WriterCtx);
  1391. } else {
  1392. WriteAsOperandInternal(Out, MD, WriterCtx);
  1393. WriterCtx.onWriteMetadataAsOperand(MD);
  1394. }
  1395. if (mi + 1 != me)
  1396. Out << ", ";
  1397. }
  1398. Out << "}";
  1399. }
  1400. namespace {
  1401. struct FieldSeparator {
  1402. bool Skip = true;
  1403. const char *Sep;
  1404. FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
  1405. };
  1406. raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
  1407. if (FS.Skip) {
  1408. FS.Skip = false;
  1409. return OS;
  1410. }
  1411. return OS << FS.Sep;
  1412. }
  1413. struct MDFieldPrinter {
  1414. raw_ostream &Out;
  1415. FieldSeparator FS;
  1416. AsmWriterContext &WriterCtx;
  1417. explicit MDFieldPrinter(raw_ostream &Out)
  1418. : Out(Out), WriterCtx(AsmWriterContext::getEmpty()) {}
  1419. MDFieldPrinter(raw_ostream &Out, AsmWriterContext &Ctx)
  1420. : Out(Out), WriterCtx(Ctx) {}
  1421. void printTag(const DINode *N);
  1422. void printMacinfoType(const DIMacroNode *N);
  1423. void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);
  1424. void printString(StringRef Name, StringRef Value,
  1425. bool ShouldSkipEmpty = true);
  1426. void printMetadata(StringRef Name, const Metadata *MD,
  1427. bool ShouldSkipNull = true);
  1428. template <class IntTy>
  1429. void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
  1430. void printAPInt(StringRef Name, const APInt &Int, bool IsUnsigned,
  1431. bool ShouldSkipZero);
  1432. void printBool(StringRef Name, bool Value,
  1433. std::optional<bool> Default = std::nullopt);
  1434. void printDIFlags(StringRef Name, DINode::DIFlags Flags);
  1435. void printDISPFlags(StringRef Name, DISubprogram::DISPFlags Flags);
  1436. template <class IntTy, class Stringifier>
  1437. void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
  1438. bool ShouldSkipZero = true);
  1439. void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
  1440. void printNameTableKind(StringRef Name,
  1441. DICompileUnit::DebugNameTableKind NTK);
  1442. };
  1443. } // end anonymous namespace
  1444. void MDFieldPrinter::printTag(const DINode *N) {
  1445. Out << FS << "tag: ";
  1446. auto Tag = dwarf::TagString(N->getTag());
  1447. if (!Tag.empty())
  1448. Out << Tag;
  1449. else
  1450. Out << N->getTag();
  1451. }
  1452. void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
  1453. Out << FS << "type: ";
  1454. auto Type = dwarf::MacinfoString(N->getMacinfoType());
  1455. if (!Type.empty())
  1456. Out << Type;
  1457. else
  1458. Out << N->getMacinfoType();
  1459. }
  1460. void MDFieldPrinter::printChecksum(
  1461. const DIFile::ChecksumInfo<StringRef> &Checksum) {
  1462. Out << FS << "checksumkind: " << Checksum.getKindAsString();
  1463. printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false);
  1464. }
  1465. void MDFieldPrinter::printString(StringRef Name, StringRef Value,
  1466. bool ShouldSkipEmpty) {
  1467. if (ShouldSkipEmpty && Value.empty())
  1468. return;
  1469. Out << FS << Name << ": \"";
  1470. printEscapedString(Value, Out);
  1471. Out << "\"";
  1472. }
  1473. static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
  1474. AsmWriterContext &WriterCtx) {
  1475. if (!MD) {
  1476. Out << "null";
  1477. return;
  1478. }
  1479. WriteAsOperandInternal(Out, MD, WriterCtx);
  1480. WriterCtx.onWriteMetadataAsOperand(MD);
  1481. }
  1482. void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
  1483. bool ShouldSkipNull) {
  1484. if (ShouldSkipNull && !MD)
  1485. return;
  1486. Out << FS << Name << ": ";
  1487. writeMetadataAsOperand(Out, MD, WriterCtx);
  1488. }
  1489. template <class IntTy>
  1490. void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
  1491. if (ShouldSkipZero && !Int)
  1492. return;
  1493. Out << FS << Name << ": " << Int;
  1494. }
  1495. void MDFieldPrinter::printAPInt(StringRef Name, const APInt &Int,
  1496. bool IsUnsigned, bool ShouldSkipZero) {
  1497. if (ShouldSkipZero && Int.isZero())
  1498. return;
  1499. Out << FS << Name << ": ";
  1500. Int.print(Out, !IsUnsigned);
  1501. }
  1502. void MDFieldPrinter::printBool(StringRef Name, bool Value,
  1503. std::optional<bool> Default) {
  1504. if (Default && Value == *Default)
  1505. return;
  1506. Out << FS << Name << ": " << (Value ? "true" : "false");
  1507. }
  1508. void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
  1509. if (!Flags)
  1510. return;
  1511. Out << FS << Name << ": ";
  1512. SmallVector<DINode::DIFlags, 8> SplitFlags;
  1513. auto Extra = DINode::splitFlags(Flags, SplitFlags);
  1514. FieldSeparator FlagsFS(" | ");
  1515. for (auto F : SplitFlags) {
  1516. auto StringF = DINode::getFlagString(F);
  1517. assert(!StringF.empty() && "Expected valid flag");
  1518. Out << FlagsFS << StringF;
  1519. }
  1520. if (Extra || SplitFlags.empty())
  1521. Out << FlagsFS << Extra;
  1522. }
  1523. void MDFieldPrinter::printDISPFlags(StringRef Name,
  1524. DISubprogram::DISPFlags Flags) {
  1525. // Always print this field, because no flags in the IR at all will be
  1526. // interpreted as old-style isDefinition: true.
  1527. Out << FS << Name << ": ";
  1528. if (!Flags) {
  1529. Out << 0;
  1530. return;
  1531. }
  1532. SmallVector<DISubprogram::DISPFlags, 8> SplitFlags;
  1533. auto Extra = DISubprogram::splitFlags(Flags, SplitFlags);
  1534. FieldSeparator FlagsFS(" | ");
  1535. for (auto F : SplitFlags) {
  1536. auto StringF = DISubprogram::getFlagString(F);
  1537. assert(!StringF.empty() && "Expected valid flag");
  1538. Out << FlagsFS << StringF;
  1539. }
  1540. if (Extra || SplitFlags.empty())
  1541. Out << FlagsFS << Extra;
  1542. }
  1543. void MDFieldPrinter::printEmissionKind(StringRef Name,
  1544. DICompileUnit::DebugEmissionKind EK) {
  1545. Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK);
  1546. }
  1547. void MDFieldPrinter::printNameTableKind(StringRef Name,
  1548. DICompileUnit::DebugNameTableKind NTK) {
  1549. if (NTK == DICompileUnit::DebugNameTableKind::Default)
  1550. return;
  1551. Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK);
  1552. }
  1553. template <class IntTy, class Stringifier>
  1554. void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
  1555. Stringifier toString, bool ShouldSkipZero) {
  1556. if (!Value)
  1557. return;
  1558. Out << FS << Name << ": ";
  1559. auto S = toString(Value);
  1560. if (!S.empty())
  1561. Out << S;
  1562. else
  1563. Out << Value;
  1564. }
  1565. static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
  1566. AsmWriterContext &WriterCtx) {
  1567. Out << "!GenericDINode(";
  1568. MDFieldPrinter Printer(Out, WriterCtx);
  1569. Printer.printTag(N);
  1570. Printer.printString("header", N->getHeader());
  1571. if (N->getNumDwarfOperands()) {
  1572. Out << Printer.FS << "operands: {";
  1573. FieldSeparator IFS;
  1574. for (auto &I : N->dwarf_operands()) {
  1575. Out << IFS;
  1576. writeMetadataAsOperand(Out, I, WriterCtx);
  1577. }
  1578. Out << "}";
  1579. }
  1580. Out << ")";
  1581. }
  1582. static void writeDILocation(raw_ostream &Out, const DILocation *DL,
  1583. AsmWriterContext &WriterCtx) {
  1584. Out << "!DILocation(";
  1585. MDFieldPrinter Printer(Out, WriterCtx);
  1586. // Always output the line, since 0 is a relevant and important value for it.
  1587. Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
  1588. Printer.printInt("column", DL->getColumn());
  1589. Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
  1590. Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
  1591. Printer.printBool("isImplicitCode", DL->isImplicitCode(),
  1592. /* Default */ false);
  1593. Out << ")";
  1594. }
  1595. static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL,
  1596. AsmWriterContext &WriterCtx) {
  1597. Out << "!DIAssignID()";
  1598. MDFieldPrinter Printer(Out, WriterCtx);
  1599. }
  1600. static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
  1601. AsmWriterContext &WriterCtx) {
  1602. Out << "!DISubrange(";
  1603. MDFieldPrinter Printer(Out, WriterCtx);
  1604. auto *Count = N->getRawCountNode();
  1605. if (auto *CE = dyn_cast_or_null<ConstantAsMetadata>(Count)) {
  1606. auto *CV = cast<ConstantInt>(CE->getValue());
  1607. Printer.printInt("count", CV->getSExtValue(),
  1608. /* ShouldSkipZero */ false);
  1609. } else
  1610. Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
  1611. // A lowerBound of constant 0 should not be skipped, since it is different
  1612. // from an unspecified lower bound (= nullptr).
  1613. auto *LBound = N->getRawLowerBound();
  1614. if (auto *LE = dyn_cast_or_null<ConstantAsMetadata>(LBound)) {
  1615. auto *LV = cast<ConstantInt>(LE->getValue());
  1616. Printer.printInt("lowerBound", LV->getSExtValue(),
  1617. /* ShouldSkipZero */ false);
  1618. } else
  1619. Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
  1620. auto *UBound = N->getRawUpperBound();
  1621. if (auto *UE = dyn_cast_or_null<ConstantAsMetadata>(UBound)) {
  1622. auto *UV = cast<ConstantInt>(UE->getValue());
  1623. Printer.printInt("upperBound", UV->getSExtValue(),
  1624. /* ShouldSkipZero */ false);
  1625. } else
  1626. Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
  1627. auto *Stride = N->getRawStride();
  1628. if (auto *SE = dyn_cast_or_null<ConstantAsMetadata>(Stride)) {
  1629. auto *SV = cast<ConstantInt>(SE->getValue());
  1630. Printer.printInt("stride", SV->getSExtValue(), /* ShouldSkipZero */ false);
  1631. } else
  1632. Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
  1633. Out << ")";
  1634. }
  1635. static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N,
  1636. AsmWriterContext &WriterCtx) {
  1637. Out << "!DIGenericSubrange(";
  1638. MDFieldPrinter Printer(Out, WriterCtx);
  1639. auto IsConstant = [&](Metadata *Bound) -> bool {
  1640. if (auto *BE = dyn_cast_or_null<DIExpression>(Bound)) {
  1641. return BE->isConstant() &&
  1642. DIExpression::SignedOrUnsignedConstant::SignedConstant ==
  1643. *BE->isConstant();
  1644. }
  1645. return false;
  1646. };
  1647. auto GetConstant = [&](Metadata *Bound) -> int64_t {
  1648. assert(IsConstant(Bound) && "Expected constant");
  1649. auto *BE = dyn_cast_or_null<DIExpression>(Bound);
  1650. return static_cast<int64_t>(BE->getElement(1));
  1651. };
  1652. auto *Count = N->getRawCountNode();
  1653. if (IsConstant(Count))
  1654. Printer.printInt("count", GetConstant(Count),
  1655. /* ShouldSkipZero */ false);
  1656. else
  1657. Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
  1658. auto *LBound = N->getRawLowerBound();
  1659. if (IsConstant(LBound))
  1660. Printer.printInt("lowerBound", GetConstant(LBound),
  1661. /* ShouldSkipZero */ false);
  1662. else
  1663. Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
  1664. auto *UBound = N->getRawUpperBound();
  1665. if (IsConstant(UBound))
  1666. Printer.printInt("upperBound", GetConstant(UBound),
  1667. /* ShouldSkipZero */ false);
  1668. else
  1669. Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
  1670. auto *Stride = N->getRawStride();
  1671. if (IsConstant(Stride))
  1672. Printer.printInt("stride", GetConstant(Stride),
  1673. /* ShouldSkipZero */ false);
  1674. else
  1675. Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
  1676. Out << ")";
  1677. }
  1678. static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
  1679. AsmWriterContext &) {
  1680. Out << "!DIEnumerator(";
  1681. MDFieldPrinter Printer(Out);
  1682. Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
  1683. Printer.printAPInt("value", N->getValue(), N->isUnsigned(),
  1684. /*ShouldSkipZero=*/false);
  1685. if (N->isUnsigned())
  1686. Printer.printBool("isUnsigned", true);
  1687. Out << ")";
  1688. }
  1689. static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
  1690. AsmWriterContext &) {
  1691. Out << "!DIBasicType(";
  1692. MDFieldPrinter Printer(Out);
  1693. if (N->getTag() != dwarf::DW_TAG_base_type)
  1694. Printer.printTag(N);
  1695. Printer.printString("name", N->getName());
  1696. Printer.printInt("size", N->getSizeInBits());
  1697. Printer.printInt("align", N->getAlignInBits());
  1698. Printer.printDwarfEnum("encoding", N->getEncoding(),
  1699. dwarf::AttributeEncodingString);
  1700. Printer.printDIFlags("flags", N->getFlags());
  1701. Out << ")";
  1702. }
  1703. static void writeDIStringType(raw_ostream &Out, const DIStringType *N,
  1704. AsmWriterContext &WriterCtx) {
  1705. Out << "!DIStringType(";
  1706. MDFieldPrinter Printer(Out, WriterCtx);
  1707. if (N->getTag() != dwarf::DW_TAG_string_type)
  1708. Printer.printTag(N);
  1709. Printer.printString("name", N->getName());
  1710. Printer.printMetadata("stringLength", N->getRawStringLength());
  1711. Printer.printMetadata("stringLengthExpression", N->getRawStringLengthExp());
  1712. Printer.printMetadata("stringLocationExpression",
  1713. N->getRawStringLocationExp());
  1714. Printer.printInt("size", N->getSizeInBits());
  1715. Printer.printInt("align", N->getAlignInBits());
  1716. Printer.printDwarfEnum("encoding", N->getEncoding(),
  1717. dwarf::AttributeEncodingString);
  1718. Out << ")";
  1719. }
  1720. static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
  1721. AsmWriterContext &WriterCtx) {
  1722. Out << "!DIDerivedType(";
  1723. MDFieldPrinter Printer(Out, WriterCtx);
  1724. Printer.printTag(N);
  1725. Printer.printString("name", N->getName());
  1726. Printer.printMetadata("scope", N->getRawScope());
  1727. Printer.printMetadata("file", N->getRawFile());
  1728. Printer.printInt("line", N->getLine());
  1729. Printer.printMetadata("baseType", N->getRawBaseType(),
  1730. /* ShouldSkipNull */ false);
  1731. Printer.printInt("size", N->getSizeInBits());
  1732. Printer.printInt("align", N->getAlignInBits());
  1733. Printer.printInt("offset", N->getOffsetInBits());
  1734. Printer.printDIFlags("flags", N->getFlags());
  1735. Printer.printMetadata("extraData", N->getRawExtraData());
  1736. if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
  1737. Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
  1738. /* ShouldSkipZero */ false);
  1739. Printer.printMetadata("annotations", N->getRawAnnotations());
  1740. Out << ")";
  1741. }
  1742. static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
  1743. AsmWriterContext &WriterCtx) {
  1744. Out << "!DICompositeType(";
  1745. MDFieldPrinter Printer(Out, WriterCtx);
  1746. Printer.printTag(N);
  1747. Printer.printString("name", N->getName());
  1748. Printer.printMetadata("scope", N->getRawScope());
  1749. Printer.printMetadata("file", N->getRawFile());
  1750. Printer.printInt("line", N->getLine());
  1751. Printer.printMetadata("baseType", N->getRawBaseType());
  1752. Printer.printInt("size", N->getSizeInBits());
  1753. Printer.printInt("align", N->getAlignInBits());
  1754. Printer.printInt("offset", N->getOffsetInBits());
  1755. Printer.printDIFlags("flags", N->getFlags());
  1756. Printer.printMetadata("elements", N->getRawElements());
  1757. Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
  1758. dwarf::LanguageString);
  1759. Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
  1760. Printer.printMetadata("templateParams", N->getRawTemplateParams());
  1761. Printer.printString("identifier", N->getIdentifier());
  1762. Printer.printMetadata("discriminator", N->getRawDiscriminator());
  1763. Printer.printMetadata("dataLocation", N->getRawDataLocation());
  1764. Printer.printMetadata("associated", N->getRawAssociated());
  1765. Printer.printMetadata("allocated", N->getRawAllocated());
  1766. if (auto *RankConst = N->getRankConst())
  1767. Printer.printInt("rank", RankConst->getSExtValue(),
  1768. /* ShouldSkipZero */ false);
  1769. else
  1770. Printer.printMetadata("rank", N->getRawRank(), /*ShouldSkipNull */ true);
  1771. Printer.printMetadata("annotations", N->getRawAnnotations());
  1772. Out << ")";
  1773. }
  1774. static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
  1775. AsmWriterContext &WriterCtx) {
  1776. Out << "!DISubroutineType(";
  1777. MDFieldPrinter Printer(Out, WriterCtx);
  1778. Printer.printDIFlags("flags", N->getFlags());
  1779. Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
  1780. Printer.printMetadata("types", N->getRawTypeArray(),
  1781. /* ShouldSkipNull */ false);
  1782. Out << ")";
  1783. }
  1784. static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &) {
  1785. Out << "!DIFile(";
  1786. MDFieldPrinter Printer(Out);
  1787. Printer.printString("filename", N->getFilename(),
  1788. /* ShouldSkipEmpty */ false);
  1789. Printer.printString("directory", N->getDirectory(),
  1790. /* ShouldSkipEmpty */ false);
  1791. // Print all values for checksum together, or not at all.
  1792. if (N->getChecksum())
  1793. Printer.printChecksum(*N->getChecksum());
  1794. Printer.printString("source", N->getSource().value_or(StringRef()),
  1795. /* ShouldSkipEmpty */ true);
  1796. Out << ")";
  1797. }
  1798. static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
  1799. AsmWriterContext &WriterCtx) {
  1800. Out << "!DICompileUnit(";
  1801. MDFieldPrinter Printer(Out, WriterCtx);
  1802. Printer.printDwarfEnum("language", N->getSourceLanguage(),
  1803. dwarf::LanguageString, /* ShouldSkipZero */ false);
  1804. Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
  1805. Printer.printString("producer", N->getProducer());
  1806. Printer.printBool("isOptimized", N->isOptimized());
  1807. Printer.printString("flags", N->getFlags());
  1808. Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
  1809. /* ShouldSkipZero */ false);
  1810. Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
  1811. Printer.printEmissionKind("emissionKind", N->getEmissionKind());
  1812. Printer.printMetadata("enums", N->getRawEnumTypes());
  1813. Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
  1814. Printer.printMetadata("globals", N->getRawGlobalVariables());
  1815. Printer.printMetadata("imports", N->getRawImportedEntities());
  1816. Printer.printMetadata("macros", N->getRawMacros());
  1817. Printer.printInt("dwoId", N->getDWOId());
  1818. Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
  1819. Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
  1820. false);
  1821. Printer.printNameTableKind("nameTableKind", N->getNameTableKind());
  1822. Printer.printBool("rangesBaseAddress", N->getRangesBaseAddress(), false);
  1823. Printer.printString("sysroot", N->getSysRoot());
  1824. Printer.printString("sdk", N->getSDK());
  1825. Out << ")";
  1826. }
  1827. static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
  1828. AsmWriterContext &WriterCtx) {
  1829. Out << "!DISubprogram(";
  1830. MDFieldPrinter Printer(Out, WriterCtx);
  1831. Printer.printString("name", N->getName());
  1832. Printer.printString("linkageName", N->getLinkageName());
  1833. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1834. Printer.printMetadata("file", N->getRawFile());
  1835. Printer.printInt("line", N->getLine());
  1836. Printer.printMetadata("type", N->getRawType());
  1837. Printer.printInt("scopeLine", N->getScopeLine());
  1838. Printer.printMetadata("containingType", N->getRawContainingType());
  1839. if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
  1840. N->getVirtualIndex() != 0)
  1841. Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
  1842. Printer.printInt("thisAdjustment", N->getThisAdjustment());
  1843. Printer.printDIFlags("flags", N->getFlags());
  1844. Printer.printDISPFlags("spFlags", N->getSPFlags());
  1845. Printer.printMetadata("unit", N->getRawUnit());
  1846. Printer.printMetadata("templateParams", N->getRawTemplateParams());
  1847. Printer.printMetadata("declaration", N->getRawDeclaration());
  1848. Printer.printMetadata("retainedNodes", N->getRawRetainedNodes());
  1849. Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
  1850. Printer.printMetadata("annotations", N->getRawAnnotations());
  1851. Printer.printString("targetFuncName", N->getTargetFuncName());
  1852. Out << ")";
  1853. }
  1854. static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
  1855. AsmWriterContext &WriterCtx) {
  1856. Out << "!DILexicalBlock(";
  1857. MDFieldPrinter Printer(Out, WriterCtx);
  1858. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1859. Printer.printMetadata("file", N->getRawFile());
  1860. Printer.printInt("line", N->getLine());
  1861. Printer.printInt("column", N->getColumn());
  1862. Out << ")";
  1863. }
  1864. static void writeDILexicalBlockFile(raw_ostream &Out,
  1865. const DILexicalBlockFile *N,
  1866. AsmWriterContext &WriterCtx) {
  1867. Out << "!DILexicalBlockFile(";
  1868. MDFieldPrinter Printer(Out, WriterCtx);
  1869. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1870. Printer.printMetadata("file", N->getRawFile());
  1871. Printer.printInt("discriminator", N->getDiscriminator(),
  1872. /* ShouldSkipZero */ false);
  1873. Out << ")";
  1874. }
  1875. static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
  1876. AsmWriterContext &WriterCtx) {
  1877. Out << "!DINamespace(";
  1878. MDFieldPrinter Printer(Out, WriterCtx);
  1879. Printer.printString("name", N->getName());
  1880. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1881. Printer.printBool("exportSymbols", N->getExportSymbols(), false);
  1882. Out << ")";
  1883. }
  1884. static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N,
  1885. AsmWriterContext &WriterCtx) {
  1886. Out << "!DICommonBlock(";
  1887. MDFieldPrinter Printer(Out, WriterCtx);
  1888. Printer.printMetadata("scope", N->getRawScope(), false);
  1889. Printer.printMetadata("declaration", N->getRawDecl(), false);
  1890. Printer.printString("name", N->getName());
  1891. Printer.printMetadata("file", N->getRawFile());
  1892. Printer.printInt("line", N->getLineNo());
  1893. Out << ")";
  1894. }
  1895. static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
  1896. AsmWriterContext &WriterCtx) {
  1897. Out << "!DIMacro(";
  1898. MDFieldPrinter Printer(Out, WriterCtx);
  1899. Printer.printMacinfoType(N);
  1900. Printer.printInt("line", N->getLine());
  1901. Printer.printString("name", N->getName());
  1902. Printer.printString("value", N->getValue());
  1903. Out << ")";
  1904. }
  1905. static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
  1906. AsmWriterContext &WriterCtx) {
  1907. Out << "!DIMacroFile(";
  1908. MDFieldPrinter Printer(Out, WriterCtx);
  1909. Printer.printInt("line", N->getLine());
  1910. Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
  1911. Printer.printMetadata("nodes", N->getRawElements());
  1912. Out << ")";
  1913. }
  1914. static void writeDIModule(raw_ostream &Out, const DIModule *N,
  1915. AsmWriterContext &WriterCtx) {
  1916. Out << "!DIModule(";
  1917. MDFieldPrinter Printer(Out, WriterCtx);
  1918. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1919. Printer.printString("name", N->getName());
  1920. Printer.printString("configMacros", N->getConfigurationMacros());
  1921. Printer.printString("includePath", N->getIncludePath());
  1922. Printer.printString("apinotes", N->getAPINotesFile());
  1923. Printer.printMetadata("file", N->getRawFile());
  1924. Printer.printInt("line", N->getLineNo());
  1925. Printer.printBool("isDecl", N->getIsDecl(), /* Default */ false);
  1926. Out << ")";
  1927. }
  1928. static void writeDITemplateTypeParameter(raw_ostream &Out,
  1929. const DITemplateTypeParameter *N,
  1930. AsmWriterContext &WriterCtx) {
  1931. Out << "!DITemplateTypeParameter(";
  1932. MDFieldPrinter Printer(Out, WriterCtx);
  1933. Printer.printString("name", N->getName());
  1934. Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
  1935. Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
  1936. Out << ")";
  1937. }
  1938. static void writeDITemplateValueParameter(raw_ostream &Out,
  1939. const DITemplateValueParameter *N,
  1940. AsmWriterContext &WriterCtx) {
  1941. Out << "!DITemplateValueParameter(";
  1942. MDFieldPrinter Printer(Out, WriterCtx);
  1943. if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
  1944. Printer.printTag(N);
  1945. Printer.printString("name", N->getName());
  1946. Printer.printMetadata("type", N->getRawType());
  1947. Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
  1948. Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
  1949. Out << ")";
  1950. }
  1951. static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
  1952. AsmWriterContext &WriterCtx) {
  1953. Out << "!DIGlobalVariable(";
  1954. MDFieldPrinter Printer(Out, WriterCtx);
  1955. Printer.printString("name", N->getName());
  1956. Printer.printString("linkageName", N->getLinkageName());
  1957. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1958. Printer.printMetadata("file", N->getRawFile());
  1959. Printer.printInt("line", N->getLine());
  1960. Printer.printMetadata("type", N->getRawType());
  1961. Printer.printBool("isLocal", N->isLocalToUnit());
  1962. Printer.printBool("isDefinition", N->isDefinition());
  1963. Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
  1964. Printer.printMetadata("templateParams", N->getRawTemplateParams());
  1965. Printer.printInt("align", N->getAlignInBits());
  1966. Printer.printMetadata("annotations", N->getRawAnnotations());
  1967. Out << ")";
  1968. }
  1969. static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
  1970. AsmWriterContext &WriterCtx) {
  1971. Out << "!DILocalVariable(";
  1972. MDFieldPrinter Printer(Out, WriterCtx);
  1973. Printer.printString("name", N->getName());
  1974. Printer.printInt("arg", N->getArg());
  1975. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1976. Printer.printMetadata("file", N->getRawFile());
  1977. Printer.printInt("line", N->getLine());
  1978. Printer.printMetadata("type", N->getRawType());
  1979. Printer.printDIFlags("flags", N->getFlags());
  1980. Printer.printInt("align", N->getAlignInBits());
  1981. Printer.printMetadata("annotations", N->getRawAnnotations());
  1982. Out << ")";
  1983. }
  1984. static void writeDILabel(raw_ostream &Out, const DILabel *N,
  1985. AsmWriterContext &WriterCtx) {
  1986. Out << "!DILabel(";
  1987. MDFieldPrinter Printer(Out, WriterCtx);
  1988. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1989. Printer.printString("name", N->getName());
  1990. Printer.printMetadata("file", N->getRawFile());
  1991. Printer.printInt("line", N->getLine());
  1992. Out << ")";
  1993. }
  1994. static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
  1995. AsmWriterContext &WriterCtx) {
  1996. Out << "!DIExpression(";
  1997. FieldSeparator FS;
  1998. if (N->isValid()) {
  1999. for (const DIExpression::ExprOperand &Op : N->expr_ops()) {
  2000. auto OpStr = dwarf::OperationEncodingString(Op.getOp());
  2001. assert(!OpStr.empty() && "Expected valid opcode");
  2002. Out << FS << OpStr;
  2003. if (Op.getOp() == dwarf::DW_OP_LLVM_convert) {
  2004. Out << FS << Op.getArg(0);
  2005. Out << FS << dwarf::AttributeEncodingString(Op.getArg(1));
  2006. } else {
  2007. for (unsigned A = 0, AE = Op.getNumArgs(); A != AE; ++A)
  2008. Out << FS << Op.getArg(A);
  2009. }
  2010. }
  2011. } else {
  2012. for (const auto &I : N->getElements())
  2013. Out << FS << I;
  2014. }
  2015. Out << ")";
  2016. }
  2017. static void writeDIArgList(raw_ostream &Out, const DIArgList *N,
  2018. AsmWriterContext &WriterCtx,
  2019. bool FromValue = false) {
  2020. assert(FromValue &&
  2021. "Unexpected DIArgList metadata outside of value argument");
  2022. Out << "!DIArgList(";
  2023. FieldSeparator FS;
  2024. MDFieldPrinter Printer(Out, WriterCtx);
  2025. for (Metadata *Arg : N->getArgs()) {
  2026. Out << FS;
  2027. WriteAsOperandInternal(Out, Arg, WriterCtx, true);
  2028. }
  2029. Out << ")";
  2030. }
  2031. static void writeDIGlobalVariableExpression(raw_ostream &Out,
  2032. const DIGlobalVariableExpression *N,
  2033. AsmWriterContext &WriterCtx) {
  2034. Out << "!DIGlobalVariableExpression(";
  2035. MDFieldPrinter Printer(Out, WriterCtx);
  2036. Printer.printMetadata("var", N->getVariable());
  2037. Printer.printMetadata("expr", N->getExpression());
  2038. Out << ")";
  2039. }
  2040. static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
  2041. AsmWriterContext &WriterCtx) {
  2042. Out << "!DIObjCProperty(";
  2043. MDFieldPrinter Printer(Out, WriterCtx);
  2044. Printer.printString("name", N->getName());
  2045. Printer.printMetadata("file", N->getRawFile());
  2046. Printer.printInt("line", N->getLine());
  2047. Printer.printString("setter", N->getSetterName());
  2048. Printer.printString("getter", N->getGetterName());
  2049. Printer.printInt("attributes", N->getAttributes());
  2050. Printer.printMetadata("type", N->getRawType());
  2051. Out << ")";
  2052. }
  2053. static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
  2054. AsmWriterContext &WriterCtx) {
  2055. Out << "!DIImportedEntity(";
  2056. MDFieldPrinter Printer(Out, WriterCtx);
  2057. Printer.printTag(N);
  2058. Printer.printString("name", N->getName());
  2059. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  2060. Printer.printMetadata("entity", N->getRawEntity());
  2061. Printer.printMetadata("file", N->getRawFile());
  2062. Printer.printInt("line", N->getLine());
  2063. Printer.printMetadata("elements", N->getRawElements());
  2064. Out << ")";
  2065. }
  2066. static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
  2067. AsmWriterContext &Ctx) {
  2068. if (Node->isDistinct())
  2069. Out << "distinct ";
  2070. else if (Node->isTemporary())
  2071. Out << "<temporary!> "; // Handle broken code.
  2072. switch (Node->getMetadataID()) {
  2073. default:
  2074. llvm_unreachable("Expected uniquable MDNode");
  2075. #define HANDLE_MDNODE_LEAF(CLASS) \
  2076. case Metadata::CLASS##Kind: \
  2077. write##CLASS(Out, cast<CLASS>(Node), Ctx); \
  2078. break;
  2079. #include "llvm/IR/Metadata.def"
  2080. }
  2081. }
  2082. // Full implementation of printing a Value as an operand with support for
  2083. // TypePrinting, etc.
  2084. static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
  2085. AsmWriterContext &WriterCtx) {
  2086. if (V->hasName()) {
  2087. PrintLLVMName(Out, V);
  2088. return;
  2089. }
  2090. const Constant *CV = dyn_cast<Constant>(V);
  2091. if (CV && !isa<GlobalValue>(CV)) {
  2092. assert(WriterCtx.TypePrinter && "Constants require TypePrinting!");
  2093. WriteConstantInternal(Out, CV, WriterCtx);
  2094. return;
  2095. }
  2096. if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
  2097. Out << "asm ";
  2098. if (IA->hasSideEffects())
  2099. Out << "sideeffect ";
  2100. if (IA->isAlignStack())
  2101. Out << "alignstack ";
  2102. // We don't emit the AD_ATT dialect as it's the assumed default.
  2103. if (IA->getDialect() == InlineAsm::AD_Intel)
  2104. Out << "inteldialect ";
  2105. if (IA->canThrow())
  2106. Out << "unwind ";
  2107. Out << '"';
  2108. printEscapedString(IA->getAsmString(), Out);
  2109. Out << "\", \"";
  2110. printEscapedString(IA->getConstraintString(), Out);
  2111. Out << '"';
  2112. return;
  2113. }
  2114. if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
  2115. WriteAsOperandInternal(Out, MD->getMetadata(), WriterCtx,
  2116. /* FromValue */ true);
  2117. return;
  2118. }
  2119. char Prefix = '%';
  2120. int Slot;
  2121. auto *Machine = WriterCtx.Machine;
  2122. // If we have a SlotTracker, use it.
  2123. if (Machine) {
  2124. if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
  2125. Slot = Machine->getGlobalSlot(GV);
  2126. Prefix = '@';
  2127. } else {
  2128. Slot = Machine->getLocalSlot(V);
  2129. // If the local value didn't succeed, then we may be referring to a value
  2130. // from a different function. Translate it, as this can happen when using
  2131. // address of blocks.
  2132. if (Slot == -1)
  2133. if ((Machine = createSlotTracker(V))) {
  2134. Slot = Machine->getLocalSlot(V);
  2135. delete Machine;
  2136. }
  2137. }
  2138. } else if ((Machine = createSlotTracker(V))) {
  2139. // Otherwise, create one to get the # and then destroy it.
  2140. if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
  2141. Slot = Machine->getGlobalSlot(GV);
  2142. Prefix = '@';
  2143. } else {
  2144. Slot = Machine->getLocalSlot(V);
  2145. }
  2146. delete Machine;
  2147. Machine = nullptr;
  2148. } else {
  2149. Slot = -1;
  2150. }
  2151. if (Slot != -1)
  2152. Out << Prefix << Slot;
  2153. else
  2154. Out << "<badref>";
  2155. }
  2156. static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
  2157. AsmWriterContext &WriterCtx,
  2158. bool FromValue) {
  2159. // Write DIExpressions and DIArgLists inline when used as a value. Improves
  2160. // readability of debug info intrinsics.
  2161. if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
  2162. writeDIExpression(Out, Expr, WriterCtx);
  2163. return;
  2164. }
  2165. if (const DIArgList *ArgList = dyn_cast<DIArgList>(MD)) {
  2166. writeDIArgList(Out, ArgList, WriterCtx, FromValue);
  2167. return;
  2168. }
  2169. if (const MDNode *N = dyn_cast<MDNode>(MD)) {
  2170. std::unique_ptr<SlotTracker> MachineStorage;
  2171. SaveAndRestore SARMachine(WriterCtx.Machine);
  2172. if (!WriterCtx.Machine) {
  2173. MachineStorage = std::make_unique<SlotTracker>(WriterCtx.Context);
  2174. WriterCtx.Machine = MachineStorage.get();
  2175. }
  2176. int Slot = WriterCtx.Machine->getMetadataSlot(N);
  2177. if (Slot == -1) {
  2178. if (const DILocation *Loc = dyn_cast<DILocation>(N)) {
  2179. writeDILocation(Out, Loc, WriterCtx);
  2180. return;
  2181. }
  2182. // Give the pointer value instead of "badref", since this comes up all
  2183. // the time when debugging.
  2184. Out << "<" << N << ">";
  2185. } else
  2186. Out << '!' << Slot;
  2187. return;
  2188. }
  2189. if (const MDString *MDS = dyn_cast<MDString>(MD)) {
  2190. Out << "!\"";
  2191. printEscapedString(MDS->getString(), Out);
  2192. Out << '"';
  2193. return;
  2194. }
  2195. auto *V = cast<ValueAsMetadata>(MD);
  2196. assert(WriterCtx.TypePrinter && "TypePrinter required for metadata values");
  2197. assert((FromValue || !isa<LocalAsMetadata>(V)) &&
  2198. "Unexpected function-local metadata outside of value argument");
  2199. WriterCtx.TypePrinter->print(V->getValue()->getType(), Out);
  2200. Out << ' ';
  2201. WriteAsOperandInternal(Out, V->getValue(), WriterCtx);
  2202. }
  2203. namespace {
  2204. class AssemblyWriter {
  2205. formatted_raw_ostream &Out;
  2206. const Module *TheModule = nullptr;
  2207. const ModuleSummaryIndex *TheIndex = nullptr;
  2208. std::unique_ptr<SlotTracker> SlotTrackerStorage;
  2209. SlotTracker &Machine;
  2210. TypePrinting TypePrinter;
  2211. AssemblyAnnotationWriter *AnnotationWriter = nullptr;
  2212. SetVector<const Comdat *> Comdats;
  2213. bool IsForDebug;
  2214. bool ShouldPreserveUseListOrder;
  2215. UseListOrderMap UseListOrders;
  2216. SmallVector<StringRef, 8> MDNames;
  2217. /// Synchronization scope names registered with LLVMContext.
  2218. SmallVector<StringRef, 8> SSNs;
  2219. DenseMap<const GlobalValueSummary *, GlobalValue::GUID> SummaryToGUIDMap;
  2220. public:
  2221. /// Construct an AssemblyWriter with an external SlotTracker
  2222. AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
  2223. AssemblyAnnotationWriter *AAW, bool IsForDebug,
  2224. bool ShouldPreserveUseListOrder = false);
  2225. AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
  2226. const ModuleSummaryIndex *Index, bool IsForDebug);
  2227. AsmWriterContext getContext() {
  2228. return AsmWriterContext(&TypePrinter, &Machine, TheModule);
  2229. }
  2230. void printMDNodeBody(const MDNode *MD);
  2231. void printNamedMDNode(const NamedMDNode *NMD);
  2232. void printModule(const Module *M);
  2233. void writeOperand(const Value *Op, bool PrintType);
  2234. void writeParamOperand(const Value *Operand, AttributeSet Attrs);
  2235. void writeOperandBundles(const CallBase *Call);
  2236. void writeSyncScope(const LLVMContext &Context,
  2237. SyncScope::ID SSID);
  2238. void writeAtomic(const LLVMContext &Context,
  2239. AtomicOrdering Ordering,
  2240. SyncScope::ID SSID);
  2241. void writeAtomicCmpXchg(const LLVMContext &Context,
  2242. AtomicOrdering SuccessOrdering,
  2243. AtomicOrdering FailureOrdering,
  2244. SyncScope::ID SSID);
  2245. void writeAllMDNodes();
  2246. void writeMDNode(unsigned Slot, const MDNode *Node);
  2247. void writeAttribute(const Attribute &Attr, bool InAttrGroup = false);
  2248. void writeAttributeSet(const AttributeSet &AttrSet, bool InAttrGroup = false);
  2249. void writeAllAttributeGroups();
  2250. void printTypeIdentities();
  2251. void printGlobal(const GlobalVariable *GV);
  2252. void printAlias(const GlobalAlias *GA);
  2253. void printIFunc(const GlobalIFunc *GI);
  2254. void printComdat(const Comdat *C);
  2255. void printFunction(const Function *F);
  2256. void printArgument(const Argument *FA, AttributeSet Attrs);
  2257. void printBasicBlock(const BasicBlock *BB);
  2258. void printInstructionLine(const Instruction &I);
  2259. void printInstruction(const Instruction &I);
  2260. void printUseListOrder(const Value *V, const std::vector<unsigned> &Shuffle);
  2261. void printUseLists(const Function *F);
  2262. void printModuleSummaryIndex();
  2263. void printSummaryInfo(unsigned Slot, const ValueInfo &VI);
  2264. void printSummary(const GlobalValueSummary &Summary);
  2265. void printAliasSummary(const AliasSummary *AS);
  2266. void printGlobalVarSummary(const GlobalVarSummary *GS);
  2267. void printFunctionSummary(const FunctionSummary *FS);
  2268. void printTypeIdSummary(const TypeIdSummary &TIS);
  2269. void printTypeIdCompatibleVtableSummary(const TypeIdCompatibleVtableInfo &TI);
  2270. void printTypeTestResolution(const TypeTestResolution &TTRes);
  2271. void printArgs(const std::vector<uint64_t> &Args);
  2272. void printWPDRes(const WholeProgramDevirtResolution &WPDRes);
  2273. void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo);
  2274. void printVFuncId(const FunctionSummary::VFuncId VFId);
  2275. void
  2276. printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> &VCallList,
  2277. const char *Tag);
  2278. void
  2279. printConstVCalls(const std::vector<FunctionSummary::ConstVCall> &VCallList,
  2280. const char *Tag);
  2281. private:
  2282. /// Print out metadata attachments.
  2283. void printMetadataAttachments(
  2284. const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
  2285. StringRef Separator);
  2286. // printInfoComment - Print a little comment after the instruction indicating
  2287. // which slot it occupies.
  2288. void printInfoComment(const Value &V);
  2289. // printGCRelocateComment - print comment after call to the gc.relocate
  2290. // intrinsic indicating base and derived pointer names.
  2291. void printGCRelocateComment(const GCRelocateInst &Relocate);
  2292. };
  2293. } // end anonymous namespace
  2294. AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
  2295. const Module *M, AssemblyAnnotationWriter *AAW,
  2296. bool IsForDebug, bool ShouldPreserveUseListOrder)
  2297. : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW),
  2298. IsForDebug(IsForDebug),
  2299. ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
  2300. if (!TheModule)
  2301. return;
  2302. for (const GlobalObject &GO : TheModule->global_objects())
  2303. if (const Comdat *C = GO.getComdat())
  2304. Comdats.insert(C);
  2305. }
  2306. AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
  2307. const ModuleSummaryIndex *Index, bool IsForDebug)
  2308. : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr),
  2309. IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {}
  2310. void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
  2311. if (!Operand) {
  2312. Out << "<null operand!>";
  2313. return;
  2314. }
  2315. if (PrintType) {
  2316. TypePrinter.print(Operand->getType(), Out);
  2317. Out << ' ';
  2318. }
  2319. auto WriterCtx = getContext();
  2320. WriteAsOperandInternal(Out, Operand, WriterCtx);
  2321. }
  2322. void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
  2323. SyncScope::ID SSID) {
  2324. switch (SSID) {
  2325. case SyncScope::System: {
  2326. break;
  2327. }
  2328. default: {
  2329. if (SSNs.empty())
  2330. Context.getSyncScopeNames(SSNs);
  2331. Out << " syncscope(\"";
  2332. printEscapedString(SSNs[SSID], Out);
  2333. Out << "\")";
  2334. break;
  2335. }
  2336. }
  2337. }
  2338. void AssemblyWriter::writeAtomic(const LLVMContext &Context,
  2339. AtomicOrdering Ordering,
  2340. SyncScope::ID SSID) {
  2341. if (Ordering == AtomicOrdering::NotAtomic)
  2342. return;
  2343. writeSyncScope(Context, SSID);
  2344. Out << " " << toIRString(Ordering);
  2345. }
  2346. void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
  2347. AtomicOrdering SuccessOrdering,
  2348. AtomicOrdering FailureOrdering,
  2349. SyncScope::ID SSID) {
  2350. assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
  2351. FailureOrdering != AtomicOrdering::NotAtomic);
  2352. writeSyncScope(Context, SSID);
  2353. Out << " " << toIRString(SuccessOrdering);
  2354. Out << " " << toIRString(FailureOrdering);
  2355. }
  2356. void AssemblyWriter::writeParamOperand(const Value *Operand,
  2357. AttributeSet Attrs) {
  2358. if (!Operand) {
  2359. Out << "<null operand!>";
  2360. return;
  2361. }
  2362. // Print the type
  2363. TypePrinter.print(Operand->getType(), Out);
  2364. // Print parameter attributes list
  2365. if (Attrs.hasAttributes()) {
  2366. Out << ' ';
  2367. writeAttributeSet(Attrs);
  2368. }
  2369. Out << ' ';
  2370. // Print the operand
  2371. auto WriterCtx = getContext();
  2372. WriteAsOperandInternal(Out, Operand, WriterCtx);
  2373. }
  2374. void AssemblyWriter::writeOperandBundles(const CallBase *Call) {
  2375. if (!Call->hasOperandBundles())
  2376. return;
  2377. Out << " [ ";
  2378. bool FirstBundle = true;
  2379. for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i) {
  2380. OperandBundleUse BU = Call->getOperandBundleAt(i);
  2381. if (!FirstBundle)
  2382. Out << ", ";
  2383. FirstBundle = false;
  2384. Out << '"';
  2385. printEscapedString(BU.getTagName(), Out);
  2386. Out << '"';
  2387. Out << '(';
  2388. bool FirstInput = true;
  2389. auto WriterCtx = getContext();
  2390. for (const auto &Input : BU.Inputs) {
  2391. if (!FirstInput)
  2392. Out << ", ";
  2393. FirstInput = false;
  2394. if (Input == nullptr)
  2395. Out << "<null operand bundle!>";
  2396. else {
  2397. TypePrinter.print(Input->getType(), Out);
  2398. Out << " ";
  2399. WriteAsOperandInternal(Out, Input, WriterCtx);
  2400. }
  2401. }
  2402. Out << ')';
  2403. }
  2404. Out << " ]";
  2405. }
  2406. void AssemblyWriter::printModule(const Module *M) {
  2407. Machine.initializeIfNeeded();
  2408. if (ShouldPreserveUseListOrder)
  2409. UseListOrders = predictUseListOrder(M);
  2410. if (!M->getModuleIdentifier().empty() &&
  2411. // Don't print the ID if it will start a new line (which would
  2412. // require a comment char before it).
  2413. M->getModuleIdentifier().find('\n') == std::string::npos)
  2414. Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
  2415. if (!M->getSourceFileName().empty()) {
  2416. Out << "source_filename = \"";
  2417. printEscapedString(M->getSourceFileName(), Out);
  2418. Out << "\"\n";
  2419. }
  2420. const std::string &DL = M->getDataLayoutStr();
  2421. if (!DL.empty())
  2422. Out << "target datalayout = \"" << DL << "\"\n";
  2423. if (!M->getTargetTriple().empty())
  2424. Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
  2425. if (!M->getModuleInlineAsm().empty()) {
  2426. Out << '\n';
  2427. // Split the string into lines, to make it easier to read the .ll file.
  2428. StringRef Asm = M->getModuleInlineAsm();
  2429. do {
  2430. StringRef Front;
  2431. std::tie(Front, Asm) = Asm.split('\n');
  2432. // We found a newline, print the portion of the asm string from the
  2433. // last newline up to this newline.
  2434. Out << "module asm \"";
  2435. printEscapedString(Front, Out);
  2436. Out << "\"\n";
  2437. } while (!Asm.empty());
  2438. }
  2439. printTypeIdentities();
  2440. // Output all comdats.
  2441. if (!Comdats.empty())
  2442. Out << '\n';
  2443. for (const Comdat *C : Comdats) {
  2444. printComdat(C);
  2445. if (C != Comdats.back())
  2446. Out << '\n';
  2447. }
  2448. // Output all globals.
  2449. if (!M->global_empty()) Out << '\n';
  2450. for (const GlobalVariable &GV : M->globals()) {
  2451. printGlobal(&GV); Out << '\n';
  2452. }
  2453. // Output all aliases.
  2454. if (!M->alias_empty()) Out << "\n";
  2455. for (const GlobalAlias &GA : M->aliases())
  2456. printAlias(&GA);
  2457. // Output all ifuncs.
  2458. if (!M->ifunc_empty()) Out << "\n";
  2459. for (const GlobalIFunc &GI : M->ifuncs())
  2460. printIFunc(&GI);
  2461. // Output all of the functions.
  2462. for (const Function &F : *M) {
  2463. Out << '\n';
  2464. printFunction(&F);
  2465. }
  2466. // Output global use-lists.
  2467. printUseLists(nullptr);
  2468. // Output all attribute groups.
  2469. if (!Machine.as_empty()) {
  2470. Out << '\n';
  2471. writeAllAttributeGroups();
  2472. }
  2473. // Output named metadata.
  2474. if (!M->named_metadata_empty()) Out << '\n';
  2475. for (const NamedMDNode &Node : M->named_metadata())
  2476. printNamedMDNode(&Node);
  2477. // Output metadata.
  2478. if (!Machine.mdn_empty()) {
  2479. Out << '\n';
  2480. writeAllMDNodes();
  2481. }
  2482. }
  2483. void AssemblyWriter::printModuleSummaryIndex() {
  2484. assert(TheIndex);
  2485. int NumSlots = Machine.initializeIndexIfNeeded();
  2486. Out << "\n";
  2487. // Print module path entries. To print in order, add paths to a vector
  2488. // indexed by module slot.
  2489. std::vector<std::pair<std::string, ModuleHash>> moduleVec;
  2490. std::string RegularLTOModuleName =
  2491. ModuleSummaryIndex::getRegularLTOModuleName();
  2492. moduleVec.resize(TheIndex->modulePaths().size());
  2493. for (auto &[ModPath, ModId] : TheIndex->modulePaths())
  2494. moduleVec[Machine.getModulePathSlot(ModPath)] = std::make_pair(
  2495. // A module id of -1 is a special entry for a regular LTO module created
  2496. // during the thin link.
  2497. ModId.first == -1u ? RegularLTOModuleName : std::string(ModPath),
  2498. ModId.second);
  2499. unsigned i = 0;
  2500. for (auto &ModPair : moduleVec) {
  2501. Out << "^" << i++ << " = module: (";
  2502. Out << "path: \"";
  2503. printEscapedString(ModPair.first, Out);
  2504. Out << "\", hash: (";
  2505. FieldSeparator FS;
  2506. for (auto Hash : ModPair.second)
  2507. Out << FS << Hash;
  2508. Out << "))\n";
  2509. }
  2510. // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
  2511. // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
  2512. for (auto &GlobalList : *TheIndex) {
  2513. auto GUID = GlobalList.first;
  2514. for (auto &Summary : GlobalList.second.SummaryList)
  2515. SummaryToGUIDMap[Summary.get()] = GUID;
  2516. }
  2517. // Print the global value summary entries.
  2518. for (auto &GlobalList : *TheIndex) {
  2519. auto GUID = GlobalList.first;
  2520. auto VI = TheIndex->getValueInfo(GlobalList);
  2521. printSummaryInfo(Machine.getGUIDSlot(GUID), VI);
  2522. }
  2523. // Print the TypeIdMap entries.
  2524. for (const auto &TID : TheIndex->typeIds()) {
  2525. Out << "^" << Machine.getTypeIdSlot(TID.second.first)
  2526. << " = typeid: (name: \"" << TID.second.first << "\"";
  2527. printTypeIdSummary(TID.second.second);
  2528. Out << ") ; guid = " << TID.first << "\n";
  2529. }
  2530. // Print the TypeIdCompatibleVtableMap entries.
  2531. for (auto &TId : TheIndex->typeIdCompatibleVtableMap()) {
  2532. auto GUID = GlobalValue::getGUID(TId.first);
  2533. Out << "^" << Machine.getGUIDSlot(GUID)
  2534. << " = typeidCompatibleVTable: (name: \"" << TId.first << "\"";
  2535. printTypeIdCompatibleVtableSummary(TId.second);
  2536. Out << ") ; guid = " << GUID << "\n";
  2537. }
  2538. // Don't emit flags when it's not really needed (value is zero by default).
  2539. if (TheIndex->getFlags()) {
  2540. Out << "^" << NumSlots << " = flags: " << TheIndex->getFlags() << "\n";
  2541. ++NumSlots;
  2542. }
  2543. Out << "^" << NumSlots << " = blockcount: " << TheIndex->getBlockCount()
  2544. << "\n";
  2545. }
  2546. static const char *
  2547. getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) {
  2548. switch (K) {
  2549. case WholeProgramDevirtResolution::Indir:
  2550. return "indir";
  2551. case WholeProgramDevirtResolution::SingleImpl:
  2552. return "singleImpl";
  2553. case WholeProgramDevirtResolution::BranchFunnel:
  2554. return "branchFunnel";
  2555. }
  2556. llvm_unreachable("invalid WholeProgramDevirtResolution kind");
  2557. }
  2558. static const char *getWholeProgDevirtResByArgKindName(
  2559. WholeProgramDevirtResolution::ByArg::Kind K) {
  2560. switch (K) {
  2561. case WholeProgramDevirtResolution::ByArg::Indir:
  2562. return "indir";
  2563. case WholeProgramDevirtResolution::ByArg::UniformRetVal:
  2564. return "uniformRetVal";
  2565. case WholeProgramDevirtResolution::ByArg::UniqueRetVal:
  2566. return "uniqueRetVal";
  2567. case WholeProgramDevirtResolution::ByArg::VirtualConstProp:
  2568. return "virtualConstProp";
  2569. }
  2570. llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
  2571. }
  2572. static const char *getTTResKindName(TypeTestResolution::Kind K) {
  2573. switch (K) {
  2574. case TypeTestResolution::Unknown:
  2575. return "unknown";
  2576. case TypeTestResolution::Unsat:
  2577. return "unsat";
  2578. case TypeTestResolution::ByteArray:
  2579. return "byteArray";
  2580. case TypeTestResolution::Inline:
  2581. return "inline";
  2582. case TypeTestResolution::Single:
  2583. return "single";
  2584. case TypeTestResolution::AllOnes:
  2585. return "allOnes";
  2586. }
  2587. llvm_unreachable("invalid TypeTestResolution kind");
  2588. }
  2589. void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {
  2590. Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind)
  2591. << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;
  2592. // The following fields are only used if the target does not support the use
  2593. // of absolute symbols to store constants. Print only if non-zero.
  2594. if (TTRes.AlignLog2)
  2595. Out << ", alignLog2: " << TTRes.AlignLog2;
  2596. if (TTRes.SizeM1)
  2597. Out << ", sizeM1: " << TTRes.SizeM1;
  2598. if (TTRes.BitMask)
  2599. // BitMask is uint8_t which causes it to print the corresponding char.
  2600. Out << ", bitMask: " << (unsigned)TTRes.BitMask;
  2601. if (TTRes.InlineBits)
  2602. Out << ", inlineBits: " << TTRes.InlineBits;
  2603. Out << ")";
  2604. }
  2605. void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {
  2606. Out << ", summary: (";
  2607. printTypeTestResolution(TIS.TTRes);
  2608. if (!TIS.WPDRes.empty()) {
  2609. Out << ", wpdResolutions: (";
  2610. FieldSeparator FS;
  2611. for (auto &WPDRes : TIS.WPDRes) {
  2612. Out << FS;
  2613. Out << "(offset: " << WPDRes.first << ", ";
  2614. printWPDRes(WPDRes.second);
  2615. Out << ")";
  2616. }
  2617. Out << ")";
  2618. }
  2619. Out << ")";
  2620. }
  2621. void AssemblyWriter::printTypeIdCompatibleVtableSummary(
  2622. const TypeIdCompatibleVtableInfo &TI) {
  2623. Out << ", summary: (";
  2624. FieldSeparator FS;
  2625. for (auto &P : TI) {
  2626. Out << FS;
  2627. Out << "(offset: " << P.AddressPointOffset << ", ";
  2628. Out << "^" << Machine.getGUIDSlot(P.VTableVI.getGUID());
  2629. Out << ")";
  2630. }
  2631. Out << ")";
  2632. }
  2633. void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) {
  2634. Out << "args: (";
  2635. FieldSeparator FS;
  2636. for (auto arg : Args) {
  2637. Out << FS;
  2638. Out << arg;
  2639. }
  2640. Out << ")";
  2641. }
  2642. void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {
  2643. Out << "wpdRes: (kind: ";
  2644. Out << getWholeProgDevirtResKindName(WPDRes.TheKind);
  2645. if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl)
  2646. Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";
  2647. if (!WPDRes.ResByArg.empty()) {
  2648. Out << ", resByArg: (";
  2649. FieldSeparator FS;
  2650. for (auto &ResByArg : WPDRes.ResByArg) {
  2651. Out << FS;
  2652. printArgs(ResByArg.first);
  2653. Out << ", byArg: (kind: ";
  2654. Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind);
  2655. if (ResByArg.second.TheKind ==
  2656. WholeProgramDevirtResolution::ByArg::UniformRetVal ||
  2657. ResByArg.second.TheKind ==
  2658. WholeProgramDevirtResolution::ByArg::UniqueRetVal)
  2659. Out << ", info: " << ResByArg.second.Info;
  2660. // The following fields are only used if the target does not support the
  2661. // use of absolute symbols to store constants. Print only if non-zero.
  2662. if (ResByArg.second.Byte || ResByArg.second.Bit)
  2663. Out << ", byte: " << ResByArg.second.Byte
  2664. << ", bit: " << ResByArg.second.Bit;
  2665. Out << ")";
  2666. }
  2667. Out << ")";
  2668. }
  2669. Out << ")";
  2670. }
  2671. static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) {
  2672. switch (SK) {
  2673. case GlobalValueSummary::AliasKind:
  2674. return "alias";
  2675. case GlobalValueSummary::FunctionKind:
  2676. return "function";
  2677. case GlobalValueSummary::GlobalVarKind:
  2678. return "variable";
  2679. }
  2680. llvm_unreachable("invalid summary kind");
  2681. }
  2682. void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {
  2683. Out << ", aliasee: ";
  2684. // The indexes emitted for distributed backends may not include the
  2685. // aliasee summary (only if it is being imported directly). Handle
  2686. // that case by just emitting "null" as the aliasee.
  2687. if (AS->hasAliasee())
  2688. Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]);
  2689. else
  2690. Out << "null";
  2691. }
  2692. void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {
  2693. auto VTableFuncs = GS->vTableFuncs();
  2694. Out << ", varFlags: (readonly: " << GS->VarFlags.MaybeReadOnly << ", "
  2695. << "writeonly: " << GS->VarFlags.MaybeWriteOnly << ", "
  2696. << "constant: " << GS->VarFlags.Constant;
  2697. if (!VTableFuncs.empty())
  2698. Out << ", "
  2699. << "vcall_visibility: " << GS->VarFlags.VCallVisibility;
  2700. Out << ")";
  2701. if (!VTableFuncs.empty()) {
  2702. Out << ", vTableFuncs: (";
  2703. FieldSeparator FS;
  2704. for (auto &P : VTableFuncs) {
  2705. Out << FS;
  2706. Out << "(virtFunc: ^" << Machine.getGUIDSlot(P.FuncVI.getGUID())
  2707. << ", offset: " << P.VTableOffset;
  2708. Out << ")";
  2709. }
  2710. Out << ")";
  2711. }
  2712. }
  2713. static std::string getLinkageName(GlobalValue::LinkageTypes LT) {
  2714. switch (LT) {
  2715. case GlobalValue::ExternalLinkage:
  2716. return "external";
  2717. case GlobalValue::PrivateLinkage:
  2718. return "private";
  2719. case GlobalValue::InternalLinkage:
  2720. return "internal";
  2721. case GlobalValue::LinkOnceAnyLinkage:
  2722. return "linkonce";
  2723. case GlobalValue::LinkOnceODRLinkage:
  2724. return "linkonce_odr";
  2725. case GlobalValue::WeakAnyLinkage:
  2726. return "weak";
  2727. case GlobalValue::WeakODRLinkage:
  2728. return "weak_odr";
  2729. case GlobalValue::CommonLinkage:
  2730. return "common";
  2731. case GlobalValue::AppendingLinkage:
  2732. return "appending";
  2733. case GlobalValue::ExternalWeakLinkage:
  2734. return "extern_weak";
  2735. case GlobalValue::AvailableExternallyLinkage:
  2736. return "available_externally";
  2737. }
  2738. llvm_unreachable("invalid linkage");
  2739. }
  2740. // When printing the linkage types in IR where the ExternalLinkage is
  2741. // not printed, and other linkage types are expected to be printed with
  2742. // a space after the name.
  2743. static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) {
  2744. if (LT == GlobalValue::ExternalLinkage)
  2745. return "";
  2746. return getLinkageName(LT) + " ";
  2747. }
  2748. static const char *getVisibilityName(GlobalValue::VisibilityTypes Vis) {
  2749. switch (Vis) {
  2750. case GlobalValue::DefaultVisibility:
  2751. return "default";
  2752. case GlobalValue::HiddenVisibility:
  2753. return "hidden";
  2754. case GlobalValue::ProtectedVisibility:
  2755. return "protected";
  2756. }
  2757. llvm_unreachable("invalid visibility");
  2758. }
  2759. void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {
  2760. Out << ", insts: " << FS->instCount();
  2761. if (FS->fflags().anyFlagSet())
  2762. Out << ", " << FS->fflags();
  2763. if (!FS->calls().empty()) {
  2764. Out << ", calls: (";
  2765. FieldSeparator IFS;
  2766. for (auto &Call : FS->calls()) {
  2767. Out << IFS;
  2768. Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID());
  2769. if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)
  2770. Out << ", hotness: " << getHotnessName(Call.second.getHotness());
  2771. else if (Call.second.RelBlockFreq)
  2772. Out << ", relbf: " << Call.second.RelBlockFreq;
  2773. Out << ")";
  2774. }
  2775. Out << ")";
  2776. }
  2777. if (const auto *TIdInfo = FS->getTypeIdInfo())
  2778. printTypeIdInfo(*TIdInfo);
  2779. // The AllocationType identifiers capture the profiled context behavior
  2780. // reaching a specific static allocation site (possibly cloned). Thus
  2781. // "notcoldandcold" implies there are multiple contexts which reach this site,
  2782. // some of which are cold and some of which are not, and that need to
  2783. // disambiguate via cloning or other context identification.
  2784. auto AllocTypeName = [](uint8_t Type) -> const char * {
  2785. switch (Type) {
  2786. case (uint8_t)AllocationType::None:
  2787. return "none";
  2788. case (uint8_t)AllocationType::NotCold:
  2789. return "notcold";
  2790. case (uint8_t)AllocationType::Cold:
  2791. return "cold";
  2792. case (uint8_t)AllocationType::NotCold | (uint8_t)AllocationType::Cold:
  2793. return "notcoldandcold";
  2794. }
  2795. llvm_unreachable("Unexpected alloc type");
  2796. };
  2797. if (!FS->allocs().empty()) {
  2798. Out << ", allocs: (";
  2799. FieldSeparator AFS;
  2800. for (auto &AI : FS->allocs()) {
  2801. Out << AFS;
  2802. Out << "(versions: (";
  2803. FieldSeparator VFS;
  2804. for (auto V : AI.Versions) {
  2805. Out << VFS;
  2806. Out << AllocTypeName(V);
  2807. }
  2808. Out << "), memProf: (";
  2809. FieldSeparator MIBFS;
  2810. for (auto &MIB : AI.MIBs) {
  2811. Out << MIBFS;
  2812. Out << "(type: " << AllocTypeName((uint8_t)MIB.AllocType);
  2813. Out << ", stackIds: (";
  2814. FieldSeparator SIDFS;
  2815. for (auto Id : MIB.StackIdIndices) {
  2816. Out << SIDFS;
  2817. Out << TheIndex->getStackIdAtIndex(Id);
  2818. }
  2819. Out << "))";
  2820. }
  2821. Out << "))";
  2822. }
  2823. Out << ")";
  2824. }
  2825. if (!FS->callsites().empty()) {
  2826. Out << ", callsites: (";
  2827. FieldSeparator SNFS;
  2828. for (auto &CI : FS->callsites()) {
  2829. Out << SNFS;
  2830. if (CI.Callee)
  2831. Out << "(callee: ^" << Machine.getGUIDSlot(CI.Callee.getGUID());
  2832. else
  2833. Out << "(callee: null";
  2834. Out << ", clones: (";
  2835. FieldSeparator VFS;
  2836. for (auto V : CI.Clones) {
  2837. Out << VFS;
  2838. Out << V;
  2839. }
  2840. Out << "), stackIds: (";
  2841. FieldSeparator SIDFS;
  2842. for (auto Id : CI.StackIdIndices) {
  2843. Out << SIDFS;
  2844. Out << TheIndex->getStackIdAtIndex(Id);
  2845. }
  2846. Out << "))";
  2847. }
  2848. Out << ")";
  2849. }
  2850. auto PrintRange = [&](const ConstantRange &Range) {
  2851. Out << "[" << Range.getSignedMin() << ", " << Range.getSignedMax() << "]";
  2852. };
  2853. if (!FS->paramAccesses().empty()) {
  2854. Out << ", params: (";
  2855. FieldSeparator IFS;
  2856. for (auto &PS : FS->paramAccesses()) {
  2857. Out << IFS;
  2858. Out << "(param: " << PS.ParamNo;
  2859. Out << ", offset: ";
  2860. PrintRange(PS.Use);
  2861. if (!PS.Calls.empty()) {
  2862. Out << ", calls: (";
  2863. FieldSeparator IFS;
  2864. for (auto &Call : PS.Calls) {
  2865. Out << IFS;
  2866. Out << "(callee: ^" << Machine.getGUIDSlot(Call.Callee.getGUID());
  2867. Out << ", param: " << Call.ParamNo;
  2868. Out << ", offset: ";
  2869. PrintRange(Call.Offsets);
  2870. Out << ")";
  2871. }
  2872. Out << ")";
  2873. }
  2874. Out << ")";
  2875. }
  2876. Out << ")";
  2877. }
  2878. }
  2879. void AssemblyWriter::printTypeIdInfo(
  2880. const FunctionSummary::TypeIdInfo &TIDInfo) {
  2881. Out << ", typeIdInfo: (";
  2882. FieldSeparator TIDFS;
  2883. if (!TIDInfo.TypeTests.empty()) {
  2884. Out << TIDFS;
  2885. Out << "typeTests: (";
  2886. FieldSeparator FS;
  2887. for (auto &GUID : TIDInfo.TypeTests) {
  2888. auto TidIter = TheIndex->typeIds().equal_range(GUID);
  2889. if (TidIter.first == TidIter.second) {
  2890. Out << FS;
  2891. Out << GUID;
  2892. continue;
  2893. }
  2894. // Print all type id that correspond to this GUID.
  2895. for (auto It = TidIter.first; It != TidIter.second; ++It) {
  2896. Out << FS;
  2897. auto Slot = Machine.getTypeIdSlot(It->second.first);
  2898. assert(Slot != -1);
  2899. Out << "^" << Slot;
  2900. }
  2901. }
  2902. Out << ")";
  2903. }
  2904. if (!TIDInfo.TypeTestAssumeVCalls.empty()) {
  2905. Out << TIDFS;
  2906. printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls");
  2907. }
  2908. if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {
  2909. Out << TIDFS;
  2910. printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls");
  2911. }
  2912. if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {
  2913. Out << TIDFS;
  2914. printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls,
  2915. "typeTestAssumeConstVCalls");
  2916. }
  2917. if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {
  2918. Out << TIDFS;
  2919. printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls,
  2920. "typeCheckedLoadConstVCalls");
  2921. }
  2922. Out << ")";
  2923. }
  2924. void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {
  2925. auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID);
  2926. if (TidIter.first == TidIter.second) {
  2927. Out << "vFuncId: (";
  2928. Out << "guid: " << VFId.GUID;
  2929. Out << ", offset: " << VFId.Offset;
  2930. Out << ")";
  2931. return;
  2932. }
  2933. // Print all type id that correspond to this GUID.
  2934. FieldSeparator FS;
  2935. for (auto It = TidIter.first; It != TidIter.second; ++It) {
  2936. Out << FS;
  2937. Out << "vFuncId: (";
  2938. auto Slot = Machine.getTypeIdSlot(It->second.first);
  2939. assert(Slot != -1);
  2940. Out << "^" << Slot;
  2941. Out << ", offset: " << VFId.Offset;
  2942. Out << ")";
  2943. }
  2944. }
  2945. void AssemblyWriter::printNonConstVCalls(
  2946. const std::vector<FunctionSummary::VFuncId> &VCallList, const char *Tag) {
  2947. Out << Tag << ": (";
  2948. FieldSeparator FS;
  2949. for (auto &VFuncId : VCallList) {
  2950. Out << FS;
  2951. printVFuncId(VFuncId);
  2952. }
  2953. Out << ")";
  2954. }
  2955. void AssemblyWriter::printConstVCalls(
  2956. const std::vector<FunctionSummary::ConstVCall> &VCallList,
  2957. const char *Tag) {
  2958. Out << Tag << ": (";
  2959. FieldSeparator FS;
  2960. for (auto &ConstVCall : VCallList) {
  2961. Out << FS;
  2962. Out << "(";
  2963. printVFuncId(ConstVCall.VFunc);
  2964. if (!ConstVCall.Args.empty()) {
  2965. Out << ", ";
  2966. printArgs(ConstVCall.Args);
  2967. }
  2968. Out << ")";
  2969. }
  2970. Out << ")";
  2971. }
  2972. void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {
  2973. GlobalValueSummary::GVFlags GVFlags = Summary.flags();
  2974. GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage;
  2975. Out << getSummaryKindName(Summary.getSummaryKind()) << ": ";
  2976. Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath())
  2977. << ", flags: (";
  2978. Out << "linkage: " << getLinkageName(LT);
  2979. Out << ", visibility: "
  2980. << getVisibilityName((GlobalValue::VisibilityTypes)GVFlags.Visibility);
  2981. Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;
  2982. Out << ", live: " << GVFlags.Live;
  2983. Out << ", dsoLocal: " << GVFlags.DSOLocal;
  2984. Out << ", canAutoHide: " << GVFlags.CanAutoHide;
  2985. Out << ")";
  2986. if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind)
  2987. printAliasSummary(cast<AliasSummary>(&Summary));
  2988. else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
  2989. printFunctionSummary(cast<FunctionSummary>(&Summary));
  2990. else
  2991. printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
  2992. auto RefList = Summary.refs();
  2993. if (!RefList.empty()) {
  2994. Out << ", refs: (";
  2995. FieldSeparator FS;
  2996. for (auto &Ref : RefList) {
  2997. Out << FS;
  2998. if (Ref.isReadOnly())
  2999. Out << "readonly ";
  3000. else if (Ref.isWriteOnly())
  3001. Out << "writeonly ";
  3002. Out << "^" << Machine.getGUIDSlot(Ref.getGUID());
  3003. }
  3004. Out << ")";
  3005. }
  3006. Out << ")";
  3007. }
  3008. void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {
  3009. Out << "^" << Slot << " = gv: (";
  3010. if (!VI.name().empty())
  3011. Out << "name: \"" << VI.name() << "\"";
  3012. else
  3013. Out << "guid: " << VI.getGUID();
  3014. if (!VI.getSummaryList().empty()) {
  3015. Out << ", summaries: (";
  3016. FieldSeparator FS;
  3017. for (auto &Summary : VI.getSummaryList()) {
  3018. Out << FS;
  3019. printSummary(*Summary);
  3020. }
  3021. Out << ")";
  3022. }
  3023. Out << ")";
  3024. if (!VI.name().empty())
  3025. Out << " ; guid = " << VI.getGUID();
  3026. Out << "\n";
  3027. }
  3028. static void printMetadataIdentifier(StringRef Name,
  3029. formatted_raw_ostream &Out) {
  3030. if (Name.empty()) {
  3031. Out << "<empty name> ";
  3032. } else {
  3033. if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
  3034. Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
  3035. Out << Name[0];
  3036. else
  3037. Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
  3038. for (unsigned i = 1, e = Name.size(); i != e; ++i) {
  3039. unsigned char C = Name[i];
  3040. if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
  3041. C == '.' || C == '_')
  3042. Out << C;
  3043. else
  3044. Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
  3045. }
  3046. }
  3047. }
  3048. void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
  3049. Out << '!';
  3050. printMetadataIdentifier(NMD->getName(), Out);
  3051. Out << " = !{";
  3052. for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
  3053. if (i)
  3054. Out << ", ";
  3055. // Write DIExpressions inline.
  3056. // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
  3057. MDNode *Op = NMD->getOperand(i);
  3058. assert(!isa<DIArgList>(Op) &&
  3059. "DIArgLists should not appear in NamedMDNodes");
  3060. if (auto *Expr = dyn_cast<DIExpression>(Op)) {
  3061. writeDIExpression(Out, Expr, AsmWriterContext::getEmpty());
  3062. continue;
  3063. }
  3064. int Slot = Machine.getMetadataSlot(Op);
  3065. if (Slot == -1)
  3066. Out << "<badref>";
  3067. else
  3068. Out << '!' << Slot;
  3069. }
  3070. Out << "}\n";
  3071. }
  3072. static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
  3073. formatted_raw_ostream &Out) {
  3074. switch (Vis) {
  3075. case GlobalValue::DefaultVisibility: break;
  3076. case GlobalValue::HiddenVisibility: Out << "hidden "; break;
  3077. case GlobalValue::ProtectedVisibility: Out << "protected "; break;
  3078. }
  3079. }
  3080. static void PrintDSOLocation(const GlobalValue &GV,
  3081. formatted_raw_ostream &Out) {
  3082. if (GV.isDSOLocal() && !GV.isImplicitDSOLocal())
  3083. Out << "dso_local ";
  3084. }
  3085. static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
  3086. formatted_raw_ostream &Out) {
  3087. switch (SCT) {
  3088. case GlobalValue::DefaultStorageClass: break;
  3089. case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
  3090. case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
  3091. }
  3092. }
  3093. static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
  3094. formatted_raw_ostream &Out) {
  3095. switch (TLM) {
  3096. case GlobalVariable::NotThreadLocal:
  3097. break;
  3098. case GlobalVariable::GeneralDynamicTLSModel:
  3099. Out << "thread_local ";
  3100. break;
  3101. case GlobalVariable::LocalDynamicTLSModel:
  3102. Out << "thread_local(localdynamic) ";
  3103. break;
  3104. case GlobalVariable::InitialExecTLSModel:
  3105. Out << "thread_local(initialexec) ";
  3106. break;
  3107. case GlobalVariable::LocalExecTLSModel:
  3108. Out << "thread_local(localexec) ";
  3109. break;
  3110. }
  3111. }
  3112. static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
  3113. switch (UA) {
  3114. case GlobalVariable::UnnamedAddr::None:
  3115. return "";
  3116. case GlobalVariable::UnnamedAddr::Local:
  3117. return "local_unnamed_addr";
  3118. case GlobalVariable::UnnamedAddr::Global:
  3119. return "unnamed_addr";
  3120. }
  3121. llvm_unreachable("Unknown UnnamedAddr");
  3122. }
  3123. static void maybePrintComdat(formatted_raw_ostream &Out,
  3124. const GlobalObject &GO) {
  3125. const Comdat *C = GO.getComdat();
  3126. if (!C)
  3127. return;
  3128. if (isa<GlobalVariable>(GO))
  3129. Out << ',';
  3130. Out << " comdat";
  3131. if (GO.getName() == C->getName())
  3132. return;
  3133. Out << '(';
  3134. PrintLLVMName(Out, C->getName(), ComdatPrefix);
  3135. Out << ')';
  3136. }
  3137. void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
  3138. if (GV->isMaterializable())
  3139. Out << "; Materializable\n";
  3140. AsmWriterContext WriterCtx(&TypePrinter, &Machine, GV->getParent());
  3141. WriteAsOperandInternal(Out, GV, WriterCtx);
  3142. Out << " = ";
  3143. if (!GV->hasInitializer() && GV->hasExternalLinkage())
  3144. Out << "external ";
  3145. Out << getLinkageNameWithSpace(GV->getLinkage());
  3146. PrintDSOLocation(*GV, Out);
  3147. PrintVisibility(GV->getVisibility(), Out);
  3148. PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
  3149. PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
  3150. StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
  3151. if (!UA.empty())
  3152. Out << UA << ' ';
  3153. if (unsigned AddressSpace = GV->getType()->getAddressSpace())
  3154. Out << "addrspace(" << AddressSpace << ") ";
  3155. if (GV->isExternallyInitialized()) Out << "externally_initialized ";
  3156. Out << (GV->isConstant() ? "constant " : "global ");
  3157. TypePrinter.print(GV->getValueType(), Out);
  3158. if (GV->hasInitializer()) {
  3159. Out << ' ';
  3160. writeOperand(GV->getInitializer(), false);
  3161. }
  3162. if (GV->hasSection()) {
  3163. Out << ", section \"";
  3164. printEscapedString(GV->getSection(), Out);
  3165. Out << '"';
  3166. }
  3167. if (GV->hasPartition()) {
  3168. Out << ", partition \"";
  3169. printEscapedString(GV->getPartition(), Out);
  3170. Out << '"';
  3171. }
  3172. using SanitizerMetadata = llvm::GlobalValue::SanitizerMetadata;
  3173. if (GV->hasSanitizerMetadata()) {
  3174. SanitizerMetadata MD = GV->getSanitizerMetadata();
  3175. if (MD.NoAddress)
  3176. Out << ", no_sanitize_address";
  3177. if (MD.NoHWAddress)
  3178. Out << ", no_sanitize_hwaddress";
  3179. if (MD.Memtag)
  3180. Out << ", sanitize_memtag";
  3181. if (MD.IsDynInit)
  3182. Out << ", sanitize_address_dyninit";
  3183. }
  3184. maybePrintComdat(Out, *GV);
  3185. if (MaybeAlign A = GV->getAlign())
  3186. Out << ", align " << A->value();
  3187. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  3188. GV->getAllMetadata(MDs);
  3189. printMetadataAttachments(MDs, ", ");
  3190. auto Attrs = GV->getAttributes();
  3191. if (Attrs.hasAttributes())
  3192. Out << " #" << Machine.getAttributeGroupSlot(Attrs);
  3193. printInfoComment(*GV);
  3194. }
  3195. void AssemblyWriter::printAlias(const GlobalAlias *GA) {
  3196. if (GA->isMaterializable())
  3197. Out << "; Materializable\n";
  3198. AsmWriterContext WriterCtx(&TypePrinter, &Machine, GA->getParent());
  3199. WriteAsOperandInternal(Out, GA, WriterCtx);
  3200. Out << " = ";
  3201. Out << getLinkageNameWithSpace(GA->getLinkage());
  3202. PrintDSOLocation(*GA, Out);
  3203. PrintVisibility(GA->getVisibility(), Out);
  3204. PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
  3205. PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
  3206. StringRef UA = getUnnamedAddrEncoding(GA->getUnnamedAddr());
  3207. if (!UA.empty())
  3208. Out << UA << ' ';
  3209. Out << "alias ";
  3210. TypePrinter.print(GA->getValueType(), Out);
  3211. Out << ", ";
  3212. if (const Constant *Aliasee = GA->getAliasee()) {
  3213. writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
  3214. } else {
  3215. TypePrinter.print(GA->getType(), Out);
  3216. Out << " <<NULL ALIASEE>>";
  3217. }
  3218. if (GA->hasPartition()) {
  3219. Out << ", partition \"";
  3220. printEscapedString(GA->getPartition(), Out);
  3221. Out << '"';
  3222. }
  3223. printInfoComment(*GA);
  3224. Out << '\n';
  3225. }
  3226. void AssemblyWriter::printIFunc(const GlobalIFunc *GI) {
  3227. if (GI->isMaterializable())
  3228. Out << "; Materializable\n";
  3229. AsmWriterContext WriterCtx(&TypePrinter, &Machine, GI->getParent());
  3230. WriteAsOperandInternal(Out, GI, WriterCtx);
  3231. Out << " = ";
  3232. Out << getLinkageNameWithSpace(GI->getLinkage());
  3233. PrintDSOLocation(*GI, Out);
  3234. PrintVisibility(GI->getVisibility(), Out);
  3235. Out << "ifunc ";
  3236. TypePrinter.print(GI->getValueType(), Out);
  3237. Out << ", ";
  3238. if (const Constant *Resolver = GI->getResolver()) {
  3239. writeOperand(Resolver, !isa<ConstantExpr>(Resolver));
  3240. } else {
  3241. TypePrinter.print(GI->getType(), Out);
  3242. Out << " <<NULL RESOLVER>>";
  3243. }
  3244. if (GI->hasPartition()) {
  3245. Out << ", partition \"";
  3246. printEscapedString(GI->getPartition(), Out);
  3247. Out << '"';
  3248. }
  3249. printInfoComment(*GI);
  3250. Out << '\n';
  3251. }
  3252. void AssemblyWriter::printComdat(const Comdat *C) {
  3253. C->print(Out);
  3254. }
  3255. void AssemblyWriter::printTypeIdentities() {
  3256. if (TypePrinter.empty())
  3257. return;
  3258. Out << '\n';
  3259. // Emit all numbered types.
  3260. auto &NumberedTypes = TypePrinter.getNumberedTypes();
  3261. for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {
  3262. Out << '%' << I << " = type ";
  3263. // Make sure we print out at least one level of the type structure, so
  3264. // that we do not get %2 = type %2
  3265. TypePrinter.printStructBody(NumberedTypes[I], Out);
  3266. Out << '\n';
  3267. }
  3268. auto &NamedTypes = TypePrinter.getNamedTypes();
  3269. for (StructType *NamedType : NamedTypes) {
  3270. PrintLLVMName(Out, NamedType->getName(), LocalPrefix);
  3271. Out << " = type ";
  3272. // Make sure we print out at least one level of the type structure, so
  3273. // that we do not get %FILE = type %FILE
  3274. TypePrinter.printStructBody(NamedType, Out);
  3275. Out << '\n';
  3276. }
  3277. }
  3278. /// printFunction - Print all aspects of a function.
  3279. void AssemblyWriter::printFunction(const Function *F) {
  3280. if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
  3281. if (F->isMaterializable())
  3282. Out << "; Materializable\n";
  3283. const AttributeList &Attrs = F->getAttributes();
  3284. if (Attrs.hasFnAttrs()) {
  3285. AttributeSet AS = Attrs.getFnAttrs();
  3286. std::string AttrStr;
  3287. for (const Attribute &Attr : AS) {
  3288. if (!Attr.isStringAttribute()) {
  3289. if (!AttrStr.empty()) AttrStr += ' ';
  3290. AttrStr += Attr.getAsString();
  3291. }
  3292. }
  3293. if (!AttrStr.empty())
  3294. Out << "; Function Attrs: " << AttrStr << '\n';
  3295. }
  3296. Machine.incorporateFunction(F);
  3297. if (F->isDeclaration()) {
  3298. Out << "declare";
  3299. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  3300. F->getAllMetadata(MDs);
  3301. printMetadataAttachments(MDs, " ");
  3302. Out << ' ';
  3303. } else
  3304. Out << "define ";
  3305. Out << getLinkageNameWithSpace(F->getLinkage());
  3306. PrintDSOLocation(*F, Out);
  3307. PrintVisibility(F->getVisibility(), Out);
  3308. PrintDLLStorageClass(F->getDLLStorageClass(), Out);
  3309. // Print the calling convention.
  3310. if (F->getCallingConv() != CallingConv::C) {
  3311. PrintCallingConv(F->getCallingConv(), Out);
  3312. Out << " ";
  3313. }
  3314. FunctionType *FT = F->getFunctionType();
  3315. if (Attrs.hasRetAttrs())
  3316. Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
  3317. TypePrinter.print(F->getReturnType(), Out);
  3318. AsmWriterContext WriterCtx(&TypePrinter, &Machine, F->getParent());
  3319. Out << ' ';
  3320. WriteAsOperandInternal(Out, F, WriterCtx);
  3321. Out << '(';
  3322. // Loop over the arguments, printing them...
  3323. if (F->isDeclaration() && !IsForDebug) {
  3324. // We're only interested in the type here - don't print argument names.
  3325. for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
  3326. // Insert commas as we go... the first arg doesn't get a comma
  3327. if (I)
  3328. Out << ", ";
  3329. // Output type...
  3330. TypePrinter.print(FT->getParamType(I), Out);
  3331. AttributeSet ArgAttrs = Attrs.getParamAttrs(I);
  3332. if (ArgAttrs.hasAttributes()) {
  3333. Out << ' ';
  3334. writeAttributeSet(ArgAttrs);
  3335. }
  3336. }
  3337. } else {
  3338. // The arguments are meaningful here, print them in detail.
  3339. for (const Argument &Arg : F->args()) {
  3340. // Insert commas as we go... the first arg doesn't get a comma
  3341. if (Arg.getArgNo() != 0)
  3342. Out << ", ";
  3343. printArgument(&Arg, Attrs.getParamAttrs(Arg.getArgNo()));
  3344. }
  3345. }
  3346. // Finish printing arguments...
  3347. if (FT->isVarArg()) {
  3348. if (FT->getNumParams()) Out << ", ";
  3349. Out << "..."; // Output varargs portion of signature!
  3350. }
  3351. Out << ')';
  3352. StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
  3353. if (!UA.empty())
  3354. Out << ' ' << UA;
  3355. // We print the function address space if it is non-zero or if we are writing
  3356. // a module with a non-zero program address space or if there is no valid
  3357. // Module* so that the file can be parsed without the datalayout string.
  3358. const Module *Mod = F->getParent();
  3359. if (F->getAddressSpace() != 0 || !Mod ||
  3360. Mod->getDataLayout().getProgramAddressSpace() != 0)
  3361. Out << " addrspace(" << F->getAddressSpace() << ")";
  3362. if (Attrs.hasFnAttrs())
  3363. Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttrs());
  3364. if (F->hasSection()) {
  3365. Out << " section \"";
  3366. printEscapedString(F->getSection(), Out);
  3367. Out << '"';
  3368. }
  3369. if (F->hasPartition()) {
  3370. Out << " partition \"";
  3371. printEscapedString(F->getPartition(), Out);
  3372. Out << '"';
  3373. }
  3374. maybePrintComdat(Out, *F);
  3375. if (MaybeAlign A = F->getAlign())
  3376. Out << " align " << A->value();
  3377. if (F->hasGC())
  3378. Out << " gc \"" << F->getGC() << '"';
  3379. if (F->hasPrefixData()) {
  3380. Out << " prefix ";
  3381. writeOperand(F->getPrefixData(), true);
  3382. }
  3383. if (F->hasPrologueData()) {
  3384. Out << " prologue ";
  3385. writeOperand(F->getPrologueData(), true);
  3386. }
  3387. if (F->hasPersonalityFn()) {
  3388. Out << " personality ";
  3389. writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
  3390. }
  3391. if (F->isDeclaration()) {
  3392. Out << '\n';
  3393. } else {
  3394. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  3395. F->getAllMetadata(MDs);
  3396. printMetadataAttachments(MDs, " ");
  3397. Out << " {";
  3398. // Output all of the function's basic blocks.
  3399. for (const BasicBlock &BB : *F)
  3400. printBasicBlock(&BB);
  3401. // Output the function's use-lists.
  3402. printUseLists(F);
  3403. Out << "}\n";
  3404. }
  3405. Machine.purgeFunction();
  3406. }
  3407. /// printArgument - This member is called for every argument that is passed into
  3408. /// the function. Simply print it out
  3409. void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
  3410. // Output type...
  3411. TypePrinter.print(Arg->getType(), Out);
  3412. // Output parameter attributes list
  3413. if (Attrs.hasAttributes()) {
  3414. Out << ' ';
  3415. writeAttributeSet(Attrs);
  3416. }
  3417. // Output name, if available...
  3418. if (Arg->hasName()) {
  3419. Out << ' ';
  3420. PrintLLVMName(Out, Arg);
  3421. } else {
  3422. int Slot = Machine.getLocalSlot(Arg);
  3423. assert(Slot != -1 && "expect argument in function here");
  3424. Out << " %" << Slot;
  3425. }
  3426. }
  3427. /// printBasicBlock - This member is called for each basic block in a method.
  3428. void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
  3429. bool IsEntryBlock = BB->getParent() && BB->isEntryBlock();
  3430. if (BB->hasName()) { // Print out the label if it exists...
  3431. Out << "\n";
  3432. PrintLLVMName(Out, BB->getName(), LabelPrefix);
  3433. Out << ':';
  3434. } else if (!IsEntryBlock) {
  3435. Out << "\n";
  3436. int Slot = Machine.getLocalSlot(BB);
  3437. if (Slot != -1)
  3438. Out << Slot << ":";
  3439. else
  3440. Out << "<badref>:";
  3441. }
  3442. if (!IsEntryBlock) {
  3443. // Output predecessors for the block.
  3444. Out.PadToColumn(50);
  3445. Out << ";";
  3446. const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
  3447. if (PI == PE) {
  3448. Out << " No predecessors!";
  3449. } else {
  3450. Out << " preds = ";
  3451. writeOperand(*PI, false);
  3452. for (++PI; PI != PE; ++PI) {
  3453. Out << ", ";
  3454. writeOperand(*PI, false);
  3455. }
  3456. }
  3457. }
  3458. Out << "\n";
  3459. if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
  3460. // Output all of the instructions in the basic block...
  3461. for (const Instruction &I : *BB) {
  3462. printInstructionLine(I);
  3463. }
  3464. if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
  3465. }
  3466. /// printInstructionLine - Print an instruction and a newline character.
  3467. void AssemblyWriter::printInstructionLine(const Instruction &I) {
  3468. printInstruction(I);
  3469. Out << '\n';
  3470. }
  3471. /// printGCRelocateComment - print comment after call to the gc.relocate
  3472. /// intrinsic indicating base and derived pointer names.
  3473. void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
  3474. Out << " ; (";
  3475. writeOperand(Relocate.getBasePtr(), false);
  3476. Out << ", ";
  3477. writeOperand(Relocate.getDerivedPtr(), false);
  3478. Out << ")";
  3479. }
  3480. /// printInfoComment - Print a little comment after the instruction indicating
  3481. /// which slot it occupies.
  3482. void AssemblyWriter::printInfoComment(const Value &V) {
  3483. if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
  3484. printGCRelocateComment(*Relocate);
  3485. if (AnnotationWriter)
  3486. AnnotationWriter->printInfoComment(V, Out);
  3487. }
  3488. static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,
  3489. raw_ostream &Out) {
  3490. // We print the address space of the call if it is non-zero.
  3491. if (Operand == nullptr) {
  3492. Out << " <cannot get addrspace!>";
  3493. return;
  3494. }
  3495. unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();
  3496. bool PrintAddrSpace = CallAddrSpace != 0;
  3497. if (!PrintAddrSpace) {
  3498. const Module *Mod = getModuleFromVal(I);
  3499. // We also print it if it is zero but not equal to the program address space
  3500. // or if we can't find a valid Module* to make it possible to parse
  3501. // the resulting file even without a datalayout string.
  3502. if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0)
  3503. PrintAddrSpace = true;
  3504. }
  3505. if (PrintAddrSpace)
  3506. Out << " addrspace(" << CallAddrSpace << ")";
  3507. }
  3508. // This member is called for each Instruction in a function..
  3509. void AssemblyWriter::printInstruction(const Instruction &I) {
  3510. if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
  3511. // Print out indentation for an instruction.
  3512. Out << " ";
  3513. // Print out name if it exists...
  3514. if (I.hasName()) {
  3515. PrintLLVMName(Out, &I);
  3516. Out << " = ";
  3517. } else if (!I.getType()->isVoidTy()) {
  3518. // Print out the def slot taken.
  3519. int SlotNum = Machine.getLocalSlot(&I);
  3520. if (SlotNum == -1)
  3521. Out << "<badref> = ";
  3522. else
  3523. Out << '%' << SlotNum << " = ";
  3524. }
  3525. if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
  3526. if (CI->isMustTailCall())
  3527. Out << "musttail ";
  3528. else if (CI->isTailCall())
  3529. Out << "tail ";
  3530. else if (CI->isNoTailCall())
  3531. Out << "notail ";
  3532. }
  3533. // Print out the opcode...
  3534. Out << I.getOpcodeName();
  3535. // If this is an atomic load or store, print out the atomic marker.
  3536. if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
  3537. (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
  3538. Out << " atomic";
  3539. if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
  3540. Out << " weak";
  3541. // If this is a volatile operation, print out the volatile marker.
  3542. if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
  3543. (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
  3544. (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
  3545. (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
  3546. Out << " volatile";
  3547. // Print out optimization information.
  3548. WriteOptimizationInfo(Out, &I);
  3549. // Print out the compare instruction predicates
  3550. if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
  3551. Out << ' ' << CmpInst::getPredicateName(CI->getPredicate());
  3552. // Print out the atomicrmw operation
  3553. if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
  3554. Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation());
  3555. // Print out the type of the operands...
  3556. const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
  3557. // Special case conditional branches to swizzle the condition out to the front
  3558. if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
  3559. const BranchInst &BI(cast<BranchInst>(I));
  3560. Out << ' ';
  3561. writeOperand(BI.getCondition(), true);
  3562. Out << ", ";
  3563. writeOperand(BI.getSuccessor(0), true);
  3564. Out << ", ";
  3565. writeOperand(BI.getSuccessor(1), true);
  3566. } else if (isa<SwitchInst>(I)) {
  3567. const SwitchInst& SI(cast<SwitchInst>(I));
  3568. // Special case switch instruction to get formatting nice and correct.
  3569. Out << ' ';
  3570. writeOperand(SI.getCondition(), true);
  3571. Out << ", ";
  3572. writeOperand(SI.getDefaultDest(), true);
  3573. Out << " [";
  3574. for (auto Case : SI.cases()) {
  3575. Out << "\n ";
  3576. writeOperand(Case.getCaseValue(), true);
  3577. Out << ", ";
  3578. writeOperand(Case.getCaseSuccessor(), true);
  3579. }
  3580. Out << "\n ]";
  3581. } else if (isa<IndirectBrInst>(I)) {
  3582. // Special case indirectbr instruction to get formatting nice and correct.
  3583. Out << ' ';
  3584. writeOperand(Operand, true);
  3585. Out << ", [";
  3586. for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
  3587. if (i != 1)
  3588. Out << ", ";
  3589. writeOperand(I.getOperand(i), true);
  3590. }
  3591. Out << ']';
  3592. } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
  3593. Out << ' ';
  3594. TypePrinter.print(I.getType(), Out);
  3595. Out << ' ';
  3596. for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
  3597. if (op) Out << ", ";
  3598. Out << "[ ";
  3599. writeOperand(PN->getIncomingValue(op), false); Out << ", ";
  3600. writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
  3601. }
  3602. } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
  3603. Out << ' ';
  3604. writeOperand(I.getOperand(0), true);
  3605. for (unsigned i : EVI->indices())
  3606. Out << ", " << i;
  3607. } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
  3608. Out << ' ';
  3609. writeOperand(I.getOperand(0), true); Out << ", ";
  3610. writeOperand(I.getOperand(1), true);
  3611. for (unsigned i : IVI->indices())
  3612. Out << ", " << i;
  3613. } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
  3614. Out << ' ';
  3615. TypePrinter.print(I.getType(), Out);
  3616. if (LPI->isCleanup() || LPI->getNumClauses() != 0)
  3617. Out << '\n';
  3618. if (LPI->isCleanup())
  3619. Out << " cleanup";
  3620. for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
  3621. if (i != 0 || LPI->isCleanup()) Out << "\n";
  3622. if (LPI->isCatch(i))
  3623. Out << " catch ";
  3624. else
  3625. Out << " filter ";
  3626. writeOperand(LPI->getClause(i), true);
  3627. }
  3628. } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
  3629. Out << " within ";
  3630. writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
  3631. Out << " [";
  3632. unsigned Op = 0;
  3633. for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
  3634. if (Op > 0)
  3635. Out << ", ";
  3636. writeOperand(PadBB, /*PrintType=*/true);
  3637. ++Op;
  3638. }
  3639. Out << "] unwind ";
  3640. if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
  3641. writeOperand(UnwindDest, /*PrintType=*/true);
  3642. else
  3643. Out << "to caller";
  3644. } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
  3645. Out << " within ";
  3646. writeOperand(FPI->getParentPad(), /*PrintType=*/false);
  3647. Out << " [";
  3648. for (unsigned Op = 0, NumOps = FPI->arg_size(); Op < NumOps; ++Op) {
  3649. if (Op > 0)
  3650. Out << ", ";
  3651. writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
  3652. }
  3653. Out << ']';
  3654. } else if (isa<ReturnInst>(I) && !Operand) {
  3655. Out << " void";
  3656. } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
  3657. Out << " from ";
  3658. writeOperand(CRI->getOperand(0), /*PrintType=*/false);
  3659. Out << " to ";
  3660. writeOperand(CRI->getOperand(1), /*PrintType=*/true);
  3661. } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
  3662. Out << " from ";
  3663. writeOperand(CRI->getOperand(0), /*PrintType=*/false);
  3664. Out << " unwind ";
  3665. if (CRI->hasUnwindDest())
  3666. writeOperand(CRI->getOperand(1), /*PrintType=*/true);
  3667. else
  3668. Out << "to caller";
  3669. } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
  3670. // Print the calling convention being used.
  3671. if (CI->getCallingConv() != CallingConv::C) {
  3672. Out << " ";
  3673. PrintCallingConv(CI->getCallingConv(), Out);
  3674. }
  3675. Operand = CI->getCalledOperand();
  3676. FunctionType *FTy = CI->getFunctionType();
  3677. Type *RetTy = FTy->getReturnType();
  3678. const AttributeList &PAL = CI->getAttributes();
  3679. if (PAL.hasRetAttrs())
  3680. Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
  3681. // Only print addrspace(N) if necessary:
  3682. maybePrintCallAddrSpace(Operand, &I, Out);
  3683. // If possible, print out the short form of the call instruction. We can
  3684. // only do this if the first argument is a pointer to a nonvararg function,
  3685. // and if the return type is not a pointer to a function.
  3686. Out << ' ';
  3687. TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
  3688. Out << ' ';
  3689. writeOperand(Operand, false);
  3690. Out << '(';
  3691. for (unsigned op = 0, Eop = CI->arg_size(); op < Eop; ++op) {
  3692. if (op > 0)
  3693. Out << ", ";
  3694. writeParamOperand(CI->getArgOperand(op), PAL.getParamAttrs(op));
  3695. }
  3696. // Emit an ellipsis if this is a musttail call in a vararg function. This
  3697. // is only to aid readability, musttail calls forward varargs by default.
  3698. if (CI->isMustTailCall() && CI->getParent() &&
  3699. CI->getParent()->getParent() &&
  3700. CI->getParent()->getParent()->isVarArg()) {
  3701. if (CI->arg_size() > 0)
  3702. Out << ", ";
  3703. Out << "...";
  3704. }
  3705. Out << ')';
  3706. if (PAL.hasFnAttrs())
  3707. Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
  3708. writeOperandBundles(CI);
  3709. } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
  3710. Operand = II->getCalledOperand();
  3711. FunctionType *FTy = II->getFunctionType();
  3712. Type *RetTy = FTy->getReturnType();
  3713. const AttributeList &PAL = II->getAttributes();
  3714. // Print the calling convention being used.
  3715. if (II->getCallingConv() != CallingConv::C) {
  3716. Out << " ";
  3717. PrintCallingConv(II->getCallingConv(), Out);
  3718. }
  3719. if (PAL.hasRetAttrs())
  3720. Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
  3721. // Only print addrspace(N) if necessary:
  3722. maybePrintCallAddrSpace(Operand, &I, Out);
  3723. // If possible, print out the short form of the invoke instruction. We can
  3724. // only do this if the first argument is a pointer to a nonvararg function,
  3725. // and if the return type is not a pointer to a function.
  3726. //
  3727. Out << ' ';
  3728. TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
  3729. Out << ' ';
  3730. writeOperand(Operand, false);
  3731. Out << '(';
  3732. for (unsigned op = 0, Eop = II->arg_size(); op < Eop; ++op) {
  3733. if (op)
  3734. Out << ", ";
  3735. writeParamOperand(II->getArgOperand(op), PAL.getParamAttrs(op));
  3736. }
  3737. Out << ')';
  3738. if (PAL.hasFnAttrs())
  3739. Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
  3740. writeOperandBundles(II);
  3741. Out << "\n to ";
  3742. writeOperand(II->getNormalDest(), true);
  3743. Out << " unwind ";
  3744. writeOperand(II->getUnwindDest(), true);
  3745. } else if (const CallBrInst *CBI = dyn_cast<CallBrInst>(&I)) {
  3746. Operand = CBI->getCalledOperand();
  3747. FunctionType *FTy = CBI->getFunctionType();
  3748. Type *RetTy = FTy->getReturnType();
  3749. const AttributeList &PAL = CBI->getAttributes();
  3750. // Print the calling convention being used.
  3751. if (CBI->getCallingConv() != CallingConv::C) {
  3752. Out << " ";
  3753. PrintCallingConv(CBI->getCallingConv(), Out);
  3754. }
  3755. if (PAL.hasRetAttrs())
  3756. Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
  3757. // If possible, print out the short form of the callbr instruction. We can
  3758. // only do this if the first argument is a pointer to a nonvararg function,
  3759. // and if the return type is not a pointer to a function.
  3760. //
  3761. Out << ' ';
  3762. TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
  3763. Out << ' ';
  3764. writeOperand(Operand, false);
  3765. Out << '(';
  3766. for (unsigned op = 0, Eop = CBI->arg_size(); op < Eop; ++op) {
  3767. if (op)
  3768. Out << ", ";
  3769. writeParamOperand(CBI->getArgOperand(op), PAL.getParamAttrs(op));
  3770. }
  3771. Out << ')';
  3772. if (PAL.hasFnAttrs())
  3773. Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
  3774. writeOperandBundles(CBI);
  3775. Out << "\n to ";
  3776. writeOperand(CBI->getDefaultDest(), true);
  3777. Out << " [";
  3778. for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) {
  3779. if (i != 0)
  3780. Out << ", ";
  3781. writeOperand(CBI->getIndirectDest(i), true);
  3782. }
  3783. Out << ']';
  3784. } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
  3785. Out << ' ';
  3786. if (AI->isUsedWithInAlloca())
  3787. Out << "inalloca ";
  3788. if (AI->isSwiftError())
  3789. Out << "swifterror ";
  3790. TypePrinter.print(AI->getAllocatedType(), Out);
  3791. // Explicitly write the array size if the code is broken, if it's an array
  3792. // allocation, or if the type is not canonical for scalar allocations. The
  3793. // latter case prevents the type from mutating when round-tripping through
  3794. // assembly.
  3795. if (!AI->getArraySize() || AI->isArrayAllocation() ||
  3796. !AI->getArraySize()->getType()->isIntegerTy(32)) {
  3797. Out << ", ";
  3798. writeOperand(AI->getArraySize(), true);
  3799. }
  3800. if (MaybeAlign A = AI->getAlign()) {
  3801. Out << ", align " << A->value();
  3802. }
  3803. unsigned AddrSpace = AI->getAddressSpace();
  3804. if (AddrSpace != 0) {
  3805. Out << ", addrspace(" << AddrSpace << ')';
  3806. }
  3807. } else if (isa<CastInst>(I)) {
  3808. if (Operand) {
  3809. Out << ' ';
  3810. writeOperand(Operand, true); // Work with broken code
  3811. }
  3812. Out << " to ";
  3813. TypePrinter.print(I.getType(), Out);
  3814. } else if (isa<VAArgInst>(I)) {
  3815. if (Operand) {
  3816. Out << ' ';
  3817. writeOperand(Operand, true); // Work with broken code
  3818. }
  3819. Out << ", ";
  3820. TypePrinter.print(I.getType(), Out);
  3821. } else if (Operand) { // Print the normal way.
  3822. if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
  3823. Out << ' ';
  3824. TypePrinter.print(GEP->getSourceElementType(), Out);
  3825. Out << ',';
  3826. } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
  3827. Out << ' ';
  3828. TypePrinter.print(LI->getType(), Out);
  3829. Out << ',';
  3830. }
  3831. // PrintAllTypes - Instructions who have operands of all the same type
  3832. // omit the type from all but the first operand. If the instruction has
  3833. // different type operands (for example br), then they are all printed.
  3834. bool PrintAllTypes = false;
  3835. Type *TheType = Operand->getType();
  3836. // Select, Store, ShuffleVector, CmpXchg and AtomicRMW always print all
  3837. // types.
  3838. if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) ||
  3839. isa<ReturnInst>(I) || isa<AtomicCmpXchgInst>(I) ||
  3840. isa<AtomicRMWInst>(I)) {
  3841. PrintAllTypes = true;
  3842. } else {
  3843. for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
  3844. Operand = I.getOperand(i);
  3845. // note that Operand shouldn't be null, but the test helps make dump()
  3846. // more tolerant of malformed IR
  3847. if (Operand && Operand->getType() != TheType) {
  3848. PrintAllTypes = true; // We have differing types! Print them all!
  3849. break;
  3850. }
  3851. }
  3852. }
  3853. if (!PrintAllTypes) {
  3854. Out << ' ';
  3855. TypePrinter.print(TheType, Out);
  3856. }
  3857. Out << ' ';
  3858. for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
  3859. if (i) Out << ", ";
  3860. writeOperand(I.getOperand(i), PrintAllTypes);
  3861. }
  3862. }
  3863. // Print atomic ordering/alignment for memory operations
  3864. if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
  3865. if (LI->isAtomic())
  3866. writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
  3867. if (MaybeAlign A = LI->getAlign())
  3868. Out << ", align " << A->value();
  3869. } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
  3870. if (SI->isAtomic())
  3871. writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
  3872. if (MaybeAlign A = SI->getAlign())
  3873. Out << ", align " << A->value();
  3874. } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
  3875. writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
  3876. CXI->getFailureOrdering(), CXI->getSyncScopeID());
  3877. Out << ", align " << CXI->getAlign().value();
  3878. } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
  3879. writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
  3880. RMWI->getSyncScopeID());
  3881. Out << ", align " << RMWI->getAlign().value();
  3882. } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
  3883. writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
  3884. } else if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(&I)) {
  3885. PrintShuffleMask(Out, SVI->getType(), SVI->getShuffleMask());
  3886. }
  3887. // Print Metadata info.
  3888. SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
  3889. I.getAllMetadata(InstMD);
  3890. printMetadataAttachments(InstMD, ", ");
  3891. // Print a nice comment.
  3892. printInfoComment(I);
  3893. }
  3894. void AssemblyWriter::printMetadataAttachments(
  3895. const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
  3896. StringRef Separator) {
  3897. if (MDs.empty())
  3898. return;
  3899. if (MDNames.empty())
  3900. MDs[0].second->getContext().getMDKindNames(MDNames);
  3901. auto WriterCtx = getContext();
  3902. for (const auto &I : MDs) {
  3903. unsigned Kind = I.first;
  3904. Out << Separator;
  3905. if (Kind < MDNames.size()) {
  3906. Out << "!";
  3907. printMetadataIdentifier(MDNames[Kind], Out);
  3908. } else
  3909. Out << "!<unknown kind #" << Kind << ">";
  3910. Out << ' ';
  3911. WriteAsOperandInternal(Out, I.second, WriterCtx);
  3912. }
  3913. }
  3914. void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
  3915. Out << '!' << Slot << " = ";
  3916. printMDNodeBody(Node);
  3917. Out << "\n";
  3918. }
  3919. void AssemblyWriter::writeAllMDNodes() {
  3920. SmallVector<const MDNode *, 16> Nodes;
  3921. Nodes.resize(Machine.mdn_size());
  3922. for (auto &I : llvm::make_range(Machine.mdn_begin(), Machine.mdn_end()))
  3923. Nodes[I.second] = cast<MDNode>(I.first);
  3924. for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
  3925. writeMDNode(i, Nodes[i]);
  3926. }
  3927. }
  3928. void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
  3929. auto WriterCtx = getContext();
  3930. WriteMDNodeBodyInternal(Out, Node, WriterCtx);
  3931. }
  3932. void AssemblyWriter::writeAttribute(const Attribute &Attr, bool InAttrGroup) {
  3933. if (!Attr.isTypeAttribute()) {
  3934. Out << Attr.getAsString(InAttrGroup);
  3935. return;
  3936. }
  3937. Out << Attribute::getNameFromAttrKind(Attr.getKindAsEnum());
  3938. if (Type *Ty = Attr.getValueAsType()) {
  3939. Out << '(';
  3940. TypePrinter.print(Ty, Out);
  3941. Out << ')';
  3942. }
  3943. }
  3944. void AssemblyWriter::writeAttributeSet(const AttributeSet &AttrSet,
  3945. bool InAttrGroup) {
  3946. bool FirstAttr = true;
  3947. for (const auto &Attr : AttrSet) {
  3948. if (!FirstAttr)
  3949. Out << ' ';
  3950. writeAttribute(Attr, InAttrGroup);
  3951. FirstAttr = false;
  3952. }
  3953. }
  3954. void AssemblyWriter::writeAllAttributeGroups() {
  3955. std::vector<std::pair<AttributeSet, unsigned>> asVec;
  3956. asVec.resize(Machine.as_size());
  3957. for (auto &I : llvm::make_range(Machine.as_begin(), Machine.as_end()))
  3958. asVec[I.second] = I;
  3959. for (const auto &I : asVec)
  3960. Out << "attributes #" << I.second << " = { "
  3961. << I.first.getAsString(true) << " }\n";
  3962. }
  3963. void AssemblyWriter::printUseListOrder(const Value *V,
  3964. const std::vector<unsigned> &Shuffle) {
  3965. bool IsInFunction = Machine.getFunction();
  3966. if (IsInFunction)
  3967. Out << " ";
  3968. Out << "uselistorder";
  3969. if (const BasicBlock *BB = IsInFunction ? nullptr : dyn_cast<BasicBlock>(V)) {
  3970. Out << "_bb ";
  3971. writeOperand(BB->getParent(), false);
  3972. Out << ", ";
  3973. writeOperand(BB, false);
  3974. } else {
  3975. Out << " ";
  3976. writeOperand(V, true);
  3977. }
  3978. Out << ", { ";
  3979. assert(Shuffle.size() >= 2 && "Shuffle too small");
  3980. Out << Shuffle[0];
  3981. for (unsigned I = 1, E = Shuffle.size(); I != E; ++I)
  3982. Out << ", " << Shuffle[I];
  3983. Out << " }\n";
  3984. }
  3985. void AssemblyWriter::printUseLists(const Function *F) {
  3986. auto It = UseListOrders.find(F);
  3987. if (It == UseListOrders.end())
  3988. return;
  3989. Out << "\n; uselistorder directives\n";
  3990. for (const auto &Pair : It->second)
  3991. printUseListOrder(Pair.first, Pair.second);
  3992. }
  3993. //===----------------------------------------------------------------------===//
  3994. // External Interface declarations
  3995. //===----------------------------------------------------------------------===//
  3996. void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
  3997. bool ShouldPreserveUseListOrder,
  3998. bool IsForDebug) const {
  3999. SlotTracker SlotTable(this->getParent());
  4000. formatted_raw_ostream OS(ROS);
  4001. AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
  4002. IsForDebug,
  4003. ShouldPreserveUseListOrder);
  4004. W.printFunction(this);
  4005. }
  4006. void BasicBlock::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
  4007. bool ShouldPreserveUseListOrder,
  4008. bool IsForDebug) const {
  4009. SlotTracker SlotTable(this->getParent());
  4010. formatted_raw_ostream OS(ROS);
  4011. AssemblyWriter W(OS, SlotTable, this->getModule(), AAW,
  4012. IsForDebug,
  4013. ShouldPreserveUseListOrder);
  4014. W.printBasicBlock(this);
  4015. }
  4016. void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
  4017. bool ShouldPreserveUseListOrder, bool IsForDebug) const {
  4018. SlotTracker SlotTable(this);
  4019. formatted_raw_ostream OS(ROS);
  4020. AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
  4021. ShouldPreserveUseListOrder);
  4022. W.printModule(this);
  4023. }
  4024. void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
  4025. SlotTracker SlotTable(getParent());
  4026. formatted_raw_ostream OS(ROS);
  4027. AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
  4028. W.printNamedMDNode(this);
  4029. }
  4030. void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
  4031. bool IsForDebug) const {
  4032. std::optional<SlotTracker> LocalST;
  4033. SlotTracker *SlotTable;
  4034. if (auto *ST = MST.getMachine())
  4035. SlotTable = ST;
  4036. else {
  4037. LocalST.emplace(getParent());
  4038. SlotTable = &*LocalST;
  4039. }
  4040. formatted_raw_ostream OS(ROS);
  4041. AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
  4042. W.printNamedMDNode(this);
  4043. }
  4044. void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
  4045. PrintLLVMName(ROS, getName(), ComdatPrefix);
  4046. ROS << " = comdat ";
  4047. switch (getSelectionKind()) {
  4048. case Comdat::Any:
  4049. ROS << "any";
  4050. break;
  4051. case Comdat::ExactMatch:
  4052. ROS << "exactmatch";
  4053. break;
  4054. case Comdat::Largest:
  4055. ROS << "largest";
  4056. break;
  4057. case Comdat::NoDeduplicate:
  4058. ROS << "nodeduplicate";
  4059. break;
  4060. case Comdat::SameSize:
  4061. ROS << "samesize";
  4062. break;
  4063. }
  4064. ROS << '\n';
  4065. }
  4066. void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
  4067. TypePrinting TP;
  4068. TP.print(const_cast<Type*>(this), OS);
  4069. if (NoDetails)
  4070. return;
  4071. // If the type is a named struct type, print the body as well.
  4072. if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
  4073. if (!STy->isLiteral()) {
  4074. OS << " = type ";
  4075. TP.printStructBody(STy, OS);
  4076. }
  4077. }
  4078. static bool isReferencingMDNode(const Instruction &I) {
  4079. if (const auto *CI = dyn_cast<CallInst>(&I))
  4080. if (Function *F = CI->getCalledFunction())
  4081. if (F->isIntrinsic())
  4082. for (auto &Op : I.operands())
  4083. if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
  4084. if (isa<MDNode>(V->getMetadata()))
  4085. return true;
  4086. return false;
  4087. }
  4088. void Value::print(raw_ostream &ROS, bool IsForDebug) const {
  4089. bool ShouldInitializeAllMetadata = false;
  4090. if (auto *I = dyn_cast<Instruction>(this))
  4091. ShouldInitializeAllMetadata = isReferencingMDNode(*I);
  4092. else if (isa<Function>(this) || isa<MetadataAsValue>(this))
  4093. ShouldInitializeAllMetadata = true;
  4094. ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
  4095. print(ROS, MST, IsForDebug);
  4096. }
  4097. void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
  4098. bool IsForDebug) const {
  4099. formatted_raw_ostream OS(ROS);
  4100. SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
  4101. SlotTracker &SlotTable =
  4102. MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
  4103. auto incorporateFunction = [&](const Function *F) {
  4104. if (F)
  4105. MST.incorporateFunction(*F);
  4106. };
  4107. if (const Instruction *I = dyn_cast<Instruction>(this)) {
  4108. incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
  4109. AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
  4110. W.printInstruction(*I);
  4111. } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
  4112. incorporateFunction(BB->getParent());
  4113. AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
  4114. W.printBasicBlock(BB);
  4115. } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
  4116. AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
  4117. if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
  4118. W.printGlobal(V);
  4119. else if (const Function *F = dyn_cast<Function>(GV))
  4120. W.printFunction(F);
  4121. else if (const GlobalAlias *A = dyn_cast<GlobalAlias>(GV))
  4122. W.printAlias(A);
  4123. else if (const GlobalIFunc *I = dyn_cast<GlobalIFunc>(GV))
  4124. W.printIFunc(I);
  4125. else
  4126. llvm_unreachable("Unknown GlobalValue to print out!");
  4127. } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
  4128. V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
  4129. } else if (const Constant *C = dyn_cast<Constant>(this)) {
  4130. TypePrinting TypePrinter;
  4131. TypePrinter.print(C->getType(), OS);
  4132. OS << ' ';
  4133. AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine());
  4134. WriteConstantInternal(OS, C, WriterCtx);
  4135. } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
  4136. this->printAsOperand(OS, /* PrintType */ true, MST);
  4137. } else {
  4138. llvm_unreachable("Unknown value to print out!");
  4139. }
  4140. }
  4141. /// Print without a type, skipping the TypePrinting object.
  4142. ///
  4143. /// \return \c true iff printing was successful.
  4144. static bool printWithoutType(const Value &V, raw_ostream &O,
  4145. SlotTracker *Machine, const Module *M) {
  4146. if (V.hasName() || isa<GlobalValue>(V) ||
  4147. (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
  4148. AsmWriterContext WriterCtx(nullptr, Machine, M);
  4149. WriteAsOperandInternal(O, &V, WriterCtx);
  4150. return true;
  4151. }
  4152. return false;
  4153. }
  4154. static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
  4155. ModuleSlotTracker &MST) {
  4156. TypePrinting TypePrinter(MST.getModule());
  4157. if (PrintType) {
  4158. TypePrinter.print(V.getType(), O);
  4159. O << ' ';
  4160. }
  4161. AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine(), MST.getModule());
  4162. WriteAsOperandInternal(O, &V, WriterCtx);
  4163. }
  4164. void Value::printAsOperand(raw_ostream &O, bool PrintType,
  4165. const Module *M) const {
  4166. if (!M)
  4167. M = getModuleFromVal(this);
  4168. if (!PrintType)
  4169. if (printWithoutType(*this, O, nullptr, M))
  4170. return;
  4171. SlotTracker Machine(
  4172. M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
  4173. ModuleSlotTracker MST(Machine, M);
  4174. printAsOperandImpl(*this, O, PrintType, MST);
  4175. }
  4176. void Value::printAsOperand(raw_ostream &O, bool PrintType,
  4177. ModuleSlotTracker &MST) const {
  4178. if (!PrintType)
  4179. if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
  4180. return;
  4181. printAsOperandImpl(*this, O, PrintType, MST);
  4182. }
  4183. /// Recursive version of printMetadataImpl.
  4184. static void printMetadataImplRec(raw_ostream &ROS, const Metadata &MD,
  4185. AsmWriterContext &WriterCtx) {
  4186. formatted_raw_ostream OS(ROS);
  4187. WriteAsOperandInternal(OS, &MD, WriterCtx, /* FromValue */ true);
  4188. auto *N = dyn_cast<MDNode>(&MD);
  4189. if (!N || isa<DIExpression>(MD) || isa<DIArgList>(MD))
  4190. return;
  4191. OS << " = ";
  4192. WriteMDNodeBodyInternal(OS, N, WriterCtx);
  4193. }
  4194. namespace {
  4195. struct MDTreeAsmWriterContext : public AsmWriterContext {
  4196. unsigned Level;
  4197. // {Level, Printed string}
  4198. using EntryTy = std::pair<unsigned, std::string>;
  4199. SmallVector<EntryTy, 4> Buffer;
  4200. // Used to break the cycle in case there is any.
  4201. SmallPtrSet<const Metadata *, 4> Visited;
  4202. raw_ostream &MainOS;
  4203. MDTreeAsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M,
  4204. raw_ostream &OS, const Metadata *InitMD)
  4205. : AsmWriterContext(TP, ST, M), Level(0U), Visited({InitMD}), MainOS(OS) {}
  4206. void onWriteMetadataAsOperand(const Metadata *MD) override {
  4207. if (!Visited.insert(MD).second)
  4208. return;
  4209. std::string Str;
  4210. raw_string_ostream SS(Str);
  4211. ++Level;
  4212. // A placeholder entry to memorize the correct
  4213. // position in buffer.
  4214. Buffer.emplace_back(std::make_pair(Level, ""));
  4215. unsigned InsertIdx = Buffer.size() - 1;
  4216. printMetadataImplRec(SS, *MD, *this);
  4217. Buffer[InsertIdx].second = std::move(SS.str());
  4218. --Level;
  4219. }
  4220. ~MDTreeAsmWriterContext() {
  4221. for (const auto &Entry : Buffer) {
  4222. MainOS << "\n";
  4223. unsigned NumIndent = Entry.first * 2U;
  4224. MainOS.indent(NumIndent) << Entry.second;
  4225. }
  4226. }
  4227. };
  4228. } // end anonymous namespace
  4229. static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
  4230. ModuleSlotTracker &MST, const Module *M,
  4231. bool OnlyAsOperand, bool PrintAsTree = false) {
  4232. formatted_raw_ostream OS(ROS);
  4233. TypePrinting TypePrinter(M);
  4234. std::unique_ptr<AsmWriterContext> WriterCtx;
  4235. if (PrintAsTree && !OnlyAsOperand)
  4236. WriterCtx = std::make_unique<MDTreeAsmWriterContext>(
  4237. &TypePrinter, MST.getMachine(), M, OS, &MD);
  4238. else
  4239. WriterCtx =
  4240. std::make_unique<AsmWriterContext>(&TypePrinter, MST.getMachine(), M);
  4241. WriteAsOperandInternal(OS, &MD, *WriterCtx, /* FromValue */ true);
  4242. auto *N = dyn_cast<MDNode>(&MD);
  4243. if (OnlyAsOperand || !N || isa<DIExpression>(MD) || isa<DIArgList>(MD))
  4244. return;
  4245. OS << " = ";
  4246. WriteMDNodeBodyInternal(OS, N, *WriterCtx);
  4247. }
  4248. void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
  4249. ModuleSlotTracker MST(M, isa<MDNode>(this));
  4250. printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
  4251. }
  4252. void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
  4253. const Module *M) const {
  4254. printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
  4255. }
  4256. void Metadata::print(raw_ostream &OS, const Module *M,
  4257. bool /*IsForDebug*/) const {
  4258. ModuleSlotTracker MST(M, isa<MDNode>(this));
  4259. printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
  4260. }
  4261. void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
  4262. const Module *M, bool /*IsForDebug*/) const {
  4263. printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
  4264. }
  4265. void MDNode::printTree(raw_ostream &OS, const Module *M) const {
  4266. ModuleSlotTracker MST(M, true);
  4267. printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false,
  4268. /*PrintAsTree=*/true);
  4269. }
  4270. void MDNode::printTree(raw_ostream &OS, ModuleSlotTracker &MST,
  4271. const Module *M) const {
  4272. printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false,
  4273. /*PrintAsTree=*/true);
  4274. }
  4275. void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {
  4276. SlotTracker SlotTable(this);
  4277. formatted_raw_ostream OS(ROS);
  4278. AssemblyWriter W(OS, SlotTable, this, IsForDebug);
  4279. W.printModuleSummaryIndex();
  4280. }
  4281. void ModuleSlotTracker::collectMDNodes(MachineMDNodeListType &L, unsigned LB,
  4282. unsigned UB) const {
  4283. SlotTracker *ST = MachineStorage.get();
  4284. if (!ST)
  4285. return;
  4286. for (auto &I : llvm::make_range(ST->mdn_begin(), ST->mdn_end()))
  4287. if (I.second >= LB && I.second < UB)
  4288. L.push_back(std::make_pair(I.second, I.first));
  4289. }
  4290. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  4291. // Value::dump - allow easy printing of Values from the debugger.
  4292. LLVM_DUMP_METHOD
  4293. void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
  4294. // Type::dump - allow easy printing of Types from the debugger.
  4295. LLVM_DUMP_METHOD
  4296. void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
  4297. // Module::dump() - Allow printing of Modules from the debugger.
  4298. LLVM_DUMP_METHOD
  4299. void Module::dump() const {
  4300. print(dbgs(), nullptr,
  4301. /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
  4302. }
  4303. // Allow printing of Comdats from the debugger.
  4304. LLVM_DUMP_METHOD
  4305. void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
  4306. // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
  4307. LLVM_DUMP_METHOD
  4308. void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
  4309. LLVM_DUMP_METHOD
  4310. void Metadata::dump() const { dump(nullptr); }
  4311. LLVM_DUMP_METHOD
  4312. void Metadata::dump(const Module *M) const {
  4313. print(dbgs(), M, /*IsForDebug=*/true);
  4314. dbgs() << '\n';
  4315. }
  4316. LLVM_DUMP_METHOD
  4317. void MDNode::dumpTree() const { dumpTree(nullptr); }
  4318. LLVM_DUMP_METHOD
  4319. void MDNode::dumpTree(const Module *M) const {
  4320. printTree(dbgs(), M);
  4321. dbgs() << '\n';
  4322. }
  4323. // Allow printing of ModuleSummaryIndex from the debugger.
  4324. LLVM_DUMP_METHOD
  4325. void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }
  4326. #endif