AsmWriter.cpp 112 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378
  1. //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This library implements the functionality defined in llvm/IR/Writer.h
  11. //
  12. // Note that these routines must be extremely tolerant of various errors in the
  13. // LLVM code, because it can be used for debugging transformations.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SetVector.h"
  19. #include "llvm/ADT/SmallString.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/IR/AssemblyAnnotationWriter.h"
  22. #include "llvm/IR/CFG.h"
  23. #include "llvm/IR/CallingConv.h"
  24. #include "llvm/IR/Constants.h"
  25. #include "llvm/IR/DebugInfo.h"
  26. #include "llvm/IR/DerivedTypes.h"
  27. #include "llvm/IR/IRPrintingPasses.h"
  28. #include "llvm/IR/InlineAsm.h"
  29. #include "llvm/IR/IntrinsicInst.h"
  30. #include "llvm/IR/LLVMContext.h"
  31. #include "llvm/IR/Module.h"
  32. #include "llvm/IR/ModuleSlotTracker.h"
  33. #include "llvm/IR/Operator.h"
  34. #include "llvm/IR/Statepoint.h"
  35. #include "llvm/IR/TypeFinder.h"
  36. #include "llvm/IR/UseListOrder.h"
  37. #include "llvm/IR/ValueSymbolTable.h"
  38. #include "llvm/Support/Debug.h"
  39. #include "llvm/Support/Dwarf.h"
  40. #include "llvm/Support/ErrorHandling.h"
  41. #include "llvm/Support/FormattedStream.h"
  42. #include "llvm/Support/MathExtras.h"
  43. #include "llvm/Support/raw_ostream.h"
  44. #include <algorithm>
  45. #include <cctype>
  46. using namespace llvm;
  47. // Make virtual table appear in this compilation unit.
  48. AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
  49. //===----------------------------------------------------------------------===//
  50. // Helper Functions
  51. //===----------------------------------------------------------------------===//
  52. namespace {
  53. struct OrderMap {
  54. DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
  55. unsigned size() const { return IDs.size(); }
  56. std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
  57. std::pair<unsigned, bool> lookup(const Value *V) const {
  58. return IDs.lookup(V);
  59. }
  60. void index(const Value *V) {
  61. // Explicitly sequence get-size and insert-value operations to avoid UB.
  62. unsigned ID = IDs.size() + 1;
  63. IDs[V].first = ID;
  64. }
  65. };
  66. }
  67. static void orderValue(const Value *V, OrderMap &OM) {
  68. if (OM.lookup(V).first)
  69. return;
  70. if (const Constant *C = dyn_cast<Constant>(V))
  71. if (C->getNumOperands() && !isa<GlobalValue>(C))
  72. for (const Value *Op : C->operands())
  73. if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
  74. orderValue(Op, OM);
  75. // Note: we cannot cache this lookup above, since inserting into the map
  76. // changes the map's size, and thus affects the other IDs.
  77. OM.index(V);
  78. }
  79. static OrderMap orderModule(const Module *M) {
  80. // This needs to match the order used by ValueEnumerator::ValueEnumerator()
  81. // and ValueEnumerator::incorporateFunction().
  82. OrderMap OM;
  83. for (const GlobalVariable &G : M->globals()) {
  84. if (G.hasInitializer())
  85. if (!isa<GlobalValue>(G.getInitializer()))
  86. orderValue(G.getInitializer(), OM);
  87. orderValue(&G, OM);
  88. }
  89. for (const GlobalAlias &A : M->aliases()) {
  90. if (!isa<GlobalValue>(A.getAliasee()))
  91. orderValue(A.getAliasee(), OM);
  92. orderValue(&A, OM);
  93. }
  94. for (const Function &F : *M) {
  95. if (F.hasPrefixData())
  96. if (!isa<GlobalValue>(F.getPrefixData()))
  97. orderValue(F.getPrefixData(), OM);
  98. if (F.hasPrologueData())
  99. if (!isa<GlobalValue>(F.getPrologueData()))
  100. orderValue(F.getPrologueData(), OM);
  101. if (F.hasPersonalityFn())
  102. if (!isa<GlobalValue>(F.getPersonalityFn()))
  103. orderValue(F.getPersonalityFn(), OM);
  104. orderValue(&F, OM);
  105. if (F.isDeclaration())
  106. continue;
  107. for (const Argument &A : F.args())
  108. orderValue(&A, OM);
  109. for (const BasicBlock &BB : F) {
  110. orderValue(&BB, OM);
  111. for (const Instruction &I : BB) {
  112. for (const Value *Op : I.operands())
  113. if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
  114. isa<InlineAsm>(*Op))
  115. orderValue(Op, OM);
  116. orderValue(&I, OM);
  117. }
  118. }
  119. }
  120. return OM;
  121. }
  122. static void predictValueUseListOrderImpl(const Value *V, const Function *F,
  123. unsigned ID, const OrderMap &OM,
  124. UseListOrderStack &Stack) {
  125. // Predict use-list order for this one.
  126. typedef std::pair<const Use *, unsigned> Entry;
  127. SmallVector<Entry, 64> List;
  128. for (const Use &U : V->uses())
  129. // Check if this user will be serialized.
  130. if (OM.lookup(U.getUser()).first)
  131. List.push_back(std::make_pair(&U, List.size()));
  132. if (List.size() < 2)
  133. // We may have lost some users.
  134. return;
  135. bool GetsReversed =
  136. !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
  137. if (auto *BA = dyn_cast<BlockAddress>(V))
  138. ID = OM.lookup(BA->getBasicBlock()).first;
  139. std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
  140. const Use *LU = L.first;
  141. const Use *RU = R.first;
  142. if (LU == RU)
  143. return false;
  144. auto LID = OM.lookup(LU->getUser()).first;
  145. auto RID = OM.lookup(RU->getUser()).first;
  146. // If ID is 4, then expect: 7 6 5 1 2 3.
  147. if (LID < RID) {
  148. if (GetsReversed)
  149. if (RID <= ID)
  150. return true;
  151. return false;
  152. }
  153. if (RID < LID) {
  154. if (GetsReversed)
  155. if (LID <= ID)
  156. return false;
  157. return true;
  158. }
  159. // LID and RID are equal, so we have different operands of the same user.
  160. // Assume operands are added in order for all instructions.
  161. if (GetsReversed)
  162. if (LID <= ID)
  163. return LU->getOperandNo() < RU->getOperandNo();
  164. return LU->getOperandNo() > RU->getOperandNo();
  165. });
  166. if (std::is_sorted(
  167. List.begin(), List.end(),
  168. [](const Entry &L, const Entry &R) { return L.second < R.second; }))
  169. // Order is already correct.
  170. return;
  171. // Store the shuffle.
  172. Stack.emplace_back(V, F, List.size());
  173. assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
  174. for (size_t I = 0, E = List.size(); I != E; ++I)
  175. Stack.back().Shuffle[I] = List[I].second;
  176. }
  177. static void predictValueUseListOrder(const Value *V, const Function *F,
  178. OrderMap &OM, UseListOrderStack &Stack) {
  179. auto &IDPair = OM[V];
  180. assert(IDPair.first && "Unmapped value");
  181. if (IDPair.second)
  182. // Already predicted.
  183. return;
  184. // Do the actual prediction.
  185. IDPair.second = true;
  186. if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
  187. predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
  188. // Recursive descent into constants.
  189. if (const Constant *C = dyn_cast<Constant>(V))
  190. if (C->getNumOperands()) // Visit GlobalValues.
  191. for (const Value *Op : C->operands())
  192. if (isa<Constant>(Op)) // Visit GlobalValues.
  193. predictValueUseListOrder(Op, F, OM, Stack);
  194. }
  195. static UseListOrderStack predictUseListOrder(const Module *M) {
  196. OrderMap OM = orderModule(M);
  197. // Use-list orders need to be serialized after all the users have been added
  198. // to a value, or else the shuffles will be incomplete. Store them per
  199. // function in a stack.
  200. //
  201. // Aside from function order, the order of values doesn't matter much here.
  202. UseListOrderStack Stack;
  203. // We want to visit the functions backward now so we can list function-local
  204. // constants in the last Function they're used in. Module-level constants
  205. // have already been visited above.
  206. for (auto I = M->rbegin(), E = M->rend(); I != E; ++I) {
  207. const Function &F = *I;
  208. if (F.isDeclaration())
  209. continue;
  210. for (const BasicBlock &BB : F)
  211. predictValueUseListOrder(&BB, &F, OM, Stack);
  212. for (const Argument &A : F.args())
  213. predictValueUseListOrder(&A, &F, OM, Stack);
  214. for (const BasicBlock &BB : F)
  215. for (const Instruction &I : BB)
  216. for (const Value *Op : I.operands())
  217. if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
  218. predictValueUseListOrder(Op, &F, OM, Stack);
  219. for (const BasicBlock &BB : F)
  220. for (const Instruction &I : BB)
  221. predictValueUseListOrder(&I, &F, OM, Stack);
  222. }
  223. // Visit globals last.
  224. for (const GlobalVariable &G : M->globals())
  225. predictValueUseListOrder(&G, nullptr, OM, Stack);
  226. for (const Function &F : *M)
  227. predictValueUseListOrder(&F, nullptr, OM, Stack);
  228. for (const GlobalAlias &A : M->aliases())
  229. predictValueUseListOrder(&A, nullptr, OM, Stack);
  230. for (const GlobalVariable &G : M->globals())
  231. if (G.hasInitializer())
  232. predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
  233. for (const GlobalAlias &A : M->aliases())
  234. predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
  235. for (const Function &F : *M)
  236. if (F.hasPrefixData())
  237. predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
  238. return Stack;
  239. }
  240. static const Module *getModuleFromVal(const Value *V) {
  241. if (const Argument *MA = dyn_cast<Argument>(V))
  242. return MA->getParent() ? MA->getParent()->getParent() : nullptr;
  243. if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
  244. return BB->getParent() ? BB->getParent()->getParent() : nullptr;
  245. if (const Instruction *I = dyn_cast<Instruction>(V)) {
  246. const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
  247. return M ? M->getParent() : nullptr;
  248. }
  249. if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
  250. return GV->getParent();
  251. if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
  252. for (const User *U : MAV->users())
  253. if (isa<Instruction>(U))
  254. if (const Module *M = getModuleFromVal(U))
  255. return M;
  256. return nullptr;
  257. }
  258. return nullptr;
  259. }
  260. static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
  261. switch (cc) {
  262. default: Out << "cc" << cc; break;
  263. case CallingConv::Fast: Out << "fastcc"; break;
  264. case CallingConv::Cold: Out << "coldcc"; break;
  265. case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
  266. case CallingConv::AnyReg: Out << "anyregcc"; break;
  267. case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
  268. case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
  269. case CallingConv::GHC: Out << "ghccc"; break;
  270. case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
  271. case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
  272. case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
  273. case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
  274. case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
  275. case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
  276. case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
  277. case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
  278. case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
  279. case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
  280. case CallingConv::PTX_Device: Out << "ptx_device"; break;
  281. case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
  282. case CallingConv::X86_64_Win64: Out << "x86_64_win64cc"; break;
  283. case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
  284. case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
  285. }
  286. }
  287. // PrintEscapedString - Print each character of the specified string, escaping
  288. // it if it is not printable or if it is an escape char.
  289. static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
  290. for (unsigned i = 0, e = Name.size(); i != e; ++i) {
  291. unsigned char C = Name[i];
  292. if (isprint(C) && C != '\\' && C != '"')
  293. Out << C;
  294. else
  295. Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
  296. }
  297. }
  298. enum PrefixType {
  299. GlobalPrefix,
  300. ComdatPrefix,
  301. LabelPrefix,
  302. LocalPrefix,
  303. NoPrefix
  304. };
  305. /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
  306. /// prefixed with % (if the string only contains simple characters) or is
  307. /// surrounded with ""'s (if it has special chars in it). Print it out.
  308. static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
  309. assert(!Name.empty() && "Cannot get empty name!");
  310. switch (Prefix) {
  311. case NoPrefix: break;
  312. case GlobalPrefix: OS << '@'; break;
  313. case ComdatPrefix: OS << '$'; break;
  314. case LabelPrefix: break;
  315. case LocalPrefix: OS << '%'; break;
  316. }
  317. // Scan the name to see if it needs quotes first.
  318. bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
  319. if (!NeedsQuotes) {
  320. for (unsigned i = 0, e = Name.size(); i != e; ++i) {
  321. // By making this unsigned, the value passed in to isalnum will always be
  322. // in the range 0-255. This is important when building with MSVC because
  323. // its implementation will assert. This situation can arise when dealing
  324. // with UTF-8 multibyte characters.
  325. unsigned char C = Name[i];
  326. if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
  327. C != '_') {
  328. NeedsQuotes = true;
  329. break;
  330. }
  331. }
  332. }
  333. // If we didn't need any quotes, just write out the name in one blast.
  334. if (!NeedsQuotes) {
  335. OS << Name;
  336. return;
  337. }
  338. // Okay, we need quotes. Output the quotes and escape any scary characters as
  339. // needed.
  340. OS << '"';
  341. PrintEscapedString(Name, OS);
  342. OS << '"';
  343. }
  344. /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
  345. /// prefixed with % (if the string only contains simple characters) or is
  346. /// surrounded with ""'s (if it has special chars in it). Print it out.
  347. static void PrintLLVMName(raw_ostream &OS, const Value *V) {
  348. PrintLLVMName(OS, V->getName(),
  349. isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
  350. }
  351. namespace {
  352. class TypePrinting {
  353. TypePrinting(const TypePrinting &) = delete;
  354. void operator=(const TypePrinting&) = delete;
  355. public:
  356. /// NamedTypes - The named types that are used by the current module.
  357. TypeFinder NamedTypes;
  358. /// NumberedTypes - The numbered types, along with their value.
  359. DenseMap<StructType*, unsigned> NumberedTypes;
  360. TypePrinting() = default;
  361. void incorporateTypes(const Module &M);
  362. void print(Type *Ty, raw_ostream &OS);
  363. void printStructBody(StructType *Ty, raw_ostream &OS);
  364. };
  365. } // namespace
  366. void TypePrinting::incorporateTypes(const Module &M) {
  367. NamedTypes.run(M, false);
  368. // The list of struct types we got back includes all the struct types, split
  369. // the unnamed ones out to a numbering and remove the anonymous structs.
  370. unsigned NextNumber = 0;
  371. std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
  372. for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
  373. StructType *STy = *I;
  374. // Ignore anonymous types.
  375. if (STy->isLiteral())
  376. continue;
  377. if (STy->getName().empty())
  378. NumberedTypes[STy] = NextNumber++;
  379. else
  380. *NextToUse++ = STy;
  381. }
  382. NamedTypes.erase(NextToUse, NamedTypes.end());
  383. }
  384. /// CalcTypeName - Write the specified type to the specified raw_ostream, making
  385. /// use of type names or up references to shorten the type name where possible.
  386. void TypePrinting::print(Type *Ty, raw_ostream &OS) {
  387. switch (Ty->getTypeID()) {
  388. case Type::VoidTyID: OS << "void"; return;
  389. case Type::HalfTyID: OS << "half"; return;
  390. case Type::FloatTyID: OS << "float"; return;
  391. case Type::DoubleTyID: OS << "double"; return;
  392. case Type::X86_FP80TyID: OS << "x86_fp80"; return;
  393. case Type::FP128TyID: OS << "fp128"; return;
  394. case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
  395. case Type::LabelTyID: OS << "label"; return;
  396. case Type::MetadataTyID: OS << "metadata"; return;
  397. case Type::X86_MMXTyID: OS << "x86_mmx"; return;
  398. case Type::IntegerTyID:
  399. OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
  400. return;
  401. case Type::FunctionTyID: {
  402. FunctionType *FTy = cast<FunctionType>(Ty);
  403. print(FTy->getReturnType(), OS);
  404. OS << " (";
  405. for (FunctionType::param_iterator I = FTy->param_begin(),
  406. E = FTy->param_end(); I != E; ++I) {
  407. if (I != FTy->param_begin())
  408. OS << ", ";
  409. print(*I, OS);
  410. }
  411. if (FTy->isVarArg()) {
  412. if (FTy->getNumParams()) OS << ", ";
  413. OS << "...";
  414. }
  415. OS << ')';
  416. return;
  417. }
  418. case Type::StructTyID: {
  419. StructType *STy = cast<StructType>(Ty);
  420. if (STy->isLiteral())
  421. return printStructBody(STy, OS);
  422. if (!STy->getName().empty())
  423. return PrintLLVMName(OS, STy->getName(), LocalPrefix);
  424. DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
  425. if (I != NumberedTypes.end())
  426. OS << '%' << I->second;
  427. else // Not enumerated, print the hex address.
  428. OS << "%\"type " << STy << '\"';
  429. return;
  430. }
  431. case Type::PointerTyID: {
  432. PointerType *PTy = cast<PointerType>(Ty);
  433. print(PTy->getElementType(), OS);
  434. if (unsigned AddressSpace = PTy->getAddressSpace())
  435. OS << " addrspace(" << AddressSpace << ')';
  436. OS << '*';
  437. return;
  438. }
  439. case Type::ArrayTyID: {
  440. ArrayType *ATy = cast<ArrayType>(Ty);
  441. OS << '[' << ATy->getNumElements() << " x ";
  442. print(ATy->getElementType(), OS);
  443. OS << ']';
  444. return;
  445. }
  446. case Type::VectorTyID: {
  447. VectorType *PTy = cast<VectorType>(Ty);
  448. OS << "<" << PTy->getNumElements() << " x ";
  449. print(PTy->getElementType(), OS);
  450. OS << '>';
  451. return;
  452. }
  453. }
  454. llvm_unreachable("Invalid TypeID");
  455. }
  456. void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
  457. if (STy->isOpaque()) {
  458. OS << "opaque";
  459. return;
  460. }
  461. if (STy->isPacked())
  462. OS << '<';
  463. if (STy->getNumElements() == 0) {
  464. OS << "{}";
  465. } else {
  466. StructType::element_iterator I = STy->element_begin();
  467. OS << "{ ";
  468. print(*I++, OS);
  469. for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
  470. OS << ", ";
  471. print(*I, OS);
  472. }
  473. OS << " }";
  474. }
  475. if (STy->isPacked())
  476. OS << '>';
  477. }
  478. namespace llvm {
  479. //===----------------------------------------------------------------------===//
  480. // SlotTracker Class: Enumerate slot numbers for unnamed values
  481. //===----------------------------------------------------------------------===//
  482. /// This class provides computation of slot numbers for LLVM Assembly writing.
  483. ///
  484. class SlotTracker {
  485. public:
  486. /// ValueMap - A mapping of Values to slot numbers.
  487. typedef DenseMap<const Value*, unsigned> ValueMap;
  488. private:
  489. /// TheModule - The module for which we are holding slot numbers.
  490. const Module* TheModule;
  491. /// TheFunction - The function for which we are holding slot numbers.
  492. const Function* TheFunction;
  493. bool FunctionProcessed;
  494. bool ShouldInitializeAllMetadata;
  495. /// mMap - The slot map for the module level data.
  496. ValueMap mMap;
  497. unsigned mNext;
  498. /// fMap - The slot map for the function level data.
  499. ValueMap fMap;
  500. unsigned fNext;
  501. /// mdnMap - Map for MDNodes.
  502. DenseMap<const MDNode*, unsigned> mdnMap;
  503. unsigned mdnNext;
  504. /// asMap - The slot map for attribute sets.
  505. DenseMap<AttributeSet, unsigned> asMap;
  506. unsigned asNext;
  507. public:
  508. /// Construct from a module.
  509. ///
  510. /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
  511. /// functions, giving correct numbering for metadata referenced only from
  512. /// within a function (even if no functions have been initialized).
  513. explicit SlotTracker(const Module *M,
  514. bool ShouldInitializeAllMetadata = false);
  515. /// Construct from a function, starting out in incorp state.
  516. ///
  517. /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
  518. /// functions, giving correct numbering for metadata referenced only from
  519. /// within a function (even if no functions have been initialized).
  520. explicit SlotTracker(const Function *F,
  521. bool ShouldInitializeAllMetadata = false);
  522. /// Return the slot number of the specified value in it's type
  523. /// plane. If something is not in the SlotTracker, return -1.
  524. int getLocalSlot(const Value *V);
  525. int getGlobalSlot(const GlobalValue *V);
  526. int getMetadataSlot(const MDNode *N);
  527. int getAttributeGroupSlot(AttributeSet AS);
  528. /// If you'd like to deal with a function instead of just a module, use
  529. /// this method to get its data into the SlotTracker.
  530. void incorporateFunction(const Function *F) {
  531. TheFunction = F;
  532. FunctionProcessed = false;
  533. }
  534. const Function *getFunction() const { return TheFunction; }
  535. /// After calling incorporateFunction, use this method to remove the
  536. /// most recently incorporated function from the SlotTracker. This
  537. /// will reset the state of the machine back to just the module contents.
  538. void purgeFunction();
  539. /// MDNode map iterators.
  540. typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
  541. mdn_iterator mdn_begin() { return mdnMap.begin(); }
  542. mdn_iterator mdn_end() { return mdnMap.end(); }
  543. unsigned mdn_size() const { return mdnMap.size(); }
  544. bool mdn_empty() const { return mdnMap.empty(); }
  545. /// AttributeSet map iterators.
  546. typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
  547. as_iterator as_begin() { return asMap.begin(); }
  548. as_iterator as_end() { return asMap.end(); }
  549. unsigned as_size() const { return asMap.size(); }
  550. bool as_empty() const { return asMap.empty(); }
  551. /// This function does the actual initialization.
  552. inline void initialize();
  553. // Implementation Details
  554. private:
  555. /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
  556. void CreateModuleSlot(const GlobalValue *V);
  557. /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
  558. void CreateMetadataSlot(const MDNode *N);
  559. /// CreateFunctionSlot - Insert the specified Value* into the slot table.
  560. void CreateFunctionSlot(const Value *V);
  561. /// \brief Insert the specified AttributeSet into the slot table.
  562. void CreateAttributeSetSlot(AttributeSet AS);
  563. /// Add all of the module level global variables (and their initializers)
  564. /// and function declarations, but not the contents of those functions.
  565. void processModule();
  566. /// Add all of the functions arguments, basic blocks, and instructions.
  567. void processFunction();
  568. /// Add all of the metadata from a function.
  569. void processFunctionMetadata(const Function &F);
  570. /// Add all of the metadata from an instruction.
  571. void processInstructionMetadata(const Instruction &I);
  572. SlotTracker(const SlotTracker &) = delete;
  573. void operator=(const SlotTracker &) = delete;
  574. };
  575. } // namespace llvm
  576. ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
  577. const Function *F)
  578. : M(M), F(F), Machine(&Machine) {}
  579. ModuleSlotTracker::ModuleSlotTracker(const Module *M,
  580. bool ShouldInitializeAllMetadata)
  581. : MachineStorage(M ? new SlotTracker(M, ShouldInitializeAllMetadata)
  582. : nullptr),
  583. M(M), Machine(MachineStorage.get()) {}
  584. ModuleSlotTracker::~ModuleSlotTracker() {}
  585. void ModuleSlotTracker::incorporateFunction(const Function &F) {
  586. if (!Machine)
  587. return;
  588. // Nothing to do if this is the right function already.
  589. if (this->F == &F)
  590. return;
  591. if (this->F)
  592. Machine->purgeFunction();
  593. Machine->incorporateFunction(&F);
  594. this->F = &F;
  595. }
  596. static SlotTracker *createSlotTracker(const Module *M) {
  597. return new SlotTracker(M);
  598. }
  599. static SlotTracker *createSlotTracker(const Value *V) {
  600. if (const Argument *FA = dyn_cast<Argument>(V))
  601. return new SlotTracker(FA->getParent());
  602. if (const Instruction *I = dyn_cast<Instruction>(V))
  603. if (I->getParent())
  604. return new SlotTracker(I->getParent()->getParent());
  605. if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
  606. return new SlotTracker(BB->getParent());
  607. if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
  608. return new SlotTracker(GV->getParent());
  609. if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
  610. return new SlotTracker(GA->getParent());
  611. if (const Function *Func = dyn_cast<Function>(V))
  612. return new SlotTracker(Func);
  613. return nullptr;
  614. }
  615. #if 0
  616. #define ST_DEBUG(X) dbgs() << X
  617. #else
  618. #define ST_DEBUG(X)
  619. #endif
  620. // Module level constructor. Causes the contents of the Module (sans functions)
  621. // to be added to the slot table.
  622. SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
  623. : TheModule(M), TheFunction(nullptr), FunctionProcessed(false),
  624. ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
  625. fNext(0), mdnNext(0), asNext(0) {}
  626. // Function level constructor. Causes the contents of the Module and the one
  627. // function provided to be added to the slot table.
  628. SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
  629. : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
  630. FunctionProcessed(false),
  631. ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
  632. fNext(0), mdnNext(0), asNext(0) {}
  633. inline void SlotTracker::initialize() {
  634. if (TheModule) {
  635. processModule();
  636. TheModule = nullptr; ///< Prevent re-processing next time we're called.
  637. }
  638. if (TheFunction && !FunctionProcessed)
  639. processFunction();
  640. }
  641. // Iterate through all the global variables, functions, and global
  642. // variable initializers and create slots for them.
  643. void SlotTracker::processModule() {
  644. ST_DEBUG("begin processModule!\n");
  645. // Add all of the unnamed global variables to the value table.
  646. for (const GlobalVariable &Var : TheModule->globals()) {
  647. if (!Var.hasName())
  648. CreateModuleSlot(&Var);
  649. }
  650. for (const GlobalAlias &A : TheModule->aliases()) {
  651. if (!A.hasName())
  652. CreateModuleSlot(&A);
  653. }
  654. // Add metadata used by named metadata.
  655. for (const NamedMDNode &NMD : TheModule->named_metadata()) {
  656. for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
  657. CreateMetadataSlot(NMD.getOperand(i));
  658. }
  659. for (const Function &F : *TheModule) {
  660. if (!F.hasName())
  661. // Add all the unnamed functions to the table.
  662. CreateModuleSlot(&F);
  663. if (ShouldInitializeAllMetadata)
  664. processFunctionMetadata(F);
  665. // Add all the function attributes to the table.
  666. // FIXME: Add attributes of other objects?
  667. AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
  668. if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex))
  669. CreateAttributeSetSlot(FnAttrs);
  670. }
  671. ST_DEBUG("end processModule!\n");
  672. }
  673. // Process the arguments, basic blocks, and instructions of a function.
  674. void SlotTracker::processFunction() {
  675. ST_DEBUG("begin processFunction!\n");
  676. fNext = 0;
  677. // Add all the function arguments with no names.
  678. for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
  679. AE = TheFunction->arg_end(); AI != AE; ++AI)
  680. if (!AI->hasName())
  681. CreateFunctionSlot(AI);
  682. ST_DEBUG("Inserting Instructions:\n");
  683. // Add all of the basic blocks and instructions with no names.
  684. for (auto &BB : *TheFunction) {
  685. if (!BB.hasName())
  686. CreateFunctionSlot(&BB);
  687. processFunctionMetadata(*TheFunction);
  688. for (auto &I : BB) {
  689. if (!I.getType()->isVoidTy() && !I.hasName())
  690. CreateFunctionSlot(&I);
  691. // We allow direct calls to any llvm.foo function here, because the
  692. // target may not be linked into the optimizer.
  693. if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
  694. // Add all the call attributes to the table.
  695. AttributeSet Attrs = CI->getAttributes().getFnAttributes();
  696. if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
  697. CreateAttributeSetSlot(Attrs);
  698. } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
  699. // Add all the call attributes to the table.
  700. AttributeSet Attrs = II->getAttributes().getFnAttributes();
  701. if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
  702. CreateAttributeSetSlot(Attrs);
  703. }
  704. }
  705. }
  706. FunctionProcessed = true;
  707. ST_DEBUG("end processFunction!\n");
  708. }
  709. void SlotTracker::processFunctionMetadata(const Function &F) {
  710. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  711. for (auto &BB : F) {
  712. F.getAllMetadata(MDs);
  713. for (auto &MD : MDs)
  714. CreateMetadataSlot(MD.second);
  715. for (auto &I : BB)
  716. processInstructionMetadata(I);
  717. }
  718. }
  719. void SlotTracker::processInstructionMetadata(const Instruction &I) {
  720. // Process metadata used directly by intrinsics.
  721. if (const CallInst *CI = dyn_cast<CallInst>(&I))
  722. if (Function *F = CI->getCalledFunction())
  723. if (F->isIntrinsic())
  724. for (auto &Op : I.operands())
  725. if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
  726. if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
  727. CreateMetadataSlot(N);
  728. // Process metadata attached to this instruction.
  729. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  730. I.getAllMetadata(MDs);
  731. for (auto &MD : MDs)
  732. CreateMetadataSlot(MD.second);
  733. }
  734. /// Clean up after incorporating a function. This is the only way to get out of
  735. /// the function incorporation state that affects get*Slot/Create*Slot. Function
  736. /// incorporation state is indicated by TheFunction != 0.
  737. void SlotTracker::purgeFunction() {
  738. ST_DEBUG("begin purgeFunction!\n");
  739. fMap.clear(); // Simply discard the function level map
  740. TheFunction = nullptr;
  741. FunctionProcessed = false;
  742. ST_DEBUG("end purgeFunction!\n");
  743. }
  744. /// getGlobalSlot - Get the slot number of a global value.
  745. int SlotTracker::getGlobalSlot(const GlobalValue *V) {
  746. // Check for uninitialized state and do lazy initialization.
  747. initialize();
  748. // Find the value in the module map
  749. ValueMap::iterator MI = mMap.find(V);
  750. return MI == mMap.end() ? -1 : (int)MI->second;
  751. }
  752. /// getMetadataSlot - Get the slot number of a MDNode.
  753. int SlotTracker::getMetadataSlot(const MDNode *N) {
  754. // Check for uninitialized state and do lazy initialization.
  755. initialize();
  756. // Find the MDNode in the module map
  757. mdn_iterator MI = mdnMap.find(N);
  758. return MI == mdnMap.end() ? -1 : (int)MI->second;
  759. }
  760. /// getLocalSlot - Get the slot number for a value that is local to a function.
  761. int SlotTracker::getLocalSlot(const Value *V) {
  762. assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
  763. // Check for uninitialized state and do lazy initialization.
  764. initialize();
  765. ValueMap::iterator FI = fMap.find(V);
  766. return FI == fMap.end() ? -1 : (int)FI->second;
  767. }
  768. int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
  769. // Check for uninitialized state and do lazy initialization.
  770. initialize();
  771. // Find the AttributeSet in the module map.
  772. as_iterator AI = asMap.find(AS);
  773. return AI == asMap.end() ? -1 : (int)AI->second;
  774. }
  775. /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
  776. void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
  777. assert(V && "Can't insert a null Value into SlotTracker!");
  778. assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
  779. assert(!V->hasName() && "Doesn't need a slot!");
  780. unsigned DestSlot = mNext++;
  781. mMap[V] = DestSlot;
  782. ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
  783. DestSlot << " [");
  784. // G = Global, F = Function, A = Alias, o = other
  785. ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
  786. (isa<Function>(V) ? 'F' :
  787. (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
  788. }
  789. /// CreateSlot - Create a new slot for the specified value if it has no name.
  790. void SlotTracker::CreateFunctionSlot(const Value *V) {
  791. assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
  792. unsigned DestSlot = fNext++;
  793. fMap[V] = DestSlot;
  794. // G = Global, F = Function, o = other
  795. ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
  796. DestSlot << " [o]\n");
  797. }
  798. /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
  799. void SlotTracker::CreateMetadataSlot(const MDNode *N) {
  800. assert(N && "Can't insert a null Value into SlotTracker!");
  801. unsigned DestSlot = mdnNext;
  802. if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
  803. return;
  804. ++mdnNext;
  805. // Recursively add any MDNodes referenced by operands.
  806. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
  807. if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
  808. CreateMetadataSlot(Op);
  809. }
  810. void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
  811. assert(AS.hasAttributes(AttributeSet::FunctionIndex) &&
  812. "Doesn't need a slot!");
  813. as_iterator I = asMap.find(AS);
  814. if (I != asMap.end())
  815. return;
  816. unsigned DestSlot = asNext++;
  817. asMap[AS] = DestSlot;
  818. }
  819. //===----------------------------------------------------------------------===//
  820. // AsmWriter Implementation
  821. //===----------------------------------------------------------------------===//
  822. static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
  823. TypePrinting *TypePrinter,
  824. SlotTracker *Machine,
  825. const Module *Context);
  826. static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
  827. TypePrinting *TypePrinter,
  828. SlotTracker *Machine, const Module *Context,
  829. bool FromValue = false);
  830. static const char *getPredicateText(unsigned predicate) {
  831. const char * pred = "unknown";
  832. switch (predicate) {
  833. case FCmpInst::FCMP_FALSE: pred = "false"; break;
  834. case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
  835. case FCmpInst::FCMP_OGT: pred = "ogt"; break;
  836. case FCmpInst::FCMP_OGE: pred = "oge"; break;
  837. case FCmpInst::FCMP_OLT: pred = "olt"; break;
  838. case FCmpInst::FCMP_OLE: pred = "ole"; break;
  839. case FCmpInst::FCMP_ONE: pred = "one"; break;
  840. case FCmpInst::FCMP_ORD: pred = "ord"; break;
  841. case FCmpInst::FCMP_UNO: pred = "uno"; break;
  842. case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
  843. case FCmpInst::FCMP_UGT: pred = "ugt"; break;
  844. case FCmpInst::FCMP_UGE: pred = "uge"; break;
  845. case FCmpInst::FCMP_ULT: pred = "ult"; break;
  846. case FCmpInst::FCMP_ULE: pred = "ule"; break;
  847. case FCmpInst::FCMP_UNE: pred = "une"; break;
  848. case FCmpInst::FCMP_TRUE: pred = "true"; break;
  849. case ICmpInst::ICMP_EQ: pred = "eq"; break;
  850. case ICmpInst::ICMP_NE: pred = "ne"; break;
  851. case ICmpInst::ICMP_SGT: pred = "sgt"; break;
  852. case ICmpInst::ICMP_SGE: pred = "sge"; break;
  853. case ICmpInst::ICMP_SLT: pred = "slt"; break;
  854. case ICmpInst::ICMP_SLE: pred = "sle"; break;
  855. case ICmpInst::ICMP_UGT: pred = "ugt"; break;
  856. case ICmpInst::ICMP_UGE: pred = "uge"; break;
  857. case ICmpInst::ICMP_ULT: pred = "ult"; break;
  858. case ICmpInst::ICMP_ULE: pred = "ule"; break;
  859. }
  860. return pred;
  861. }
  862. static void writeAtomicRMWOperation(raw_ostream &Out,
  863. AtomicRMWInst::BinOp Op) {
  864. switch (Op) {
  865. default: Out << " <unknown operation " << Op << ">"; break;
  866. case AtomicRMWInst::Xchg: Out << " xchg"; break;
  867. case AtomicRMWInst::Add: Out << " add"; break;
  868. case AtomicRMWInst::Sub: Out << " sub"; break;
  869. case AtomicRMWInst::And: Out << " and"; break;
  870. case AtomicRMWInst::Nand: Out << " nand"; break;
  871. case AtomicRMWInst::Or: Out << " or"; break;
  872. case AtomicRMWInst::Xor: Out << " xor"; break;
  873. case AtomicRMWInst::Max: Out << " max"; break;
  874. case AtomicRMWInst::Min: Out << " min"; break;
  875. case AtomicRMWInst::UMax: Out << " umax"; break;
  876. case AtomicRMWInst::UMin: Out << " umin"; break;
  877. }
  878. }
  879. static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
  880. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(U)) {
  881. // Unsafe algebra implies all the others, no need to write them all out
  882. if (FPOp->hasUnsafeAlgebra())
  883. Out << " fast";
  884. else {
  885. if (FPOp->hasNoNaNs())
  886. Out << " nnan";
  887. if (FPOp->hasNoInfs())
  888. Out << " ninf";
  889. if (FPOp->hasNoSignedZeros())
  890. Out << " nsz";
  891. if (FPOp->hasAllowReciprocal())
  892. Out << " arcp";
  893. }
  894. }
  895. if (const OverflowingBinaryOperator *OBO =
  896. dyn_cast<OverflowingBinaryOperator>(U)) {
  897. if (OBO->hasNoUnsignedWrap())
  898. Out << " nuw";
  899. if (OBO->hasNoSignedWrap())
  900. Out << " nsw";
  901. } else if (const PossiblyExactOperator *Div =
  902. dyn_cast<PossiblyExactOperator>(U)) {
  903. if (Div->isExact())
  904. Out << " exact";
  905. } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  906. if (GEP->isInBounds())
  907. Out << " inbounds";
  908. }
  909. }
  910. static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
  911. TypePrinting &TypePrinter,
  912. SlotTracker *Machine,
  913. const Module *Context) {
  914. if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
  915. if (CI->getType()->isIntegerTy(1)) {
  916. Out << (CI->getZExtValue() ? "true" : "false");
  917. return;
  918. }
  919. Out << CI->getValue();
  920. return;
  921. }
  922. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
  923. if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
  924. &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
  925. // We would like to output the FP constant value in exponential notation,
  926. // but we cannot do this if doing so will lose precision. Check here to
  927. // make sure that we only output it in exponential format if we can parse
  928. // the value back and get the same value.
  929. //
  930. bool ignored;
  931. bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
  932. bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
  933. bool isInf = CFP->getValueAPF().isInfinity();
  934. bool isNaN = CFP->getValueAPF().isNaN();
  935. if (!isHalf && !isInf && !isNaN) {
  936. double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
  937. CFP->getValueAPF().convertToFloat();
  938. SmallString<128> StrVal;
  939. raw_svector_ostream(StrVal) << Val;
  940. // Check to make sure that the stringized number is not some string like
  941. // "Inf" or NaN, that atof will accept, but the lexer will not. Check
  942. // that the string matches the "[-+]?[0-9]" regex.
  943. //
  944. if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
  945. ((StrVal[0] == '-' || StrVal[0] == '+') &&
  946. (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
  947. // Reparse stringized version!
  948. if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
  949. Out << StrVal;
  950. return;
  951. }
  952. }
  953. }
  954. // Otherwise we could not reparse it to exactly the same value, so we must
  955. // output the string in hexadecimal format! Note that loading and storing
  956. // floating point types changes the bits of NaNs on some hosts, notably
  957. // x86, so we must not use these types.
  958. static_assert(sizeof(double) == sizeof(uint64_t),
  959. "assuming that double is 64 bits!");
  960. char Buffer[40];
  961. APFloat apf = CFP->getValueAPF();
  962. // Halves and floats are represented in ASCII IR as double, convert.
  963. if (!isDouble)
  964. apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
  965. &ignored);
  966. Out << "0x" <<
  967. utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
  968. Buffer+40);
  969. return;
  970. }
  971. // Either half, or some form of long double.
  972. // These appear as a magic letter identifying the type, then a
  973. // fixed number of hex digits.
  974. Out << "0x";
  975. // Bit position, in the current word, of the next nibble to print.
  976. int shiftcount;
  977. if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
  978. Out << 'K';
  979. // api needed to prevent premature destruction
  980. APInt api = CFP->getValueAPF().bitcastToAPInt();
  981. const uint64_t* p = api.getRawData();
  982. uint64_t word = p[1];
  983. shiftcount = 12;
  984. int width = api.getBitWidth();
  985. for (int j=0; j<width; j+=4, shiftcount-=4) {
  986. unsigned int nibble = (word>>shiftcount) & 15;
  987. if (nibble < 10)
  988. Out << (unsigned char)(nibble + '0');
  989. else
  990. Out << (unsigned char)(nibble - 10 + 'A');
  991. if (shiftcount == 0 && j+4 < width) {
  992. word = *p;
  993. shiftcount = 64;
  994. if (width-j-4 < 64)
  995. shiftcount = width-j-4;
  996. }
  997. }
  998. return;
  999. } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
  1000. shiftcount = 60;
  1001. Out << 'L';
  1002. } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
  1003. shiftcount = 60;
  1004. Out << 'M';
  1005. } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
  1006. shiftcount = 12;
  1007. Out << 'H';
  1008. } else
  1009. llvm_unreachable("Unsupported floating point type");
  1010. // api needed to prevent premature destruction
  1011. APInt api = CFP->getValueAPF().bitcastToAPInt();
  1012. const uint64_t* p = api.getRawData();
  1013. uint64_t word = *p;
  1014. int width = api.getBitWidth();
  1015. for (int j=0; j<width; j+=4, shiftcount-=4) {
  1016. unsigned int nibble = (word>>shiftcount) & 15;
  1017. if (nibble < 10)
  1018. Out << (unsigned char)(nibble + '0');
  1019. else
  1020. Out << (unsigned char)(nibble - 10 + 'A');
  1021. if (shiftcount == 0 && j+4 < width) {
  1022. word = *(++p);
  1023. shiftcount = 64;
  1024. if (width-j-4 < 64)
  1025. shiftcount = width-j-4;
  1026. }
  1027. }
  1028. return;
  1029. }
  1030. if (isa<ConstantAggregateZero>(CV)) {
  1031. Out << "zeroinitializer";
  1032. return;
  1033. }
  1034. if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
  1035. Out << "blockaddress(";
  1036. WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
  1037. Context);
  1038. Out << ", ";
  1039. WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
  1040. Context);
  1041. Out << ")";
  1042. return;
  1043. }
  1044. if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
  1045. Type *ETy = CA->getType()->getElementType();
  1046. Out << '[';
  1047. TypePrinter.print(ETy, Out);
  1048. Out << ' ';
  1049. WriteAsOperandInternal(Out, CA->getOperand(0),
  1050. &TypePrinter, Machine,
  1051. Context);
  1052. for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
  1053. Out << ", ";
  1054. TypePrinter.print(ETy, Out);
  1055. Out << ' ';
  1056. WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
  1057. Context);
  1058. }
  1059. Out << ']';
  1060. return;
  1061. }
  1062. if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
  1063. // As a special case, print the array as a string if it is an array of
  1064. // i8 with ConstantInt values.
  1065. if (CA->isString()) {
  1066. Out << "c\"";
  1067. PrintEscapedString(CA->getAsString(), Out);
  1068. Out << '"';
  1069. return;
  1070. }
  1071. Type *ETy = CA->getType()->getElementType();
  1072. Out << '[';
  1073. TypePrinter.print(ETy, Out);
  1074. Out << ' ';
  1075. WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
  1076. &TypePrinter, Machine,
  1077. Context);
  1078. for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
  1079. Out << ", ";
  1080. TypePrinter.print(ETy, Out);
  1081. Out << ' ';
  1082. WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
  1083. Machine, Context);
  1084. }
  1085. Out << ']';
  1086. return;
  1087. }
  1088. if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
  1089. if (CS->getType()->isPacked())
  1090. Out << '<';
  1091. Out << '{';
  1092. unsigned N = CS->getNumOperands();
  1093. if (N) {
  1094. Out << ' ';
  1095. TypePrinter.print(CS->getOperand(0)->getType(), Out);
  1096. Out << ' ';
  1097. WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
  1098. Context);
  1099. for (unsigned i = 1; i < N; i++) {
  1100. Out << ", ";
  1101. TypePrinter.print(CS->getOperand(i)->getType(), Out);
  1102. Out << ' ';
  1103. WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
  1104. Context);
  1105. }
  1106. Out << ' ';
  1107. }
  1108. Out << '}';
  1109. if (CS->getType()->isPacked())
  1110. Out << '>';
  1111. return;
  1112. }
  1113. if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
  1114. Type *ETy = CV->getType()->getVectorElementType();
  1115. Out << '<';
  1116. TypePrinter.print(ETy, Out);
  1117. Out << ' ';
  1118. WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
  1119. Machine, Context);
  1120. for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
  1121. Out << ", ";
  1122. TypePrinter.print(ETy, Out);
  1123. Out << ' ';
  1124. WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
  1125. Machine, Context);
  1126. }
  1127. Out << '>';
  1128. return;
  1129. }
  1130. if (isa<ConstantPointerNull>(CV)) {
  1131. Out << "null";
  1132. return;
  1133. }
  1134. if (isa<UndefValue>(CV)) {
  1135. Out << "undef";
  1136. return;
  1137. }
  1138. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
  1139. Out << CE->getOpcodeName();
  1140. WriteOptimizationInfo(Out, CE);
  1141. if (CE->isCompare())
  1142. Out << ' ' << getPredicateText(CE->getPredicate());
  1143. Out << " (";
  1144. if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
  1145. TypePrinter.print(
  1146. cast<PointerType>(GEP->getPointerOperandType()->getScalarType())
  1147. ->getElementType(),
  1148. Out);
  1149. Out << ", ";
  1150. }
  1151. for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
  1152. TypePrinter.print((*OI)->getType(), Out);
  1153. Out << ' ';
  1154. WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
  1155. if (OI+1 != CE->op_end())
  1156. Out << ", ";
  1157. }
  1158. if (CE->hasIndices()) {
  1159. ArrayRef<unsigned> Indices = CE->getIndices();
  1160. for (unsigned i = 0, e = Indices.size(); i != e; ++i)
  1161. Out << ", " << Indices[i];
  1162. }
  1163. if (CE->isCast()) {
  1164. Out << " to ";
  1165. TypePrinter.print(CE->getType(), Out);
  1166. }
  1167. Out << ')';
  1168. return;
  1169. }
  1170. Out << "<placeholder or erroneous Constant>";
  1171. }
  1172. static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
  1173. TypePrinting *TypePrinter, SlotTracker *Machine,
  1174. const Module *Context) {
  1175. Out << "!{";
  1176. for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
  1177. const Metadata *MD = Node->getOperand(mi);
  1178. if (!MD)
  1179. Out << "null";
  1180. else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
  1181. Value *V = MDV->getValue();
  1182. TypePrinter->print(V->getType(), Out);
  1183. Out << ' ';
  1184. WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
  1185. } else {
  1186. WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
  1187. }
  1188. if (mi + 1 != me)
  1189. Out << ", ";
  1190. }
  1191. Out << "}";
  1192. }
  1193. namespace {
  1194. struct FieldSeparator {
  1195. bool Skip;
  1196. const char *Sep;
  1197. FieldSeparator(const char *Sep = ", ") : Skip(true), Sep(Sep) {}
  1198. };
  1199. raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
  1200. if (FS.Skip) {
  1201. FS.Skip = false;
  1202. return OS;
  1203. }
  1204. return OS << FS.Sep;
  1205. }
  1206. struct MDFieldPrinter {
  1207. raw_ostream &Out;
  1208. FieldSeparator FS;
  1209. TypePrinting *TypePrinter;
  1210. SlotTracker *Machine;
  1211. const Module *Context;
  1212. explicit MDFieldPrinter(raw_ostream &Out)
  1213. : Out(Out), TypePrinter(nullptr), Machine(nullptr), Context(nullptr) {}
  1214. MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
  1215. SlotTracker *Machine, const Module *Context)
  1216. : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
  1217. }
  1218. void printTag(const DINode *N);
  1219. void printString(StringRef Name, StringRef Value,
  1220. bool ShouldSkipEmpty = true);
  1221. void printMetadata(StringRef Name, const Metadata *MD,
  1222. bool ShouldSkipNull = true);
  1223. template <class IntTy>
  1224. void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
  1225. void printBool(StringRef Name, bool Value);
  1226. void printDIFlags(StringRef Name, unsigned Flags);
  1227. template <class IntTy, class Stringifier>
  1228. void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
  1229. bool ShouldSkipZero = true);
  1230. };
  1231. } // end namespace
  1232. void MDFieldPrinter::printTag(const DINode *N) {
  1233. Out << FS << "tag: ";
  1234. if (const char *Tag = dwarf::TagString(N->getTag()))
  1235. Out << Tag;
  1236. else
  1237. Out << N->getTag();
  1238. }
  1239. void MDFieldPrinter::printString(StringRef Name, StringRef Value,
  1240. bool ShouldSkipEmpty) {
  1241. if (ShouldSkipEmpty && Value.empty())
  1242. return;
  1243. Out << FS << Name << ": \"";
  1244. PrintEscapedString(Value, Out);
  1245. Out << "\"";
  1246. }
  1247. static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
  1248. TypePrinting *TypePrinter,
  1249. SlotTracker *Machine,
  1250. const Module *Context) {
  1251. if (!MD) {
  1252. Out << "null";
  1253. return;
  1254. }
  1255. WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
  1256. }
  1257. void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
  1258. bool ShouldSkipNull) {
  1259. if (ShouldSkipNull && !MD)
  1260. return;
  1261. Out << FS << Name << ": ";
  1262. writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
  1263. }
  1264. template <class IntTy>
  1265. void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
  1266. if (ShouldSkipZero && !Int)
  1267. return;
  1268. Out << FS << Name << ": " << Int;
  1269. }
  1270. void MDFieldPrinter::printBool(StringRef Name, bool Value) {
  1271. Out << FS << Name << ": " << (Value ? "true" : "false");
  1272. }
  1273. void MDFieldPrinter::printDIFlags(StringRef Name, unsigned Flags) {
  1274. if (!Flags)
  1275. return;
  1276. Out << FS << Name << ": ";
  1277. SmallVector<unsigned, 8> SplitFlags;
  1278. unsigned Extra = DINode::splitFlags(Flags, SplitFlags);
  1279. FieldSeparator FlagsFS(" | ");
  1280. for (unsigned F : SplitFlags) {
  1281. const char *StringF = DINode::getFlagString(F);
  1282. assert(StringF && "Expected valid flag");
  1283. Out << FlagsFS << StringF;
  1284. }
  1285. if (Extra || SplitFlags.empty())
  1286. Out << FlagsFS << Extra;
  1287. }
  1288. template <class IntTy, class Stringifier>
  1289. void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
  1290. Stringifier toString, bool ShouldSkipZero) {
  1291. if (!Value)
  1292. return;
  1293. Out << FS << Name << ": ";
  1294. if (const char *S = toString(Value))
  1295. Out << S;
  1296. else
  1297. Out << Value;
  1298. }
  1299. static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
  1300. TypePrinting *TypePrinter, SlotTracker *Machine,
  1301. const Module *Context) {
  1302. Out << "!GenericDINode(";
  1303. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1304. Printer.printTag(N);
  1305. Printer.printString("header", N->getHeader());
  1306. if (N->getNumDwarfOperands()) {
  1307. Out << Printer.FS << "operands: {";
  1308. FieldSeparator IFS;
  1309. for (auto &I : N->dwarf_operands()) {
  1310. Out << IFS;
  1311. writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
  1312. }
  1313. Out << "}";
  1314. }
  1315. Out << ")";
  1316. }
  1317. static void writeDILocation(raw_ostream &Out, const DILocation *DL,
  1318. TypePrinting *TypePrinter, SlotTracker *Machine,
  1319. const Module *Context) {
  1320. Out << "!DILocation(";
  1321. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1322. // Always output the line, since 0 is a relevant and important value for it.
  1323. Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
  1324. Printer.printInt("column", DL->getColumn());
  1325. Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
  1326. Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
  1327. Out << ")";
  1328. }
  1329. static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
  1330. TypePrinting *, SlotTracker *, const Module *) {
  1331. Out << "!DISubrange(";
  1332. MDFieldPrinter Printer(Out);
  1333. Printer.printInt("count", N->getCount(), /* ShouldSkipZero */ false);
  1334. Printer.printInt("lowerBound", N->getLowerBound());
  1335. Out << ")";
  1336. }
  1337. static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
  1338. TypePrinting *, SlotTracker *, const Module *) {
  1339. Out << "!DIEnumerator(";
  1340. MDFieldPrinter Printer(Out);
  1341. Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
  1342. Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
  1343. Out << ")";
  1344. }
  1345. static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
  1346. TypePrinting *, SlotTracker *, const Module *) {
  1347. Out << "!DIBasicType(";
  1348. MDFieldPrinter Printer(Out);
  1349. if (N->getTag() != dwarf::DW_TAG_base_type)
  1350. Printer.printTag(N);
  1351. Printer.printString("name", N->getName());
  1352. Printer.printInt("size", N->getSizeInBits());
  1353. Printer.printInt("align", N->getAlignInBits());
  1354. Printer.printDwarfEnum("encoding", N->getEncoding(),
  1355. dwarf::AttributeEncodingString);
  1356. Out << ")";
  1357. }
  1358. static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
  1359. TypePrinting *TypePrinter, SlotTracker *Machine,
  1360. const Module *Context) {
  1361. Out << "!DIDerivedType(";
  1362. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1363. Printer.printTag(N);
  1364. Printer.printString("name", N->getName());
  1365. Printer.printMetadata("scope", N->getRawScope());
  1366. Printer.printMetadata("file", N->getRawFile());
  1367. Printer.printInt("line", N->getLine());
  1368. Printer.printMetadata("baseType", N->getRawBaseType(),
  1369. /* ShouldSkipNull */ false);
  1370. Printer.printInt("size", N->getSizeInBits());
  1371. Printer.printInt("align", N->getAlignInBits());
  1372. Printer.printInt("offset", N->getOffsetInBits());
  1373. Printer.printDIFlags("flags", N->getFlags());
  1374. Printer.printMetadata("extraData", N->getRawExtraData());
  1375. Out << ")";
  1376. }
  1377. static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
  1378. TypePrinting *TypePrinter,
  1379. SlotTracker *Machine, const Module *Context) {
  1380. Out << "!DICompositeType(";
  1381. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1382. Printer.printTag(N);
  1383. Printer.printString("name", N->getName());
  1384. Printer.printMetadata("scope", N->getRawScope());
  1385. Printer.printMetadata("file", N->getRawFile());
  1386. Printer.printInt("line", N->getLine());
  1387. Printer.printMetadata("baseType", N->getRawBaseType());
  1388. Printer.printInt("size", N->getSizeInBits());
  1389. Printer.printInt("align", N->getAlignInBits());
  1390. Printer.printInt("offset", N->getOffsetInBits());
  1391. Printer.printDIFlags("flags", N->getFlags());
  1392. Printer.printMetadata("elements", N->getRawElements());
  1393. Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
  1394. dwarf::LanguageString);
  1395. Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
  1396. Printer.printMetadata("templateParams", N->getRawTemplateParams());
  1397. Printer.printString("identifier", N->getIdentifier());
  1398. Out << ")";
  1399. }
  1400. static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
  1401. TypePrinting *TypePrinter,
  1402. SlotTracker *Machine, const Module *Context) {
  1403. Out << "!DISubroutineType(";
  1404. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1405. Printer.printDIFlags("flags", N->getFlags());
  1406. Printer.printMetadata("types", N->getRawTypeArray(),
  1407. /* ShouldSkipNull */ false);
  1408. Out << ")";
  1409. }
  1410. static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
  1411. SlotTracker *, const Module *) {
  1412. Out << "!DIFile(";
  1413. MDFieldPrinter Printer(Out);
  1414. Printer.printString("filename", N->getFilename(),
  1415. /* ShouldSkipEmpty */ false);
  1416. Printer.printString("directory", N->getDirectory(),
  1417. /* ShouldSkipEmpty */ false);
  1418. Out << ")";
  1419. }
  1420. static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
  1421. TypePrinting *TypePrinter, SlotTracker *Machine,
  1422. const Module *Context) {
  1423. Out << "!DICompileUnit(";
  1424. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1425. Printer.printDwarfEnum("language", N->getSourceLanguage(),
  1426. dwarf::LanguageString, /* ShouldSkipZero */ false);
  1427. Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
  1428. Printer.printString("producer", N->getProducer());
  1429. Printer.printBool("isOptimized", N->isOptimized());
  1430. Printer.printString("flags", N->getFlags());
  1431. Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
  1432. /* ShouldSkipZero */ false);
  1433. Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
  1434. Printer.printInt("emissionKind", N->getEmissionKind(),
  1435. /* ShouldSkipZero */ false);
  1436. Printer.printMetadata("enums", N->getRawEnumTypes());
  1437. Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
  1438. Printer.printMetadata("subprograms", N->getRawSubprograms());
  1439. Printer.printMetadata("globals", N->getRawGlobalVariables());
  1440. Printer.printMetadata("imports", N->getRawImportedEntities());
  1441. Printer.printInt("dwoId", N->getDWOId());
  1442. Out << ")";
  1443. }
  1444. static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
  1445. TypePrinting *TypePrinter, SlotTracker *Machine,
  1446. const Module *Context) {
  1447. Out << "!DISubprogram(";
  1448. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1449. Printer.printString("name", N->getName());
  1450. Printer.printString("linkageName", N->getLinkageName());
  1451. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1452. Printer.printMetadata("file", N->getRawFile());
  1453. Printer.printInt("line", N->getLine());
  1454. Printer.printMetadata("type", N->getRawType());
  1455. Printer.printBool("isLocal", N->isLocalToUnit());
  1456. Printer.printBool("isDefinition", N->isDefinition());
  1457. Printer.printInt("scopeLine", N->getScopeLine());
  1458. Printer.printMetadata("containingType", N->getRawContainingType());
  1459. Printer.printDwarfEnum("virtuality", N->getVirtuality(),
  1460. dwarf::VirtualityString);
  1461. Printer.printInt("virtualIndex", N->getVirtualIndex());
  1462. Printer.printDIFlags("flags", N->getFlags());
  1463. Printer.printBool("isOptimized", N->isOptimized());
  1464. Printer.printMetadata("function", N->getRawFunction());
  1465. Printer.printMetadata("templateParams", N->getRawTemplateParams());
  1466. Printer.printMetadata("declaration", N->getRawDeclaration());
  1467. Printer.printMetadata("variables", N->getRawVariables());
  1468. Out << ")";
  1469. }
  1470. static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
  1471. TypePrinting *TypePrinter, SlotTracker *Machine,
  1472. const Module *Context) {
  1473. Out << "!DILexicalBlock(";
  1474. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1475. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1476. Printer.printMetadata("file", N->getRawFile());
  1477. Printer.printInt("line", N->getLine());
  1478. Printer.printInt("column", N->getColumn());
  1479. Out << ")";
  1480. }
  1481. static void writeDILexicalBlockFile(raw_ostream &Out,
  1482. const DILexicalBlockFile *N,
  1483. TypePrinting *TypePrinter,
  1484. SlotTracker *Machine,
  1485. const Module *Context) {
  1486. Out << "!DILexicalBlockFile(";
  1487. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1488. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1489. Printer.printMetadata("file", N->getRawFile());
  1490. Printer.printInt("discriminator", N->getDiscriminator(),
  1491. /* ShouldSkipZero */ false);
  1492. Out << ")";
  1493. }
  1494. static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
  1495. TypePrinting *TypePrinter, SlotTracker *Machine,
  1496. const Module *Context) {
  1497. Out << "!DINamespace(";
  1498. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1499. Printer.printString("name", N->getName());
  1500. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1501. Printer.printMetadata("file", N->getRawFile());
  1502. Printer.printInt("line", N->getLine());
  1503. Out << ")";
  1504. }
  1505. static void writeDIModule(raw_ostream &Out, const DIModule *N,
  1506. TypePrinting *TypePrinter, SlotTracker *Machine,
  1507. const Module *Context) {
  1508. Out << "!DIModule(";
  1509. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1510. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1511. Printer.printString("name", N->getName());
  1512. Printer.printString("configMacros", N->getConfigurationMacros());
  1513. Printer.printString("includePath", N->getIncludePath());
  1514. Printer.printString("isysroot", N->getISysRoot());
  1515. Out << ")";
  1516. }
  1517. static void writeDITemplateTypeParameter(raw_ostream &Out,
  1518. const DITemplateTypeParameter *N,
  1519. TypePrinting *TypePrinter,
  1520. SlotTracker *Machine,
  1521. const Module *Context) {
  1522. Out << "!DITemplateTypeParameter(";
  1523. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1524. Printer.printString("name", N->getName());
  1525. Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
  1526. Out << ")";
  1527. }
  1528. static void writeDITemplateValueParameter(raw_ostream &Out,
  1529. const DITemplateValueParameter *N,
  1530. TypePrinting *TypePrinter,
  1531. SlotTracker *Machine,
  1532. const Module *Context) {
  1533. Out << "!DITemplateValueParameter(";
  1534. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1535. if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
  1536. Printer.printTag(N);
  1537. Printer.printString("name", N->getName());
  1538. Printer.printMetadata("type", N->getRawType());
  1539. Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
  1540. Out << ")";
  1541. }
  1542. static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
  1543. TypePrinting *TypePrinter,
  1544. SlotTracker *Machine, const Module *Context) {
  1545. Out << "!DIGlobalVariable(";
  1546. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1547. Printer.printString("name", N->getName());
  1548. Printer.printString("linkageName", N->getLinkageName());
  1549. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1550. Printer.printMetadata("file", N->getRawFile());
  1551. Printer.printInt("line", N->getLine());
  1552. Printer.printMetadata("type", N->getRawType());
  1553. Printer.printBool("isLocal", N->isLocalToUnit());
  1554. Printer.printBool("isDefinition", N->isDefinition());
  1555. Printer.printMetadata("variable", N->getRawVariable());
  1556. Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
  1557. Out << ")";
  1558. }
  1559. static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
  1560. TypePrinting *TypePrinter,
  1561. SlotTracker *Machine, const Module *Context) {
  1562. Out << "!DILocalVariable(";
  1563. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1564. Printer.printTag(N);
  1565. Printer.printString("name", N->getName());
  1566. Printer.printInt("arg", N->getArg(),
  1567. /* ShouldSkipZero */
  1568. N->getTag() == dwarf::DW_TAG_auto_variable);
  1569. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1570. Printer.printMetadata("file", N->getRawFile());
  1571. Printer.printInt("line", N->getLine());
  1572. Printer.printMetadata("type", N->getRawType());
  1573. Printer.printDIFlags("flags", N->getFlags());
  1574. Out << ")";
  1575. }
  1576. static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
  1577. TypePrinting *TypePrinter, SlotTracker *Machine,
  1578. const Module *Context) {
  1579. Out << "!DIExpression(";
  1580. FieldSeparator FS;
  1581. if (N->isValid()) {
  1582. for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
  1583. const char *OpStr = dwarf::OperationEncodingString(I->getOp());
  1584. assert(OpStr && "Expected valid opcode");
  1585. Out << FS << OpStr;
  1586. for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
  1587. Out << FS << I->getArg(A);
  1588. }
  1589. } else {
  1590. for (const auto &I : N->getElements())
  1591. Out << FS << I;
  1592. }
  1593. Out << ")";
  1594. }
  1595. static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
  1596. TypePrinting *TypePrinter, SlotTracker *Machine,
  1597. const Module *Context) {
  1598. Out << "!DIObjCProperty(";
  1599. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1600. Printer.printString("name", N->getName());
  1601. Printer.printMetadata("file", N->getRawFile());
  1602. Printer.printInt("line", N->getLine());
  1603. Printer.printString("setter", N->getSetterName());
  1604. Printer.printString("getter", N->getGetterName());
  1605. Printer.printInt("attributes", N->getAttributes());
  1606. Printer.printMetadata("type", N->getRawType());
  1607. Out << ")";
  1608. }
  1609. static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
  1610. TypePrinting *TypePrinter,
  1611. SlotTracker *Machine, const Module *Context) {
  1612. Out << "!DIImportedEntity(";
  1613. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1614. Printer.printTag(N);
  1615. Printer.printString("name", N->getName());
  1616. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1617. Printer.printMetadata("entity", N->getRawEntity());
  1618. Printer.printInt("line", N->getLine());
  1619. Out << ")";
  1620. }
  1621. static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
  1622. TypePrinting *TypePrinter,
  1623. SlotTracker *Machine,
  1624. const Module *Context) {
  1625. if (Node->isDistinct())
  1626. Out << "distinct ";
  1627. else if (Node->isTemporary())
  1628. Out << "<temporary!> "; // Handle broken code.
  1629. switch (Node->getMetadataID()) {
  1630. default:
  1631. llvm_unreachable("Expected uniquable MDNode");
  1632. #define HANDLE_MDNODE_LEAF(CLASS) \
  1633. case Metadata::CLASS##Kind: \
  1634. write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \
  1635. break;
  1636. #include "llvm/IR/Metadata.def"
  1637. }
  1638. }
  1639. // Full implementation of printing a Value as an operand with support for
  1640. // TypePrinting, etc.
  1641. static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
  1642. TypePrinting *TypePrinter,
  1643. SlotTracker *Machine,
  1644. const Module *Context) {
  1645. if (V->hasName()) {
  1646. PrintLLVMName(Out, V);
  1647. return;
  1648. }
  1649. const Constant *CV = dyn_cast<Constant>(V);
  1650. if (CV && !isa<GlobalValue>(CV)) {
  1651. assert(TypePrinter && "Constants require TypePrinting!");
  1652. WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
  1653. return;
  1654. }
  1655. if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
  1656. Out << "asm ";
  1657. if (IA->hasSideEffects())
  1658. Out << "sideeffect ";
  1659. if (IA->isAlignStack())
  1660. Out << "alignstack ";
  1661. // We don't emit the AD_ATT dialect as it's the assumed default.
  1662. if (IA->getDialect() == InlineAsm::AD_Intel)
  1663. Out << "inteldialect ";
  1664. Out << '"';
  1665. PrintEscapedString(IA->getAsmString(), Out);
  1666. Out << "\", \"";
  1667. PrintEscapedString(IA->getConstraintString(), Out);
  1668. Out << '"';
  1669. return;
  1670. }
  1671. if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
  1672. WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
  1673. Context, /* FromValue */ true);
  1674. return;
  1675. }
  1676. char Prefix = '%';
  1677. int Slot;
  1678. // If we have a SlotTracker, use it.
  1679. if (Machine) {
  1680. if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
  1681. Slot = Machine->getGlobalSlot(GV);
  1682. Prefix = '@';
  1683. } else {
  1684. Slot = Machine->getLocalSlot(V);
  1685. // If the local value didn't succeed, then we may be referring to a value
  1686. // from a different function. Translate it, as this can happen when using
  1687. // address of blocks.
  1688. if (Slot == -1)
  1689. if ((Machine = createSlotTracker(V))) {
  1690. Slot = Machine->getLocalSlot(V);
  1691. delete Machine;
  1692. }
  1693. }
  1694. } else if ((Machine = createSlotTracker(V))) {
  1695. // Otherwise, create one to get the # and then destroy it.
  1696. if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
  1697. Slot = Machine->getGlobalSlot(GV);
  1698. Prefix = '@';
  1699. } else {
  1700. Slot = Machine->getLocalSlot(V);
  1701. }
  1702. delete Machine;
  1703. Machine = nullptr;
  1704. } else {
  1705. Slot = -1;
  1706. }
  1707. if (Slot != -1)
  1708. Out << Prefix << Slot;
  1709. else
  1710. Out << "<badref>";
  1711. }
  1712. static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
  1713. TypePrinting *TypePrinter,
  1714. SlotTracker *Machine, const Module *Context,
  1715. bool FromValue) {
  1716. if (const MDNode *N = dyn_cast<MDNode>(MD)) {
  1717. std::unique_ptr<SlotTracker> MachineStorage;
  1718. if (!Machine) {
  1719. MachineStorage = make_unique<SlotTracker>(Context);
  1720. Machine = MachineStorage.get();
  1721. }
  1722. int Slot = Machine->getMetadataSlot(N);
  1723. if (Slot == -1)
  1724. // Give the pointer value instead of "badref", since this comes up all
  1725. // the time when debugging.
  1726. Out << "<" << N << ">";
  1727. else
  1728. Out << '!' << Slot;
  1729. return;
  1730. }
  1731. if (const MDString *MDS = dyn_cast<MDString>(MD)) {
  1732. Out << "!\"";
  1733. PrintEscapedString(MDS->getString(), Out);
  1734. Out << '"';
  1735. return;
  1736. }
  1737. auto *V = cast<ValueAsMetadata>(MD);
  1738. assert(TypePrinter && "TypePrinter required for metadata values");
  1739. assert((FromValue || !isa<LocalAsMetadata>(V)) &&
  1740. "Unexpected function-local metadata outside of value argument");
  1741. TypePrinter->print(V->getValue()->getType(), Out);
  1742. Out << ' ';
  1743. WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
  1744. }
  1745. namespace {
  1746. class AssemblyWriter {
  1747. formatted_raw_ostream &Out;
  1748. const Module *TheModule;
  1749. std::unique_ptr<SlotTracker> SlotTrackerStorage;
  1750. SlotTracker &Machine;
  1751. TypePrinting TypePrinter;
  1752. AssemblyAnnotationWriter *AnnotationWriter;
  1753. SetVector<const Comdat *> Comdats;
  1754. bool ShouldPreserveUseListOrder;
  1755. UseListOrderStack UseListOrders;
  1756. SmallVector<StringRef, 8> MDNames;
  1757. public:
  1758. /// Construct an AssemblyWriter with an external SlotTracker
  1759. AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
  1760. AssemblyAnnotationWriter *AAW,
  1761. bool ShouldPreserveUseListOrder = false);
  1762. /// Construct an AssemblyWriter with an internally allocated SlotTracker
  1763. AssemblyWriter(formatted_raw_ostream &o, const Module *M,
  1764. AssemblyAnnotationWriter *AAW,
  1765. bool ShouldPreserveUseListOrder = false);
  1766. void printMDNodeBody(const MDNode *MD);
  1767. void printNamedMDNode(const NamedMDNode *NMD);
  1768. void printModule(const Module *M);
  1769. void writeOperand(const Value *Op, bool PrintType);
  1770. void writeParamOperand(const Value *Operand, AttributeSet Attrs,unsigned Idx);
  1771. void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
  1772. void writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
  1773. AtomicOrdering FailureOrdering,
  1774. SynchronizationScope SynchScope);
  1775. void writeAllMDNodes();
  1776. void writeMDNode(unsigned Slot, const MDNode *Node);
  1777. void writeAllAttributeGroups();
  1778. void printTypeIdentities();
  1779. void printGlobal(const GlobalVariable *GV);
  1780. void printAlias(const GlobalAlias *GV);
  1781. void printComdat(const Comdat *C);
  1782. void printFunction(const Function *F);
  1783. void printArgument(const Argument *FA, AttributeSet Attrs, unsigned Idx);
  1784. void printBasicBlock(const BasicBlock *BB);
  1785. void printInstructionLine(const Instruction &I);
  1786. void printInstruction(const Instruction &I);
  1787. void printUseListOrder(const UseListOrder &Order);
  1788. void printUseLists(const Function *F);
  1789. private:
  1790. void init();
  1791. /// \brief Print out metadata attachments.
  1792. void printMetadataAttachments(
  1793. const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
  1794. StringRef Separator);
  1795. // printInfoComment - Print a little comment after the instruction indicating
  1796. // which slot it occupies.
  1797. void printInfoComment(const Value &V);
  1798. // printGCRelocateComment - print comment after call to the gc.relocate
  1799. // intrinsic indicating base and derived pointer names.
  1800. void printGCRelocateComment(const Value &V);
  1801. };
  1802. } // namespace
  1803. void AssemblyWriter::init() {
  1804. if (!TheModule)
  1805. return;
  1806. TypePrinter.incorporateTypes(*TheModule);
  1807. for (const Function &F : *TheModule)
  1808. if (const Comdat *C = F.getComdat())
  1809. Comdats.insert(C);
  1810. for (const GlobalVariable &GV : TheModule->globals())
  1811. if (const Comdat *C = GV.getComdat())
  1812. Comdats.insert(C);
  1813. }
  1814. AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
  1815. const Module *M, AssemblyAnnotationWriter *AAW,
  1816. bool ShouldPreserveUseListOrder)
  1817. : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW),
  1818. ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
  1819. init();
  1820. }
  1821. AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, const Module *M,
  1822. AssemblyAnnotationWriter *AAW,
  1823. bool ShouldPreserveUseListOrder)
  1824. : Out(o), TheModule(M), SlotTrackerStorage(createSlotTracker(M)),
  1825. Machine(*SlotTrackerStorage), AnnotationWriter(AAW),
  1826. ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
  1827. init();
  1828. }
  1829. void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
  1830. if (!Operand) {
  1831. Out << "<null operand!>";
  1832. return;
  1833. }
  1834. if (PrintType) {
  1835. TypePrinter.print(Operand->getType(), Out);
  1836. Out << ' ';
  1837. }
  1838. WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
  1839. }
  1840. void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
  1841. SynchronizationScope SynchScope) {
  1842. if (Ordering == NotAtomic)
  1843. return;
  1844. switch (SynchScope) {
  1845. case SingleThread: Out << " singlethread"; break;
  1846. case CrossThread: break;
  1847. }
  1848. switch (Ordering) {
  1849. default: Out << " <bad ordering " << int(Ordering) << ">"; break;
  1850. case Unordered: Out << " unordered"; break;
  1851. case Monotonic: Out << " monotonic"; break;
  1852. case Acquire: Out << " acquire"; break;
  1853. case Release: Out << " release"; break;
  1854. case AcquireRelease: Out << " acq_rel"; break;
  1855. case SequentiallyConsistent: Out << " seq_cst"; break;
  1856. }
  1857. }
  1858. void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
  1859. AtomicOrdering FailureOrdering,
  1860. SynchronizationScope SynchScope) {
  1861. assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic);
  1862. switch (SynchScope) {
  1863. case SingleThread: Out << " singlethread"; break;
  1864. case CrossThread: break;
  1865. }
  1866. switch (SuccessOrdering) {
  1867. default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break;
  1868. case Unordered: Out << " unordered"; break;
  1869. case Monotonic: Out << " monotonic"; break;
  1870. case Acquire: Out << " acquire"; break;
  1871. case Release: Out << " release"; break;
  1872. case AcquireRelease: Out << " acq_rel"; break;
  1873. case SequentiallyConsistent: Out << " seq_cst"; break;
  1874. }
  1875. switch (FailureOrdering) {
  1876. default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break;
  1877. case Unordered: Out << " unordered"; break;
  1878. case Monotonic: Out << " monotonic"; break;
  1879. case Acquire: Out << " acquire"; break;
  1880. case Release: Out << " release"; break;
  1881. case AcquireRelease: Out << " acq_rel"; break;
  1882. case SequentiallyConsistent: Out << " seq_cst"; break;
  1883. }
  1884. }
  1885. void AssemblyWriter::writeParamOperand(const Value *Operand,
  1886. AttributeSet Attrs, unsigned Idx) {
  1887. if (!Operand) {
  1888. Out << "<null operand!>";
  1889. return;
  1890. }
  1891. // Print the type
  1892. TypePrinter.print(Operand->getType(), Out);
  1893. // Print parameter attributes list
  1894. if (Attrs.hasAttributes(Idx))
  1895. Out << ' ' << Attrs.getAsString(Idx);
  1896. Out << ' ';
  1897. // Print the operand
  1898. WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
  1899. }
  1900. void AssemblyWriter::printModule(const Module *M) {
  1901. Machine.initialize();
  1902. if (ShouldPreserveUseListOrder)
  1903. UseListOrders = predictUseListOrder(M);
  1904. if (!M->getModuleIdentifier().empty() &&
  1905. // Don't print the ID if it will start a new line (which would
  1906. // require a comment char before it).
  1907. M->getModuleIdentifier().find('\n') == std::string::npos)
  1908. Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
  1909. const std::string &DL = M->getDataLayoutStr();
  1910. if (!DL.empty())
  1911. Out << "target datalayout = \"" << DL << "\"\n";
  1912. if (!M->getTargetTriple().empty())
  1913. Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
  1914. if (!M->getModuleInlineAsm().empty()) {
  1915. Out << '\n';
  1916. // Split the string into lines, to make it easier to read the .ll file.
  1917. StringRef Asm = M->getModuleInlineAsm();
  1918. do {
  1919. StringRef Front;
  1920. std::tie(Front, Asm) = Asm.split('\n');
  1921. // We found a newline, print the portion of the asm string from the
  1922. // last newline up to this newline.
  1923. Out << "module asm \"";
  1924. PrintEscapedString(Front, Out);
  1925. Out << "\"\n";
  1926. } while (!Asm.empty());
  1927. }
  1928. printTypeIdentities();
  1929. // Output all comdats.
  1930. if (!Comdats.empty())
  1931. Out << '\n';
  1932. for (const Comdat *C : Comdats) {
  1933. printComdat(C);
  1934. if (C != Comdats.back())
  1935. Out << '\n';
  1936. }
  1937. // Output all globals.
  1938. if (!M->global_empty()) Out << '\n';
  1939. for (const GlobalVariable &GV : M->globals()) {
  1940. printGlobal(&GV); Out << '\n';
  1941. }
  1942. // Output all aliases.
  1943. if (!M->alias_empty()) Out << "\n";
  1944. for (const GlobalAlias &GA : M->aliases())
  1945. printAlias(&GA);
  1946. // Output global use-lists.
  1947. printUseLists(nullptr);
  1948. // Output all of the functions.
  1949. for (const Function &F : *M)
  1950. printFunction(&F);
  1951. assert(UseListOrders.empty() && "All use-lists should have been consumed");
  1952. // Output all attribute groups.
  1953. if (!Machine.as_empty()) {
  1954. Out << '\n';
  1955. writeAllAttributeGroups();
  1956. }
  1957. // Output named metadata.
  1958. if (!M->named_metadata_empty()) Out << '\n';
  1959. for (const NamedMDNode &Node : M->named_metadata())
  1960. printNamedMDNode(&Node);
  1961. // Output metadata.
  1962. if (!Machine.mdn_empty()) {
  1963. Out << '\n';
  1964. writeAllMDNodes();
  1965. }
  1966. }
  1967. static void printMetadataIdentifier(StringRef Name,
  1968. formatted_raw_ostream &Out) {
  1969. if (Name.empty()) {
  1970. Out << "<empty name> ";
  1971. } else {
  1972. if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
  1973. Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
  1974. Out << Name[0];
  1975. else
  1976. Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
  1977. for (unsigned i = 1, e = Name.size(); i != e; ++i) {
  1978. unsigned char C = Name[i];
  1979. if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
  1980. C == '.' || C == '_')
  1981. Out << C;
  1982. else
  1983. Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
  1984. }
  1985. }
  1986. }
  1987. void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
  1988. Out << '!';
  1989. printMetadataIdentifier(NMD->getName(), Out);
  1990. Out << " = !{";
  1991. for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
  1992. if (i)
  1993. Out << ", ";
  1994. int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
  1995. if (Slot == -1)
  1996. Out << "<badref>";
  1997. else
  1998. Out << '!' << Slot;
  1999. }
  2000. Out << "}\n";
  2001. }
  2002. static void PrintLinkage(GlobalValue::LinkageTypes LT,
  2003. formatted_raw_ostream &Out) {
  2004. switch (LT) {
  2005. case GlobalValue::ExternalLinkage: break;
  2006. case GlobalValue::PrivateLinkage: Out << "private "; break;
  2007. case GlobalValue::InternalLinkage: Out << "internal "; break;
  2008. case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
  2009. case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
  2010. case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
  2011. case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
  2012. case GlobalValue::CommonLinkage: Out << "common "; break;
  2013. case GlobalValue::AppendingLinkage: Out << "appending "; break;
  2014. case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
  2015. case GlobalValue::AvailableExternallyLinkage:
  2016. Out << "available_externally ";
  2017. break;
  2018. }
  2019. }
  2020. static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
  2021. formatted_raw_ostream &Out) {
  2022. switch (Vis) {
  2023. case GlobalValue::DefaultVisibility: break;
  2024. case GlobalValue::HiddenVisibility: Out << "hidden "; break;
  2025. case GlobalValue::ProtectedVisibility: Out << "protected "; break;
  2026. }
  2027. }
  2028. static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
  2029. formatted_raw_ostream &Out) {
  2030. switch (SCT) {
  2031. case GlobalValue::DefaultStorageClass: break;
  2032. case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
  2033. case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
  2034. }
  2035. }
  2036. static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
  2037. formatted_raw_ostream &Out) {
  2038. switch (TLM) {
  2039. case GlobalVariable::NotThreadLocal:
  2040. break;
  2041. case GlobalVariable::GeneralDynamicTLSModel:
  2042. Out << "thread_local ";
  2043. break;
  2044. case GlobalVariable::LocalDynamicTLSModel:
  2045. Out << "thread_local(localdynamic) ";
  2046. break;
  2047. case GlobalVariable::InitialExecTLSModel:
  2048. Out << "thread_local(initialexec) ";
  2049. break;
  2050. case GlobalVariable::LocalExecTLSModel:
  2051. Out << "thread_local(localexec) ";
  2052. break;
  2053. }
  2054. }
  2055. static void maybePrintComdat(formatted_raw_ostream &Out,
  2056. const GlobalObject &GO) {
  2057. const Comdat *C = GO.getComdat();
  2058. if (!C)
  2059. return;
  2060. if (isa<GlobalVariable>(GO))
  2061. Out << ',';
  2062. Out << " comdat";
  2063. if (GO.getName() == C->getName())
  2064. return;
  2065. Out << '(';
  2066. PrintLLVMName(Out, C->getName(), ComdatPrefix);
  2067. Out << ')';
  2068. }
  2069. void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
  2070. if (GV->isMaterializable())
  2071. Out << "; Materializable\n";
  2072. WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
  2073. Out << " = ";
  2074. if (!GV->hasInitializer() && GV->hasExternalLinkage())
  2075. Out << "external ";
  2076. PrintLinkage(GV->getLinkage(), Out);
  2077. PrintVisibility(GV->getVisibility(), Out);
  2078. PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
  2079. PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
  2080. if (GV->hasUnnamedAddr())
  2081. Out << "unnamed_addr ";
  2082. if (unsigned AddressSpace = GV->getType()->getAddressSpace())
  2083. Out << "addrspace(" << AddressSpace << ") ";
  2084. if (GV->isExternallyInitialized()) Out << "externally_initialized ";
  2085. Out << (GV->isConstant() ? "constant " : "global ");
  2086. TypePrinter.print(GV->getType()->getElementType(), Out);
  2087. if (GV->hasInitializer()) {
  2088. Out << ' ';
  2089. writeOperand(GV->getInitializer(), false);
  2090. }
  2091. if (GV->hasSection()) {
  2092. Out << ", section \"";
  2093. PrintEscapedString(GV->getSection(), Out);
  2094. Out << '"';
  2095. }
  2096. maybePrintComdat(Out, *GV);
  2097. if (GV->getAlignment())
  2098. Out << ", align " << GV->getAlignment();
  2099. printInfoComment(*GV);
  2100. }
  2101. void AssemblyWriter::printAlias(const GlobalAlias *GA) {
  2102. if (GA->isMaterializable())
  2103. Out << "; Materializable\n";
  2104. WriteAsOperandInternal(Out, GA, &TypePrinter, &Machine, GA->getParent());
  2105. Out << " = ";
  2106. PrintLinkage(GA->getLinkage(), Out);
  2107. PrintVisibility(GA->getVisibility(), Out);
  2108. PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
  2109. PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
  2110. if (GA->hasUnnamedAddr())
  2111. Out << "unnamed_addr ";
  2112. Out << "alias ";
  2113. const Constant *Aliasee = GA->getAliasee();
  2114. if (!Aliasee) {
  2115. TypePrinter.print(GA->getType(), Out);
  2116. Out << " <<NULL ALIASEE>>";
  2117. } else {
  2118. writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
  2119. }
  2120. printInfoComment(*GA);
  2121. Out << '\n';
  2122. }
  2123. void AssemblyWriter::printComdat(const Comdat *C) {
  2124. C->print(Out);
  2125. }
  2126. void AssemblyWriter::printTypeIdentities() {
  2127. if (TypePrinter.NumberedTypes.empty() &&
  2128. TypePrinter.NamedTypes.empty())
  2129. return;
  2130. Out << '\n';
  2131. // We know all the numbers that each type is used and we know that it is a
  2132. // dense assignment. Convert the map to an index table.
  2133. std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
  2134. for (DenseMap<StructType*, unsigned>::iterator I =
  2135. TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
  2136. I != E; ++I) {
  2137. assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
  2138. NumberedTypes[I->second] = I->first;
  2139. }
  2140. // Emit all numbered types.
  2141. for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
  2142. Out << '%' << i << " = type ";
  2143. // Make sure we print out at least one level of the type structure, so
  2144. // that we do not get %2 = type %2
  2145. TypePrinter.printStructBody(NumberedTypes[i], Out);
  2146. Out << '\n';
  2147. }
  2148. for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
  2149. PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
  2150. Out << " = type ";
  2151. // Make sure we print out at least one level of the type structure, so
  2152. // that we do not get %FILE = type %FILE
  2153. TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
  2154. Out << '\n';
  2155. }
  2156. }
  2157. /// printFunction - Print all aspects of a function.
  2158. ///
  2159. void AssemblyWriter::printFunction(const Function *F) {
  2160. // Print out the return type and name.
  2161. Out << '\n';
  2162. if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
  2163. if (F->isMaterializable())
  2164. Out << "; Materializable\n";
  2165. const AttributeSet &Attrs = F->getAttributes();
  2166. if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
  2167. AttributeSet AS = Attrs.getFnAttributes();
  2168. std::string AttrStr;
  2169. unsigned Idx = 0;
  2170. for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
  2171. if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
  2172. break;
  2173. for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
  2174. I != E; ++I) {
  2175. Attribute Attr = *I;
  2176. if (!Attr.isStringAttribute()) {
  2177. if (!AttrStr.empty()) AttrStr += ' ';
  2178. AttrStr += Attr.getAsString();
  2179. }
  2180. }
  2181. if (!AttrStr.empty())
  2182. Out << "; Function Attrs: " << AttrStr << '\n';
  2183. }
  2184. if (F->isDeclaration())
  2185. Out << "declare ";
  2186. else
  2187. Out << "define ";
  2188. PrintLinkage(F->getLinkage(), Out);
  2189. PrintVisibility(F->getVisibility(), Out);
  2190. PrintDLLStorageClass(F->getDLLStorageClass(), Out);
  2191. // Print the calling convention.
  2192. if (F->getCallingConv() != CallingConv::C) {
  2193. PrintCallingConv(F->getCallingConv(), Out);
  2194. Out << " ";
  2195. }
  2196. FunctionType *FT = F->getFunctionType();
  2197. if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
  2198. Out << Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
  2199. TypePrinter.print(F->getReturnType(), Out);
  2200. Out << ' ';
  2201. WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
  2202. Out << '(';
  2203. Machine.incorporateFunction(F);
  2204. // Loop over the arguments, printing them...
  2205. unsigned Idx = 1;
  2206. if (!F->isDeclaration()) {
  2207. // If this isn't a declaration, print the argument names as well.
  2208. for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
  2209. I != E; ++I) {
  2210. // Insert commas as we go... the first arg doesn't get a comma
  2211. if (I != F->arg_begin()) Out << ", ";
  2212. printArgument(I, Attrs, Idx);
  2213. Idx++;
  2214. }
  2215. } else {
  2216. // Otherwise, print the types from the function type.
  2217. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  2218. // Insert commas as we go... the first arg doesn't get a comma
  2219. if (i) Out << ", ";
  2220. // Output type...
  2221. TypePrinter.print(FT->getParamType(i), Out);
  2222. if (Attrs.hasAttributes(i+1))
  2223. Out << ' ' << Attrs.getAsString(i+1);
  2224. }
  2225. }
  2226. // Finish printing arguments...
  2227. if (FT->isVarArg()) {
  2228. if (FT->getNumParams()) Out << ", ";
  2229. Out << "..."; // Output varargs portion of signature!
  2230. }
  2231. Out << ')';
  2232. if (F->hasUnnamedAddr())
  2233. Out << " unnamed_addr";
  2234. if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
  2235. Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
  2236. if (F->hasSection()) {
  2237. Out << " section \"";
  2238. PrintEscapedString(F->getSection(), Out);
  2239. Out << '"';
  2240. }
  2241. maybePrintComdat(Out, *F);
  2242. if (F->getAlignment())
  2243. Out << " align " << F->getAlignment();
  2244. if (F->hasGC())
  2245. Out << " gc \"" << F->getGC() << '"';
  2246. if (F->hasPrefixData()) {
  2247. Out << " prefix ";
  2248. writeOperand(F->getPrefixData(), true);
  2249. }
  2250. if (F->hasPrologueData()) {
  2251. Out << " prologue ";
  2252. writeOperand(F->getPrologueData(), true);
  2253. }
  2254. if (F->hasPersonalityFn()) {
  2255. Out << " personality ";
  2256. writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
  2257. }
  2258. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  2259. F->getAllMetadata(MDs);
  2260. printMetadataAttachments(MDs, " ");
  2261. if (F->isDeclaration()) {
  2262. Out << '\n';
  2263. } else {
  2264. Out << " {";
  2265. // Output all of the function's basic blocks.
  2266. for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
  2267. printBasicBlock(I);
  2268. // Output the function's use-lists.
  2269. printUseLists(F);
  2270. Out << "}\n";
  2271. }
  2272. Machine.purgeFunction();
  2273. }
  2274. /// printArgument - This member is called for every argument that is passed into
  2275. /// the function. Simply print it out
  2276. ///
  2277. void AssemblyWriter::printArgument(const Argument *Arg,
  2278. AttributeSet Attrs, unsigned Idx) {
  2279. // Output type...
  2280. TypePrinter.print(Arg->getType(), Out);
  2281. // Output parameter attributes list
  2282. if (Attrs.hasAttributes(Idx))
  2283. Out << ' ' << Attrs.getAsString(Idx);
  2284. // Output name, if available...
  2285. if (Arg->hasName()) {
  2286. Out << ' ';
  2287. PrintLLVMName(Out, Arg);
  2288. }
  2289. }
  2290. /// printBasicBlock - This member is called for each basic block in a method.
  2291. ///
  2292. void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
  2293. if (BB->hasName()) { // Print out the label if it exists...
  2294. Out << "\n";
  2295. PrintLLVMName(Out, BB->getName(), LabelPrefix);
  2296. Out << ':';
  2297. } else if (!BB->use_empty()) { // Don't print block # of no uses...
  2298. Out << "\n; <label>:";
  2299. int Slot = Machine.getLocalSlot(BB);
  2300. if (Slot != -1)
  2301. Out << Slot;
  2302. else
  2303. Out << "<badref>";
  2304. }
  2305. if (!BB->getParent()) {
  2306. Out.PadToColumn(50);
  2307. Out << "; Error: Block without parent!";
  2308. } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
  2309. // Output predecessors for the block.
  2310. Out.PadToColumn(50);
  2311. Out << ";";
  2312. const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
  2313. if (PI == PE) {
  2314. Out << " No predecessors!";
  2315. } else {
  2316. Out << " preds = ";
  2317. writeOperand(*PI, false);
  2318. for (++PI; PI != PE; ++PI) {
  2319. Out << ", ";
  2320. writeOperand(*PI, false);
  2321. }
  2322. }
  2323. }
  2324. Out << "\n";
  2325. if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
  2326. // Output all of the instructions in the basic block...
  2327. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  2328. printInstructionLine(*I);
  2329. }
  2330. if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
  2331. }
  2332. /// printInstructionLine - Print an instruction and a newline character.
  2333. void AssemblyWriter::printInstructionLine(const Instruction &I) {
  2334. printInstruction(I);
  2335. Out << '\n';
  2336. }
  2337. /// printGCRelocateComment - print comment after call to the gc.relocate
  2338. /// intrinsic indicating base and derived pointer names.
  2339. void AssemblyWriter::printGCRelocateComment(const Value &V) {
  2340. assert(isGCRelocate(&V));
  2341. GCRelocateOperands GCOps(cast<Instruction>(&V));
  2342. Out << " ; (";
  2343. writeOperand(GCOps.getBasePtr(), false);
  2344. Out << ", ";
  2345. writeOperand(GCOps.getDerivedPtr(), false);
  2346. Out << ")";
  2347. }
  2348. /// printInfoComment - Print a little comment after the instruction indicating
  2349. /// which slot it occupies.
  2350. ///
  2351. void AssemblyWriter::printInfoComment(const Value &V) {
  2352. if (isGCRelocate(&V))
  2353. printGCRelocateComment(V);
  2354. if (AnnotationWriter)
  2355. AnnotationWriter->printInfoComment(V, Out);
  2356. }
  2357. // This member is called for each Instruction in a function..
  2358. void AssemblyWriter::printInstruction(const Instruction &I) {
  2359. if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
  2360. // Print out indentation for an instruction.
  2361. Out << " ";
  2362. // Print out name if it exists...
  2363. if (I.hasName()) {
  2364. PrintLLVMName(Out, &I);
  2365. Out << " = ";
  2366. } else if (!I.getType()->isVoidTy()) {
  2367. // Print out the def slot taken.
  2368. int SlotNum = Machine.getLocalSlot(&I);
  2369. if (SlotNum == -1)
  2370. Out << "<badref> = ";
  2371. else
  2372. Out << '%' << SlotNum << " = ";
  2373. }
  2374. if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
  2375. if (CI->isMustTailCall())
  2376. Out << "musttail ";
  2377. else if (CI->isTailCall())
  2378. Out << "tail ";
  2379. }
  2380. // Print out the opcode...
  2381. Out << I.getOpcodeName();
  2382. // If this is an atomic load or store, print out the atomic marker.
  2383. if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
  2384. (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
  2385. Out << " atomic";
  2386. if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
  2387. Out << " weak";
  2388. // If this is a volatile operation, print out the volatile marker.
  2389. if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
  2390. (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
  2391. (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
  2392. (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
  2393. Out << " volatile";
  2394. // Print out optimization information.
  2395. WriteOptimizationInfo(Out, &I);
  2396. // Print out the compare instruction predicates
  2397. if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
  2398. Out << ' ' << getPredicateText(CI->getPredicate());
  2399. // Print out the atomicrmw operation
  2400. if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
  2401. writeAtomicRMWOperation(Out, RMWI->getOperation());
  2402. // Print out the type of the operands...
  2403. const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
  2404. // Special case conditional branches to swizzle the condition out to the front
  2405. if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
  2406. const BranchInst &BI(cast<BranchInst>(I));
  2407. Out << ' ';
  2408. writeOperand(BI.getCondition(), true);
  2409. Out << ", ";
  2410. writeOperand(BI.getSuccessor(0), true);
  2411. Out << ", ";
  2412. writeOperand(BI.getSuccessor(1), true);
  2413. } else if (isa<SwitchInst>(I)) {
  2414. const SwitchInst& SI(cast<SwitchInst>(I));
  2415. // Special case switch instruction to get formatting nice and correct.
  2416. Out << ' ';
  2417. writeOperand(SI.getCondition(), true);
  2418. Out << ", ";
  2419. writeOperand(SI.getDefaultDest(), true);
  2420. Out << " [";
  2421. for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
  2422. i != e; ++i) {
  2423. Out << "\n ";
  2424. writeOperand(i.getCaseValue(), true);
  2425. Out << ", ";
  2426. writeOperand(i.getCaseSuccessor(), true);
  2427. }
  2428. Out << "\n ]";
  2429. } else if (isa<IndirectBrInst>(I)) {
  2430. // Special case indirectbr instruction to get formatting nice and correct.
  2431. Out << ' ';
  2432. writeOperand(Operand, true);
  2433. Out << ", [";
  2434. for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
  2435. if (i != 1)
  2436. Out << ", ";
  2437. writeOperand(I.getOperand(i), true);
  2438. }
  2439. Out << ']';
  2440. } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
  2441. Out << ' ';
  2442. TypePrinter.print(I.getType(), Out);
  2443. Out << ' ';
  2444. for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
  2445. if (op) Out << ", ";
  2446. Out << "[ ";
  2447. writeOperand(PN->getIncomingValue(op), false); Out << ", ";
  2448. writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
  2449. }
  2450. } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
  2451. Out << ' ';
  2452. writeOperand(I.getOperand(0), true);
  2453. for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
  2454. Out << ", " << *i;
  2455. } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
  2456. Out << ' ';
  2457. writeOperand(I.getOperand(0), true); Out << ", ";
  2458. writeOperand(I.getOperand(1), true);
  2459. for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
  2460. Out << ", " << *i;
  2461. } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
  2462. Out << ' ';
  2463. TypePrinter.print(I.getType(), Out);
  2464. if (LPI->isCleanup() || LPI->getNumClauses() != 0)
  2465. Out << '\n';
  2466. if (LPI->isCleanup())
  2467. Out << " cleanup";
  2468. for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
  2469. if (i != 0 || LPI->isCleanup()) Out << "\n";
  2470. if (LPI->isCatch(i))
  2471. Out << " catch ";
  2472. else
  2473. Out << " filter ";
  2474. writeOperand(LPI->getClause(i), true);
  2475. }
  2476. } else if (isa<ReturnInst>(I) && !Operand) {
  2477. Out << " void";
  2478. } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
  2479. // Print the calling convention being used.
  2480. if (CI->getCallingConv() != CallingConv::C) {
  2481. Out << " ";
  2482. PrintCallingConv(CI->getCallingConv(), Out);
  2483. }
  2484. Operand = CI->getCalledValue();
  2485. FunctionType *FTy = cast<FunctionType>(CI->getFunctionType());
  2486. Type *RetTy = FTy->getReturnType();
  2487. const AttributeSet &PAL = CI->getAttributes();
  2488. if (PAL.hasAttributes(AttributeSet::ReturnIndex))
  2489. Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
  2490. // If possible, print out the short form of the call instruction. We can
  2491. // only do this if the first argument is a pointer to a nonvararg function,
  2492. // and if the return type is not a pointer to a function.
  2493. //
  2494. Out << ' ';
  2495. TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
  2496. Out << ' ';
  2497. writeOperand(Operand, false);
  2498. Out << '(';
  2499. for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
  2500. if (op > 0)
  2501. Out << ", ";
  2502. writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
  2503. }
  2504. // Emit an ellipsis if this is a musttail call in a vararg function. This
  2505. // is only to aid readability, musttail calls forward varargs by default.
  2506. if (CI->isMustTailCall() && CI->getParent() &&
  2507. CI->getParent()->getParent() &&
  2508. CI->getParent()->getParent()->isVarArg())
  2509. Out << ", ...";
  2510. Out << ')';
  2511. if (PAL.hasAttributes(AttributeSet::FunctionIndex))
  2512. Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
  2513. } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
  2514. Operand = II->getCalledValue();
  2515. FunctionType *FTy = cast<FunctionType>(II->getFunctionType());
  2516. Type *RetTy = FTy->getReturnType();
  2517. const AttributeSet &PAL = II->getAttributes();
  2518. // Print the calling convention being used.
  2519. if (II->getCallingConv() != CallingConv::C) {
  2520. Out << " ";
  2521. PrintCallingConv(II->getCallingConv(), Out);
  2522. }
  2523. if (PAL.hasAttributes(AttributeSet::ReturnIndex))
  2524. Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
  2525. // If possible, print out the short form of the invoke instruction. We can
  2526. // only do this if the first argument is a pointer to a nonvararg function,
  2527. // and if the return type is not a pointer to a function.
  2528. //
  2529. Out << ' ';
  2530. TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
  2531. Out << ' ';
  2532. writeOperand(Operand, false);
  2533. Out << '(';
  2534. for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
  2535. if (op)
  2536. Out << ", ";
  2537. writeParamOperand(II->getArgOperand(op), PAL, op + 1);
  2538. }
  2539. Out << ')';
  2540. if (PAL.hasAttributes(AttributeSet::FunctionIndex))
  2541. Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
  2542. Out << "\n to ";
  2543. writeOperand(II->getNormalDest(), true);
  2544. Out << " unwind ";
  2545. writeOperand(II->getUnwindDest(), true);
  2546. } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
  2547. Out << ' ';
  2548. if (AI->isUsedWithInAlloca())
  2549. Out << "inalloca ";
  2550. TypePrinter.print(AI->getAllocatedType(), Out);
  2551. // Explicitly write the array size if the code is broken, if it's an array
  2552. // allocation, or if the type is not canonical for scalar allocations. The
  2553. // latter case prevents the type from mutating when round-tripping through
  2554. // assembly.
  2555. if (!AI->getArraySize() || AI->isArrayAllocation() ||
  2556. !AI->getArraySize()->getType()->isIntegerTy(32)) {
  2557. Out << ", ";
  2558. writeOperand(AI->getArraySize(), true);
  2559. }
  2560. if (AI->getAlignment()) {
  2561. Out << ", align " << AI->getAlignment();
  2562. }
  2563. } else if (isa<CastInst>(I)) {
  2564. if (Operand) {
  2565. Out << ' ';
  2566. writeOperand(Operand, true); // Work with broken code
  2567. }
  2568. Out << " to ";
  2569. TypePrinter.print(I.getType(), Out);
  2570. } else if (isa<VAArgInst>(I)) {
  2571. if (Operand) {
  2572. Out << ' ';
  2573. writeOperand(Operand, true); // Work with broken code
  2574. }
  2575. Out << ", ";
  2576. TypePrinter.print(I.getType(), Out);
  2577. } else if (Operand) { // Print the normal way.
  2578. if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
  2579. Out << ' ';
  2580. TypePrinter.print(GEP->getSourceElementType(), Out);
  2581. Out << ',';
  2582. } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
  2583. Out << ' ';
  2584. TypePrinter.print(LI->getType(), Out);
  2585. Out << ',';
  2586. }
  2587. // PrintAllTypes - Instructions who have operands of all the same type
  2588. // omit the type from all but the first operand. If the instruction has
  2589. // different type operands (for example br), then they are all printed.
  2590. bool PrintAllTypes = false;
  2591. Type *TheType = Operand->getType();
  2592. // Select, Store and ShuffleVector always print all types.
  2593. if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
  2594. || isa<ReturnInst>(I)) {
  2595. PrintAllTypes = true;
  2596. } else {
  2597. for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
  2598. Operand = I.getOperand(i);
  2599. // note that Operand shouldn't be null, but the test helps make dump()
  2600. // more tolerant of malformed IR
  2601. if (Operand && Operand->getType() != TheType) {
  2602. PrintAllTypes = true; // We have differing types! Print them all!
  2603. break;
  2604. }
  2605. }
  2606. }
  2607. if (!PrintAllTypes) {
  2608. Out << ' ';
  2609. TypePrinter.print(TheType, Out);
  2610. }
  2611. Out << ' ';
  2612. for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
  2613. if (i) Out << ", ";
  2614. writeOperand(I.getOperand(i), PrintAllTypes);
  2615. }
  2616. }
  2617. // Print atomic ordering/alignment for memory operations
  2618. if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
  2619. if (LI->isAtomic())
  2620. writeAtomic(LI->getOrdering(), LI->getSynchScope());
  2621. if (LI->getAlignment())
  2622. Out << ", align " << LI->getAlignment();
  2623. } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
  2624. if (SI->isAtomic())
  2625. writeAtomic(SI->getOrdering(), SI->getSynchScope());
  2626. if (SI->getAlignment())
  2627. Out << ", align " << SI->getAlignment();
  2628. } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
  2629. writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
  2630. CXI->getSynchScope());
  2631. } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
  2632. writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
  2633. } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
  2634. writeAtomic(FI->getOrdering(), FI->getSynchScope());
  2635. }
  2636. // Print Metadata info.
  2637. SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
  2638. I.getAllMetadata(InstMD);
  2639. printMetadataAttachments(InstMD, ", ");
  2640. // Print a nice comment.
  2641. printInfoComment(I);
  2642. }
  2643. void AssemblyWriter::printMetadataAttachments(
  2644. const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
  2645. StringRef Separator) {
  2646. if (MDs.empty())
  2647. return;
  2648. if (MDNames.empty())
  2649. TheModule->getMDKindNames(MDNames);
  2650. for (const auto &I : MDs) {
  2651. unsigned Kind = I.first;
  2652. Out << Separator;
  2653. if (Kind < MDNames.size()) {
  2654. Out << "!";
  2655. printMetadataIdentifier(MDNames[Kind], Out);
  2656. } else
  2657. Out << "!<unknown kind #" << Kind << ">";
  2658. Out << ' ';
  2659. WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
  2660. }
  2661. }
  2662. void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
  2663. Out << '!' << Slot << " = ";
  2664. printMDNodeBody(Node);
  2665. Out << "\n";
  2666. }
  2667. void AssemblyWriter::writeAllMDNodes() {
  2668. SmallVector<const MDNode *, 16> Nodes;
  2669. Nodes.resize(Machine.mdn_size());
  2670. for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
  2671. I != E; ++I)
  2672. Nodes[I->second] = cast<MDNode>(I->first);
  2673. for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
  2674. writeMDNode(i, Nodes[i]);
  2675. }
  2676. }
  2677. void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
  2678. WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
  2679. }
  2680. void AssemblyWriter::writeAllAttributeGroups() {
  2681. std::vector<std::pair<AttributeSet, unsigned> > asVec;
  2682. asVec.resize(Machine.as_size());
  2683. for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
  2684. I != E; ++I)
  2685. asVec[I->second] = *I;
  2686. for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
  2687. I = asVec.begin(), E = asVec.end(); I != E; ++I)
  2688. Out << "attributes #" << I->second << " = { "
  2689. << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
  2690. }
  2691. void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
  2692. bool IsInFunction = Machine.getFunction();
  2693. if (IsInFunction)
  2694. Out << " ";
  2695. Out << "uselistorder";
  2696. if (const BasicBlock *BB =
  2697. IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
  2698. Out << "_bb ";
  2699. writeOperand(BB->getParent(), false);
  2700. Out << ", ";
  2701. writeOperand(BB, false);
  2702. } else {
  2703. Out << " ";
  2704. writeOperand(Order.V, true);
  2705. }
  2706. Out << ", { ";
  2707. assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
  2708. Out << Order.Shuffle[0];
  2709. for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
  2710. Out << ", " << Order.Shuffle[I];
  2711. Out << " }\n";
  2712. }
  2713. void AssemblyWriter::printUseLists(const Function *F) {
  2714. auto hasMore =
  2715. [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
  2716. if (!hasMore())
  2717. // Nothing to do.
  2718. return;
  2719. Out << "\n; uselistorder directives\n";
  2720. while (hasMore()) {
  2721. printUseListOrder(UseListOrders.back());
  2722. UseListOrders.pop_back();
  2723. }
  2724. }
  2725. //===----------------------------------------------------------------------===//
  2726. // External Interface declarations
  2727. //===----------------------------------------------------------------------===//
  2728. void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
  2729. SlotTracker SlotTable(this->getParent());
  2730. formatted_raw_ostream OS(ROS);
  2731. AssemblyWriter W(OS, SlotTable, this->getParent(), AAW);
  2732. W.printFunction(this);
  2733. }
  2734. void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
  2735. bool ShouldPreserveUseListOrder) const {
  2736. SlotTracker SlotTable(this);
  2737. formatted_raw_ostream OS(ROS);
  2738. AssemblyWriter W(OS, SlotTable, this, AAW, ShouldPreserveUseListOrder);
  2739. W.printModule(this);
  2740. }
  2741. void NamedMDNode::print(raw_ostream &ROS) const {
  2742. SlotTracker SlotTable(getParent());
  2743. formatted_raw_ostream OS(ROS);
  2744. AssemblyWriter W(OS, SlotTable, getParent(), nullptr);
  2745. W.printNamedMDNode(this);
  2746. }
  2747. void Comdat::print(raw_ostream &ROS) const {
  2748. PrintLLVMName(ROS, getName(), ComdatPrefix);
  2749. ROS << " = comdat ";
  2750. switch (getSelectionKind()) {
  2751. case Comdat::Any:
  2752. ROS << "any";
  2753. break;
  2754. case Comdat::ExactMatch:
  2755. ROS << "exactmatch";
  2756. break;
  2757. case Comdat::Largest:
  2758. ROS << "largest";
  2759. break;
  2760. case Comdat::NoDuplicates:
  2761. ROS << "noduplicates";
  2762. break;
  2763. case Comdat::SameSize:
  2764. ROS << "samesize";
  2765. break;
  2766. }
  2767. ROS << '\n';
  2768. }
  2769. void Type::print(raw_ostream &OS) const {
  2770. TypePrinting TP;
  2771. TP.print(const_cast<Type*>(this), OS);
  2772. // If the type is a named struct type, print the body as well.
  2773. if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
  2774. if (!STy->isLiteral()) {
  2775. OS << " = type ";
  2776. TP.printStructBody(STy, OS);
  2777. }
  2778. }
  2779. static bool isReferencingMDNode(const Instruction &I) {
  2780. if (const auto *CI = dyn_cast<CallInst>(&I))
  2781. if (Function *F = CI->getCalledFunction())
  2782. if (F->isIntrinsic())
  2783. for (auto &Op : I.operands())
  2784. if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
  2785. if (isa<MDNode>(V->getMetadata()))
  2786. return true;
  2787. return false;
  2788. }
  2789. void Value::print(raw_ostream &ROS) const {
  2790. bool ShouldInitializeAllMetadata = false;
  2791. if (auto *I = dyn_cast<Instruction>(this))
  2792. ShouldInitializeAllMetadata = isReferencingMDNode(*I);
  2793. else if (isa<Function>(this) || isa<MetadataAsValue>(this))
  2794. ShouldInitializeAllMetadata = true;
  2795. ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
  2796. print(ROS, MST);
  2797. }
  2798. void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST) const {
  2799. formatted_raw_ostream OS(ROS);
  2800. SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
  2801. SlotTracker &SlotTable =
  2802. MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
  2803. auto incorporateFunction = [&](const Function *F) {
  2804. if (F)
  2805. MST.incorporateFunction(*F);
  2806. };
  2807. if (const Instruction *I = dyn_cast<Instruction>(this)) {
  2808. incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
  2809. AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr);
  2810. W.printInstruction(*I);
  2811. } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
  2812. incorporateFunction(BB->getParent());
  2813. AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr);
  2814. W.printBasicBlock(BB);
  2815. } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
  2816. AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr);
  2817. if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
  2818. W.printGlobal(V);
  2819. else if (const Function *F = dyn_cast<Function>(GV))
  2820. W.printFunction(F);
  2821. else
  2822. W.printAlias(cast<GlobalAlias>(GV));
  2823. } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
  2824. V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
  2825. } else if (const Constant *C = dyn_cast<Constant>(this)) {
  2826. TypePrinting TypePrinter;
  2827. TypePrinter.print(C->getType(), OS);
  2828. OS << ' ';
  2829. WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
  2830. } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
  2831. this->printAsOperand(OS, /* PrintType */ true, MST);
  2832. } else {
  2833. llvm_unreachable("Unknown value to print out!");
  2834. }
  2835. }
  2836. /// Print without a type, skipping the TypePrinting object.
  2837. ///
  2838. /// \return \c true iff printing was succesful.
  2839. static bool printWithoutType(const Value &V, raw_ostream &O,
  2840. SlotTracker *Machine, const Module *M) {
  2841. if (V.hasName() || isa<GlobalValue>(V) ||
  2842. (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
  2843. WriteAsOperandInternal(O, &V, nullptr, Machine, M);
  2844. return true;
  2845. }
  2846. return false;
  2847. }
  2848. static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
  2849. ModuleSlotTracker &MST) {
  2850. TypePrinting TypePrinter;
  2851. if (const Module *M = MST.getModule())
  2852. TypePrinter.incorporateTypes(*M);
  2853. if (PrintType) {
  2854. TypePrinter.print(V.getType(), O);
  2855. O << ' ';
  2856. }
  2857. WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
  2858. MST.getModule());
  2859. }
  2860. void Value::printAsOperand(raw_ostream &O, bool PrintType,
  2861. const Module *M) const {
  2862. if (!M)
  2863. M = getModuleFromVal(this);
  2864. if (!PrintType)
  2865. if (printWithoutType(*this, O, nullptr, M))
  2866. return;
  2867. SlotTracker Machine(
  2868. M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
  2869. ModuleSlotTracker MST(Machine, M);
  2870. printAsOperandImpl(*this, O, PrintType, MST);
  2871. }
  2872. void Value::printAsOperand(raw_ostream &O, bool PrintType,
  2873. ModuleSlotTracker &MST) const {
  2874. if (!PrintType)
  2875. if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
  2876. return;
  2877. printAsOperandImpl(*this, O, PrintType, MST);
  2878. }
  2879. static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
  2880. ModuleSlotTracker &MST, const Module *M,
  2881. bool OnlyAsOperand) {
  2882. formatted_raw_ostream OS(ROS);
  2883. TypePrinting TypePrinter;
  2884. if (M)
  2885. TypePrinter.incorporateTypes(*M);
  2886. WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
  2887. /* FromValue */ true);
  2888. auto *N = dyn_cast<MDNode>(&MD);
  2889. if (OnlyAsOperand || !N)
  2890. return;
  2891. OS << " = ";
  2892. WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
  2893. }
  2894. void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
  2895. ModuleSlotTracker MST(M, isa<MDNode>(this));
  2896. printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
  2897. }
  2898. void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
  2899. const Module *M) const {
  2900. printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
  2901. }
  2902. void Metadata::print(raw_ostream &OS, const Module *M) const {
  2903. ModuleSlotTracker MST(M, isa<MDNode>(this));
  2904. printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
  2905. }
  2906. void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
  2907. const Module *M) const {
  2908. printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
  2909. }
  2910. // Value::dump - allow easy printing of Values from the debugger.
  2911. LLVM_DUMP_METHOD
  2912. void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
  2913. // Type::dump - allow easy printing of Types from the debugger.
  2914. LLVM_DUMP_METHOD
  2915. void Type::dump() const { print(dbgs()); dbgs() << '\n'; }
  2916. // Module::dump() - Allow printing of Modules from the debugger.
  2917. LLVM_DUMP_METHOD
  2918. void Module::dump() const { print(dbgs(), nullptr); }
  2919. // \brief Allow printing of Comdats from the debugger.
  2920. LLVM_DUMP_METHOD
  2921. void Comdat::dump() const { print(dbgs()); }
  2922. // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
  2923. LLVM_DUMP_METHOD
  2924. void NamedMDNode::dump() const { print(dbgs()); }
  2925. LLVM_DUMP_METHOD
  2926. void Metadata::dump() const { dump(nullptr); }
  2927. LLVM_DUMP_METHOD
  2928. void Metadata::dump(const Module *M) const {
  2929. print(dbgs(), M);
  2930. dbgs() << '\n';
  2931. }