AsmPrinter.cpp 135 KB

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