AsmWriter.cpp 147 KB

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