AsmWriter.cpp 157 KB

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