AsmPrinter.cpp 149 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054
  1. //===- AsmPrinter.cpp - Common AsmPrinter code ----------------------------===//
  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 file implements the AsmPrinter class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/CodeGen/AsmPrinter.h"
  13. #include "CodeViewDebug.h"
  14. #include "DwarfDebug.h"
  15. #include "DwarfException.h"
  16. #include "PseudoProbePrinter.h"
  17. #include "WasmException.h"
  18. #include "WinCFGuard.h"
  19. #include "WinException.h"
  20. #include "llvm/ADT/APFloat.h"
  21. #include "llvm/ADT/APInt.h"
  22. #include "llvm/ADT/DenseMap.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/ADT/SmallPtrSet.h"
  25. #include "llvm/ADT/SmallString.h"
  26. #include "llvm/ADT/SmallVector.h"
  27. #include "llvm/ADT/Statistic.h"
  28. #include "llvm/ADT/StringRef.h"
  29. #include "llvm/ADT/TinyPtrVector.h"
  30. #include "llvm/ADT/Triple.h"
  31. #include "llvm/ADT/Twine.h"
  32. #include "llvm/Analysis/ConstantFolding.h"
  33. #include "llvm/Analysis/EHPersonalities.h"
  34. #include "llvm/Analysis/MemoryLocation.h"
  35. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  36. #include "llvm/BinaryFormat/COFF.h"
  37. #include "llvm/BinaryFormat/Dwarf.h"
  38. #include "llvm/BinaryFormat/ELF.h"
  39. #include "llvm/CodeGen/GCMetadata.h"
  40. #include "llvm/CodeGen/GCMetadataPrinter.h"
  41. #include "llvm/CodeGen/MachineBasicBlock.h"
  42. #include "llvm/CodeGen/MachineConstantPool.h"
  43. #include "llvm/CodeGen/MachineDominators.h"
  44. #include "llvm/CodeGen/MachineFrameInfo.h"
  45. #include "llvm/CodeGen/MachineFunction.h"
  46. #include "llvm/CodeGen/MachineFunctionPass.h"
  47. #include "llvm/CodeGen/MachineInstr.h"
  48. #include "llvm/CodeGen/MachineInstrBundle.h"
  49. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  50. #include "llvm/CodeGen/MachineLoopInfo.h"
  51. #include "llvm/CodeGen/MachineModuleInfo.h"
  52. #include "llvm/CodeGen/MachineModuleInfoImpls.h"
  53. #include "llvm/CodeGen/MachineOperand.h"
  54. #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
  55. #include "llvm/CodeGen/StackMaps.h"
  56. #include "llvm/CodeGen/TargetFrameLowering.h"
  57. #include "llvm/CodeGen/TargetInstrInfo.h"
  58. #include "llvm/CodeGen/TargetLowering.h"
  59. #include "llvm/CodeGen/TargetOpcodes.h"
  60. #include "llvm/CodeGen/TargetRegisterInfo.h"
  61. #include "llvm/Config/config.h"
  62. #include "llvm/IR/BasicBlock.h"
  63. #include "llvm/IR/Comdat.h"
  64. #include "llvm/IR/Constant.h"
  65. #include "llvm/IR/Constants.h"
  66. #include "llvm/IR/DataLayout.h"
  67. #include "llvm/IR/DebugInfoMetadata.h"
  68. #include "llvm/IR/DerivedTypes.h"
  69. #include "llvm/IR/Function.h"
  70. #include "llvm/IR/GCStrategy.h"
  71. #include "llvm/IR/GlobalAlias.h"
  72. #include "llvm/IR/GlobalIFunc.h"
  73. #include "llvm/IR/GlobalObject.h"
  74. #include "llvm/IR/GlobalValue.h"
  75. #include "llvm/IR/GlobalVariable.h"
  76. #include "llvm/IR/Instruction.h"
  77. #include "llvm/IR/Mangler.h"
  78. #include "llvm/IR/Metadata.h"
  79. #include "llvm/IR/Module.h"
  80. #include "llvm/IR/Operator.h"
  81. #include "llvm/IR/PseudoProbe.h"
  82. #include "llvm/IR/Type.h"
  83. #include "llvm/IR/Value.h"
  84. #include "llvm/IR/ValueHandle.h"
  85. #include "llvm/MC/MCAsmInfo.h"
  86. #include "llvm/MC/MCContext.h"
  87. #include "llvm/MC/MCDirectives.h"
  88. #include "llvm/MC/MCExpr.h"
  89. #include "llvm/MC/MCInst.h"
  90. #include "llvm/MC/MCSection.h"
  91. #include "llvm/MC/MCSectionCOFF.h"
  92. #include "llvm/MC/MCSectionELF.h"
  93. #include "llvm/MC/MCSectionMachO.h"
  94. #include "llvm/MC/MCStreamer.h"
  95. #include "llvm/MC/MCSubtargetInfo.h"
  96. #include "llvm/MC/MCSymbol.h"
  97. #include "llvm/MC/MCSymbolELF.h"
  98. #include "llvm/MC/MCTargetOptions.h"
  99. #include "llvm/MC/MCValue.h"
  100. #include "llvm/MC/SectionKind.h"
  101. #include "llvm/Pass.h"
  102. #include "llvm/Remarks/RemarkStreamer.h"
  103. #include "llvm/Support/Casting.h"
  104. #include "llvm/Support/Compiler.h"
  105. #include "llvm/Support/ErrorHandling.h"
  106. #include "llvm/Support/FileSystem.h"
  107. #include "llvm/Support/Format.h"
  108. #include "llvm/Support/MathExtras.h"
  109. #include "llvm/Support/Path.h"
  110. #include "llvm/Support/Timer.h"
  111. #include "llvm/Support/raw_ostream.h"
  112. #include "llvm/Target/TargetLoweringObjectFile.h"
  113. #include "llvm/Target/TargetMachine.h"
  114. #include "llvm/Target/TargetOptions.h"
  115. #include <algorithm>
  116. #include <cassert>
  117. #include <cinttypes>
  118. #include <cstdint>
  119. #include <iterator>
  120. #include <memory>
  121. #include <optional>
  122. #include <string>
  123. #include <utility>
  124. #include <vector>
  125. using namespace llvm;
  126. #define DEBUG_TYPE "asm-printer"
  127. const char DWARFGroupName[] = "dwarf";
  128. const char DWARFGroupDescription[] = "DWARF Emission";
  129. const char DbgTimerName[] = "emit";
  130. const char DbgTimerDescription[] = "Debug Info Emission";
  131. const char EHTimerName[] = "write_exception";
  132. const char EHTimerDescription[] = "DWARF Exception Writer";
  133. const char CFGuardName[] = "Control Flow Guard";
  134. const char CFGuardDescription[] = "Control Flow Guard";
  135. const char CodeViewLineTablesGroupName[] = "linetables";
  136. const char CodeViewLineTablesGroupDescription[] = "CodeView Line Tables";
  137. const char PPTimerName[] = "emit";
  138. const char PPTimerDescription[] = "Pseudo Probe Emission";
  139. const char PPGroupName[] = "pseudo probe";
  140. const char PPGroupDescription[] = "Pseudo Probe Emission";
  141. STATISTIC(EmittedInsts, "Number of machine instrs printed");
  142. char AsmPrinter::ID = 0;
  143. namespace {
  144. class AddrLabelMapCallbackPtr final : CallbackVH {
  145. AddrLabelMap *Map = nullptr;
  146. public:
  147. AddrLabelMapCallbackPtr() = default;
  148. AddrLabelMapCallbackPtr(Value *V) : CallbackVH(V) {}
  149. void setPtr(BasicBlock *BB) {
  150. ValueHandleBase::operator=(BB);
  151. }
  152. void setMap(AddrLabelMap *map) { Map = map; }
  153. void deleted() override;
  154. void allUsesReplacedWith(Value *V2) override;
  155. };
  156. } // namespace
  157. class llvm::AddrLabelMap {
  158. MCContext &Context;
  159. struct AddrLabelSymEntry {
  160. /// The symbols for the label.
  161. TinyPtrVector<MCSymbol *> Symbols;
  162. Function *Fn; // The containing function of the BasicBlock.
  163. unsigned Index; // The index in BBCallbacks for the BasicBlock.
  164. };
  165. DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
  166. /// Callbacks for the BasicBlock's that we have entries for. We use this so
  167. /// we get notified if a block is deleted or RAUWd.
  168. std::vector<AddrLabelMapCallbackPtr> BBCallbacks;
  169. /// This is a per-function list of symbols whose corresponding BasicBlock got
  170. /// deleted. These symbols need to be emitted at some point in the file, so
  171. /// AsmPrinter emits them after the function body.
  172. DenseMap<AssertingVH<Function>, std::vector<MCSymbol *>>
  173. DeletedAddrLabelsNeedingEmission;
  174. public:
  175. AddrLabelMap(MCContext &context) : Context(context) {}
  176. ~AddrLabelMap() {
  177. assert(DeletedAddrLabelsNeedingEmission.empty() &&
  178. "Some labels for deleted blocks never got emitted");
  179. }
  180. ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB);
  181. void takeDeletedSymbolsForFunction(Function *F,
  182. std::vector<MCSymbol *> &Result);
  183. void UpdateForDeletedBlock(BasicBlock *BB);
  184. void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
  185. };
  186. ArrayRef<MCSymbol *> AddrLabelMap::getAddrLabelSymbolToEmit(BasicBlock *BB) {
  187. assert(BB->hasAddressTaken() &&
  188. "Shouldn't get label for block without address taken");
  189. AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
  190. // If we already had an entry for this block, just return it.
  191. if (!Entry.Symbols.empty()) {
  192. assert(BB->getParent() == Entry.Fn && "Parent changed");
  193. return Entry.Symbols;
  194. }
  195. // Otherwise, this is a new entry, create a new symbol for it and add an
  196. // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
  197. BBCallbacks.emplace_back(BB);
  198. BBCallbacks.back().setMap(this);
  199. Entry.Index = BBCallbacks.size() - 1;
  200. Entry.Fn = BB->getParent();
  201. MCSymbol *Sym = BB->hasAddressTaken() ? Context.createNamedTempSymbol()
  202. : Context.createTempSymbol();
  203. Entry.Symbols.push_back(Sym);
  204. return Entry.Symbols;
  205. }
  206. /// If we have any deleted symbols for F, return them.
  207. void AddrLabelMap::takeDeletedSymbolsForFunction(
  208. Function *F, std::vector<MCSymbol *> &Result) {
  209. DenseMap<AssertingVH<Function>, std::vector<MCSymbol *>>::iterator I =
  210. DeletedAddrLabelsNeedingEmission.find(F);
  211. // If there are no entries for the function, just return.
  212. if (I == DeletedAddrLabelsNeedingEmission.end())
  213. return;
  214. // Otherwise, take the list.
  215. std::swap(Result, I->second);
  216. DeletedAddrLabelsNeedingEmission.erase(I);
  217. }
  218. //===- Address of Block Management ----------------------------------------===//
  219. ArrayRef<MCSymbol *>
  220. AsmPrinter::getAddrLabelSymbolToEmit(const BasicBlock *BB) {
  221. // Lazily create AddrLabelSymbols.
  222. if (!AddrLabelSymbols)
  223. AddrLabelSymbols = std::make_unique<AddrLabelMap>(OutContext);
  224. return AddrLabelSymbols->getAddrLabelSymbolToEmit(
  225. const_cast<BasicBlock *>(BB));
  226. }
  227. void AsmPrinter::takeDeletedSymbolsForFunction(
  228. const Function *F, std::vector<MCSymbol *> &Result) {
  229. // If no blocks have had their addresses taken, we're done.
  230. if (!AddrLabelSymbols)
  231. return;
  232. return AddrLabelSymbols->takeDeletedSymbolsForFunction(
  233. const_cast<Function *>(F), Result);
  234. }
  235. void AddrLabelMap::UpdateForDeletedBlock(BasicBlock *BB) {
  236. // If the block got deleted, there is no need for the symbol. If the symbol
  237. // was already emitted, we can just forget about it, otherwise we need to
  238. // queue it up for later emission when the function is output.
  239. AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
  240. AddrLabelSymbols.erase(BB);
  241. assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
  242. BBCallbacks[Entry.Index] = nullptr; // Clear the callback.
  243. #if !LLVM_MEMORY_SANITIZER_BUILD
  244. // BasicBlock is destroyed already, so this access is UB detectable by msan.
  245. assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
  246. "Block/parent mismatch");
  247. #endif
  248. for (MCSymbol *Sym : Entry.Symbols) {
  249. if (Sym->isDefined())
  250. return;
  251. // If the block is not yet defined, we need to emit it at the end of the
  252. // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list
  253. // for the containing Function. Since the block is being deleted, its
  254. // parent may already be removed, we have to get the function from 'Entry'.
  255. DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
  256. }
  257. }
  258. void AddrLabelMap::UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New) {
  259. // Get the entry for the RAUW'd block and remove it from our map.
  260. AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
  261. AddrLabelSymbols.erase(Old);
  262. assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
  263. AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
  264. // If New is not address taken, just move our symbol over to it.
  265. if (NewEntry.Symbols.empty()) {
  266. BBCallbacks[OldEntry.Index].setPtr(New); // Update the callback.
  267. NewEntry = std::move(OldEntry); // Set New's entry.
  268. return;
  269. }
  270. BBCallbacks[OldEntry.Index] = nullptr; // Update the callback.
  271. // Otherwise, we need to add the old symbols to the new block's set.
  272. llvm::append_range(NewEntry.Symbols, OldEntry.Symbols);
  273. }
  274. void AddrLabelMapCallbackPtr::deleted() {
  275. Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
  276. }
  277. void AddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
  278. Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
  279. }
  280. /// getGVAlignment - Return the alignment to use for the specified global
  281. /// value. This rounds up to the preferred alignment if possible and legal.
  282. Align AsmPrinter::getGVAlignment(const GlobalObject *GV, const DataLayout &DL,
  283. Align InAlign) {
  284. Align Alignment;
  285. if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
  286. Alignment = DL.getPreferredAlign(GVar);
  287. // If InAlign is specified, round it to it.
  288. if (InAlign > Alignment)
  289. Alignment = InAlign;
  290. // If the GV has a specified alignment, take it into account.
  291. const MaybeAlign GVAlign(GV->getAlign());
  292. if (!GVAlign)
  293. return Alignment;
  294. assert(GVAlign && "GVAlign must be set");
  295. // If the GVAlign is larger than NumBits, or if we are required to obey
  296. // NumBits because the GV has an assigned section, obey it.
  297. if (*GVAlign > Alignment || GV->hasSection())
  298. Alignment = *GVAlign;
  299. return Alignment;
  300. }
  301. AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
  302. : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
  303. OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)),
  304. SM(*this) {
  305. VerboseAsm = OutStreamer->isVerboseAsm();
  306. DwarfUsesRelocationsAcrossSections =
  307. MAI->doesDwarfUseRelocationsAcrossSections();
  308. }
  309. AsmPrinter::~AsmPrinter() {
  310. assert(!DD && Handlers.size() == NumUserHandlers &&
  311. "Debug/EH info didn't get finalized");
  312. }
  313. bool AsmPrinter::isPositionIndependent() const {
  314. return TM.isPositionIndependent();
  315. }
  316. /// getFunctionNumber - Return a unique ID for the current function.
  317. unsigned AsmPrinter::getFunctionNumber() const {
  318. return MF->getFunctionNumber();
  319. }
  320. const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
  321. return *TM.getObjFileLowering();
  322. }
  323. const DataLayout &AsmPrinter::getDataLayout() const {
  324. return MMI->getModule()->getDataLayout();
  325. }
  326. // Do not use the cached DataLayout because some client use it without a Module
  327. // (dsymutil, llvm-dwarfdump).
  328. unsigned AsmPrinter::getPointerSize() const {
  329. return TM.getPointerSize(0); // FIXME: Default address space
  330. }
  331. const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
  332. assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
  333. return MF->getSubtarget<MCSubtargetInfo>();
  334. }
  335. void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
  336. S.emitInstruction(Inst, getSubtargetInfo());
  337. }
  338. void AsmPrinter::emitInitialRawDwarfLocDirective(const MachineFunction &MF) {
  339. if (DD) {
  340. assert(OutStreamer->hasRawTextSupport() &&
  341. "Expected assembly output mode.");
  342. // This is NVPTX specific and it's unclear why.
  343. // PR51079: If we have code without debug information we need to give up.
  344. DISubprogram *MFSP = MF.getFunction().getSubprogram();
  345. if (!MFSP)
  346. return;
  347. (void)DD->emitInitialLocDirective(MF, /*CUID=*/0);
  348. }
  349. }
  350. /// getCurrentSection() - Return the current section we are emitting to.
  351. const MCSection *AsmPrinter::getCurrentSection() const {
  352. return OutStreamer->getCurrentSectionOnly();
  353. }
  354. void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
  355. AU.setPreservesAll();
  356. MachineFunctionPass::getAnalysisUsage(AU);
  357. AU.addRequired<MachineOptimizationRemarkEmitterPass>();
  358. AU.addRequired<GCModuleInfo>();
  359. }
  360. bool AsmPrinter::doInitialization(Module &M) {
  361. auto *MMIWP = getAnalysisIfAvailable<MachineModuleInfoWrapperPass>();
  362. MMI = MMIWP ? &MMIWP->getMMI() : nullptr;
  363. HasSplitStack = false;
  364. HasNoSplitStack = false;
  365. AddrLabelSymbols = nullptr;
  366. // Initialize TargetLoweringObjectFile.
  367. const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
  368. .Initialize(OutContext, TM);
  369. const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
  370. .getModuleMetadata(M);
  371. OutStreamer->initSections(false, *TM.getMCSubtargetInfo());
  372. // Emit the version-min deployment target directive if needed.
  373. //
  374. // FIXME: If we end up with a collection of these sorts of Darwin-specific
  375. // or ELF-specific things, it may make sense to have a platform helper class
  376. // that will work with the target helper class. For now keep it here, as the
  377. // alternative is duplicated code in each of the target asm printers that
  378. // use the directive, where it would need the same conditionalization
  379. // anyway.
  380. const Triple &Target = TM.getTargetTriple();
  381. Triple TVT(M.getDarwinTargetVariantTriple());
  382. OutStreamer->emitVersionForTarget(
  383. Target, M.getSDKVersion(),
  384. M.getDarwinTargetVariantTriple().empty() ? nullptr : &TVT,
  385. M.getDarwinTargetVariantSDKVersion());
  386. // Allow the target to emit any magic that it wants at the start of the file.
  387. emitStartOfAsmFile(M);
  388. // Very minimal debug info. It is ignored if we emit actual debug info. If we
  389. // don't, this at least helps the user find where a global came from.
  390. if (MAI->hasSingleParameterDotFile()) {
  391. // .file "foo.c"
  392. SmallString<128> FileName;
  393. if (MAI->hasBasenameOnlyForFileDirective())
  394. FileName = llvm::sys::path::filename(M.getSourceFileName());
  395. else
  396. FileName = M.getSourceFileName();
  397. if (MAI->hasFourStringsDotFile()) {
  398. #ifdef PACKAGE_VENDOR
  399. const char VerStr[] =
  400. PACKAGE_VENDOR " " PACKAGE_NAME " version " PACKAGE_VERSION;
  401. #else
  402. const char VerStr[] = PACKAGE_NAME " version " PACKAGE_VERSION;
  403. #endif
  404. // TODO: Add timestamp and description.
  405. OutStreamer->emitFileDirective(FileName, VerStr, "", "");
  406. } else {
  407. OutStreamer->emitFileDirective(FileName);
  408. }
  409. }
  410. GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
  411. assert(MI && "AsmPrinter didn't require GCModuleInfo?");
  412. for (const auto &I : *MI)
  413. if (GCMetadataPrinter *MP = getOrCreateGCPrinter(*I))
  414. MP->beginAssembly(M, *MI, *this);
  415. // Emit module-level inline asm if it exists.
  416. if (!M.getModuleInlineAsm().empty()) {
  417. OutStreamer->AddComment("Start of file scope inline assembly");
  418. OutStreamer->addBlankLine();
  419. emitInlineAsm(M.getModuleInlineAsm() + "\n", *TM.getMCSubtargetInfo(),
  420. TM.Options.MCOptions);
  421. OutStreamer->AddComment("End of file scope inline assembly");
  422. OutStreamer->addBlankLine();
  423. }
  424. if (MAI->doesSupportDebugInformation()) {
  425. bool EmitCodeView = M.getCodeViewFlag();
  426. if (EmitCodeView && TM.getTargetTriple().isOSWindows()) {
  427. Handlers.emplace_back(std::make_unique<CodeViewDebug>(this),
  428. DbgTimerName, DbgTimerDescription,
  429. CodeViewLineTablesGroupName,
  430. CodeViewLineTablesGroupDescription);
  431. }
  432. if (!EmitCodeView || M.getDwarfVersion()) {
  433. if (MMI->hasDebugInfo()) {
  434. DD = new DwarfDebug(this);
  435. Handlers.emplace_back(std::unique_ptr<DwarfDebug>(DD), DbgTimerName,
  436. DbgTimerDescription, DWARFGroupName,
  437. DWARFGroupDescription);
  438. }
  439. }
  440. }
  441. if (M.getNamedMetadata(PseudoProbeDescMetadataName)) {
  442. PP = new PseudoProbeHandler(this);
  443. Handlers.emplace_back(std::unique_ptr<PseudoProbeHandler>(PP), PPTimerName,
  444. PPTimerDescription, PPGroupName, PPGroupDescription);
  445. }
  446. switch (MAI->getExceptionHandlingType()) {
  447. case ExceptionHandling::None:
  448. // We may want to emit CFI for debug.
  449. [[fallthrough]];
  450. case ExceptionHandling::SjLj:
  451. case ExceptionHandling::DwarfCFI:
  452. case ExceptionHandling::ARM:
  453. for (auto &F : M.getFunctionList()) {
  454. if (getFunctionCFISectionType(F) != CFISection::None)
  455. ModuleCFISection = getFunctionCFISectionType(F);
  456. // If any function needsUnwindTableEntry(), it needs .eh_frame and hence
  457. // the module needs .eh_frame. If we have found that case, we are done.
  458. if (ModuleCFISection == CFISection::EH)
  459. break;
  460. }
  461. assert(MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI ||
  462. ModuleCFISection != CFISection::EH);
  463. break;
  464. default:
  465. break;
  466. }
  467. EHStreamer *ES = nullptr;
  468. switch (MAI->getExceptionHandlingType()) {
  469. case ExceptionHandling::None:
  470. if (!needsCFIForDebug())
  471. break;
  472. [[fallthrough]];
  473. case ExceptionHandling::SjLj:
  474. case ExceptionHandling::DwarfCFI:
  475. ES = new DwarfCFIException(this);
  476. break;
  477. case ExceptionHandling::ARM:
  478. ES = new ARMException(this);
  479. break;
  480. case ExceptionHandling::WinEH:
  481. switch (MAI->getWinEHEncodingType()) {
  482. default: llvm_unreachable("unsupported unwinding information encoding");
  483. case WinEH::EncodingType::Invalid:
  484. break;
  485. case WinEH::EncodingType::X86:
  486. case WinEH::EncodingType::Itanium:
  487. ES = new WinException(this);
  488. break;
  489. }
  490. break;
  491. case ExceptionHandling::Wasm:
  492. ES = new WasmException(this);
  493. break;
  494. case ExceptionHandling::AIX:
  495. ES = new AIXException(this);
  496. break;
  497. }
  498. if (ES)
  499. Handlers.emplace_back(std::unique_ptr<EHStreamer>(ES), EHTimerName,
  500. EHTimerDescription, DWARFGroupName,
  501. DWARFGroupDescription);
  502. // Emit tables for any value of cfguard flag (i.e. cfguard=1 or cfguard=2).
  503. if (mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("cfguard")))
  504. Handlers.emplace_back(std::make_unique<WinCFGuard>(this), CFGuardName,
  505. CFGuardDescription, DWARFGroupName,
  506. DWARFGroupDescription);
  507. for (const HandlerInfo &HI : Handlers) {
  508. NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
  509. HI.TimerGroupDescription, TimePassesIsEnabled);
  510. HI.Handler->beginModule(&M);
  511. }
  512. return false;
  513. }
  514. static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
  515. if (!MAI.hasWeakDefCanBeHiddenDirective())
  516. return false;
  517. return GV->canBeOmittedFromSymbolTable();
  518. }
  519. void AsmPrinter::emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
  520. GlobalValue::LinkageTypes Linkage = GV->getLinkage();
  521. switch (Linkage) {
  522. case GlobalValue::CommonLinkage:
  523. case GlobalValue::LinkOnceAnyLinkage:
  524. case GlobalValue::LinkOnceODRLinkage:
  525. case GlobalValue::WeakAnyLinkage:
  526. case GlobalValue::WeakODRLinkage:
  527. if (MAI->hasWeakDefDirective()) {
  528. // .globl _foo
  529. OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
  530. if (!canBeHidden(GV, *MAI))
  531. // .weak_definition _foo
  532. OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefinition);
  533. else
  534. OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
  535. } else if (MAI->avoidWeakIfComdat() && GV->hasComdat()) {
  536. // .globl _foo
  537. OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
  538. //NOTE: linkonce is handled by the section the symbol was assigned to.
  539. } else {
  540. // .weak _foo
  541. OutStreamer->emitSymbolAttribute(GVSym, MCSA_Weak);
  542. }
  543. return;
  544. case GlobalValue::ExternalLinkage:
  545. OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
  546. return;
  547. case GlobalValue::PrivateLinkage:
  548. case GlobalValue::InternalLinkage:
  549. return;
  550. case GlobalValue::ExternalWeakLinkage:
  551. case GlobalValue::AvailableExternallyLinkage:
  552. case GlobalValue::AppendingLinkage:
  553. llvm_unreachable("Should never emit this");
  554. }
  555. llvm_unreachable("Unknown linkage type!");
  556. }
  557. void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
  558. const GlobalValue *GV) const {
  559. TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler());
  560. }
  561. MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
  562. return TM.getSymbol(GV);
  563. }
  564. MCSymbol *AsmPrinter::getSymbolPreferLocal(const GlobalValue &GV) const {
  565. // On ELF, use .Lfoo$local if GV is a non-interposable GlobalObject with an
  566. // exact definion (intersection of GlobalValue::hasExactDefinition() and
  567. // !isInterposable()). These linkages include: external, appending, internal,
  568. // private. It may be profitable to use a local alias for external. The
  569. // assembler would otherwise be conservative and assume a global default
  570. // visibility symbol can be interposable, even if the code generator already
  571. // assumed it.
  572. if (TM.getTargetTriple().isOSBinFormatELF() && GV.canBenefitFromLocalAlias()) {
  573. const Module &M = *GV.getParent();
  574. if (TM.getRelocationModel() != Reloc::Static &&
  575. M.getPIELevel() == PIELevel::Default && GV.isDSOLocal())
  576. return getSymbolWithGlobalValueBase(&GV, "$local");
  577. }
  578. return TM.getSymbol(&GV);
  579. }
  580. /// EmitGlobalVariable - Emit the specified global variable to the .s file.
  581. void AsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
  582. bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal();
  583. assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
  584. "No emulated TLS variables in the common section");
  585. // Never emit TLS variable xyz in emulated TLS model.
  586. // The initialization value is in __emutls_t.xyz instead of xyz.
  587. if (IsEmuTLSVar)
  588. return;
  589. if (GV->hasInitializer()) {
  590. // Check to see if this is a special global used by LLVM, if so, emit it.
  591. if (emitSpecialLLVMGlobal(GV))
  592. return;
  593. // Skip the emission of global equivalents. The symbol can be emitted later
  594. // on by emitGlobalGOTEquivs in case it turns out to be needed.
  595. if (GlobalGOTEquivs.count(getSymbol(GV)))
  596. return;
  597. if (isVerbose()) {
  598. // When printing the control variable __emutls_v.*,
  599. // we don't need to print the original TLS variable name.
  600. GV->printAsOperand(OutStreamer->getCommentOS(),
  601. /*PrintType=*/false, GV->getParent());
  602. OutStreamer->getCommentOS() << '\n';
  603. }
  604. }
  605. MCSymbol *GVSym = getSymbol(GV);
  606. MCSymbol *EmittedSym = GVSym;
  607. // getOrCreateEmuTLSControlSym only creates the symbol with name and default
  608. // attributes.
  609. // GV's or GVSym's attributes will be used for the EmittedSym.
  610. emitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
  611. if (GV->isTagged()) {
  612. Triple T = TM.getTargetTriple();
  613. if (T.getArch() != Triple::aarch64 || !T.isAndroid())
  614. OutContext.reportError(SMLoc(),
  615. "Tagged symbols (-fsanitize=memtag-globals) are "
  616. "only supported on aarch64 + Android.");
  617. OutStreamer->emitSymbolAttribute(EmittedSym, MAI->getMemtagAttr());
  618. }
  619. if (!GV->hasInitializer()) // External globals require no extra code.
  620. return;
  621. GVSym->redefineIfPossible();
  622. if (GVSym->isDefined() || GVSym->isVariable())
  623. OutContext.reportError(SMLoc(), "symbol '" + Twine(GVSym->getName()) +
  624. "' is already defined");
  625. if (MAI->hasDotTypeDotSizeDirective())
  626. OutStreamer->emitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
  627. SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
  628. const DataLayout &DL = GV->getParent()->getDataLayout();
  629. uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
  630. // If the alignment is specified, we *must* obey it. Overaligning a global
  631. // with a specified alignment is a prompt way to break globals emitted to
  632. // sections and expected to be contiguous (e.g. ObjC metadata).
  633. const Align Alignment = getGVAlignment(GV, DL);
  634. for (const HandlerInfo &HI : Handlers) {
  635. NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
  636. HI.TimerGroupName, HI.TimerGroupDescription,
  637. TimePassesIsEnabled);
  638. HI.Handler->setSymbolSize(GVSym, Size);
  639. }
  640. // Handle common symbols
  641. if (GVKind.isCommon()) {
  642. if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
  643. // .comm _foo, 42, 4
  644. OutStreamer->emitCommonSymbol(GVSym, Size, Alignment);
  645. return;
  646. }
  647. // Determine to which section this global should be emitted.
  648. MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM);
  649. // If we have a bss global going to a section that supports the
  650. // zerofill directive, do so here.
  651. if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() &&
  652. TheSection->isVirtualSection()) {
  653. if (Size == 0)
  654. Size = 1; // zerofill of 0 bytes is undefined.
  655. emitLinkage(GV, GVSym);
  656. // .zerofill __DATA, __bss, _foo, 400, 5
  657. OutStreamer->emitZerofill(TheSection, GVSym, Size, Alignment);
  658. return;
  659. }
  660. // If this is a BSS local symbol and we are emitting in the BSS
  661. // section use .lcomm/.comm directive.
  662. if (GVKind.isBSSLocal() &&
  663. getObjFileLowering().getBSSSection() == TheSection) {
  664. if (Size == 0)
  665. Size = 1; // .comm Foo, 0 is undefined, avoid it.
  666. // Use .lcomm only if it supports user-specified alignment.
  667. // Otherwise, while it would still be correct to use .lcomm in some
  668. // cases (e.g. when Align == 1), the external assembler might enfore
  669. // some -unknown- default alignment behavior, which could cause
  670. // spurious differences between external and integrated assembler.
  671. // Prefer to simply fall back to .local / .comm in this case.
  672. if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
  673. // .lcomm _foo, 42
  674. OutStreamer->emitLocalCommonSymbol(GVSym, Size, Alignment);
  675. return;
  676. }
  677. // .local _foo
  678. OutStreamer->emitSymbolAttribute(GVSym, MCSA_Local);
  679. // .comm _foo, 42, 4
  680. OutStreamer->emitCommonSymbol(GVSym, Size, Alignment);
  681. return;
  682. }
  683. // Handle thread local data for mach-o which requires us to output an
  684. // additional structure of data and mangle the original symbol so that we
  685. // can reference it later.
  686. //
  687. // TODO: This should become an "emit thread local global" method on TLOF.
  688. // All of this macho specific stuff should be sunk down into TLOFMachO and
  689. // stuff like "TLSExtraDataSection" should no longer be part of the parent
  690. // TLOF class. This will also make it more obvious that stuff like
  691. // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
  692. // specific code.
  693. if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
  694. // Emit the .tbss symbol
  695. MCSymbol *MangSym =
  696. OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
  697. if (GVKind.isThreadBSS()) {
  698. TheSection = getObjFileLowering().getTLSBSSSection();
  699. OutStreamer->emitTBSSSymbol(TheSection, MangSym, Size, Alignment);
  700. } else if (GVKind.isThreadData()) {
  701. OutStreamer->switchSection(TheSection);
  702. emitAlignment(Alignment, GV);
  703. OutStreamer->emitLabel(MangSym);
  704. emitGlobalConstant(GV->getParent()->getDataLayout(),
  705. GV->getInitializer());
  706. }
  707. OutStreamer->addBlankLine();
  708. // Emit the variable struct for the runtime.
  709. MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection();
  710. OutStreamer->switchSection(TLVSect);
  711. // Emit the linkage here.
  712. emitLinkage(GV, GVSym);
  713. OutStreamer->emitLabel(GVSym);
  714. // Three pointers in size:
  715. // - __tlv_bootstrap - used to make sure support exists
  716. // - spare pointer, used when mapped by the runtime
  717. // - pointer to mangled symbol above with initializer
  718. unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
  719. OutStreamer->emitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
  720. PtrSize);
  721. OutStreamer->emitIntValue(0, PtrSize);
  722. OutStreamer->emitSymbolValue(MangSym, PtrSize);
  723. OutStreamer->addBlankLine();
  724. return;
  725. }
  726. MCSymbol *EmittedInitSym = GVSym;
  727. OutStreamer->switchSection(TheSection);
  728. emitLinkage(GV, EmittedInitSym);
  729. emitAlignment(Alignment, GV);
  730. OutStreamer->emitLabel(EmittedInitSym);
  731. MCSymbol *LocalAlias = getSymbolPreferLocal(*GV);
  732. if (LocalAlias != EmittedInitSym)
  733. OutStreamer->emitLabel(LocalAlias);
  734. emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
  735. if (MAI->hasDotTypeDotSizeDirective())
  736. // .size foo, 42
  737. OutStreamer->emitELFSize(EmittedInitSym,
  738. MCConstantExpr::create(Size, OutContext));
  739. OutStreamer->addBlankLine();
  740. }
  741. /// Emit the directive and value for debug thread local expression
  742. ///
  743. /// \p Value - The value to emit.
  744. /// \p Size - The size of the integer (in bytes) to emit.
  745. void AsmPrinter::emitDebugValue(const MCExpr *Value, unsigned Size) const {
  746. OutStreamer->emitValue(Value, Size);
  747. }
  748. void AsmPrinter::emitFunctionHeaderComment() {}
  749. /// EmitFunctionHeader - This method emits the header for the current
  750. /// function.
  751. void AsmPrinter::emitFunctionHeader() {
  752. const Function &F = MF->getFunction();
  753. if (isVerbose())
  754. OutStreamer->getCommentOS()
  755. << "-- Begin function "
  756. << GlobalValue::dropLLVMManglingEscape(F.getName()) << '\n';
  757. // Print out constants referenced by the function
  758. emitConstantPool();
  759. // Print the 'header' of function.
  760. // If basic block sections are desired, explicitly request a unique section
  761. // for this function's entry block.
  762. if (MF->front().isBeginSection())
  763. MF->setSection(getObjFileLowering().getUniqueSectionForFunction(F, TM));
  764. else
  765. MF->setSection(getObjFileLowering().SectionForGlobal(&F, TM));
  766. OutStreamer->switchSection(MF->getSection());
  767. if (!MAI->hasVisibilityOnlyWithLinkage())
  768. emitVisibility(CurrentFnSym, F.getVisibility());
  769. if (MAI->needsFunctionDescriptors())
  770. emitLinkage(&F, CurrentFnDescSym);
  771. emitLinkage(&F, CurrentFnSym);
  772. if (MAI->hasFunctionAlignment())
  773. emitAlignment(MF->getAlignment(), &F);
  774. if (MAI->hasDotTypeDotSizeDirective())
  775. OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
  776. if (F.hasFnAttribute(Attribute::Cold))
  777. OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_Cold);
  778. if (isVerbose()) {
  779. F.printAsOperand(OutStreamer->getCommentOS(),
  780. /*PrintType=*/false, F.getParent());
  781. emitFunctionHeaderComment();
  782. OutStreamer->getCommentOS() << '\n';
  783. }
  784. // Emit the prefix data.
  785. if (F.hasPrefixData()) {
  786. if (MAI->hasSubsectionsViaSymbols()) {
  787. // Preserving prefix data on platforms which use subsections-via-symbols
  788. // is a bit tricky. Here we introduce a symbol for the prefix data
  789. // and use the .alt_entry attribute to mark the function's real entry point
  790. // as an alternative entry point to the prefix-data symbol.
  791. MCSymbol *PrefixSym = OutContext.createLinkerPrivateTempSymbol();
  792. OutStreamer->emitLabel(PrefixSym);
  793. emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
  794. // Emit an .alt_entry directive for the actual function symbol.
  795. OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_AltEntry);
  796. } else {
  797. emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
  798. }
  799. }
  800. // Emit KCFI type information before patchable-function-prefix nops.
  801. emitKCFITypeId(*MF);
  802. // Emit M NOPs for -fpatchable-function-entry=N,M where M>0. We arbitrarily
  803. // place prefix data before NOPs.
  804. unsigned PatchableFunctionPrefix = 0;
  805. unsigned PatchableFunctionEntry = 0;
  806. (void)F.getFnAttribute("patchable-function-prefix")
  807. .getValueAsString()
  808. .getAsInteger(10, PatchableFunctionPrefix);
  809. (void)F.getFnAttribute("patchable-function-entry")
  810. .getValueAsString()
  811. .getAsInteger(10, PatchableFunctionEntry);
  812. if (PatchableFunctionPrefix) {
  813. CurrentPatchableFunctionEntrySym =
  814. OutContext.createLinkerPrivateTempSymbol();
  815. OutStreamer->emitLabel(CurrentPatchableFunctionEntrySym);
  816. emitNops(PatchableFunctionPrefix);
  817. } else if (PatchableFunctionEntry) {
  818. // May be reassigned when emitting the body, to reference the label after
  819. // the initial BTI (AArch64) or endbr32/endbr64 (x86).
  820. CurrentPatchableFunctionEntrySym = CurrentFnBegin;
  821. }
  822. // Emit the function descriptor. This is a virtual function to allow targets
  823. // to emit their specific function descriptor. Right now it is only used by
  824. // the AIX target. The PowerPC 64-bit V1 ELF target also uses function
  825. // descriptors and should be converted to use this hook as well.
  826. if (MAI->needsFunctionDescriptors())
  827. emitFunctionDescriptor();
  828. // Emit the CurrentFnSym. This is a virtual function to allow targets to do
  829. // their wild and crazy things as required.
  830. emitFunctionEntryLabel();
  831. // If the function had address-taken blocks that got deleted, then we have
  832. // references to the dangling symbols. Emit them at the start of the function
  833. // so that we don't get references to undefined symbols.
  834. std::vector<MCSymbol*> DeadBlockSyms;
  835. takeDeletedSymbolsForFunction(&F, DeadBlockSyms);
  836. for (MCSymbol *DeadBlockSym : DeadBlockSyms) {
  837. OutStreamer->AddComment("Address taken block that was later removed");
  838. OutStreamer->emitLabel(DeadBlockSym);
  839. }
  840. if (CurrentFnBegin) {
  841. if (MAI->useAssignmentForEHBegin()) {
  842. MCSymbol *CurPos = OutContext.createTempSymbol();
  843. OutStreamer->emitLabel(CurPos);
  844. OutStreamer->emitAssignment(CurrentFnBegin,
  845. MCSymbolRefExpr::create(CurPos, OutContext));
  846. } else {
  847. OutStreamer->emitLabel(CurrentFnBegin);
  848. }
  849. }
  850. // Emit pre-function debug and/or EH information.
  851. for (const HandlerInfo &HI : Handlers) {
  852. NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
  853. HI.TimerGroupDescription, TimePassesIsEnabled);
  854. HI.Handler->beginFunction(MF);
  855. }
  856. for (const HandlerInfo &HI : Handlers) {
  857. NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
  858. HI.TimerGroupDescription, TimePassesIsEnabled);
  859. HI.Handler->beginBasicBlockSection(MF->front());
  860. }
  861. // Emit the prologue data.
  862. if (F.hasPrologueData())
  863. emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrologueData());
  864. // Emit the function prologue data for the indirect call sanitizer.
  865. if (const MDNode *MD = F.getMetadata(LLVMContext::MD_func_sanitize)) {
  866. assert(TM.getTargetTriple().getArch() == Triple::x86 ||
  867. TM.getTargetTriple().getArch() == Triple::x86_64);
  868. assert(MD->getNumOperands() == 2);
  869. auto *PrologueSig = mdconst::extract<Constant>(MD->getOperand(0));
  870. auto *FTRTTIProxy = mdconst::extract<Constant>(MD->getOperand(1));
  871. assert(PrologueSig && FTRTTIProxy);
  872. emitGlobalConstant(F.getParent()->getDataLayout(), PrologueSig);
  873. const MCExpr *Proxy = lowerConstant(FTRTTIProxy);
  874. const MCExpr *FnExp = MCSymbolRefExpr::create(CurrentFnSym, OutContext);
  875. const MCExpr *PCRel = MCBinaryExpr::createSub(Proxy, FnExp, OutContext);
  876. // Use 32 bit since only small code model is supported.
  877. OutStreamer->emitValue(PCRel, 4u);
  878. }
  879. }
  880. /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
  881. /// function. This can be overridden by targets as required to do custom stuff.
  882. void AsmPrinter::emitFunctionEntryLabel() {
  883. CurrentFnSym->redefineIfPossible();
  884. // The function label could have already been emitted if two symbols end up
  885. // conflicting due to asm renaming. Detect this and emit an error.
  886. if (CurrentFnSym->isVariable())
  887. report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
  888. "' is a protected alias");
  889. OutStreamer->emitLabel(CurrentFnSym);
  890. if (TM.getTargetTriple().isOSBinFormatELF()) {
  891. MCSymbol *Sym = getSymbolPreferLocal(MF->getFunction());
  892. if (Sym != CurrentFnSym) {
  893. cast<MCSymbolELF>(Sym)->setType(ELF::STT_FUNC);
  894. CurrentFnBeginLocal = Sym;
  895. OutStreamer->emitLabel(Sym);
  896. if (MAI->hasDotTypeDotSizeDirective())
  897. OutStreamer->emitSymbolAttribute(Sym, MCSA_ELF_TypeFunction);
  898. }
  899. }
  900. }
  901. /// emitComments - Pretty-print comments for instructions.
  902. static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
  903. const MachineFunction *MF = MI.getMF();
  904. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  905. // Check for spills and reloads
  906. // We assume a single instruction only has a spill or reload, not
  907. // both.
  908. std::optional<unsigned> Size;
  909. if ((Size = MI.getRestoreSize(TII))) {
  910. CommentOS << *Size << "-byte Reload\n";
  911. } else if ((Size = MI.getFoldedRestoreSize(TII))) {
  912. if (*Size) {
  913. if (*Size == unsigned(MemoryLocation::UnknownSize))
  914. CommentOS << "Unknown-size Folded Reload\n";
  915. else
  916. CommentOS << *Size << "-byte Folded Reload\n";
  917. }
  918. } else if ((Size = MI.getSpillSize(TII))) {
  919. CommentOS << *Size << "-byte Spill\n";
  920. } else if ((Size = MI.getFoldedSpillSize(TII))) {
  921. if (*Size) {
  922. if (*Size == unsigned(MemoryLocation::UnknownSize))
  923. CommentOS << "Unknown-size Folded Spill\n";
  924. else
  925. CommentOS << *Size << "-byte Folded Spill\n";
  926. }
  927. }
  928. // Check for spill-induced copies
  929. if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
  930. CommentOS << " Reload Reuse\n";
  931. }
  932. /// emitImplicitDef - This method emits the specified machine instruction
  933. /// that is an implicit def.
  934. void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
  935. Register RegNo = MI->getOperand(0).getReg();
  936. SmallString<128> Str;
  937. raw_svector_ostream OS(Str);
  938. OS << "implicit-def: "
  939. << printReg(RegNo, MF->getSubtarget().getRegisterInfo());
  940. OutStreamer->AddComment(OS.str());
  941. OutStreamer->addBlankLine();
  942. }
  943. static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
  944. std::string Str;
  945. raw_string_ostream OS(Str);
  946. OS << "kill:";
  947. for (const MachineOperand &Op : MI->operands()) {
  948. assert(Op.isReg() && "KILL instruction must have only register operands");
  949. OS << ' ' << (Op.isDef() ? "def " : "killed ")
  950. << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo());
  951. }
  952. AP.OutStreamer->AddComment(OS.str());
  953. AP.OutStreamer->addBlankLine();
  954. }
  955. /// emitDebugValueComment - This method handles the target-independent form
  956. /// of DBG_VALUE, returning true if it was able to do so. A false return
  957. /// means the target will need to handle MI in EmitInstruction.
  958. static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
  959. // This code handles only the 4-operand target-independent form.
  960. if (MI->isNonListDebugValue() && MI->getNumOperands() != 4)
  961. return false;
  962. SmallString<128> Str;
  963. raw_svector_ostream OS(Str);
  964. OS << "DEBUG_VALUE: ";
  965. const DILocalVariable *V = MI->getDebugVariable();
  966. if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
  967. StringRef Name = SP->getName();
  968. if (!Name.empty())
  969. OS << Name << ":";
  970. }
  971. OS << V->getName();
  972. OS << " <- ";
  973. const DIExpression *Expr = MI->getDebugExpression();
  974. // First convert this to a non-variadic expression if possible, to simplify
  975. // the output.
  976. if (auto NonVariadicExpr = DIExpression::convertToNonVariadicExpression(Expr))
  977. Expr = *NonVariadicExpr;
  978. // Then, output the possibly-simplified expression.
  979. if (Expr->getNumElements()) {
  980. OS << '[';
  981. ListSeparator LS;
  982. for (auto &Op : Expr->expr_ops()) {
  983. OS << LS << dwarf::OperationEncodingString(Op.getOp());
  984. for (unsigned I = 0; I < Op.getNumArgs(); ++I)
  985. OS << ' ' << Op.getArg(I);
  986. }
  987. OS << "] ";
  988. }
  989. // Register or immediate value. Register 0 means undef.
  990. for (const MachineOperand &Op : MI->debug_operands()) {
  991. if (&Op != MI->debug_operands().begin())
  992. OS << ", ";
  993. switch (Op.getType()) {
  994. case MachineOperand::MO_FPImmediate: {
  995. APFloat APF = APFloat(Op.getFPImm()->getValueAPF());
  996. Type *ImmTy = Op.getFPImm()->getType();
  997. if (ImmTy->isBFloatTy() || ImmTy->isHalfTy() || ImmTy->isFloatTy() ||
  998. ImmTy->isDoubleTy()) {
  999. OS << APF.convertToDouble();
  1000. } else {
  1001. // There is no good way to print long double. Convert a copy to
  1002. // double. Ah well, it's only a comment.
  1003. bool ignored;
  1004. APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
  1005. &ignored);
  1006. OS << "(long double) " << APF.convertToDouble();
  1007. }
  1008. break;
  1009. }
  1010. case MachineOperand::MO_Immediate: {
  1011. OS << Op.getImm();
  1012. break;
  1013. }
  1014. case MachineOperand::MO_CImmediate: {
  1015. Op.getCImm()->getValue().print(OS, false /*isSigned*/);
  1016. break;
  1017. }
  1018. case MachineOperand::MO_TargetIndex: {
  1019. OS << "!target-index(" << Op.getIndex() << "," << Op.getOffset() << ")";
  1020. break;
  1021. }
  1022. case MachineOperand::MO_Register:
  1023. case MachineOperand::MO_FrameIndex: {
  1024. Register Reg;
  1025. std::optional<StackOffset> Offset;
  1026. if (Op.isReg()) {
  1027. Reg = Op.getReg();
  1028. } else {
  1029. const TargetFrameLowering *TFI =
  1030. AP.MF->getSubtarget().getFrameLowering();
  1031. Offset = TFI->getFrameIndexReference(*AP.MF, Op.getIndex(), Reg);
  1032. }
  1033. if (!Reg) {
  1034. // Suppress offset, it is not meaningful here.
  1035. OS << "undef";
  1036. break;
  1037. }
  1038. // The second operand is only an offset if it's an immediate.
  1039. if (MI->isIndirectDebugValue())
  1040. Offset = StackOffset::getFixed(MI->getDebugOffset().getImm());
  1041. if (Offset)
  1042. OS << '[';
  1043. OS << printReg(Reg, AP.MF->getSubtarget().getRegisterInfo());
  1044. if (Offset)
  1045. OS << '+' << Offset->getFixed() << ']';
  1046. break;
  1047. }
  1048. default:
  1049. llvm_unreachable("Unknown operand type");
  1050. }
  1051. }
  1052. // NOTE: Want this comment at start of line, don't emit with AddComment.
  1053. AP.OutStreamer->emitRawComment(OS.str());
  1054. return true;
  1055. }
  1056. /// This method handles the target-independent form of DBG_LABEL, returning
  1057. /// true if it was able to do so. A false return means the target will need
  1058. /// to handle MI in EmitInstruction.
  1059. static bool emitDebugLabelComment(const MachineInstr *MI, AsmPrinter &AP) {
  1060. if (MI->getNumOperands() != 1)
  1061. return false;
  1062. SmallString<128> Str;
  1063. raw_svector_ostream OS(Str);
  1064. OS << "DEBUG_LABEL: ";
  1065. const DILabel *V = MI->getDebugLabel();
  1066. if (auto *SP = dyn_cast<DISubprogram>(
  1067. V->getScope()->getNonLexicalBlockFileScope())) {
  1068. StringRef Name = SP->getName();
  1069. if (!Name.empty())
  1070. OS << Name << ":";
  1071. }
  1072. OS << V->getName();
  1073. // NOTE: Want this comment at start of line, don't emit with AddComment.
  1074. AP.OutStreamer->emitRawComment(OS.str());
  1075. return true;
  1076. }
  1077. AsmPrinter::CFISection
  1078. AsmPrinter::getFunctionCFISectionType(const Function &F) const {
  1079. // Ignore functions that won't get emitted.
  1080. if (F.isDeclarationForLinker())
  1081. return CFISection::None;
  1082. if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
  1083. F.needsUnwindTableEntry())
  1084. return CFISection::EH;
  1085. if (MMI->hasDebugInfo() || TM.Options.ForceDwarfFrameSection)
  1086. return CFISection::Debug;
  1087. return CFISection::None;
  1088. }
  1089. AsmPrinter::CFISection
  1090. AsmPrinter::getFunctionCFISectionType(const MachineFunction &MF) const {
  1091. return getFunctionCFISectionType(MF.getFunction());
  1092. }
  1093. bool AsmPrinter::needsSEHMoves() {
  1094. return MAI->usesWindowsCFI() && MF->getFunction().needsUnwindTableEntry();
  1095. }
  1096. bool AsmPrinter::needsCFIForDebug() const {
  1097. return MAI->getExceptionHandlingType() == ExceptionHandling::None &&
  1098. MAI->doesUseCFIForDebug() && ModuleCFISection == CFISection::Debug;
  1099. }
  1100. void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
  1101. ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
  1102. if (!needsCFIForDebug() &&
  1103. ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
  1104. ExceptionHandlingType != ExceptionHandling::ARM)
  1105. return;
  1106. if (getFunctionCFISectionType(*MF) == CFISection::None)
  1107. return;
  1108. // If there is no "real" instruction following this CFI instruction, skip
  1109. // emitting it; it would be beyond the end of the function's FDE range.
  1110. auto *MBB = MI.getParent();
  1111. auto I = std::next(MI.getIterator());
  1112. while (I != MBB->end() && I->isTransient())
  1113. ++I;
  1114. if (I == MBB->instr_end() &&
  1115. MBB->getReverseIterator() == MBB->getParent()->rbegin())
  1116. return;
  1117. const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions();
  1118. unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
  1119. const MCCFIInstruction &CFI = Instrs[CFIIndex];
  1120. emitCFIInstruction(CFI);
  1121. }
  1122. void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
  1123. // The operands are the MCSymbol and the frame offset of the allocation.
  1124. MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
  1125. int FrameOffset = MI.getOperand(1).getImm();
  1126. // Emit a symbol assignment.
  1127. OutStreamer->emitAssignment(FrameAllocSym,
  1128. MCConstantExpr::create(FrameOffset, OutContext));
  1129. }
  1130. /// Returns the BB metadata to be emitted in the .llvm_bb_addr_map section for a
  1131. /// given basic block. This can be used to capture more precise profile
  1132. /// information. We use the last 4 bits (LSBs) to encode the following
  1133. /// information:
  1134. /// * (1): set if return block (ret or tail call).
  1135. /// * (2): set if ends with a tail call.
  1136. /// * (3): set if exception handling (EH) landing pad.
  1137. /// * (4): set if the block can fall through to its next.
  1138. /// The remaining bits are zero.
  1139. static unsigned getBBAddrMapMetadata(const MachineBasicBlock &MBB) {
  1140. const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
  1141. return ((unsigned)MBB.isReturnBlock()) |
  1142. ((!MBB.empty() && TII->isTailCall(MBB.back())) << 1) |
  1143. (MBB.isEHPad() << 2) |
  1144. (const_cast<MachineBasicBlock &>(MBB).canFallThrough() << 3);
  1145. }
  1146. void AsmPrinter::emitBBAddrMapSection(const MachineFunction &MF) {
  1147. MCSection *BBAddrMapSection =
  1148. getObjFileLowering().getBBAddrMapSection(*MF.getSection());
  1149. assert(BBAddrMapSection && ".llvm_bb_addr_map section is not initialized.");
  1150. const MCSymbol *FunctionSymbol = getFunctionBegin();
  1151. OutStreamer->pushSection();
  1152. OutStreamer->switchSection(BBAddrMapSection);
  1153. OutStreamer->AddComment("version");
  1154. uint8_t BBAddrMapVersion = OutStreamer->getContext().getBBAddrMapVersion();
  1155. OutStreamer->emitInt8(BBAddrMapVersion);
  1156. OutStreamer->AddComment("feature");
  1157. OutStreamer->emitInt8(0);
  1158. OutStreamer->AddComment("function address");
  1159. OutStreamer->emitSymbolValue(FunctionSymbol, getPointerSize());
  1160. OutStreamer->AddComment("number of basic blocks");
  1161. OutStreamer->emitULEB128IntValue(MF.size());
  1162. const MCSymbol *PrevMBBEndSymbol = FunctionSymbol;
  1163. // Emit BB Information for each basic block in the funciton.
  1164. for (const MachineBasicBlock &MBB : MF) {
  1165. const MCSymbol *MBBSymbol =
  1166. MBB.isEntryBlock() ? FunctionSymbol : MBB.getSymbol();
  1167. // TODO: Remove this check when version 1 is deprecated.
  1168. if (BBAddrMapVersion > 1) {
  1169. OutStreamer->AddComment("BB id");
  1170. // Emit the BB ID for this basic block.
  1171. OutStreamer->emitULEB128IntValue(*MBB.getBBID());
  1172. }
  1173. // Emit the basic block offset relative to the end of the previous block.
  1174. // This is zero unless the block is padded due to alignment.
  1175. emitLabelDifferenceAsULEB128(MBBSymbol, PrevMBBEndSymbol);
  1176. // Emit the basic block size. When BBs have alignments, their size cannot
  1177. // always be computed from their offsets.
  1178. emitLabelDifferenceAsULEB128(MBB.getEndSymbol(), MBBSymbol);
  1179. // Emit the Metadata.
  1180. OutStreamer->emitULEB128IntValue(getBBAddrMapMetadata(MBB));
  1181. PrevMBBEndSymbol = MBB.getEndSymbol();
  1182. }
  1183. OutStreamer->popSection();
  1184. }
  1185. void AsmPrinter::emitKCFITrapEntry(const MachineFunction &MF,
  1186. const MCSymbol *Symbol) {
  1187. MCSection *Section =
  1188. getObjFileLowering().getKCFITrapSection(*MF.getSection());
  1189. if (!Section)
  1190. return;
  1191. OutStreamer->pushSection();
  1192. OutStreamer->switchSection(Section);
  1193. MCSymbol *Loc = OutContext.createLinkerPrivateTempSymbol();
  1194. OutStreamer->emitLabel(Loc);
  1195. OutStreamer->emitAbsoluteSymbolDiff(Symbol, Loc, 4);
  1196. OutStreamer->popSection();
  1197. }
  1198. void AsmPrinter::emitKCFITypeId(const MachineFunction &MF) {
  1199. const Function &F = MF.getFunction();
  1200. if (const MDNode *MD = F.getMetadata(LLVMContext::MD_kcfi_type))
  1201. emitGlobalConstant(F.getParent()->getDataLayout(),
  1202. mdconst::extract<ConstantInt>(MD->getOperand(0)));
  1203. }
  1204. void AsmPrinter::emitPseudoProbe(const MachineInstr &MI) {
  1205. if (PP) {
  1206. auto GUID = MI.getOperand(0).getImm();
  1207. auto Index = MI.getOperand(1).getImm();
  1208. auto Type = MI.getOperand(2).getImm();
  1209. auto Attr = MI.getOperand(3).getImm();
  1210. DILocation *DebugLoc = MI.getDebugLoc();
  1211. PP->emitPseudoProbe(GUID, Index, Type, Attr, DebugLoc);
  1212. }
  1213. }
  1214. void AsmPrinter::emitStackSizeSection(const MachineFunction &MF) {
  1215. if (!MF.getTarget().Options.EmitStackSizeSection)
  1216. return;
  1217. MCSection *StackSizeSection =
  1218. getObjFileLowering().getStackSizesSection(*getCurrentSection());
  1219. if (!StackSizeSection)
  1220. return;
  1221. const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
  1222. // Don't emit functions with dynamic stack allocations.
  1223. if (FrameInfo.hasVarSizedObjects())
  1224. return;
  1225. OutStreamer->pushSection();
  1226. OutStreamer->switchSection(StackSizeSection);
  1227. const MCSymbol *FunctionSymbol = getFunctionBegin();
  1228. uint64_t StackSize =
  1229. FrameInfo.getStackSize() + FrameInfo.getUnsafeStackSize();
  1230. OutStreamer->emitSymbolValue(FunctionSymbol, TM.getProgramPointerSize());
  1231. OutStreamer->emitULEB128IntValue(StackSize);
  1232. OutStreamer->popSection();
  1233. }
  1234. void AsmPrinter::emitStackUsage(const MachineFunction &MF) {
  1235. const std::string &OutputFilename = MF.getTarget().Options.StackUsageOutput;
  1236. // OutputFilename empty implies -fstack-usage is not passed.
  1237. if (OutputFilename.empty())
  1238. return;
  1239. const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
  1240. uint64_t StackSize =
  1241. FrameInfo.getStackSize() + FrameInfo.getUnsafeStackSize();
  1242. if (StackUsageStream == nullptr) {
  1243. std::error_code EC;
  1244. StackUsageStream =
  1245. std::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::OF_Text);
  1246. if (EC) {
  1247. errs() << "Could not open file: " << EC.message();
  1248. return;
  1249. }
  1250. }
  1251. *StackUsageStream << MF.getFunction().getParent()->getName();
  1252. if (const DISubprogram *DSP = MF.getFunction().getSubprogram())
  1253. *StackUsageStream << ':' << DSP->getLine();
  1254. *StackUsageStream << ':' << MF.getName() << '\t' << StackSize << '\t';
  1255. if (FrameInfo.hasVarSizedObjects())
  1256. *StackUsageStream << "dynamic\n";
  1257. else
  1258. *StackUsageStream << "static\n";
  1259. }
  1260. void AsmPrinter::emitPCSectionsLabel(const MachineFunction &MF,
  1261. const MDNode &MD) {
  1262. MCSymbol *S = MF.getContext().createTempSymbol("pcsection");
  1263. OutStreamer->emitLabel(S);
  1264. PCSectionsSymbols[&MD].emplace_back(S);
  1265. }
  1266. void AsmPrinter::emitPCSections(const MachineFunction &MF) {
  1267. const Function &F = MF.getFunction();
  1268. if (PCSectionsSymbols.empty() && !F.hasMetadata(LLVMContext::MD_pcsections))
  1269. return;
  1270. const CodeModel::Model CM = MF.getTarget().getCodeModel();
  1271. const unsigned RelativeRelocSize =
  1272. (CM == CodeModel::Medium || CM == CodeModel::Large) ? getPointerSize()
  1273. : 4;
  1274. // Switch to PCSection, short-circuiting the common case where the current
  1275. // section is still valid (assume most MD_pcsections contain just 1 section).
  1276. auto SwitchSection = [&, Prev = StringRef()](const StringRef &Sec) mutable {
  1277. if (Sec == Prev)
  1278. return;
  1279. MCSection *S = getObjFileLowering().getPCSection(Sec, MF.getSection());
  1280. assert(S && "PC section is not initialized");
  1281. OutStreamer->switchSection(S);
  1282. Prev = Sec;
  1283. };
  1284. // Emit symbols into sections and data as specified in the pcsections MDNode.
  1285. auto EmitForMD = [&](const MDNode &MD, ArrayRef<const MCSymbol *> Syms,
  1286. bool Deltas) {
  1287. // Expect the first operand to be a section name. After that, a tuple of
  1288. // constants may appear, which will simply be emitted into the current
  1289. // section (the user of MD_pcsections decides the format of encoded data).
  1290. assert(isa<MDString>(MD.getOperand(0)) && "first operand not a string");
  1291. for (const MDOperand &MDO : MD.operands()) {
  1292. if (auto *S = dyn_cast<MDString>(MDO)) {
  1293. SwitchSection(S->getString());
  1294. const MCSymbol *Prev = Syms.front();
  1295. for (const MCSymbol *Sym : Syms) {
  1296. if (Sym == Prev || !Deltas) {
  1297. // Use the entry itself as the base of the relative offset.
  1298. MCSymbol *Base = MF.getContext().createTempSymbol("pcsection_base");
  1299. OutStreamer->emitLabel(Base);
  1300. // Emit relative relocation `addr - base`, which avoids a dynamic
  1301. // relocation in the final binary. User will get the address with
  1302. // `base + addr`.
  1303. emitLabelDifference(Sym, Base, RelativeRelocSize);
  1304. } else {
  1305. emitLabelDifference(Sym, Prev, 4);
  1306. }
  1307. Prev = Sym;
  1308. }
  1309. } else {
  1310. assert(isa<MDNode>(MDO) && "expecting either string or tuple");
  1311. const auto *AuxMDs = cast<MDNode>(MDO);
  1312. for (const MDOperand &AuxMDO : AuxMDs->operands()) {
  1313. assert(isa<ConstantAsMetadata>(AuxMDO) && "expecting a constant");
  1314. const auto *C = cast<ConstantAsMetadata>(AuxMDO);
  1315. emitGlobalConstant(F.getParent()->getDataLayout(), C->getValue());
  1316. }
  1317. }
  1318. }
  1319. };
  1320. OutStreamer->pushSection();
  1321. // Emit PCs for function start and function size.
  1322. if (const MDNode *MD = F.getMetadata(LLVMContext::MD_pcsections))
  1323. EmitForMD(*MD, {getFunctionBegin(), getFunctionEnd()}, true);
  1324. // Emit PCs for instructions collected.
  1325. for (const auto &MS : PCSectionsSymbols)
  1326. EmitForMD(*MS.first, MS.second, false);
  1327. OutStreamer->popSection();
  1328. PCSectionsSymbols.clear();
  1329. }
  1330. /// Returns true if function begin and end labels should be emitted.
  1331. static bool needFuncLabels(const MachineFunction &MF) {
  1332. MachineModuleInfo &MMI = MF.getMMI();
  1333. if (!MF.getLandingPads().empty() || MF.hasEHFunclets() ||
  1334. MMI.hasDebugInfo() ||
  1335. MF.getFunction().hasMetadata(LLVMContext::MD_pcsections))
  1336. return true;
  1337. // We might emit an EH table that uses function begin and end labels even if
  1338. // we don't have any landingpads.
  1339. if (!MF.getFunction().hasPersonalityFn())
  1340. return false;
  1341. return !isNoOpWithoutInvoke(
  1342. classifyEHPersonality(MF.getFunction().getPersonalityFn()));
  1343. }
  1344. /// EmitFunctionBody - This method emits the body and trailer for a
  1345. /// function.
  1346. void AsmPrinter::emitFunctionBody() {
  1347. emitFunctionHeader();
  1348. // Emit target-specific gunk before the function body.
  1349. emitFunctionBodyStart();
  1350. if (isVerbose()) {
  1351. // Get MachineDominatorTree or compute it on the fly if it's unavailable
  1352. MDT = getAnalysisIfAvailable<MachineDominatorTree>();
  1353. if (!MDT) {
  1354. OwnedMDT = std::make_unique<MachineDominatorTree>();
  1355. OwnedMDT->getBase().recalculate(*MF);
  1356. MDT = OwnedMDT.get();
  1357. }
  1358. // Get MachineLoopInfo or compute it on the fly if it's unavailable
  1359. MLI = getAnalysisIfAvailable<MachineLoopInfo>();
  1360. if (!MLI) {
  1361. OwnedMLI = std::make_unique<MachineLoopInfo>();
  1362. OwnedMLI->getBase().analyze(MDT->getBase());
  1363. MLI = OwnedMLI.get();
  1364. }
  1365. }
  1366. // Print out code for the function.
  1367. bool HasAnyRealCode = false;
  1368. int NumInstsInFunction = 0;
  1369. bool CanDoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
  1370. for (auto &MBB : *MF) {
  1371. // Print a label for the basic block.
  1372. emitBasicBlockStart(MBB);
  1373. DenseMap<StringRef, unsigned> MnemonicCounts;
  1374. for (auto &MI : MBB) {
  1375. // Print the assembly for the instruction.
  1376. if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
  1377. !MI.isDebugInstr()) {
  1378. HasAnyRealCode = true;
  1379. ++NumInstsInFunction;
  1380. }
  1381. // If there is a pre-instruction symbol, emit a label for it here.
  1382. if (MCSymbol *S = MI.getPreInstrSymbol())
  1383. OutStreamer->emitLabel(S);
  1384. if (MDNode *MD = MI.getPCSections())
  1385. emitPCSectionsLabel(*MF, *MD);
  1386. for (const HandlerInfo &HI : Handlers) {
  1387. NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
  1388. HI.TimerGroupDescription, TimePassesIsEnabled);
  1389. HI.Handler->beginInstruction(&MI);
  1390. }
  1391. if (isVerbose())
  1392. emitComments(MI, OutStreamer->getCommentOS());
  1393. switch (MI.getOpcode()) {
  1394. case TargetOpcode::CFI_INSTRUCTION:
  1395. emitCFIInstruction(MI);
  1396. break;
  1397. case TargetOpcode::LOCAL_ESCAPE:
  1398. emitFrameAlloc(MI);
  1399. break;
  1400. case TargetOpcode::ANNOTATION_LABEL:
  1401. case TargetOpcode::EH_LABEL:
  1402. case TargetOpcode::GC_LABEL:
  1403. OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol());
  1404. break;
  1405. case TargetOpcode::INLINEASM:
  1406. case TargetOpcode::INLINEASM_BR:
  1407. emitInlineAsm(&MI);
  1408. break;
  1409. case TargetOpcode::DBG_VALUE:
  1410. case TargetOpcode::DBG_VALUE_LIST:
  1411. if (isVerbose()) {
  1412. if (!emitDebugValueComment(&MI, *this))
  1413. emitInstruction(&MI);
  1414. }
  1415. break;
  1416. case TargetOpcode::DBG_INSTR_REF:
  1417. // This instruction reference will have been resolved to a machine
  1418. // location, and a nearby DBG_VALUE created. We can safely ignore
  1419. // the instruction reference.
  1420. break;
  1421. case TargetOpcode::DBG_PHI:
  1422. // This instruction is only used to label a program point, it's purely
  1423. // meta information.
  1424. break;
  1425. case TargetOpcode::DBG_LABEL:
  1426. if (isVerbose()) {
  1427. if (!emitDebugLabelComment(&MI, *this))
  1428. emitInstruction(&MI);
  1429. }
  1430. break;
  1431. case TargetOpcode::IMPLICIT_DEF:
  1432. if (isVerbose()) emitImplicitDef(&MI);
  1433. break;
  1434. case TargetOpcode::KILL:
  1435. if (isVerbose()) emitKill(&MI, *this);
  1436. break;
  1437. case TargetOpcode::PSEUDO_PROBE:
  1438. emitPseudoProbe(MI);
  1439. break;
  1440. case TargetOpcode::ARITH_FENCE:
  1441. if (isVerbose())
  1442. OutStreamer->emitRawComment("ARITH_FENCE");
  1443. break;
  1444. case TargetOpcode::MEMBARRIER:
  1445. OutStreamer->emitRawComment("MEMBARRIER");
  1446. break;
  1447. default:
  1448. emitInstruction(&MI);
  1449. if (CanDoExtraAnalysis) {
  1450. MCInst MCI;
  1451. MCI.setOpcode(MI.getOpcode());
  1452. auto Name = OutStreamer->getMnemonic(MCI);
  1453. auto I = MnemonicCounts.insert({Name, 0u});
  1454. I.first->second++;
  1455. }
  1456. break;
  1457. }
  1458. // If there is a post-instruction symbol, emit a label for it here.
  1459. if (MCSymbol *S = MI.getPostInstrSymbol())
  1460. OutStreamer->emitLabel(S);
  1461. for (const HandlerInfo &HI : Handlers) {
  1462. NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
  1463. HI.TimerGroupDescription, TimePassesIsEnabled);
  1464. HI.Handler->endInstruction();
  1465. }
  1466. }
  1467. // We must emit temporary symbol for the end of this basic block, if either
  1468. // we have BBLabels enabled or if this basic blocks marks the end of a
  1469. // section.
  1470. if (MF->hasBBLabels() ||
  1471. (MAI->hasDotTypeDotSizeDirective() && MBB.isEndSection()))
  1472. OutStreamer->emitLabel(MBB.getEndSymbol());
  1473. if (MBB.isEndSection()) {
  1474. // The size directive for the section containing the entry block is
  1475. // handled separately by the function section.
  1476. if (!MBB.sameSection(&MF->front())) {
  1477. if (MAI->hasDotTypeDotSizeDirective()) {
  1478. // Emit the size directive for the basic block section.
  1479. const MCExpr *SizeExp = MCBinaryExpr::createSub(
  1480. MCSymbolRefExpr::create(MBB.getEndSymbol(), OutContext),
  1481. MCSymbolRefExpr::create(CurrentSectionBeginSym, OutContext),
  1482. OutContext);
  1483. OutStreamer->emitELFSize(CurrentSectionBeginSym, SizeExp);
  1484. }
  1485. MBBSectionRanges[MBB.getSectionIDNum()] =
  1486. MBBSectionRange{CurrentSectionBeginSym, MBB.getEndSymbol()};
  1487. }
  1488. }
  1489. emitBasicBlockEnd(MBB);
  1490. if (CanDoExtraAnalysis) {
  1491. // Skip empty blocks.
  1492. if (MBB.empty())
  1493. continue;
  1494. MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionMix",
  1495. MBB.begin()->getDebugLoc(), &MBB);
  1496. // Generate instruction mix remark. First, sort counts in descending order
  1497. // by count and name.
  1498. SmallVector<std::pair<StringRef, unsigned>, 128> MnemonicVec;
  1499. for (auto &KV : MnemonicCounts)
  1500. MnemonicVec.emplace_back(KV.first, KV.second);
  1501. sort(MnemonicVec, [](const std::pair<StringRef, unsigned> &A,
  1502. const std::pair<StringRef, unsigned> &B) {
  1503. if (A.second > B.second)
  1504. return true;
  1505. if (A.second == B.second)
  1506. return StringRef(A.first) < StringRef(B.first);
  1507. return false;
  1508. });
  1509. R << "BasicBlock: " << ore::NV("BasicBlock", MBB.getName()) << "\n";
  1510. for (auto &KV : MnemonicVec) {
  1511. auto Name = (Twine("INST_") + getToken(KV.first.trim()).first).str();
  1512. R << KV.first << ": " << ore::NV(Name, KV.second) << "\n";
  1513. }
  1514. ORE->emit(R);
  1515. }
  1516. }
  1517. EmittedInsts += NumInstsInFunction;
  1518. MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount",
  1519. MF->getFunction().getSubprogram(),
  1520. &MF->front());
  1521. R << ore::NV("NumInstructions", NumInstsInFunction)
  1522. << " instructions in function";
  1523. ORE->emit(R);
  1524. // If the function is empty and the object file uses .subsections_via_symbols,
  1525. // then we need to emit *something* to the function body to prevent the
  1526. // labels from collapsing together. Just emit a noop.
  1527. // Similarly, don't emit empty functions on Windows either. It can lead to
  1528. // duplicate entries (two functions with the same RVA) in the Guard CF Table
  1529. // after linking, causing the kernel not to load the binary:
  1530. // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html
  1531. // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer.
  1532. const Triple &TT = TM.getTargetTriple();
  1533. if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() ||
  1534. (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
  1535. MCInst Noop = MF->getSubtarget().getInstrInfo()->getNop();
  1536. // Targets can opt-out of emitting the noop here by leaving the opcode
  1537. // unspecified.
  1538. if (Noop.getOpcode()) {
  1539. OutStreamer->AddComment("avoids zero-length function");
  1540. emitNops(1);
  1541. }
  1542. }
  1543. // Switch to the original section in case basic block sections was used.
  1544. OutStreamer->switchSection(MF->getSection());
  1545. const Function &F = MF->getFunction();
  1546. for (const auto &BB : F) {
  1547. if (!BB.hasAddressTaken())
  1548. continue;
  1549. MCSymbol *Sym = GetBlockAddressSymbol(&BB);
  1550. if (Sym->isDefined())
  1551. continue;
  1552. OutStreamer->AddComment("Address of block that was removed by CodeGen");
  1553. OutStreamer->emitLabel(Sym);
  1554. }
  1555. // Emit target-specific gunk after the function body.
  1556. emitFunctionBodyEnd();
  1557. // Even though wasm supports .type and .size in general, function symbols
  1558. // are automatically sized.
  1559. bool EmitFunctionSize = MAI->hasDotTypeDotSizeDirective() && !TT.isWasm();
  1560. if (needFuncLabels(*MF) || EmitFunctionSize) {
  1561. // Create a symbol for the end of function.
  1562. CurrentFnEnd = createTempSymbol("func_end");
  1563. OutStreamer->emitLabel(CurrentFnEnd);
  1564. }
  1565. // If the target wants a .size directive for the size of the function, emit
  1566. // it.
  1567. if (EmitFunctionSize) {
  1568. // We can get the size as difference between the function label and the
  1569. // temp label.
  1570. const MCExpr *SizeExp = MCBinaryExpr::createSub(
  1571. MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
  1572. MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext);
  1573. OutStreamer->emitELFSize(CurrentFnSym, SizeExp);
  1574. if (CurrentFnBeginLocal)
  1575. OutStreamer->emitELFSize(CurrentFnBeginLocal, SizeExp);
  1576. }
  1577. // Call endBasicBlockSection on the last block now, if it wasn't already
  1578. // called.
  1579. if (!MF->back().isEndSection()) {
  1580. for (const HandlerInfo &HI : Handlers) {
  1581. NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
  1582. HI.TimerGroupDescription, TimePassesIsEnabled);
  1583. HI.Handler->endBasicBlockSection(MF->back());
  1584. }
  1585. }
  1586. for (const HandlerInfo &HI : Handlers) {
  1587. NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
  1588. HI.TimerGroupDescription, TimePassesIsEnabled);
  1589. HI.Handler->markFunctionEnd();
  1590. }
  1591. MBBSectionRanges[MF->front().getSectionIDNum()] =
  1592. MBBSectionRange{CurrentFnBegin, CurrentFnEnd};
  1593. // Print out jump tables referenced by the function.
  1594. emitJumpTableInfo();
  1595. // Emit post-function debug and/or EH information.
  1596. for (const HandlerInfo &HI : Handlers) {
  1597. NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
  1598. HI.TimerGroupDescription, TimePassesIsEnabled);
  1599. HI.Handler->endFunction(MF);
  1600. }
  1601. // Emit section containing BB address offsets and their metadata, when
  1602. // BB labels are requested for this function. Skip empty functions.
  1603. if (MF->hasBBLabels() && HasAnyRealCode)
  1604. emitBBAddrMapSection(*MF);
  1605. // Emit sections containing instruction and function PCs.
  1606. emitPCSections(*MF);
  1607. // Emit section containing stack size metadata.
  1608. emitStackSizeSection(*MF);
  1609. // Emit .su file containing function stack size information.
  1610. emitStackUsage(*MF);
  1611. emitPatchableFunctionEntries();
  1612. if (isVerbose())
  1613. OutStreamer->getCommentOS() << "-- End function\n";
  1614. OutStreamer->addBlankLine();
  1615. }
  1616. /// Compute the number of Global Variables that uses a Constant.
  1617. static unsigned getNumGlobalVariableUses(const Constant *C) {
  1618. if (!C)
  1619. return 0;
  1620. if (isa<GlobalVariable>(C))
  1621. return 1;
  1622. unsigned NumUses = 0;
  1623. for (const auto *CU : C->users())
  1624. NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
  1625. return NumUses;
  1626. }
  1627. /// Only consider global GOT equivalents if at least one user is a
  1628. /// cstexpr inside an initializer of another global variables. Also, don't
  1629. /// handle cstexpr inside instructions. During global variable emission,
  1630. /// candidates are skipped and are emitted later in case at least one cstexpr
  1631. /// isn't replaced by a PC relative GOT entry access.
  1632. static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
  1633. unsigned &NumGOTEquivUsers) {
  1634. // Global GOT equivalents are unnamed private globals with a constant
  1635. // pointer initializer to another global symbol. They must point to a
  1636. // GlobalVariable or Function, i.e., as GlobalValue.
  1637. if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
  1638. !GV->isConstant() || !GV->isDiscardableIfUnused() ||
  1639. !isa<GlobalValue>(GV->getOperand(0)))
  1640. return false;
  1641. // To be a got equivalent, at least one of its users need to be a constant
  1642. // expression used by another global variable.
  1643. for (const auto *U : GV->users())
  1644. NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
  1645. return NumGOTEquivUsers > 0;
  1646. }
  1647. /// Unnamed constant global variables solely contaning a pointer to
  1648. /// another globals variable is equivalent to a GOT table entry; it contains the
  1649. /// the address of another symbol. Optimize it and replace accesses to these
  1650. /// "GOT equivalents" by using the GOT entry for the final global instead.
  1651. /// Compute GOT equivalent candidates among all global variables to avoid
  1652. /// emitting them if possible later on, after it use is replaced by a GOT entry
  1653. /// access.
  1654. void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
  1655. if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
  1656. return;
  1657. for (const auto &G : M.globals()) {
  1658. unsigned NumGOTEquivUsers = 0;
  1659. if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
  1660. continue;
  1661. const MCSymbol *GOTEquivSym = getSymbol(&G);
  1662. GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
  1663. }
  1664. }
  1665. /// Constant expressions using GOT equivalent globals may not be eligible
  1666. /// for PC relative GOT entry conversion, in such cases we need to emit such
  1667. /// globals we previously omitted in EmitGlobalVariable.
  1668. void AsmPrinter::emitGlobalGOTEquivs() {
  1669. if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
  1670. return;
  1671. SmallVector<const GlobalVariable *, 8> FailedCandidates;
  1672. for (auto &I : GlobalGOTEquivs) {
  1673. const GlobalVariable *GV = I.second.first;
  1674. unsigned Cnt = I.second.second;
  1675. if (Cnt)
  1676. FailedCandidates.push_back(GV);
  1677. }
  1678. GlobalGOTEquivs.clear();
  1679. for (const auto *GV : FailedCandidates)
  1680. emitGlobalVariable(GV);
  1681. }
  1682. void AsmPrinter::emitGlobalAlias(Module &M, const GlobalAlias &GA) {
  1683. MCSymbol *Name = getSymbol(&GA);
  1684. bool IsFunction = GA.getValueType()->isFunctionTy();
  1685. // Treat bitcasts of functions as functions also. This is important at least
  1686. // on WebAssembly where object and function addresses can't alias each other.
  1687. if (!IsFunction)
  1688. IsFunction = isa<Function>(GA.getAliasee()->stripPointerCasts());
  1689. // AIX's assembly directive `.set` is not usable for aliasing purpose,
  1690. // so AIX has to use the extra-label-at-definition strategy. At this
  1691. // point, all the extra label is emitted, we just have to emit linkage for
  1692. // those labels.
  1693. if (TM.getTargetTriple().isOSBinFormatXCOFF()) {
  1694. assert(MAI->hasVisibilityOnlyWithLinkage() &&
  1695. "Visibility should be handled with emitLinkage() on AIX.");
  1696. // Linkage for alias of global variable has been emitted.
  1697. if (isa<GlobalVariable>(GA.getAliaseeObject()))
  1698. return;
  1699. emitLinkage(&GA, Name);
  1700. // If it's a function, also emit linkage for aliases of function entry
  1701. // point.
  1702. if (IsFunction)
  1703. emitLinkage(&GA,
  1704. getObjFileLowering().getFunctionEntryPointSymbol(&GA, TM));
  1705. return;
  1706. }
  1707. if (GA.hasExternalLinkage() || !MAI->getWeakRefDirective())
  1708. OutStreamer->emitSymbolAttribute(Name, MCSA_Global);
  1709. else if (GA.hasWeakLinkage() || GA.hasLinkOnceLinkage())
  1710. OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference);
  1711. else
  1712. assert(GA.hasLocalLinkage() && "Invalid alias linkage");
  1713. // Set the symbol type to function if the alias has a function type.
  1714. // This affects codegen when the aliasee is not a function.
  1715. if (IsFunction) {
  1716. OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeFunction);
  1717. if (TM.getTargetTriple().isOSBinFormatCOFF()) {
  1718. OutStreamer->beginCOFFSymbolDef(Name);
  1719. OutStreamer->emitCOFFSymbolStorageClass(
  1720. GA.hasLocalLinkage() ? COFF::IMAGE_SYM_CLASS_STATIC
  1721. : COFF::IMAGE_SYM_CLASS_EXTERNAL);
  1722. OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
  1723. << COFF::SCT_COMPLEX_TYPE_SHIFT);
  1724. OutStreamer->endCOFFSymbolDef();
  1725. }
  1726. }
  1727. emitVisibility(Name, GA.getVisibility());
  1728. const MCExpr *Expr = lowerConstant(GA.getAliasee());
  1729. if (MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr))
  1730. OutStreamer->emitSymbolAttribute(Name, MCSA_AltEntry);
  1731. // Emit the directives as assignments aka .set:
  1732. OutStreamer->emitAssignment(Name, Expr);
  1733. MCSymbol *LocalAlias = getSymbolPreferLocal(GA);
  1734. if (LocalAlias != Name)
  1735. OutStreamer->emitAssignment(LocalAlias, Expr);
  1736. // If the aliasee does not correspond to a symbol in the output, i.e. the
  1737. // alias is not of an object or the aliased object is private, then set the
  1738. // size of the alias symbol from the type of the alias. We don't do this in
  1739. // other situations as the alias and aliasee having differing types but same
  1740. // size may be intentional.
  1741. const GlobalObject *BaseObject = GA.getAliaseeObject();
  1742. if (MAI->hasDotTypeDotSizeDirective() && GA.getValueType()->isSized() &&
  1743. (!BaseObject || BaseObject->hasPrivateLinkage())) {
  1744. const DataLayout &DL = M.getDataLayout();
  1745. uint64_t Size = DL.getTypeAllocSize(GA.getValueType());
  1746. OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext));
  1747. }
  1748. }
  1749. void AsmPrinter::emitGlobalIFunc(Module &M, const GlobalIFunc &GI) {
  1750. assert(!TM.getTargetTriple().isOSBinFormatXCOFF() &&
  1751. "IFunc is not supported on AIX.");
  1752. MCSymbol *Name = getSymbol(&GI);
  1753. if (GI.hasExternalLinkage() || !MAI->getWeakRefDirective())
  1754. OutStreamer->emitSymbolAttribute(Name, MCSA_Global);
  1755. else if (GI.hasWeakLinkage() || GI.hasLinkOnceLinkage())
  1756. OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference);
  1757. else
  1758. assert(GI.hasLocalLinkage() && "Invalid ifunc linkage");
  1759. OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeIndFunction);
  1760. emitVisibility(Name, GI.getVisibility());
  1761. // Emit the directives as assignments aka .set:
  1762. const MCExpr *Expr = lowerConstant(GI.getResolver());
  1763. OutStreamer->emitAssignment(Name, Expr);
  1764. MCSymbol *LocalAlias = getSymbolPreferLocal(GI);
  1765. if (LocalAlias != Name)
  1766. OutStreamer->emitAssignment(LocalAlias, Expr);
  1767. }
  1768. void AsmPrinter::emitRemarksSection(remarks::RemarkStreamer &RS) {
  1769. if (!RS.needsSection())
  1770. return;
  1771. remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer();
  1772. std::optional<SmallString<128>> Filename;
  1773. if (std::optional<StringRef> FilenameRef = RS.getFilename()) {
  1774. Filename = *FilenameRef;
  1775. sys::fs::make_absolute(*Filename);
  1776. assert(!Filename->empty() && "The filename can't be empty.");
  1777. }
  1778. std::string Buf;
  1779. raw_string_ostream OS(Buf);
  1780. std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
  1781. Filename ? RemarkSerializer.metaSerializer(OS, Filename->str())
  1782. : RemarkSerializer.metaSerializer(OS);
  1783. MetaSerializer->emit();
  1784. // Switch to the remarks section.
  1785. MCSection *RemarksSection =
  1786. OutContext.getObjectFileInfo()->getRemarksSection();
  1787. OutStreamer->switchSection(RemarksSection);
  1788. OutStreamer->emitBinaryData(OS.str());
  1789. }
  1790. bool AsmPrinter::doFinalization(Module &M) {
  1791. // Set the MachineFunction to nullptr so that we can catch attempted
  1792. // accesses to MF specific features at the module level and so that
  1793. // we can conditionalize accesses based on whether or not it is nullptr.
  1794. MF = nullptr;
  1795. // Gather all GOT equivalent globals in the module. We really need two
  1796. // passes over the globals: one to compute and another to avoid its emission
  1797. // in EmitGlobalVariable, otherwise we would not be able to handle cases
  1798. // where the got equivalent shows up before its use.
  1799. computeGlobalGOTEquivs(M);
  1800. // Emit global variables.
  1801. for (const auto &G : M.globals())
  1802. emitGlobalVariable(&G);
  1803. // Emit remaining GOT equivalent globals.
  1804. emitGlobalGOTEquivs();
  1805. const TargetLoweringObjectFile &TLOF = getObjFileLowering();
  1806. // Emit linkage(XCOFF) and visibility info for declarations
  1807. for (const Function &F : M) {
  1808. if (!F.isDeclarationForLinker())
  1809. continue;
  1810. MCSymbol *Name = getSymbol(&F);
  1811. // Function getSymbol gives us the function descriptor symbol for XCOFF.
  1812. if (!TM.getTargetTriple().isOSBinFormatXCOFF()) {
  1813. GlobalValue::VisibilityTypes V = F.getVisibility();
  1814. if (V == GlobalValue::DefaultVisibility)
  1815. continue;
  1816. emitVisibility(Name, V, false);
  1817. continue;
  1818. }
  1819. if (F.isIntrinsic())
  1820. continue;
  1821. // Handle the XCOFF case.
  1822. // Variable `Name` is the function descriptor symbol (see above). Get the
  1823. // function entry point symbol.
  1824. MCSymbol *FnEntryPointSym = TLOF.getFunctionEntryPointSymbol(&F, TM);
  1825. // Emit linkage for the function entry point.
  1826. emitLinkage(&F, FnEntryPointSym);
  1827. // Emit linkage for the function descriptor.
  1828. emitLinkage(&F, Name);
  1829. }
  1830. // Emit the remarks section contents.
  1831. // FIXME: Figure out when is the safest time to emit this section. It should
  1832. // not come after debug info.
  1833. if (remarks::RemarkStreamer *RS = M.getContext().getMainRemarkStreamer())
  1834. emitRemarksSection(*RS);
  1835. TLOF.emitModuleMetadata(*OutStreamer, M);
  1836. if (TM.getTargetTriple().isOSBinFormatELF()) {
  1837. MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
  1838. // Output stubs for external and common global variables.
  1839. MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
  1840. if (!Stubs.empty()) {
  1841. OutStreamer->switchSection(TLOF.getDataSection());
  1842. const DataLayout &DL = M.getDataLayout();
  1843. emitAlignment(Align(DL.getPointerSize()));
  1844. for (const auto &Stub : Stubs) {
  1845. OutStreamer->emitLabel(Stub.first);
  1846. OutStreamer->emitSymbolValue(Stub.second.getPointer(),
  1847. DL.getPointerSize());
  1848. }
  1849. }
  1850. }
  1851. if (TM.getTargetTriple().isOSBinFormatCOFF()) {
  1852. MachineModuleInfoCOFF &MMICOFF =
  1853. MMI->getObjFileInfo<MachineModuleInfoCOFF>();
  1854. // Output stubs for external and common global variables.
  1855. MachineModuleInfoCOFF::SymbolListTy Stubs = MMICOFF.GetGVStubList();
  1856. if (!Stubs.empty()) {
  1857. const DataLayout &DL = M.getDataLayout();
  1858. for (const auto &Stub : Stubs) {
  1859. SmallString<256> SectionName = StringRef(".rdata$");
  1860. SectionName += Stub.first->getName();
  1861. OutStreamer->switchSection(OutContext.getCOFFSection(
  1862. SectionName,
  1863. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ |
  1864. COFF::IMAGE_SCN_LNK_COMDAT,
  1865. SectionKind::getReadOnly(), Stub.first->getName(),
  1866. COFF::IMAGE_COMDAT_SELECT_ANY));
  1867. emitAlignment(Align(DL.getPointerSize()));
  1868. OutStreamer->emitSymbolAttribute(Stub.first, MCSA_Global);
  1869. OutStreamer->emitLabel(Stub.first);
  1870. OutStreamer->emitSymbolValue(Stub.second.getPointer(),
  1871. DL.getPointerSize());
  1872. }
  1873. }
  1874. }
  1875. // This needs to happen before emitting debug information since that can end
  1876. // arbitrary sections.
  1877. if (auto *TS = OutStreamer->getTargetStreamer())
  1878. TS->emitConstantPools();
  1879. // Emit Stack maps before any debug info. Mach-O requires that no data or
  1880. // text sections come after debug info has been emitted. This matters for
  1881. // stack maps as they are arbitrary data, and may even have a custom format
  1882. // through user plugins.
  1883. emitStackMaps();
  1884. // Finalize debug and EH information.
  1885. for (const HandlerInfo &HI : Handlers) {
  1886. NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
  1887. HI.TimerGroupDescription, TimePassesIsEnabled);
  1888. HI.Handler->endModule();
  1889. }
  1890. // This deletes all the ephemeral handlers that AsmPrinter added, while
  1891. // keeping all the user-added handlers alive until the AsmPrinter is
  1892. // destroyed.
  1893. Handlers.erase(Handlers.begin() + NumUserHandlers, Handlers.end());
  1894. DD = nullptr;
  1895. // If the target wants to know about weak references, print them all.
  1896. if (MAI->getWeakRefDirective()) {
  1897. // FIXME: This is not lazy, it would be nice to only print weak references
  1898. // to stuff that is actually used. Note that doing so would require targets
  1899. // to notice uses in operands (due to constant exprs etc). This should
  1900. // happen with the MC stuff eventually.
  1901. // Print out module-level global objects here.
  1902. for (const auto &GO : M.global_objects()) {
  1903. if (!GO.hasExternalWeakLinkage())
  1904. continue;
  1905. OutStreamer->emitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
  1906. }
  1907. if (shouldEmitWeakSwiftAsyncExtendedFramePointerFlags()) {
  1908. auto SymbolName = "swift_async_extendedFramePointerFlags";
  1909. auto Global = M.getGlobalVariable(SymbolName);
  1910. if (!Global) {
  1911. auto Int8PtrTy = Type::getInt8PtrTy(M.getContext());
  1912. Global = new GlobalVariable(M, Int8PtrTy, false,
  1913. GlobalValue::ExternalWeakLinkage, nullptr,
  1914. SymbolName);
  1915. OutStreamer->emitSymbolAttribute(getSymbol(Global), MCSA_WeakReference);
  1916. }
  1917. }
  1918. }
  1919. // Print aliases in topological order, that is, for each alias a = b,
  1920. // b must be printed before a.
  1921. // This is because on some targets (e.g. PowerPC) linker expects aliases in
  1922. // such an order to generate correct TOC information.
  1923. SmallVector<const GlobalAlias *, 16> AliasStack;
  1924. SmallPtrSet<const GlobalAlias *, 16> AliasVisited;
  1925. for (const auto &Alias : M.aliases()) {
  1926. if (Alias.hasAvailableExternallyLinkage())
  1927. continue;
  1928. for (const GlobalAlias *Cur = &Alias; Cur;
  1929. Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
  1930. if (!AliasVisited.insert(Cur).second)
  1931. break;
  1932. AliasStack.push_back(Cur);
  1933. }
  1934. for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack))
  1935. emitGlobalAlias(M, *AncestorAlias);
  1936. AliasStack.clear();
  1937. }
  1938. for (const auto &IFunc : M.ifuncs())
  1939. emitGlobalIFunc(M, IFunc);
  1940. GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
  1941. assert(MI && "AsmPrinter didn't require GCModuleInfo?");
  1942. for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
  1943. if (GCMetadataPrinter *MP = getOrCreateGCPrinter(**--I))
  1944. MP->finishAssembly(M, *MI, *this);
  1945. // Emit llvm.ident metadata in an '.ident' directive.
  1946. emitModuleIdents(M);
  1947. // Emit bytes for llvm.commandline metadata.
  1948. emitModuleCommandLines(M);
  1949. // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
  1950. // split-stack is used.
  1951. if (TM.getTargetTriple().isOSBinFormatELF() && HasSplitStack) {
  1952. OutStreamer->switchSection(OutContext.getELFSection(".note.GNU-split-stack",
  1953. ELF::SHT_PROGBITS, 0));
  1954. if (HasNoSplitStack)
  1955. OutStreamer->switchSection(OutContext.getELFSection(
  1956. ".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0));
  1957. }
  1958. // If we don't have any trampolines, then we don't require stack memory
  1959. // to be executable. Some targets have a directive to declare this.
  1960. Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
  1961. if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
  1962. if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
  1963. OutStreamer->switchSection(S);
  1964. if (TM.Options.EmitAddrsig) {
  1965. // Emit address-significance attributes for all globals.
  1966. OutStreamer->emitAddrsig();
  1967. for (const GlobalValue &GV : M.global_values()) {
  1968. if (!GV.use_empty() && !GV.isThreadLocal() &&
  1969. !GV.hasDLLImportStorageClass() && !GV.getName().startswith("llvm.") &&
  1970. !GV.hasAtLeastLocalUnnamedAddr())
  1971. OutStreamer->emitAddrsigSym(getSymbol(&GV));
  1972. }
  1973. }
  1974. // Emit symbol partition specifications (ELF only).
  1975. if (TM.getTargetTriple().isOSBinFormatELF()) {
  1976. unsigned UniqueID = 0;
  1977. for (const GlobalValue &GV : M.global_values()) {
  1978. if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
  1979. GV.getVisibility() != GlobalValue::DefaultVisibility)
  1980. continue;
  1981. OutStreamer->switchSection(
  1982. OutContext.getELFSection(".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0,
  1983. "", false, ++UniqueID, nullptr));
  1984. OutStreamer->emitBytes(GV.getPartition());
  1985. OutStreamer->emitZeros(1);
  1986. OutStreamer->emitValue(
  1987. MCSymbolRefExpr::create(getSymbol(&GV), OutContext),
  1988. MAI->getCodePointerSize());
  1989. }
  1990. }
  1991. // Allow the target to emit any magic that it wants at the end of the file,
  1992. // after everything else has gone out.
  1993. emitEndOfAsmFile(M);
  1994. MMI = nullptr;
  1995. AddrLabelSymbols = nullptr;
  1996. OutStreamer->finish();
  1997. OutStreamer->reset();
  1998. OwnedMLI.reset();
  1999. OwnedMDT.reset();
  2000. return false;
  2001. }
  2002. MCSymbol *AsmPrinter::getMBBExceptionSym(const MachineBasicBlock &MBB) {
  2003. auto Res = MBBSectionExceptionSyms.try_emplace(MBB.getSectionIDNum());
  2004. if (Res.second)
  2005. Res.first->second = createTempSymbol("exception");
  2006. return Res.first->second;
  2007. }
  2008. void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
  2009. this->MF = &MF;
  2010. const Function &F = MF.getFunction();
  2011. // Record that there are split-stack functions, so we will emit a special
  2012. // section to tell the linker.
  2013. if (MF.shouldSplitStack()) {
  2014. HasSplitStack = true;
  2015. if (!MF.getFrameInfo().needsSplitStackProlog())
  2016. HasNoSplitStack = true;
  2017. } else
  2018. HasNoSplitStack = true;
  2019. // Get the function symbol.
  2020. if (!MAI->needsFunctionDescriptors()) {
  2021. CurrentFnSym = getSymbol(&MF.getFunction());
  2022. } else {
  2023. assert(TM.getTargetTriple().isOSAIX() &&
  2024. "Only AIX uses the function descriptor hooks.");
  2025. // AIX is unique here in that the name of the symbol emitted for the
  2026. // function body does not have the same name as the source function's
  2027. // C-linkage name.
  2028. assert(CurrentFnDescSym && "The function descriptor symbol needs to be"
  2029. " initalized first.");
  2030. // Get the function entry point symbol.
  2031. CurrentFnSym = getObjFileLowering().getFunctionEntryPointSymbol(&F, TM);
  2032. }
  2033. CurrentFnSymForSize = CurrentFnSym;
  2034. CurrentFnBegin = nullptr;
  2035. CurrentFnBeginLocal = nullptr;
  2036. CurrentSectionBeginSym = nullptr;
  2037. MBBSectionRanges.clear();
  2038. MBBSectionExceptionSyms.clear();
  2039. bool NeedsLocalForSize = MAI->needsLocalForSize();
  2040. if (F.hasFnAttribute("patchable-function-entry") ||
  2041. F.hasFnAttribute("function-instrument") ||
  2042. F.hasFnAttribute("xray-instruction-threshold") ||
  2043. needFuncLabels(MF) || NeedsLocalForSize ||
  2044. MF.getTarget().Options.EmitStackSizeSection || MF.hasBBLabels()) {
  2045. CurrentFnBegin = createTempSymbol("func_begin");
  2046. if (NeedsLocalForSize)
  2047. CurrentFnSymForSize = CurrentFnBegin;
  2048. }
  2049. ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
  2050. }
  2051. namespace {
  2052. // Keep track the alignment, constpool entries per Section.
  2053. struct SectionCPs {
  2054. MCSection *S;
  2055. Align Alignment;
  2056. SmallVector<unsigned, 4> CPEs;
  2057. SectionCPs(MCSection *s, Align a) : S(s), Alignment(a) {}
  2058. };
  2059. } // end anonymous namespace
  2060. /// EmitConstantPool - Print to the current output stream assembly
  2061. /// representations of the constants in the constant pool MCP. This is
  2062. /// used to print out constants which have been "spilled to memory" by
  2063. /// the code generator.
  2064. void AsmPrinter::emitConstantPool() {
  2065. const MachineConstantPool *MCP = MF->getConstantPool();
  2066. const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
  2067. if (CP.empty()) return;
  2068. // Calculate sections for constant pool entries. We collect entries to go into
  2069. // the same section together to reduce amount of section switch statements.
  2070. SmallVector<SectionCPs, 4> CPSections;
  2071. for (unsigned i = 0, e = CP.size(); i != e; ++i) {
  2072. const MachineConstantPoolEntry &CPE = CP[i];
  2073. Align Alignment = CPE.getAlign();
  2074. SectionKind Kind = CPE.getSectionKind(&getDataLayout());
  2075. const Constant *C = nullptr;
  2076. if (!CPE.isMachineConstantPoolEntry())
  2077. C = CPE.Val.ConstVal;
  2078. MCSection *S = getObjFileLowering().getSectionForConstant(
  2079. getDataLayout(), Kind, C, Alignment);
  2080. // The number of sections are small, just do a linear search from the
  2081. // last section to the first.
  2082. bool Found = false;
  2083. unsigned SecIdx = CPSections.size();
  2084. while (SecIdx != 0) {
  2085. if (CPSections[--SecIdx].S == S) {
  2086. Found = true;
  2087. break;
  2088. }
  2089. }
  2090. if (!Found) {
  2091. SecIdx = CPSections.size();
  2092. CPSections.push_back(SectionCPs(S, Alignment));
  2093. }
  2094. if (Alignment > CPSections[SecIdx].Alignment)
  2095. CPSections[SecIdx].Alignment = Alignment;
  2096. CPSections[SecIdx].CPEs.push_back(i);
  2097. }
  2098. // Now print stuff into the calculated sections.
  2099. const MCSection *CurSection = nullptr;
  2100. unsigned Offset = 0;
  2101. for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
  2102. for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
  2103. unsigned CPI = CPSections[i].CPEs[j];
  2104. MCSymbol *Sym = GetCPISymbol(CPI);
  2105. if (!Sym->isUndefined())
  2106. continue;
  2107. if (CurSection != CPSections[i].S) {
  2108. OutStreamer->switchSection(CPSections[i].S);
  2109. emitAlignment(Align(CPSections[i].Alignment));
  2110. CurSection = CPSections[i].S;
  2111. Offset = 0;
  2112. }
  2113. MachineConstantPoolEntry CPE = CP[CPI];
  2114. // Emit inter-object padding for alignment.
  2115. unsigned NewOffset = alignTo(Offset, CPE.getAlign());
  2116. OutStreamer->emitZeros(NewOffset - Offset);
  2117. Offset = NewOffset + CPE.getSizeInBytes(getDataLayout());
  2118. OutStreamer->emitLabel(Sym);
  2119. if (CPE.isMachineConstantPoolEntry())
  2120. emitMachineConstantPoolValue(CPE.Val.MachineCPVal);
  2121. else
  2122. emitGlobalConstant(getDataLayout(), CPE.Val.ConstVal);
  2123. }
  2124. }
  2125. }
  2126. // Print assembly representations of the jump tables used by the current
  2127. // function.
  2128. void AsmPrinter::emitJumpTableInfo() {
  2129. const DataLayout &DL = MF->getDataLayout();
  2130. const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
  2131. if (!MJTI) return;
  2132. if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
  2133. const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
  2134. if (JT.empty()) return;
  2135. // Pick the directive to use to print the jump table entries, and switch to
  2136. // the appropriate section.
  2137. const Function &F = MF->getFunction();
  2138. const TargetLoweringObjectFile &TLOF = getObjFileLowering();
  2139. bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
  2140. MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
  2141. F);
  2142. if (JTInDiffSection) {
  2143. // Drop it in the readonly section.
  2144. MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM);
  2145. OutStreamer->switchSection(ReadOnlySection);
  2146. }
  2147. emitAlignment(Align(MJTI->getEntryAlignment(DL)));
  2148. // Jump tables in code sections are marked with a data_region directive
  2149. // where that's supported.
  2150. if (!JTInDiffSection)
  2151. OutStreamer->emitDataRegion(MCDR_DataRegionJT32);
  2152. for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
  2153. const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
  2154. // If this jump table was deleted, ignore it.
  2155. if (JTBBs.empty()) continue;
  2156. // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
  2157. /// emit a .set directive for each unique entry.
  2158. if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
  2159. MAI->doesSetDirectiveSuppressReloc()) {
  2160. SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
  2161. const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
  2162. const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
  2163. for (const MachineBasicBlock *MBB : JTBBs) {
  2164. if (!EmittedSets.insert(MBB).second)
  2165. continue;
  2166. // .set LJTSet, LBB32-base
  2167. const MCExpr *LHS =
  2168. MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
  2169. OutStreamer->emitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
  2170. MCBinaryExpr::createSub(LHS, Base,
  2171. OutContext));
  2172. }
  2173. }
  2174. // On some targets (e.g. Darwin) we want to emit two consecutive labels
  2175. // before each jump table. The first label is never referenced, but tells
  2176. // the assembler and linker the extents of the jump table object. The
  2177. // second label is actually referenced by the code.
  2178. if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
  2179. // FIXME: This doesn't have to have any specific name, just any randomly
  2180. // named and numbered local label started with 'l' would work. Simplify
  2181. // GetJTISymbol.
  2182. OutStreamer->emitLabel(GetJTISymbol(JTI, true));
  2183. MCSymbol* JTISymbol = GetJTISymbol(JTI);
  2184. OutStreamer->emitLabel(JTISymbol);
  2185. for (const MachineBasicBlock *MBB : JTBBs)
  2186. emitJumpTableEntry(MJTI, MBB, JTI);
  2187. }
  2188. if (!JTInDiffSection)
  2189. OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
  2190. }
  2191. /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
  2192. /// current stream.
  2193. void AsmPrinter::emitJumpTableEntry(const MachineJumpTableInfo *MJTI,
  2194. const MachineBasicBlock *MBB,
  2195. unsigned UID) const {
  2196. assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
  2197. const MCExpr *Value = nullptr;
  2198. switch (MJTI->getEntryKind()) {
  2199. case MachineJumpTableInfo::EK_Inline:
  2200. llvm_unreachable("Cannot emit EK_Inline jump table entry");
  2201. case MachineJumpTableInfo::EK_Custom32:
  2202. Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
  2203. MJTI, MBB, UID, OutContext);
  2204. break;
  2205. case MachineJumpTableInfo::EK_BlockAddress:
  2206. // EK_BlockAddress - Each entry is a plain address of block, e.g.:
  2207. // .word LBB123
  2208. Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
  2209. break;
  2210. case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
  2211. // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
  2212. // with a relocation as gp-relative, e.g.:
  2213. // .gprel32 LBB123
  2214. MCSymbol *MBBSym = MBB->getSymbol();
  2215. OutStreamer->emitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
  2216. return;
  2217. }
  2218. case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
  2219. // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
  2220. // with a relocation as gp-relative, e.g.:
  2221. // .gpdword LBB123
  2222. MCSymbol *MBBSym = MBB->getSymbol();
  2223. OutStreamer->emitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
  2224. return;
  2225. }
  2226. case MachineJumpTableInfo::EK_LabelDifference32: {
  2227. // Each entry is the address of the block minus the address of the jump
  2228. // table. This is used for PIC jump tables where gprel32 is not supported.
  2229. // e.g.:
  2230. // .word LBB123 - LJTI1_2
  2231. // If the .set directive avoids relocations, this is emitted as:
  2232. // .set L4_5_set_123, LBB123 - LJTI1_2
  2233. // .word L4_5_set_123
  2234. if (MAI->doesSetDirectiveSuppressReloc()) {
  2235. Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
  2236. OutContext);
  2237. break;
  2238. }
  2239. Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
  2240. const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
  2241. const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
  2242. Value = MCBinaryExpr::createSub(Value, Base, OutContext);
  2243. break;
  2244. }
  2245. }
  2246. assert(Value && "Unknown entry kind!");
  2247. unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
  2248. OutStreamer->emitValue(Value, EntrySize);
  2249. }
  2250. /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
  2251. /// special global used by LLVM. If so, emit it and return true, otherwise
  2252. /// do nothing and return false.
  2253. bool AsmPrinter::emitSpecialLLVMGlobal(const GlobalVariable *GV) {
  2254. if (GV->getName() == "llvm.used") {
  2255. if (MAI->hasNoDeadStrip()) // No need to emit this at all.
  2256. emitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
  2257. return true;
  2258. }
  2259. // Ignore debug and non-emitted data. This handles llvm.compiler.used.
  2260. if (GV->getSection() == "llvm.metadata" ||
  2261. GV->hasAvailableExternallyLinkage())
  2262. return true;
  2263. if (!GV->hasAppendingLinkage()) return false;
  2264. assert(GV->hasInitializer() && "Not a special LLVM global!");
  2265. if (GV->getName() == "llvm.global_ctors") {
  2266. emitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
  2267. /* isCtor */ true);
  2268. return true;
  2269. }
  2270. if (GV->getName() == "llvm.global_dtors") {
  2271. emitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
  2272. /* isCtor */ false);
  2273. return true;
  2274. }
  2275. report_fatal_error("unknown special variable");
  2276. }
  2277. /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
  2278. /// global in the specified llvm.used list.
  2279. void AsmPrinter::emitLLVMUsedList(const ConstantArray *InitList) {
  2280. // Should be an array of 'i8*'.
  2281. for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
  2282. const GlobalValue *GV =
  2283. dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
  2284. if (GV)
  2285. OutStreamer->emitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
  2286. }
  2287. }
  2288. void AsmPrinter::preprocessXXStructorList(const DataLayout &DL,
  2289. const Constant *List,
  2290. SmallVector<Structor, 8> &Structors) {
  2291. // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is
  2292. // the init priority.
  2293. if (!isa<ConstantArray>(List))
  2294. return;
  2295. // Gather the structors in a form that's convenient for sorting by priority.
  2296. for (Value *O : cast<ConstantArray>(List)->operands()) {
  2297. auto *CS = cast<ConstantStruct>(O);
  2298. if (CS->getOperand(1)->isNullValue())
  2299. break; // Found a null terminator, skip the rest.
  2300. ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
  2301. if (!Priority)
  2302. continue; // Malformed.
  2303. Structors.push_back(Structor());
  2304. Structor &S = Structors.back();
  2305. S.Priority = Priority->getLimitedValue(65535);
  2306. S.Func = CS->getOperand(1);
  2307. if (!CS->getOperand(2)->isNullValue()) {
  2308. if (TM.getTargetTriple().isOSAIX())
  2309. llvm::report_fatal_error(
  2310. "associated data of XXStructor list is not yet supported on AIX");
  2311. S.ComdatKey =
  2312. dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
  2313. }
  2314. }
  2315. // Emit the function pointers in the target-specific order
  2316. llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) {
  2317. return L.Priority < R.Priority;
  2318. });
  2319. }
  2320. /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
  2321. /// priority.
  2322. void AsmPrinter::emitXXStructorList(const DataLayout &DL, const Constant *List,
  2323. bool IsCtor) {
  2324. SmallVector<Structor, 8> Structors;
  2325. preprocessXXStructorList(DL, List, Structors);
  2326. if (Structors.empty())
  2327. return;
  2328. // Emit the structors in reverse order if we are using the .ctor/.dtor
  2329. // initialization scheme.
  2330. if (!TM.Options.UseInitArray)
  2331. std::reverse(Structors.begin(), Structors.end());
  2332. const Align Align = DL.getPointerPrefAlignment();
  2333. for (Structor &S : Structors) {
  2334. const TargetLoweringObjectFile &Obj = getObjFileLowering();
  2335. const MCSymbol *KeySym = nullptr;
  2336. if (GlobalValue *GV = S.ComdatKey) {
  2337. if (GV->isDeclarationForLinker())
  2338. // If the associated variable is not defined in this module
  2339. // (it might be available_externally, or have been an
  2340. // available_externally definition that was dropped by the
  2341. // EliminateAvailableExternally pass), some other TU
  2342. // will provide its dynamic initializer.
  2343. continue;
  2344. KeySym = getSymbol(GV);
  2345. }
  2346. MCSection *OutputSection =
  2347. (IsCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
  2348. : Obj.getStaticDtorSection(S.Priority, KeySym));
  2349. OutStreamer->switchSection(OutputSection);
  2350. if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
  2351. emitAlignment(Align);
  2352. emitXXStructor(DL, S.Func);
  2353. }
  2354. }
  2355. void AsmPrinter::emitModuleIdents(Module &M) {
  2356. if (!MAI->hasIdentDirective())
  2357. return;
  2358. if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
  2359. for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
  2360. const MDNode *N = NMD->getOperand(i);
  2361. assert(N->getNumOperands() == 1 &&
  2362. "llvm.ident metadata entry can have only one operand");
  2363. const MDString *S = cast<MDString>(N->getOperand(0));
  2364. OutStreamer->emitIdent(S->getString());
  2365. }
  2366. }
  2367. }
  2368. void AsmPrinter::emitModuleCommandLines(Module &M) {
  2369. MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines();
  2370. if (!CommandLine)
  2371. return;
  2372. const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
  2373. if (!NMD || !NMD->getNumOperands())
  2374. return;
  2375. OutStreamer->pushSection();
  2376. OutStreamer->switchSection(CommandLine);
  2377. OutStreamer->emitZeros(1);
  2378. for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
  2379. const MDNode *N = NMD->getOperand(i);
  2380. assert(N->getNumOperands() == 1 &&
  2381. "llvm.commandline metadata entry can have only one operand");
  2382. const MDString *S = cast<MDString>(N->getOperand(0));
  2383. OutStreamer->emitBytes(S->getString());
  2384. OutStreamer->emitZeros(1);
  2385. }
  2386. OutStreamer->popSection();
  2387. }
  2388. //===--------------------------------------------------------------------===//
  2389. // Emission and print routines
  2390. //
  2391. /// Emit a byte directive and value.
  2392. ///
  2393. void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); }
  2394. /// Emit a short directive and value.
  2395. void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); }
  2396. /// Emit a long directive and value.
  2397. void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); }
  2398. /// Emit a long long directive and value.
  2399. void AsmPrinter::emitInt64(uint64_t Value) const {
  2400. OutStreamer->emitInt64(Value);
  2401. }
  2402. /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
  2403. /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
  2404. /// .set if it avoids relocations.
  2405. void AsmPrinter::emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
  2406. unsigned Size) const {
  2407. OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
  2408. }
  2409. /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
  2410. /// where the size in bytes of the directive is specified by Size and Label
  2411. /// specifies the label. This implicitly uses .set if it is available.
  2412. void AsmPrinter::emitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
  2413. unsigned Size,
  2414. bool IsSectionRelative) const {
  2415. if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
  2416. OutStreamer->emitCOFFSecRel32(Label, Offset);
  2417. if (Size > 4)
  2418. OutStreamer->emitZeros(Size - 4);
  2419. return;
  2420. }
  2421. // Emit Label+Offset (or just Label if Offset is zero)
  2422. const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
  2423. if (Offset)
  2424. Expr = MCBinaryExpr::createAdd(
  2425. Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
  2426. OutStreamer->emitValue(Expr, Size);
  2427. }
  2428. //===----------------------------------------------------------------------===//
  2429. // EmitAlignment - Emit an alignment directive to the specified power of
  2430. // two boundary. If a global value is specified, and if that global has
  2431. // an explicit alignment requested, it will override the alignment request
  2432. // if required for correctness.
  2433. void AsmPrinter::emitAlignment(Align Alignment, const GlobalObject *GV,
  2434. unsigned MaxBytesToEmit) const {
  2435. if (GV)
  2436. Alignment = getGVAlignment(GV, GV->getParent()->getDataLayout(), Alignment);
  2437. if (Alignment == Align(1))
  2438. return; // 1-byte aligned: no need to emit alignment.
  2439. if (getCurrentSection()->getKind().isText()) {
  2440. const MCSubtargetInfo *STI = nullptr;
  2441. if (this->MF)
  2442. STI = &getSubtargetInfo();
  2443. else
  2444. STI = TM.getMCSubtargetInfo();
  2445. OutStreamer->emitCodeAlignment(Alignment, STI, MaxBytesToEmit);
  2446. } else
  2447. OutStreamer->emitValueToAlignment(Alignment, 0, 1, MaxBytesToEmit);
  2448. }
  2449. //===----------------------------------------------------------------------===//
  2450. // Constant emission.
  2451. //===----------------------------------------------------------------------===//
  2452. const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
  2453. MCContext &Ctx = OutContext;
  2454. if (CV->isNullValue() || isa<UndefValue>(CV))
  2455. return MCConstantExpr::create(0, Ctx);
  2456. if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
  2457. return MCConstantExpr::create(CI->getZExtValue(), Ctx);
  2458. if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
  2459. return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
  2460. if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
  2461. return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx);
  2462. if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV))
  2463. return getObjFileLowering().lowerDSOLocalEquivalent(Equiv, TM);
  2464. if (const NoCFIValue *NC = dyn_cast<NoCFIValue>(CV))
  2465. return MCSymbolRefExpr::create(getSymbol(NC->getGlobalValue()), Ctx);
  2466. const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
  2467. if (!CE) {
  2468. llvm_unreachable("Unknown constant value to lower!");
  2469. }
  2470. // The constant expression opcodes are limited to those that are necessary
  2471. // to represent relocations on supported targets. Expressions involving only
  2472. // constant addresses are constant folded instead.
  2473. switch (CE->getOpcode()) {
  2474. default:
  2475. break; // Error
  2476. case Instruction::AddrSpaceCast: {
  2477. const Constant *Op = CE->getOperand(0);
  2478. unsigned DstAS = CE->getType()->getPointerAddressSpace();
  2479. unsigned SrcAS = Op->getType()->getPointerAddressSpace();
  2480. if (TM.isNoopAddrSpaceCast(SrcAS, DstAS))
  2481. return lowerConstant(Op);
  2482. break; // Error
  2483. }
  2484. case Instruction::GetElementPtr: {
  2485. // Generate a symbolic expression for the byte address
  2486. APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
  2487. cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
  2488. const MCExpr *Base = lowerConstant(CE->getOperand(0));
  2489. if (!OffsetAI)
  2490. return Base;
  2491. int64_t Offset = OffsetAI.getSExtValue();
  2492. return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
  2493. Ctx);
  2494. }
  2495. case Instruction::Trunc:
  2496. // We emit the value and depend on the assembler to truncate the generated
  2497. // expression properly. This is important for differences between
  2498. // blockaddress labels. Since the two labels are in the same function, it
  2499. // is reasonable to treat their delta as a 32-bit value.
  2500. [[fallthrough]];
  2501. case Instruction::BitCast:
  2502. return lowerConstant(CE->getOperand(0));
  2503. case Instruction::IntToPtr: {
  2504. const DataLayout &DL = getDataLayout();
  2505. // Handle casts to pointers by changing them into casts to the appropriate
  2506. // integer type. This promotes constant folding and simplifies this code.
  2507. Constant *Op = CE->getOperand(0);
  2508. Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
  2509. false/*ZExt*/);
  2510. return lowerConstant(Op);
  2511. }
  2512. case Instruction::PtrToInt: {
  2513. const DataLayout &DL = getDataLayout();
  2514. // Support only foldable casts to/from pointers that can be eliminated by
  2515. // changing the pointer to the appropriately sized integer type.
  2516. Constant *Op = CE->getOperand(0);
  2517. Type *Ty = CE->getType();
  2518. const MCExpr *OpExpr = lowerConstant(Op);
  2519. // We can emit the pointer value into this slot if the slot is an
  2520. // integer slot equal to the size of the pointer.
  2521. //
  2522. // If the pointer is larger than the resultant integer, then
  2523. // as with Trunc just depend on the assembler to truncate it.
  2524. if (DL.getTypeAllocSize(Ty).getFixedValue() <=
  2525. DL.getTypeAllocSize(Op->getType()).getFixedValue())
  2526. return OpExpr;
  2527. break; // Error
  2528. }
  2529. case Instruction::Sub: {
  2530. GlobalValue *LHSGV;
  2531. APInt LHSOffset;
  2532. DSOLocalEquivalent *DSOEquiv;
  2533. if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
  2534. getDataLayout(), &DSOEquiv)) {
  2535. GlobalValue *RHSGV;
  2536. APInt RHSOffset;
  2537. if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
  2538. getDataLayout())) {
  2539. const MCExpr *RelocExpr =
  2540. getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM);
  2541. if (!RelocExpr) {
  2542. const MCExpr *LHSExpr =
  2543. MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx);
  2544. if (DSOEquiv &&
  2545. getObjFileLowering().supportDSOLocalEquivalentLowering())
  2546. LHSExpr =
  2547. getObjFileLowering().lowerDSOLocalEquivalent(DSOEquiv, TM);
  2548. RelocExpr = MCBinaryExpr::createSub(
  2549. LHSExpr, MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx);
  2550. }
  2551. int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
  2552. if (Addend != 0)
  2553. RelocExpr = MCBinaryExpr::createAdd(
  2554. RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx);
  2555. return RelocExpr;
  2556. }
  2557. }
  2558. const MCExpr *LHS = lowerConstant(CE->getOperand(0));
  2559. const MCExpr *RHS = lowerConstant(CE->getOperand(1));
  2560. return MCBinaryExpr::createSub(LHS, RHS, Ctx);
  2561. break;
  2562. }
  2563. case Instruction::Add: {
  2564. const MCExpr *LHS = lowerConstant(CE->getOperand(0));
  2565. const MCExpr *RHS = lowerConstant(CE->getOperand(1));
  2566. return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
  2567. }
  2568. }
  2569. // If the code isn't optimized, there may be outstanding folding
  2570. // opportunities. Attempt to fold the expression using DataLayout as a
  2571. // last resort before giving up.
  2572. Constant *C = ConstantFoldConstant(CE, getDataLayout());
  2573. if (C != CE)
  2574. return lowerConstant(C);
  2575. // Otherwise report the problem to the user.
  2576. std::string S;
  2577. raw_string_ostream OS(S);
  2578. OS << "Unsupported expression in static initializer: ";
  2579. CE->printAsOperand(OS, /*PrintType=*/false,
  2580. !MF ? nullptr : MF->getFunction().getParent());
  2581. report_fatal_error(Twine(OS.str()));
  2582. }
  2583. static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
  2584. AsmPrinter &AP,
  2585. const Constant *BaseCV = nullptr,
  2586. uint64_t Offset = 0,
  2587. AsmPrinter::AliasMapTy *AliasList = nullptr);
  2588. static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
  2589. static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
  2590. /// isRepeatedByteSequence - Determine whether the given value is
  2591. /// composed of a repeated sequence of identical bytes and return the
  2592. /// byte value. If it is not a repeated sequence, return -1.
  2593. static int isRepeatedByteSequence(const ConstantDataSequential *V) {
  2594. StringRef Data = V->getRawDataValues();
  2595. assert(!Data.empty() && "Empty aggregates should be CAZ node");
  2596. char C = Data[0];
  2597. for (unsigned i = 1, e = Data.size(); i != e; ++i)
  2598. if (Data[i] != C) return -1;
  2599. return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
  2600. }
  2601. /// isRepeatedByteSequence - Determine whether the given value is
  2602. /// composed of a repeated sequence of identical bytes and return the
  2603. /// byte value. If it is not a repeated sequence, return -1.
  2604. static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
  2605. if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  2606. uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
  2607. assert(Size % 8 == 0);
  2608. // Extend the element to take zero padding into account.
  2609. APInt Value = CI->getValue().zext(Size);
  2610. if (!Value.isSplat(8))
  2611. return -1;
  2612. return Value.zextOrTrunc(8).getZExtValue();
  2613. }
  2614. if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
  2615. // Make sure all array elements are sequences of the same repeated
  2616. // byte.
  2617. assert(CA->getNumOperands() != 0 && "Should be a CAZ");
  2618. Constant *Op0 = CA->getOperand(0);
  2619. int Byte = isRepeatedByteSequence(Op0, DL);
  2620. if (Byte == -1)
  2621. return -1;
  2622. // All array elements must be equal.
  2623. for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
  2624. if (CA->getOperand(i) != Op0)
  2625. return -1;
  2626. return Byte;
  2627. }
  2628. if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
  2629. return isRepeatedByteSequence(CDS);
  2630. return -1;
  2631. }
  2632. static void emitGlobalAliasInline(AsmPrinter &AP, uint64_t Offset,
  2633. AsmPrinter::AliasMapTy *AliasList) {
  2634. if (AliasList) {
  2635. auto AliasIt = AliasList->find(Offset);
  2636. if (AliasIt != AliasList->end()) {
  2637. for (const GlobalAlias *GA : AliasIt->second)
  2638. AP.OutStreamer->emitLabel(AP.getSymbol(GA));
  2639. AliasList->erase(Offset);
  2640. }
  2641. }
  2642. }
  2643. static void emitGlobalConstantDataSequential(
  2644. const DataLayout &DL, const ConstantDataSequential *CDS, AsmPrinter &AP,
  2645. AsmPrinter::AliasMapTy *AliasList) {
  2646. // See if we can aggregate this into a .fill, if so, emit it as such.
  2647. int Value = isRepeatedByteSequence(CDS, DL);
  2648. if (Value != -1) {
  2649. uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
  2650. // Don't emit a 1-byte object as a .fill.
  2651. if (Bytes > 1)
  2652. return AP.OutStreamer->emitFill(Bytes, Value);
  2653. }
  2654. // If this can be emitted with .ascii/.asciz, emit it as such.
  2655. if (CDS->isString())
  2656. return AP.OutStreamer->emitBytes(CDS->getAsString());
  2657. // Otherwise, emit the values in successive locations.
  2658. unsigned ElementByteSize = CDS->getElementByteSize();
  2659. if (isa<IntegerType>(CDS->getElementType())) {
  2660. for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) {
  2661. emitGlobalAliasInline(AP, ElementByteSize * I, AliasList);
  2662. if (AP.isVerbose())
  2663. AP.OutStreamer->getCommentOS()
  2664. << format("0x%" PRIx64 "\n", CDS->getElementAsInteger(I));
  2665. AP.OutStreamer->emitIntValue(CDS->getElementAsInteger(I),
  2666. ElementByteSize);
  2667. }
  2668. } else {
  2669. Type *ET = CDS->getElementType();
  2670. for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) {
  2671. emitGlobalAliasInline(AP, ElementByteSize * I, AliasList);
  2672. emitGlobalConstantFP(CDS->getElementAsAPFloat(I), ET, AP);
  2673. }
  2674. }
  2675. unsigned Size = DL.getTypeAllocSize(CDS->getType());
  2676. unsigned EmittedSize =
  2677. DL.getTypeAllocSize(CDS->getElementType()) * CDS->getNumElements();
  2678. assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!");
  2679. if (unsigned Padding = Size - EmittedSize)
  2680. AP.OutStreamer->emitZeros(Padding);
  2681. }
  2682. static void emitGlobalConstantArray(const DataLayout &DL,
  2683. const ConstantArray *CA, AsmPrinter &AP,
  2684. const Constant *BaseCV, uint64_t Offset,
  2685. AsmPrinter::AliasMapTy *AliasList) {
  2686. // See if we can aggregate some values. Make sure it can be
  2687. // represented as a series of bytes of the constant value.
  2688. int Value = isRepeatedByteSequence(CA, DL);
  2689. if (Value != -1) {
  2690. uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
  2691. AP.OutStreamer->emitFill(Bytes, Value);
  2692. } else {
  2693. for (unsigned I = 0, E = CA->getNumOperands(); I != E; ++I) {
  2694. emitGlobalConstantImpl(DL, CA->getOperand(I), AP, BaseCV, Offset,
  2695. AliasList);
  2696. Offset += DL.getTypeAllocSize(CA->getOperand(I)->getType());
  2697. }
  2698. }
  2699. }
  2700. static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP);
  2701. static void emitGlobalConstantVector(const DataLayout &DL,
  2702. const ConstantVector *CV, AsmPrinter &AP,
  2703. AsmPrinter::AliasMapTy *AliasList) {
  2704. Type *ElementType = CV->getType()->getElementType();
  2705. uint64_t ElementSizeInBits = DL.getTypeSizeInBits(ElementType);
  2706. uint64_t ElementAllocSizeInBits = DL.getTypeAllocSizeInBits(ElementType);
  2707. uint64_t EmittedSize;
  2708. if (ElementSizeInBits != ElementAllocSizeInBits) {
  2709. // If the allocation size of an element is different from the size in bits,
  2710. // printing each element separately will insert incorrect padding.
  2711. //
  2712. // The general algorithm here is complicated; instead of writing it out
  2713. // here, just use the existing code in ConstantFolding.
  2714. Type *IntT =
  2715. IntegerType::get(CV->getContext(), DL.getTypeSizeInBits(CV->getType()));
  2716. ConstantInt *CI = dyn_cast_or_null<ConstantInt>(ConstantFoldConstant(
  2717. ConstantExpr::getBitCast(const_cast<ConstantVector *>(CV), IntT), DL));
  2718. if (!CI) {
  2719. report_fatal_error(
  2720. "Cannot lower vector global with unusual element type");
  2721. }
  2722. emitGlobalAliasInline(AP, 0, AliasList);
  2723. emitGlobalConstantLargeInt(CI, AP);
  2724. EmittedSize = DL.getTypeStoreSize(CV->getType());
  2725. } else {
  2726. for (unsigned I = 0, E = CV->getType()->getNumElements(); I != E; ++I) {
  2727. emitGlobalAliasInline(AP, DL.getTypeAllocSize(CV->getType()) * I, AliasList);
  2728. emitGlobalConstantImpl(DL, CV->getOperand(I), AP);
  2729. }
  2730. EmittedSize =
  2731. DL.getTypeAllocSize(ElementType) * CV->getType()->getNumElements();
  2732. }
  2733. unsigned Size = DL.getTypeAllocSize(CV->getType());
  2734. if (unsigned Padding = Size - EmittedSize)
  2735. AP.OutStreamer->emitZeros(Padding);
  2736. }
  2737. static void emitGlobalConstantStruct(const DataLayout &DL,
  2738. const ConstantStruct *CS, AsmPrinter &AP,
  2739. const Constant *BaseCV, uint64_t Offset,
  2740. AsmPrinter::AliasMapTy *AliasList) {
  2741. // Print the fields in successive locations. Pad to align if needed!
  2742. unsigned Size = DL.getTypeAllocSize(CS->getType());
  2743. const StructLayout *Layout = DL.getStructLayout(CS->getType());
  2744. uint64_t SizeSoFar = 0;
  2745. for (unsigned I = 0, E = CS->getNumOperands(); I != E; ++I) {
  2746. const Constant *Field = CS->getOperand(I);
  2747. // Print the actual field value.
  2748. emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar,
  2749. AliasList);
  2750. // Check if padding is needed and insert one or more 0s.
  2751. uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
  2752. uint64_t PadSize = ((I == E - 1 ? Size : Layout->getElementOffset(I + 1)) -
  2753. Layout->getElementOffset(I)) -
  2754. FieldSize;
  2755. SizeSoFar += FieldSize + PadSize;
  2756. // Insert padding - this may include padding to increase the size of the
  2757. // current field up to the ABI size (if the struct is not packed) as well
  2758. // as padding to ensure that the next field starts at the right offset.
  2759. AP.OutStreamer->emitZeros(PadSize);
  2760. }
  2761. assert(SizeSoFar == Layout->getSizeInBytes() &&
  2762. "Layout of constant struct may be incorrect!");
  2763. }
  2764. static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
  2765. assert(ET && "Unknown float type");
  2766. APInt API = APF.bitcastToAPInt();
  2767. // First print a comment with what we think the original floating-point value
  2768. // should have been.
  2769. if (AP.isVerbose()) {
  2770. SmallString<8> StrVal;
  2771. APF.toString(StrVal);
  2772. ET->print(AP.OutStreamer->getCommentOS());
  2773. AP.OutStreamer->getCommentOS() << ' ' << StrVal << '\n';
  2774. }
  2775. // Now iterate through the APInt chunks, emitting them in endian-correct
  2776. // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
  2777. // floats).
  2778. unsigned NumBytes = API.getBitWidth() / 8;
  2779. unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
  2780. const uint64_t *p = API.getRawData();
  2781. // PPC's long double has odd notions of endianness compared to how LLVM
  2782. // handles it: p[0] goes first for *big* endian on PPC.
  2783. if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
  2784. int Chunk = API.getNumWords() - 1;
  2785. if (TrailingBytes)
  2786. AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes);
  2787. for (; Chunk >= 0; --Chunk)
  2788. AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
  2789. } else {
  2790. unsigned Chunk;
  2791. for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
  2792. AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
  2793. if (TrailingBytes)
  2794. AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes);
  2795. }
  2796. // Emit the tail padding for the long double.
  2797. const DataLayout &DL = AP.getDataLayout();
  2798. AP.OutStreamer->emitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
  2799. }
  2800. static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
  2801. emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
  2802. }
  2803. static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
  2804. const DataLayout &DL = AP.getDataLayout();
  2805. unsigned BitWidth = CI->getBitWidth();
  2806. // Copy the value as we may massage the layout for constants whose bit width
  2807. // is not a multiple of 64-bits.
  2808. APInt Realigned(CI->getValue());
  2809. uint64_t ExtraBits = 0;
  2810. unsigned ExtraBitsSize = BitWidth & 63;
  2811. if (ExtraBitsSize) {
  2812. // The bit width of the data is not a multiple of 64-bits.
  2813. // The extra bits are expected to be at the end of the chunk of the memory.
  2814. // Little endian:
  2815. // * Nothing to be done, just record the extra bits to emit.
  2816. // Big endian:
  2817. // * Record the extra bits to emit.
  2818. // * Realign the raw data to emit the chunks of 64-bits.
  2819. if (DL.isBigEndian()) {
  2820. // Basically the structure of the raw data is a chunk of 64-bits cells:
  2821. // 0 1 BitWidth / 64
  2822. // [chunk1][chunk2] ... [chunkN].
  2823. // The most significant chunk is chunkN and it should be emitted first.
  2824. // However, due to the alignment issue chunkN contains useless bits.
  2825. // Realign the chunks so that they contain only useful information:
  2826. // ExtraBits 0 1 (BitWidth / 64) - 1
  2827. // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
  2828. ExtraBitsSize = alignTo(ExtraBitsSize, 8);
  2829. ExtraBits = Realigned.getRawData()[0] &
  2830. (((uint64_t)-1) >> (64 - ExtraBitsSize));
  2831. Realigned.lshrInPlace(ExtraBitsSize);
  2832. } else
  2833. ExtraBits = Realigned.getRawData()[BitWidth / 64];
  2834. }
  2835. // We don't expect assemblers to support integer data directives
  2836. // for more than 64 bits, so we emit the data in at most 64-bit
  2837. // quantities at a time.
  2838. const uint64_t *RawData = Realigned.getRawData();
  2839. for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
  2840. uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
  2841. AP.OutStreamer->emitIntValue(Val, 8);
  2842. }
  2843. if (ExtraBitsSize) {
  2844. // Emit the extra bits after the 64-bits chunks.
  2845. // Emit a directive that fills the expected size.
  2846. uint64_t Size = AP.getDataLayout().getTypeStoreSize(CI->getType());
  2847. Size -= (BitWidth / 64) * 8;
  2848. assert(Size && Size * 8 >= ExtraBitsSize &&
  2849. (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
  2850. == ExtraBits && "Directive too small for extra bits.");
  2851. AP.OutStreamer->emitIntValue(ExtraBits, Size);
  2852. }
  2853. }
  2854. /// Transform a not absolute MCExpr containing a reference to a GOT
  2855. /// equivalent global, by a target specific GOT pc relative access to the
  2856. /// final symbol.
  2857. static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
  2858. const Constant *BaseCst,
  2859. uint64_t Offset) {
  2860. // The global @foo below illustrates a global that uses a got equivalent.
  2861. //
  2862. // @bar = global i32 42
  2863. // @gotequiv = private unnamed_addr constant i32* @bar
  2864. // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
  2865. // i64 ptrtoint (i32* @foo to i64))
  2866. // to i32)
  2867. //
  2868. // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
  2869. // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
  2870. // form:
  2871. //
  2872. // foo = cstexpr, where
  2873. // cstexpr := <gotequiv> - "." + <cst>
  2874. // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
  2875. //
  2876. // After canonicalization by evaluateAsRelocatable `ME` turns into:
  2877. //
  2878. // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
  2879. // gotpcrelcst := <offset from @foo base> + <cst>
  2880. MCValue MV;
  2881. if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
  2882. return;
  2883. const MCSymbolRefExpr *SymA = MV.getSymA();
  2884. if (!SymA)
  2885. return;
  2886. // Check that GOT equivalent symbol is cached.
  2887. const MCSymbol *GOTEquivSym = &SymA->getSymbol();
  2888. if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
  2889. return;
  2890. const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
  2891. if (!BaseGV)
  2892. return;
  2893. // Check for a valid base symbol
  2894. const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
  2895. const MCSymbolRefExpr *SymB = MV.getSymB();
  2896. if (!SymB || BaseSym != &SymB->getSymbol())
  2897. return;
  2898. // Make sure to match:
  2899. //
  2900. // gotpcrelcst := <offset from @foo base> + <cst>
  2901. //
  2902. // If gotpcrelcst is positive it means that we can safely fold the pc rel
  2903. // displacement into the GOTPCREL. We can also can have an extra offset <cst>
  2904. // if the target knows how to encode it.
  2905. int64_t GOTPCRelCst = Offset + MV.getConstant();
  2906. if (GOTPCRelCst < 0)
  2907. return;
  2908. if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
  2909. return;
  2910. // Emit the GOT PC relative to replace the got equivalent global, i.e.:
  2911. //
  2912. // bar:
  2913. // .long 42
  2914. // gotequiv:
  2915. // .quad bar
  2916. // foo:
  2917. // .long gotequiv - "." + <cst>
  2918. //
  2919. // is replaced by the target specific equivalent to:
  2920. //
  2921. // bar:
  2922. // .long 42
  2923. // foo:
  2924. // .long bar@GOTPCREL+<gotpcrelcst>
  2925. AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
  2926. const GlobalVariable *GV = Result.first;
  2927. int NumUses = (int)Result.second;
  2928. const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
  2929. const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
  2930. *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
  2931. FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
  2932. // Update GOT equivalent usage information
  2933. --NumUses;
  2934. if (NumUses >= 0)
  2935. AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
  2936. }
  2937. static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
  2938. AsmPrinter &AP, const Constant *BaseCV,
  2939. uint64_t Offset,
  2940. AsmPrinter::AliasMapTy *AliasList) {
  2941. emitGlobalAliasInline(AP, Offset, AliasList);
  2942. uint64_t Size = DL.getTypeAllocSize(CV->getType());
  2943. // Globals with sub-elements such as combinations of arrays and structs
  2944. // are handled recursively by emitGlobalConstantImpl. Keep track of the
  2945. // constant symbol base and the current position with BaseCV and Offset.
  2946. if (!BaseCV && CV->hasOneUse())
  2947. BaseCV = dyn_cast<Constant>(CV->user_back());
  2948. if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
  2949. return AP.OutStreamer->emitZeros(Size);
  2950. if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
  2951. const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType());
  2952. if (StoreSize <= 8) {
  2953. if (AP.isVerbose())
  2954. AP.OutStreamer->getCommentOS()
  2955. << format("0x%" PRIx64 "\n", CI->getZExtValue());
  2956. AP.OutStreamer->emitIntValue(CI->getZExtValue(), StoreSize);
  2957. } else {
  2958. emitGlobalConstantLargeInt(CI, AP);
  2959. }
  2960. // Emit tail padding if needed
  2961. if (Size != StoreSize)
  2962. AP.OutStreamer->emitZeros(Size - StoreSize);
  2963. return;
  2964. }
  2965. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
  2966. return emitGlobalConstantFP(CFP, AP);
  2967. if (isa<ConstantPointerNull>(CV)) {
  2968. AP.OutStreamer->emitIntValue(0, Size);
  2969. return;
  2970. }
  2971. if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
  2972. return emitGlobalConstantDataSequential(DL, CDS, AP, AliasList);
  2973. if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
  2974. return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset, AliasList);
  2975. if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
  2976. return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset, AliasList);
  2977. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
  2978. // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
  2979. // vectors).
  2980. if (CE->getOpcode() == Instruction::BitCast)
  2981. return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
  2982. if (Size > 8) {
  2983. // If the constant expression's size is greater than 64-bits, then we have
  2984. // to emit the value in chunks. Try to constant fold the value and emit it
  2985. // that way.
  2986. Constant *New = ConstantFoldConstant(CE, DL);
  2987. if (New != CE)
  2988. return emitGlobalConstantImpl(DL, New, AP);
  2989. }
  2990. }
  2991. if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
  2992. return emitGlobalConstantVector(DL, V, AP, AliasList);
  2993. // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
  2994. // thread the streamer with EmitValue.
  2995. const MCExpr *ME = AP.lowerConstant(CV);
  2996. // Since lowerConstant already folded and got rid of all IR pointer and
  2997. // integer casts, detect GOT equivalent accesses by looking into the MCExpr
  2998. // directly.
  2999. if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
  3000. handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
  3001. AP.OutStreamer->emitValue(ME, Size);
  3002. }
  3003. /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
  3004. void AsmPrinter::emitGlobalConstant(const DataLayout &DL, const Constant *CV,
  3005. AliasMapTy *AliasList) {
  3006. uint64_t Size = DL.getTypeAllocSize(CV->getType());
  3007. if (Size)
  3008. emitGlobalConstantImpl(DL, CV, *this, nullptr, 0, AliasList);
  3009. else if (MAI->hasSubsectionsViaSymbols()) {
  3010. // If the global has zero size, emit a single byte so that two labels don't
  3011. // look like they are at the same location.
  3012. OutStreamer->emitIntValue(0, 1);
  3013. }
  3014. if (!AliasList)
  3015. return;
  3016. // TODO: These remaining aliases are not emitted in the correct location. Need
  3017. // to handle the case where the alias offset doesn't refer to any sub-element.
  3018. for (auto &AliasPair : *AliasList) {
  3019. for (const GlobalAlias *GA : AliasPair.second)
  3020. OutStreamer->emitLabel(getSymbol(GA));
  3021. }
  3022. }
  3023. void AsmPrinter::emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
  3024. // Target doesn't support this yet!
  3025. llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
  3026. }
  3027. void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
  3028. if (Offset > 0)
  3029. OS << '+' << Offset;
  3030. else if (Offset < 0)
  3031. OS << Offset;
  3032. }
  3033. void AsmPrinter::emitNops(unsigned N) {
  3034. MCInst Nop = MF->getSubtarget().getInstrInfo()->getNop();
  3035. for (; N; --N)
  3036. EmitToStreamer(*OutStreamer, Nop);
  3037. }
  3038. //===----------------------------------------------------------------------===//
  3039. // Symbol Lowering Routines.
  3040. //===----------------------------------------------------------------------===//
  3041. MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
  3042. return OutContext.createTempSymbol(Name, true);
  3043. }
  3044. MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
  3045. return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(
  3046. BA->getBasicBlock());
  3047. }
  3048. MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
  3049. return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(BB);
  3050. }
  3051. /// GetCPISymbol - Return the symbol for the specified constant pool entry.
  3052. MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
  3053. if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) {
  3054. const MachineConstantPoolEntry &CPE =
  3055. MF->getConstantPool()->getConstants()[CPID];
  3056. if (!CPE.isMachineConstantPoolEntry()) {
  3057. const DataLayout &DL = MF->getDataLayout();
  3058. SectionKind Kind = CPE.getSectionKind(&DL);
  3059. const Constant *C = CPE.Val.ConstVal;
  3060. Align Alignment = CPE.Alignment;
  3061. if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>(
  3062. getObjFileLowering().getSectionForConstant(DL, Kind, C,
  3063. Alignment))) {
  3064. if (MCSymbol *Sym = S->getCOMDATSymbol()) {
  3065. if (Sym->isUndefined())
  3066. OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);
  3067. return Sym;
  3068. }
  3069. }
  3070. }
  3071. }
  3072. const DataLayout &DL = getDataLayout();
  3073. return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
  3074. "CPI" + Twine(getFunctionNumber()) + "_" +
  3075. Twine(CPID));
  3076. }
  3077. /// GetJTISymbol - Return the symbol for the specified jump table entry.
  3078. MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
  3079. return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
  3080. }
  3081. /// GetJTSetSymbol - Return the symbol for the specified jump table .set
  3082. /// FIXME: privatize to AsmPrinter.
  3083. MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
  3084. const DataLayout &DL = getDataLayout();
  3085. return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
  3086. Twine(getFunctionNumber()) + "_" +
  3087. Twine(UID) + "_set_" + Twine(MBBID));
  3088. }
  3089. MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
  3090. StringRef Suffix) const {
  3091. return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM);
  3092. }
  3093. /// Return the MCSymbol for the specified ExternalSymbol.
  3094. MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
  3095. SmallString<60> NameStr;
  3096. Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
  3097. return OutContext.getOrCreateSymbol(NameStr);
  3098. }
  3099. /// PrintParentLoopComment - Print comments about parent loops of this one.
  3100. static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
  3101. unsigned FunctionNumber) {
  3102. if (!Loop) return;
  3103. PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
  3104. OS.indent(Loop->getLoopDepth()*2)
  3105. << "Parent Loop BB" << FunctionNumber << "_"
  3106. << Loop->getHeader()->getNumber()
  3107. << " Depth=" << Loop->getLoopDepth() << '\n';
  3108. }
  3109. /// PrintChildLoopComment - Print comments about child loops within
  3110. /// the loop for this basic block, with nesting.
  3111. static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
  3112. unsigned FunctionNumber) {
  3113. // Add child loop information
  3114. for (const MachineLoop *CL : *Loop) {
  3115. OS.indent(CL->getLoopDepth()*2)
  3116. << "Child Loop BB" << FunctionNumber << "_"
  3117. << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
  3118. << '\n';
  3119. PrintChildLoopComment(OS, CL, FunctionNumber);
  3120. }
  3121. }
  3122. /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
  3123. static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
  3124. const MachineLoopInfo *LI,
  3125. const AsmPrinter &AP) {
  3126. // Add loop depth information
  3127. const MachineLoop *Loop = LI->getLoopFor(&MBB);
  3128. if (!Loop) return;
  3129. MachineBasicBlock *Header = Loop->getHeader();
  3130. assert(Header && "No header for loop");
  3131. // If this block is not a loop header, just print out what is the loop header
  3132. // and return.
  3133. if (Header != &MBB) {
  3134. AP.OutStreamer->AddComment(" in Loop: Header=BB" +
  3135. Twine(AP.getFunctionNumber())+"_" +
  3136. Twine(Loop->getHeader()->getNumber())+
  3137. " Depth="+Twine(Loop->getLoopDepth()));
  3138. return;
  3139. }
  3140. // Otherwise, it is a loop header. Print out information about child and
  3141. // parent loops.
  3142. raw_ostream &OS = AP.OutStreamer->getCommentOS();
  3143. PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
  3144. OS << "=>";
  3145. OS.indent(Loop->getLoopDepth()*2-2);
  3146. OS << "This ";
  3147. if (Loop->isInnermost())
  3148. OS << "Inner ";
  3149. OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
  3150. PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
  3151. }
  3152. /// emitBasicBlockStart - This method prints the label for the specified
  3153. /// MachineBasicBlock, an alignment (if present) and a comment describing
  3154. /// it if appropriate.
  3155. void AsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) {
  3156. // End the previous funclet and start a new one.
  3157. if (MBB.isEHFuncletEntry()) {
  3158. for (const HandlerInfo &HI : Handlers) {
  3159. HI.Handler->endFunclet();
  3160. HI.Handler->beginFunclet(MBB);
  3161. }
  3162. }
  3163. // Switch to a new section if this basic block must begin a section. The
  3164. // entry block is always placed in the function section and is handled
  3165. // separately.
  3166. if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
  3167. OutStreamer->switchSection(
  3168. getObjFileLowering().getSectionForMachineBasicBlock(MF->getFunction(),
  3169. MBB, TM));
  3170. CurrentSectionBeginSym = MBB.getSymbol();
  3171. }
  3172. // Emit an alignment directive for this block, if needed.
  3173. const Align Alignment = MBB.getAlignment();
  3174. if (Alignment != Align(1))
  3175. emitAlignment(Alignment, nullptr, MBB.getMaxBytesForAlignment());
  3176. // If the block has its address taken, emit any labels that were used to
  3177. // reference the block. It is possible that there is more than one label
  3178. // here, because multiple LLVM BB's may have been RAUW'd to this block after
  3179. // the references were generated.
  3180. if (MBB.isIRBlockAddressTaken()) {
  3181. if (isVerbose())
  3182. OutStreamer->AddComment("Block address taken");
  3183. BasicBlock *BB = MBB.getAddressTakenIRBlock();
  3184. assert(BB && BB->hasAddressTaken() && "Missing BB");
  3185. for (MCSymbol *Sym : getAddrLabelSymbolToEmit(BB))
  3186. OutStreamer->emitLabel(Sym);
  3187. } else if (isVerbose() && MBB.isMachineBlockAddressTaken()) {
  3188. OutStreamer->AddComment("Block address taken");
  3189. }
  3190. // Print some verbose block comments.
  3191. if (isVerbose()) {
  3192. if (const BasicBlock *BB = MBB.getBasicBlock()) {
  3193. if (BB->hasName()) {
  3194. BB->printAsOperand(OutStreamer->getCommentOS(),
  3195. /*PrintType=*/false, BB->getModule());
  3196. OutStreamer->getCommentOS() << '\n';
  3197. }
  3198. }
  3199. assert(MLI != nullptr && "MachineLoopInfo should has been computed");
  3200. emitBasicBlockLoopComments(MBB, MLI, *this);
  3201. }
  3202. // Print the main label for the block.
  3203. if (shouldEmitLabelForBasicBlock(MBB)) {
  3204. if (isVerbose() && MBB.hasLabelMustBeEmitted())
  3205. OutStreamer->AddComment("Label of block must be emitted");
  3206. OutStreamer->emitLabel(MBB.getSymbol());
  3207. } else {
  3208. if (isVerbose()) {
  3209. // NOTE: Want this comment at start of line, don't emit with AddComment.
  3210. OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
  3211. false);
  3212. }
  3213. }
  3214. if (MBB.isEHCatchretTarget() &&
  3215. MAI->getExceptionHandlingType() == ExceptionHandling::WinEH) {
  3216. OutStreamer->emitLabel(MBB.getEHCatchretSymbol());
  3217. }
  3218. // With BB sections, each basic block must handle CFI information on its own
  3219. // if it begins a section (Entry block call is handled separately, next to
  3220. // beginFunction).
  3221. if (MBB.isBeginSection() && !MBB.isEntryBlock())
  3222. for (const HandlerInfo &HI : Handlers)
  3223. HI.Handler->beginBasicBlockSection(MBB);
  3224. }
  3225. void AsmPrinter::emitBasicBlockEnd(const MachineBasicBlock &MBB) {
  3226. // Check if CFI information needs to be updated for this MBB with basic block
  3227. // sections.
  3228. if (MBB.isEndSection())
  3229. for (const HandlerInfo &HI : Handlers)
  3230. HI.Handler->endBasicBlockSection(MBB);
  3231. }
  3232. void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility,
  3233. bool IsDefinition) const {
  3234. MCSymbolAttr Attr = MCSA_Invalid;
  3235. switch (Visibility) {
  3236. default: break;
  3237. case GlobalValue::HiddenVisibility:
  3238. if (IsDefinition)
  3239. Attr = MAI->getHiddenVisibilityAttr();
  3240. else
  3241. Attr = MAI->getHiddenDeclarationVisibilityAttr();
  3242. break;
  3243. case GlobalValue::ProtectedVisibility:
  3244. Attr = MAI->getProtectedVisibilityAttr();
  3245. break;
  3246. }
  3247. if (Attr != MCSA_Invalid)
  3248. OutStreamer->emitSymbolAttribute(Sym, Attr);
  3249. }
  3250. bool AsmPrinter::shouldEmitLabelForBasicBlock(
  3251. const MachineBasicBlock &MBB) const {
  3252. // With `-fbasic-block-sections=`, a label is needed for every non-entry block
  3253. // in the labels mode (option `=labels`) and every section beginning in the
  3254. // sections mode (`=all` and `=list=`).
  3255. if ((MF->hasBBLabels() || MBB.isBeginSection()) && !MBB.isEntryBlock())
  3256. return true;
  3257. // A label is needed for any block with at least one predecessor (when that
  3258. // predecessor is not the fallthrough predecessor, or if it is an EH funclet
  3259. // entry, or if a label is forced).
  3260. return !MBB.pred_empty() &&
  3261. (!isBlockOnlyReachableByFallthrough(&MBB) || MBB.isEHFuncletEntry() ||
  3262. MBB.hasLabelMustBeEmitted());
  3263. }
  3264. /// isBlockOnlyReachableByFallthough - Return true if the basic block has
  3265. /// exactly one predecessor and the control transfer mechanism between
  3266. /// the predecessor and this block is a fall-through.
  3267. bool AsmPrinter::
  3268. isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
  3269. // If this is a landing pad, it isn't a fall through. If it has no preds,
  3270. // then nothing falls through to it.
  3271. if (MBB->isEHPad() || MBB->pred_empty())
  3272. return false;
  3273. // If there isn't exactly one predecessor, it can't be a fall through.
  3274. if (MBB->pred_size() > 1)
  3275. return false;
  3276. // The predecessor has to be immediately before this block.
  3277. MachineBasicBlock *Pred = *MBB->pred_begin();
  3278. if (!Pred->isLayoutSuccessor(MBB))
  3279. return false;
  3280. // If the block is completely empty, then it definitely does fall through.
  3281. if (Pred->empty())
  3282. return true;
  3283. // Check the terminators in the previous blocks
  3284. for (const auto &MI : Pred->terminators()) {
  3285. // If it is not a simple branch, we are in a table somewhere.
  3286. if (!MI.isBranch() || MI.isIndirectBranch())
  3287. return false;
  3288. // If we are the operands of one of the branches, this is not a fall
  3289. // through. Note that targets with delay slots will usually bundle
  3290. // terminators with the delay slot instruction.
  3291. for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
  3292. if (OP->isJTI())
  3293. return false;
  3294. if (OP->isMBB() && OP->getMBB() == MBB)
  3295. return false;
  3296. }
  3297. }
  3298. return true;
  3299. }
  3300. GCMetadataPrinter *AsmPrinter::getOrCreateGCPrinter(GCStrategy &S) {
  3301. if (!S.usesMetadata())
  3302. return nullptr;
  3303. auto [GCPI, Inserted] = GCMetadataPrinters.insert({&S, nullptr});
  3304. if (!Inserted)
  3305. return GCPI->second.get();
  3306. auto Name = S.getName();
  3307. for (const GCMetadataPrinterRegistry::entry &GCMetaPrinter :
  3308. GCMetadataPrinterRegistry::entries())
  3309. if (Name == GCMetaPrinter.getName()) {
  3310. std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate();
  3311. GMP->S = &S;
  3312. GCPI->second = std::move(GMP);
  3313. return GCPI->second.get();
  3314. }
  3315. report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
  3316. }
  3317. void AsmPrinter::emitStackMaps() {
  3318. GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
  3319. assert(MI && "AsmPrinter didn't require GCModuleInfo?");
  3320. bool NeedsDefault = false;
  3321. if (MI->begin() == MI->end())
  3322. // No GC strategy, use the default format.
  3323. NeedsDefault = true;
  3324. else
  3325. for (const auto &I : *MI) {
  3326. if (GCMetadataPrinter *MP = getOrCreateGCPrinter(*I))
  3327. if (MP->emitStackMaps(SM, *this))
  3328. continue;
  3329. // The strategy doesn't have printer or doesn't emit custom stack maps.
  3330. // Use the default format.
  3331. NeedsDefault = true;
  3332. }
  3333. if (NeedsDefault)
  3334. SM.serializeToStackMapSection();
  3335. }
  3336. /// Pin vtable to this file.
  3337. AsmPrinterHandler::~AsmPrinterHandler() = default;
  3338. void AsmPrinterHandler::markFunctionEnd() {}
  3339. // In the binary's "xray_instr_map" section, an array of these function entries
  3340. // describes each instrumentation point. When XRay patches your code, the index
  3341. // into this table will be given to your handler as a patch point identifier.
  3342. void AsmPrinter::XRayFunctionEntry::emit(int Bytes, MCStreamer *Out) const {
  3343. auto Kind8 = static_cast<uint8_t>(Kind);
  3344. Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
  3345. Out->emitBinaryData(
  3346. StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
  3347. Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
  3348. auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
  3349. assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size");
  3350. Out->emitZeros(Padding);
  3351. }
  3352. void AsmPrinter::emitXRayTable() {
  3353. if (Sleds.empty())
  3354. return;
  3355. auto PrevSection = OutStreamer->getCurrentSectionOnly();
  3356. const Function &F = MF->getFunction();
  3357. MCSection *InstMap = nullptr;
  3358. MCSection *FnSledIndex = nullptr;
  3359. const Triple &TT = TM.getTargetTriple();
  3360. // Use PC-relative addresses on all targets.
  3361. if (TT.isOSBinFormatELF()) {
  3362. auto LinkedToSym = cast<MCSymbolELF>(CurrentFnSym);
  3363. auto Flags = ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
  3364. StringRef GroupName;
  3365. if (F.hasComdat()) {
  3366. Flags |= ELF::SHF_GROUP;
  3367. GroupName = F.getComdat()->getName();
  3368. }
  3369. InstMap = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS,
  3370. Flags, 0, GroupName, F.hasComdat(),
  3371. MCSection::NonUniqueID, LinkedToSym);
  3372. if (!TM.Options.XRayOmitFunctionIndex)
  3373. FnSledIndex = OutContext.getELFSection(
  3374. "xray_fn_idx", ELF::SHT_PROGBITS, Flags | ELF::SHF_WRITE, 0,
  3375. GroupName, F.hasComdat(), MCSection::NonUniqueID, LinkedToSym);
  3376. } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
  3377. InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0,
  3378. SectionKind::getReadOnlyWithRel());
  3379. if (!TM.Options.XRayOmitFunctionIndex)
  3380. FnSledIndex = OutContext.getMachOSection(
  3381. "__DATA", "xray_fn_idx", 0, SectionKind::getReadOnlyWithRel());
  3382. } else {
  3383. llvm_unreachable("Unsupported target");
  3384. }
  3385. auto WordSizeBytes = MAI->getCodePointerSize();
  3386. // Now we switch to the instrumentation map section. Because this is done
  3387. // per-function, we are able to create an index entry that will represent the
  3388. // range of sleds associated with a function.
  3389. auto &Ctx = OutContext;
  3390. MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true);
  3391. OutStreamer->switchSection(InstMap);
  3392. OutStreamer->emitLabel(SledsStart);
  3393. for (const auto &Sled : Sleds) {
  3394. MCSymbol *Dot = Ctx.createTempSymbol();
  3395. OutStreamer->emitLabel(Dot);
  3396. OutStreamer->emitValueImpl(
  3397. MCBinaryExpr::createSub(MCSymbolRefExpr::create(Sled.Sled, Ctx),
  3398. MCSymbolRefExpr::create(Dot, Ctx), Ctx),
  3399. WordSizeBytes);
  3400. OutStreamer->emitValueImpl(
  3401. MCBinaryExpr::createSub(
  3402. MCSymbolRefExpr::create(CurrentFnBegin, Ctx),
  3403. MCBinaryExpr::createAdd(MCSymbolRefExpr::create(Dot, Ctx),
  3404. MCConstantExpr::create(WordSizeBytes, Ctx),
  3405. Ctx),
  3406. Ctx),
  3407. WordSizeBytes);
  3408. Sled.emit(WordSizeBytes, OutStreamer.get());
  3409. }
  3410. MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
  3411. OutStreamer->emitLabel(SledsEnd);
  3412. // We then emit a single entry in the index per function. We use the symbols
  3413. // that bound the instrumentation map as the range for a specific function.
  3414. // Each entry here will be 2 * word size aligned, as we're writing down two
  3415. // pointers. This should work for both 32-bit and 64-bit platforms.
  3416. if (FnSledIndex) {
  3417. OutStreamer->switchSection(FnSledIndex);
  3418. OutStreamer->emitCodeAlignment(Align(2 * WordSizeBytes),
  3419. &getSubtargetInfo());
  3420. OutStreamer->emitSymbolValue(SledsStart, WordSizeBytes, false);
  3421. OutStreamer->emitSymbolValue(SledsEnd, WordSizeBytes, false);
  3422. OutStreamer->switchSection(PrevSection);
  3423. }
  3424. Sleds.clear();
  3425. }
  3426. void AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI,
  3427. SledKind Kind, uint8_t Version) {
  3428. const Function &F = MI.getMF()->getFunction();
  3429. auto Attr = F.getFnAttribute("function-instrument");
  3430. bool LogArgs = F.hasFnAttribute("xray-log-args");
  3431. bool AlwaysInstrument =
  3432. Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
  3433. if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
  3434. Kind = SledKind::LOG_ARGS_ENTER;
  3435. Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
  3436. AlwaysInstrument, &F, Version});
  3437. }
  3438. void AsmPrinter::emitPatchableFunctionEntries() {
  3439. const Function &F = MF->getFunction();
  3440. unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0;
  3441. (void)F.getFnAttribute("patchable-function-prefix")
  3442. .getValueAsString()
  3443. .getAsInteger(10, PatchableFunctionPrefix);
  3444. (void)F.getFnAttribute("patchable-function-entry")
  3445. .getValueAsString()
  3446. .getAsInteger(10, PatchableFunctionEntry);
  3447. if (!PatchableFunctionPrefix && !PatchableFunctionEntry)
  3448. return;
  3449. const unsigned PointerSize = getPointerSize();
  3450. if (TM.getTargetTriple().isOSBinFormatELF()) {
  3451. auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC;
  3452. const MCSymbolELF *LinkedToSym = nullptr;
  3453. StringRef GroupName;
  3454. // GNU as < 2.35 did not support section flag 'o'. GNU ld < 2.36 did not
  3455. // support mixed SHF_LINK_ORDER and non-SHF_LINK_ORDER sections.
  3456. if (MAI->useIntegratedAssembler() || MAI->binutilsIsAtLeast(2, 36)) {
  3457. Flags |= ELF::SHF_LINK_ORDER;
  3458. if (F.hasComdat()) {
  3459. Flags |= ELF::SHF_GROUP;
  3460. GroupName = F.getComdat()->getName();
  3461. }
  3462. LinkedToSym = cast<MCSymbolELF>(CurrentFnSym);
  3463. }
  3464. OutStreamer->switchSection(OutContext.getELFSection(
  3465. "__patchable_function_entries", ELF::SHT_PROGBITS, Flags, 0, GroupName,
  3466. F.hasComdat(), MCSection::NonUniqueID, LinkedToSym));
  3467. emitAlignment(Align(PointerSize));
  3468. OutStreamer->emitSymbolValue(CurrentPatchableFunctionEntrySym, PointerSize);
  3469. }
  3470. }
  3471. uint16_t AsmPrinter::getDwarfVersion() const {
  3472. return OutStreamer->getContext().getDwarfVersion();
  3473. }
  3474. void AsmPrinter::setDwarfVersion(uint16_t Version) {
  3475. OutStreamer->getContext().setDwarfVersion(Version);
  3476. }
  3477. bool AsmPrinter::isDwarf64() const {
  3478. return OutStreamer->getContext().getDwarfFormat() == dwarf::DWARF64;
  3479. }
  3480. unsigned int AsmPrinter::getDwarfOffsetByteSize() const {
  3481. return dwarf::getDwarfOffsetByteSize(
  3482. OutStreamer->getContext().getDwarfFormat());
  3483. }
  3484. dwarf::FormParams AsmPrinter::getDwarfFormParams() const {
  3485. return {getDwarfVersion(), uint8_t(getPointerSize()),
  3486. OutStreamer->getContext().getDwarfFormat(),
  3487. doesDwarfUseRelocationsAcrossSections()};
  3488. }
  3489. unsigned int AsmPrinter::getUnitLengthFieldByteSize() const {
  3490. return dwarf::getUnitLengthFieldByteSize(
  3491. OutStreamer->getContext().getDwarfFormat());
  3492. }