TargetLoweringObjectFileImpl.cpp 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565
  1. //===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===//
  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 classes used to handle lowerings specific to common
  10. // object file formats.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
  14. #include "llvm/ADT/SmallString.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/ADT/StringRef.h"
  18. #include "llvm/ADT/Triple.h"
  19. #include "llvm/BinaryFormat/COFF.h"
  20. #include "llvm/BinaryFormat/Dwarf.h"
  21. #include "llvm/BinaryFormat/ELF.h"
  22. #include "llvm/BinaryFormat/MachO.h"
  23. #include "llvm/BinaryFormat/Wasm.h"
  24. #include "llvm/CodeGen/BasicBlockSectionUtils.h"
  25. #include "llvm/CodeGen/MachineBasicBlock.h"
  26. #include "llvm/CodeGen/MachineFunction.h"
  27. #include "llvm/CodeGen/MachineModuleInfo.h"
  28. #include "llvm/CodeGen/MachineModuleInfoImpls.h"
  29. #include "llvm/IR/Comdat.h"
  30. #include "llvm/IR/Constants.h"
  31. #include "llvm/IR/DataLayout.h"
  32. #include "llvm/IR/DerivedTypes.h"
  33. #include "llvm/IR/DiagnosticInfo.h"
  34. #include "llvm/IR/DiagnosticPrinter.h"
  35. #include "llvm/IR/Function.h"
  36. #include "llvm/IR/GlobalAlias.h"
  37. #include "llvm/IR/GlobalObject.h"
  38. #include "llvm/IR/GlobalValue.h"
  39. #include "llvm/IR/GlobalVariable.h"
  40. #include "llvm/IR/Mangler.h"
  41. #include "llvm/IR/Metadata.h"
  42. #include "llvm/IR/Module.h"
  43. #include "llvm/IR/PseudoProbe.h"
  44. #include "llvm/IR/Type.h"
  45. #include "llvm/MC/MCAsmInfo.h"
  46. #include "llvm/MC/MCContext.h"
  47. #include "llvm/MC/MCExpr.h"
  48. #include "llvm/MC/MCSectionCOFF.h"
  49. #include "llvm/MC/MCSectionELF.h"
  50. #include "llvm/MC/MCSectionGOFF.h"
  51. #include "llvm/MC/MCSectionMachO.h"
  52. #include "llvm/MC/MCSectionWasm.h"
  53. #include "llvm/MC/MCSectionXCOFF.h"
  54. #include "llvm/MC/MCStreamer.h"
  55. #include "llvm/MC/MCSymbol.h"
  56. #include "llvm/MC/MCSymbolELF.h"
  57. #include "llvm/MC/MCValue.h"
  58. #include "llvm/MC/SectionKind.h"
  59. #include "llvm/ProfileData/InstrProf.h"
  60. #include "llvm/Support/Casting.h"
  61. #include "llvm/Support/CodeGen.h"
  62. #include "llvm/Support/ErrorHandling.h"
  63. #include "llvm/Support/Format.h"
  64. #include "llvm/Support/raw_ostream.h"
  65. #include "llvm/Target/TargetMachine.h"
  66. #include <cassert>
  67. #include <string>
  68. using namespace llvm;
  69. using namespace dwarf;
  70. static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
  71. StringRef &Section) {
  72. SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
  73. M.getModuleFlagsMetadata(ModuleFlags);
  74. for (const auto &MFE: ModuleFlags) {
  75. // Ignore flags with 'Require' behaviour.
  76. if (MFE.Behavior == Module::Require)
  77. continue;
  78. StringRef Key = MFE.Key->getString();
  79. if (Key == "Objective-C Image Info Version") {
  80. Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
  81. } else if (Key == "Objective-C Garbage Collection" ||
  82. Key == "Objective-C GC Only" ||
  83. Key == "Objective-C Is Simulated" ||
  84. Key == "Objective-C Class Properties" ||
  85. Key == "Objective-C Image Swift Version") {
  86. Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
  87. } else if (Key == "Objective-C Image Info Section") {
  88. Section = cast<MDString>(MFE.Val)->getString();
  89. }
  90. // Backend generates L_OBJC_IMAGE_INFO from Swift ABI version + major + minor +
  91. // "Objective-C Garbage Collection".
  92. else if (Key == "Swift ABI Version") {
  93. Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 8;
  94. } else if (Key == "Swift Major Version") {
  95. Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 24;
  96. } else if (Key == "Swift Minor Version") {
  97. Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 16;
  98. }
  99. }
  100. }
  101. //===----------------------------------------------------------------------===//
  102. // ELF
  103. //===----------------------------------------------------------------------===//
  104. TargetLoweringObjectFileELF::TargetLoweringObjectFileELF() {
  105. SupportDSOLocalEquivalentLowering = true;
  106. }
  107. void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
  108. const TargetMachine &TgtM) {
  109. TargetLoweringObjectFile::Initialize(Ctx, TgtM);
  110. CodeModel::Model CM = TgtM.getCodeModel();
  111. InitializeELF(TgtM.Options.UseInitArray);
  112. switch (TgtM.getTargetTriple().getArch()) {
  113. case Triple::arm:
  114. case Triple::armeb:
  115. case Triple::thumb:
  116. case Triple::thumbeb:
  117. if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM)
  118. break;
  119. // Fallthrough if not using EHABI
  120. LLVM_FALLTHROUGH;
  121. case Triple::ppc:
  122. case Triple::ppcle:
  123. case Triple::x86:
  124. PersonalityEncoding = isPositionIndependent()
  125. ? dwarf::DW_EH_PE_indirect |
  126. dwarf::DW_EH_PE_pcrel |
  127. dwarf::DW_EH_PE_sdata4
  128. : dwarf::DW_EH_PE_absptr;
  129. LSDAEncoding = isPositionIndependent()
  130. ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4
  131. : dwarf::DW_EH_PE_absptr;
  132. TTypeEncoding = isPositionIndependent()
  133. ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  134. dwarf::DW_EH_PE_sdata4
  135. : dwarf::DW_EH_PE_absptr;
  136. break;
  137. case Triple::x86_64:
  138. if (isPositionIndependent()) {
  139. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  140. ((CM == CodeModel::Small || CM == CodeModel::Medium)
  141. ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
  142. LSDAEncoding = dwarf::DW_EH_PE_pcrel |
  143. (CM == CodeModel::Small
  144. ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
  145. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  146. ((CM == CodeModel::Small || CM == CodeModel::Medium)
  147. ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
  148. } else {
  149. PersonalityEncoding =
  150. (CM == CodeModel::Small || CM == CodeModel::Medium)
  151. ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
  152. LSDAEncoding = (CM == CodeModel::Small)
  153. ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
  154. TTypeEncoding = (CM == CodeModel::Small)
  155. ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
  156. }
  157. break;
  158. case Triple::hexagon:
  159. PersonalityEncoding = dwarf::DW_EH_PE_absptr;
  160. LSDAEncoding = dwarf::DW_EH_PE_absptr;
  161. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  162. if (isPositionIndependent()) {
  163. PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
  164. LSDAEncoding |= dwarf::DW_EH_PE_pcrel;
  165. TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
  166. }
  167. break;
  168. case Triple::aarch64:
  169. case Triple::aarch64_be:
  170. case Triple::aarch64_32:
  171. // The small model guarantees static code/data size < 4GB, but not where it
  172. // will be in memory. Most of these could end up >2GB away so even a signed
  173. // pc-relative 32-bit address is insufficient, theoretically.
  174. if (isPositionIndependent()) {
  175. // ILP32 uses sdata4 instead of sdata8
  176. if (TgtM.getTargetTriple().getEnvironment() == Triple::GNUILP32) {
  177. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  178. dwarf::DW_EH_PE_sdata4;
  179. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  180. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  181. dwarf::DW_EH_PE_sdata4;
  182. } else {
  183. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  184. dwarf::DW_EH_PE_sdata8;
  185. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8;
  186. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  187. dwarf::DW_EH_PE_sdata8;
  188. }
  189. } else {
  190. PersonalityEncoding = dwarf::DW_EH_PE_absptr;
  191. LSDAEncoding = dwarf::DW_EH_PE_absptr;
  192. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  193. }
  194. break;
  195. case Triple::lanai:
  196. LSDAEncoding = dwarf::DW_EH_PE_absptr;
  197. PersonalityEncoding = dwarf::DW_EH_PE_absptr;
  198. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  199. break;
  200. case Triple::mips:
  201. case Triple::mipsel:
  202. case Triple::mips64:
  203. case Triple::mips64el:
  204. // MIPS uses indirect pointer to refer personality functions and types, so
  205. // that the eh_frame section can be read-only. DW.ref.personality will be
  206. // generated for relocation.
  207. PersonalityEncoding = dwarf::DW_EH_PE_indirect;
  208. // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
  209. // identify N64 from just a triple.
  210. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  211. dwarf::DW_EH_PE_sdata4;
  212. // We don't support PC-relative LSDA references in GAS so we use the default
  213. // DW_EH_PE_absptr for those.
  214. // FreeBSD must be explicit about the data size and using pcrel since it's
  215. // assembler/linker won't do the automatic conversion that the Linux tools
  216. // do.
  217. if (TgtM.getTargetTriple().isOSFreeBSD()) {
  218. PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  219. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  220. }
  221. break;
  222. case Triple::ppc64:
  223. case Triple::ppc64le:
  224. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  225. dwarf::DW_EH_PE_udata8;
  226. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8;
  227. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  228. dwarf::DW_EH_PE_udata8;
  229. break;
  230. case Triple::sparcel:
  231. case Triple::sparc:
  232. if (isPositionIndependent()) {
  233. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  234. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  235. dwarf::DW_EH_PE_sdata4;
  236. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  237. dwarf::DW_EH_PE_sdata4;
  238. } else {
  239. LSDAEncoding = dwarf::DW_EH_PE_absptr;
  240. PersonalityEncoding = dwarf::DW_EH_PE_absptr;
  241. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  242. }
  243. CallSiteEncoding = dwarf::DW_EH_PE_udata4;
  244. break;
  245. case Triple::riscv32:
  246. case Triple::riscv64:
  247. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  248. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  249. dwarf::DW_EH_PE_sdata4;
  250. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  251. dwarf::DW_EH_PE_sdata4;
  252. CallSiteEncoding = dwarf::DW_EH_PE_udata4;
  253. break;
  254. case Triple::sparcv9:
  255. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  256. if (isPositionIndependent()) {
  257. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  258. dwarf::DW_EH_PE_sdata4;
  259. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  260. dwarf::DW_EH_PE_sdata4;
  261. } else {
  262. PersonalityEncoding = dwarf::DW_EH_PE_absptr;
  263. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  264. }
  265. break;
  266. case Triple::systemz:
  267. // All currently-defined code models guarantee that 4-byte PC-relative
  268. // values will be in range.
  269. if (isPositionIndependent()) {
  270. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  271. dwarf::DW_EH_PE_sdata4;
  272. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  273. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  274. dwarf::DW_EH_PE_sdata4;
  275. } else {
  276. PersonalityEncoding = dwarf::DW_EH_PE_absptr;
  277. LSDAEncoding = dwarf::DW_EH_PE_absptr;
  278. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  279. }
  280. break;
  281. default:
  282. break;
  283. }
  284. }
  285. void TargetLoweringObjectFileELF::getModuleMetadata(Module &M) {
  286. SmallVector<GlobalValue *, 4> Vec;
  287. collectUsedGlobalVariables(M, Vec, false);
  288. for (GlobalValue *GV : Vec)
  289. if (auto *GO = dyn_cast<GlobalObject>(GV))
  290. Used.insert(GO);
  291. }
  292. void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer,
  293. Module &M) const {
  294. auto &C = getContext();
  295. if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
  296. auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
  297. ELF::SHF_EXCLUDE);
  298. Streamer.SwitchSection(S);
  299. for (const auto *Operand : LinkerOptions->operands()) {
  300. if (cast<MDNode>(Operand)->getNumOperands() != 2)
  301. report_fatal_error("invalid llvm.linker.options");
  302. for (const auto &Option : cast<MDNode>(Operand)->operands()) {
  303. Streamer.emitBytes(cast<MDString>(Option)->getString());
  304. Streamer.emitInt8(0);
  305. }
  306. }
  307. }
  308. if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) {
  309. auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES,
  310. ELF::SHF_MERGE | ELF::SHF_STRINGS, 1);
  311. Streamer.SwitchSection(S);
  312. for (const auto *Operand : DependentLibraries->operands()) {
  313. Streamer.emitBytes(
  314. cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString());
  315. Streamer.emitInt8(0);
  316. }
  317. }
  318. if (NamedMDNode *FuncInfo = M.getNamedMetadata(PseudoProbeDescMetadataName)) {
  319. // Emit a descriptor for every function including functions that have an
  320. // available external linkage. We may not want this for imported functions
  321. // that has code in another thinLTO module but we don't have a good way to
  322. // tell them apart from inline functions defined in header files. Therefore
  323. // we put each descriptor in a separate comdat section and rely on the
  324. // linker to deduplicate.
  325. for (const auto *Operand : FuncInfo->operands()) {
  326. const auto *MD = cast<MDNode>(Operand);
  327. auto *GUID = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
  328. auto *Hash = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
  329. auto *Name = cast<MDString>(MD->getOperand(2));
  330. auto *S = C.getObjectFileInfo()->getPseudoProbeDescSection(
  331. TM->getFunctionSections() ? Name->getString() : StringRef());
  332. Streamer.SwitchSection(S);
  333. Streamer.emitInt64(GUID->getZExtValue());
  334. Streamer.emitInt64(Hash->getZExtValue());
  335. Streamer.emitULEB128IntValue(Name->getString().size());
  336. Streamer.emitBytes(Name->getString());
  337. }
  338. }
  339. unsigned Version = 0;
  340. unsigned Flags = 0;
  341. StringRef Section;
  342. GetObjCImageInfo(M, Version, Flags, Section);
  343. if (!Section.empty()) {
  344. auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
  345. Streamer.SwitchSection(S);
  346. Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
  347. Streamer.emitInt32(Version);
  348. Streamer.emitInt32(Flags);
  349. Streamer.AddBlankLine();
  350. }
  351. emitCGProfileMetadata(Streamer, M);
  352. }
  353. MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
  354. const GlobalValue *GV, const TargetMachine &TM,
  355. MachineModuleInfo *MMI) const {
  356. unsigned Encoding = getPersonalityEncoding();
  357. if ((Encoding & 0x80) == DW_EH_PE_indirect)
  358. return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
  359. TM.getSymbol(GV)->getName());
  360. if ((Encoding & 0x70) == DW_EH_PE_absptr)
  361. return TM.getSymbol(GV);
  362. report_fatal_error("We do not support this DWARF encoding yet!");
  363. }
  364. void TargetLoweringObjectFileELF::emitPersonalityValue(
  365. MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
  366. SmallString<64> NameData("DW.ref.");
  367. NameData += Sym->getName();
  368. MCSymbolELF *Label =
  369. cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
  370. Streamer.emitSymbolAttribute(Label, MCSA_Hidden);
  371. Streamer.emitSymbolAttribute(Label, MCSA_Weak);
  372. unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
  373. MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
  374. ELF::SHT_PROGBITS, Flags, 0);
  375. unsigned Size = DL.getPointerSize();
  376. Streamer.SwitchSection(Sec);
  377. Streamer.emitValueToAlignment(DL.getPointerABIAlignment(0).value());
  378. Streamer.emitSymbolAttribute(Label, MCSA_ELF_TypeObject);
  379. const MCExpr *E = MCConstantExpr::create(Size, getContext());
  380. Streamer.emitELFSize(Label, E);
  381. Streamer.emitLabel(Label);
  382. Streamer.emitSymbolValue(Sym, Size);
  383. }
  384. const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
  385. const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
  386. MachineModuleInfo *MMI, MCStreamer &Streamer) const {
  387. if (Encoding & DW_EH_PE_indirect) {
  388. MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
  389. MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
  390. // Add information about the stub reference to ELFMMI so that the stub
  391. // gets emitted by the asmprinter.
  392. MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
  393. if (!StubSym.getPointer()) {
  394. MCSymbol *Sym = TM.getSymbol(GV);
  395. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  396. }
  397. return TargetLoweringObjectFile::
  398. getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
  399. Encoding & ~DW_EH_PE_indirect, Streamer);
  400. }
  401. return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
  402. MMI, Streamer);
  403. }
  404. static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
  405. // N.B.: The defaults used in here are not the same ones used in MC.
  406. // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
  407. // both gas and MC will produce a section with no flags. Given
  408. // section(".eh_frame") gcc will produce:
  409. //
  410. // .section .eh_frame,"a",@progbits
  411. if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
  412. /*AddSegmentInfo=*/false) ||
  413. Name == getInstrProfSectionName(IPSK_covfun, Triple::ELF,
  414. /*AddSegmentInfo=*/false) ||
  415. Name == ".llvmbc" || Name == ".llvmcmd")
  416. return SectionKind::getMetadata();
  417. if (Name.empty() || Name[0] != '.') return K;
  418. // Default implementation based on some magic section names.
  419. if (Name == ".bss" ||
  420. Name.startswith(".bss.") ||
  421. Name.startswith(".gnu.linkonce.b.") ||
  422. Name.startswith(".llvm.linkonce.b.") ||
  423. Name == ".sbss" ||
  424. Name.startswith(".sbss.") ||
  425. Name.startswith(".gnu.linkonce.sb.") ||
  426. Name.startswith(".llvm.linkonce.sb."))
  427. return SectionKind::getBSS();
  428. if (Name == ".tdata" ||
  429. Name.startswith(".tdata.") ||
  430. Name.startswith(".gnu.linkonce.td.") ||
  431. Name.startswith(".llvm.linkonce.td."))
  432. return SectionKind::getThreadData();
  433. if (Name == ".tbss" ||
  434. Name.startswith(".tbss.") ||
  435. Name.startswith(".gnu.linkonce.tb.") ||
  436. Name.startswith(".llvm.linkonce.tb."))
  437. return SectionKind::getThreadBSS();
  438. return K;
  439. }
  440. static bool hasPrefix(StringRef SectionName, StringRef Prefix) {
  441. return SectionName.consume_front(Prefix) &&
  442. (SectionName.empty() || SectionName[0] == '.');
  443. }
  444. static unsigned getELFSectionType(StringRef Name, SectionKind K) {
  445. // Use SHT_NOTE for section whose name starts with ".note" to allow
  446. // emitting ELF notes from C variable declaration.
  447. // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
  448. if (Name.startswith(".note"))
  449. return ELF::SHT_NOTE;
  450. if (hasPrefix(Name, ".init_array"))
  451. return ELF::SHT_INIT_ARRAY;
  452. if (hasPrefix(Name, ".fini_array"))
  453. return ELF::SHT_FINI_ARRAY;
  454. if (hasPrefix(Name, ".preinit_array"))
  455. return ELF::SHT_PREINIT_ARRAY;
  456. if (K.isBSS() || K.isThreadBSS())
  457. return ELF::SHT_NOBITS;
  458. return ELF::SHT_PROGBITS;
  459. }
  460. static unsigned getELFSectionFlags(SectionKind K) {
  461. unsigned Flags = 0;
  462. if (!K.isMetadata())
  463. Flags |= ELF::SHF_ALLOC;
  464. if (K.isText())
  465. Flags |= ELF::SHF_EXECINSTR;
  466. if (K.isExecuteOnly())
  467. Flags |= ELF::SHF_ARM_PURECODE;
  468. if (K.isWriteable())
  469. Flags |= ELF::SHF_WRITE;
  470. if (K.isThreadLocal())
  471. Flags |= ELF::SHF_TLS;
  472. if (K.isMergeableCString() || K.isMergeableConst())
  473. Flags |= ELF::SHF_MERGE;
  474. if (K.isMergeableCString())
  475. Flags |= ELF::SHF_STRINGS;
  476. return Flags;
  477. }
  478. static const Comdat *getELFComdat(const GlobalValue *GV) {
  479. const Comdat *C = GV->getComdat();
  480. if (!C)
  481. return nullptr;
  482. if (C->getSelectionKind() != Comdat::Any &&
  483. C->getSelectionKind() != Comdat::NoDeduplicate)
  484. report_fatal_error("ELF COMDATs only support SelectionKind::Any and "
  485. "SelectionKind::NoDeduplicate, '" +
  486. C->getName() + "' cannot be lowered.");
  487. return C;
  488. }
  489. static const MCSymbolELF *getLinkedToSymbol(const GlobalObject *GO,
  490. const TargetMachine &TM) {
  491. MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
  492. if (!MD)
  493. return nullptr;
  494. const MDOperand &Op = MD->getOperand(0);
  495. if (!Op.get())
  496. return nullptr;
  497. auto *VM = dyn_cast<ValueAsMetadata>(Op);
  498. if (!VM)
  499. report_fatal_error("MD_associated operand is not ValueAsMetadata");
  500. auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue());
  501. return OtherGV ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV)) : nullptr;
  502. }
  503. static unsigned getEntrySizeForKind(SectionKind Kind) {
  504. if (Kind.isMergeable1ByteCString())
  505. return 1;
  506. else if (Kind.isMergeable2ByteCString())
  507. return 2;
  508. else if (Kind.isMergeable4ByteCString())
  509. return 4;
  510. else if (Kind.isMergeableConst4())
  511. return 4;
  512. else if (Kind.isMergeableConst8())
  513. return 8;
  514. else if (Kind.isMergeableConst16())
  515. return 16;
  516. else if (Kind.isMergeableConst32())
  517. return 32;
  518. else {
  519. // We shouldn't have mergeable C strings or mergeable constants that we
  520. // didn't handle above.
  521. assert(!Kind.isMergeableCString() && "unknown string width");
  522. assert(!Kind.isMergeableConst() && "unknown data width");
  523. return 0;
  524. }
  525. }
  526. /// Return the section prefix name used by options FunctionsSections and
  527. /// DataSections.
  528. static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
  529. if (Kind.isText())
  530. return ".text";
  531. if (Kind.isReadOnly())
  532. return ".rodata";
  533. if (Kind.isBSS())
  534. return ".bss";
  535. if (Kind.isThreadData())
  536. return ".tdata";
  537. if (Kind.isThreadBSS())
  538. return ".tbss";
  539. if (Kind.isData())
  540. return ".data";
  541. if (Kind.isReadOnlyWithRel())
  542. return ".data.rel.ro";
  543. llvm_unreachable("Unknown section kind");
  544. }
  545. static SmallString<128>
  546. getELFSectionNameForGlobal(const GlobalObject *GO, SectionKind Kind,
  547. Mangler &Mang, const TargetMachine &TM,
  548. unsigned EntrySize, bool UniqueSectionName) {
  549. SmallString<128> Name;
  550. if (Kind.isMergeableCString()) {
  551. // We also need alignment here.
  552. // FIXME: this is getting the alignment of the character, not the
  553. // alignment of the global!
  554. Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign(
  555. cast<GlobalVariable>(GO));
  556. std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
  557. Name = SizeSpec + utostr(Alignment.value());
  558. } else if (Kind.isMergeableConst()) {
  559. Name = ".rodata.cst";
  560. Name += utostr(EntrySize);
  561. } else {
  562. Name = getSectionPrefixForGlobal(Kind);
  563. }
  564. bool HasPrefix = false;
  565. if (const auto *F = dyn_cast<Function>(GO)) {
  566. if (Optional<StringRef> Prefix = F->getSectionPrefix()) {
  567. raw_svector_ostream(Name) << '.' << *Prefix;
  568. HasPrefix = true;
  569. }
  570. }
  571. if (UniqueSectionName) {
  572. Name.push_back('.');
  573. TM.getNameWithPrefix(Name, GO, Mang, /*MayAlwaysUsePrivate*/true);
  574. } else if (HasPrefix)
  575. // For distinguishing between .text.${text-section-prefix}. (with trailing
  576. // dot) and .text.${function-name}
  577. Name.push_back('.');
  578. return Name;
  579. }
  580. namespace {
  581. class LoweringDiagnosticInfo : public DiagnosticInfo {
  582. const Twine &Msg;
  583. public:
  584. LoweringDiagnosticInfo(const Twine &DiagMsg,
  585. DiagnosticSeverity Severity = DS_Error)
  586. : DiagnosticInfo(DK_Lowering, Severity), Msg(DiagMsg) {}
  587. void print(DiagnosticPrinter &DP) const override { DP << Msg; }
  588. };
  589. }
  590. /// Calculate an appropriate unique ID for a section, and update Flags,
  591. /// EntrySize and NextUniqueID where appropriate.
  592. static unsigned
  593. calcUniqueIDUpdateFlagsAndSize(const GlobalObject *GO, StringRef SectionName,
  594. SectionKind Kind, const TargetMachine &TM,
  595. MCContext &Ctx, Mangler &Mang, unsigned &Flags,
  596. unsigned &EntrySize, unsigned &NextUniqueID,
  597. const bool Retain, const bool ForceUnique) {
  598. // Increment uniqueID if we are forced to emit a unique section.
  599. // This works perfectly fine with section attribute or pragma section as the
  600. // sections with the same name are grouped together by the assembler.
  601. if (ForceUnique)
  602. return NextUniqueID++;
  603. // A section can have at most one associated section. Put each global with
  604. // MD_associated in a unique section.
  605. const bool Associated = GO->getMetadata(LLVMContext::MD_associated);
  606. if (Associated) {
  607. Flags |= ELF::SHF_LINK_ORDER;
  608. return NextUniqueID++;
  609. }
  610. if (Retain) {
  611. if ((Ctx.getAsmInfo()->useIntegratedAssembler() ||
  612. Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36)) &&
  613. !TM.getTargetTriple().isOSSolaris())
  614. Flags |= ELF::SHF_GNU_RETAIN;
  615. return NextUniqueID++;
  616. }
  617. // If two symbols with differing sizes end up in the same mergeable section
  618. // that section can be assigned an incorrect entry size. To avoid this we
  619. // usually put symbols of the same size into distinct mergeable sections with
  620. // the same name. Doing so relies on the ",unique ," assembly feature. This
  621. // feature is not avalible until bintuils version 2.35
  622. // (https://sourceware.org/bugzilla/show_bug.cgi?id=25380).
  623. const bool SupportsUnique = Ctx.getAsmInfo()->useIntegratedAssembler() ||
  624. Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35);
  625. if (!SupportsUnique) {
  626. Flags &= ~ELF::SHF_MERGE;
  627. EntrySize = 0;
  628. return MCContext::GenericSectionID;
  629. }
  630. const bool SymbolMergeable = Flags & ELF::SHF_MERGE;
  631. const bool SeenSectionNameBefore =
  632. Ctx.isELFGenericMergeableSection(SectionName);
  633. // If this is the first ocurrence of this section name, treat it as the
  634. // generic section
  635. if (!SymbolMergeable && !SeenSectionNameBefore)
  636. return MCContext::GenericSectionID;
  637. // Symbols must be placed into sections with compatible entry sizes. Generate
  638. // unique sections for symbols that have not been assigned to compatible
  639. // sections.
  640. const auto PreviousID =
  641. Ctx.getELFUniqueIDForEntsize(SectionName, Flags, EntrySize);
  642. if (PreviousID)
  643. return *PreviousID;
  644. // If the user has specified the same section name as would be created
  645. // implicitly for this symbol e.g. .rodata.str1.1, then we don't need
  646. // to unique the section as the entry size for this symbol will be
  647. // compatible with implicitly created sections.
  648. SmallString<128> ImplicitSectionNameStem =
  649. getELFSectionNameForGlobal(GO, Kind, Mang, TM, EntrySize, false);
  650. if (SymbolMergeable &&
  651. Ctx.isELFImplicitMergeableSectionNamePrefix(SectionName) &&
  652. SectionName.startswith(ImplicitSectionNameStem))
  653. return MCContext::GenericSectionID;
  654. // We have seen this section name before, but with different flags or entity
  655. // size. Create a new unique ID.
  656. return NextUniqueID++;
  657. }
  658. static MCSection *selectExplicitSectionGlobal(
  659. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM,
  660. MCContext &Ctx, Mangler &Mang, unsigned &NextUniqueID,
  661. bool Retain, bool ForceUnique) {
  662. StringRef SectionName = GO->getSection();
  663. // Check if '#pragma clang section' name is applicable.
  664. // Note that pragma directive overrides -ffunction-section, -fdata-section
  665. // and so section name is exactly as user specified and not uniqued.
  666. const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
  667. if (GV && GV->hasImplicitSection()) {
  668. auto Attrs = GV->getAttributes();
  669. if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
  670. SectionName = Attrs.getAttribute("bss-section").getValueAsString();
  671. } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
  672. SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
  673. } else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) {
  674. SectionName = Attrs.getAttribute("relro-section").getValueAsString();
  675. } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
  676. SectionName = Attrs.getAttribute("data-section").getValueAsString();
  677. }
  678. }
  679. const Function *F = dyn_cast<Function>(GO);
  680. if (F && F->hasFnAttribute("implicit-section-name")) {
  681. SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
  682. }
  683. // Infer section flags from the section name if we can.
  684. Kind = getELFKindForNamedSection(SectionName, Kind);
  685. StringRef Group = "";
  686. bool IsComdat = false;
  687. unsigned Flags = getELFSectionFlags(Kind);
  688. if (const Comdat *C = getELFComdat(GO)) {
  689. Group = C->getName();
  690. IsComdat = C->getSelectionKind() == Comdat::Any;
  691. Flags |= ELF::SHF_GROUP;
  692. }
  693. unsigned EntrySize = getEntrySizeForKind(Kind);
  694. const unsigned UniqueID = calcUniqueIDUpdateFlagsAndSize(
  695. GO, SectionName, Kind, TM, Ctx, Mang, Flags, EntrySize, NextUniqueID,
  696. Retain, ForceUnique);
  697. const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
  698. MCSectionELF *Section = Ctx.getELFSection(
  699. SectionName, getELFSectionType(SectionName, Kind), Flags, EntrySize,
  700. Group, IsComdat, UniqueID, LinkedToSym);
  701. // Make sure that we did not get some other section with incompatible sh_link.
  702. // This should not be possible due to UniqueID code above.
  703. assert(Section->getLinkedToSymbol() == LinkedToSym &&
  704. "Associated symbol mismatch between sections");
  705. if (!(Ctx.getAsmInfo()->useIntegratedAssembler() ||
  706. Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35))) {
  707. // If we are using GNU as before 2.35, then this symbol might have
  708. // been placed in an incompatible mergeable section. Emit an error if this
  709. // is the case to avoid creating broken output.
  710. if ((Section->getFlags() & ELF::SHF_MERGE) &&
  711. (Section->getEntrySize() != getEntrySizeForKind(Kind)))
  712. GO->getContext().diagnose(LoweringDiagnosticInfo(
  713. "Symbol '" + GO->getName() + "' from module '" +
  714. (GO->getParent() ? GO->getParent()->getSourceFileName() : "unknown") +
  715. "' required a section with entry-size=" +
  716. Twine(getEntrySizeForKind(Kind)) + " but was placed in section '" +
  717. SectionName + "' with entry-size=" + Twine(Section->getEntrySize()) +
  718. ": Explicit assignment by pragma or attribute of an incompatible "
  719. "symbol to this section?"));
  720. }
  721. return Section;
  722. }
  723. MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
  724. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  725. return selectExplicitSectionGlobal(GO, Kind, TM, getContext(), getMangler(),
  726. NextUniqueID, Used.count(GO),
  727. /* ForceUnique = */false);
  728. }
  729. static MCSectionELF *selectELFSectionForGlobal(
  730. MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
  731. const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
  732. unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
  733. StringRef Group = "";
  734. bool IsComdat = false;
  735. if (const Comdat *C = getELFComdat(GO)) {
  736. Flags |= ELF::SHF_GROUP;
  737. Group = C->getName();
  738. IsComdat = C->getSelectionKind() == Comdat::Any;
  739. }
  740. // Get the section entry size based on the kind.
  741. unsigned EntrySize = getEntrySizeForKind(Kind);
  742. bool UniqueSectionName = false;
  743. unsigned UniqueID = MCContext::GenericSectionID;
  744. if (EmitUniqueSection) {
  745. if (TM.getUniqueSectionNames()) {
  746. UniqueSectionName = true;
  747. } else {
  748. UniqueID = *NextUniqueID;
  749. (*NextUniqueID)++;
  750. }
  751. }
  752. SmallString<128> Name = getELFSectionNameForGlobal(
  753. GO, Kind, Mang, TM, EntrySize, UniqueSectionName);
  754. // Use 0 as the unique ID for execute-only text.
  755. if (Kind.isExecuteOnly())
  756. UniqueID = 0;
  757. return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
  758. EntrySize, Group, IsComdat, UniqueID,
  759. AssociatedSymbol);
  760. }
  761. static MCSection *selectELFSectionForGlobal(
  762. MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
  763. const TargetMachine &TM, bool Retain, bool EmitUniqueSection,
  764. unsigned Flags, unsigned *NextUniqueID) {
  765. const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
  766. if (LinkedToSym) {
  767. EmitUniqueSection = true;
  768. Flags |= ELF::SHF_LINK_ORDER;
  769. }
  770. if (Retain &&
  771. (Ctx.getAsmInfo()->useIntegratedAssembler() ||
  772. Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36)) &&
  773. !TM.getTargetTriple().isOSSolaris()) {
  774. EmitUniqueSection = true;
  775. Flags |= ELF::SHF_GNU_RETAIN;
  776. }
  777. MCSectionELF *Section = selectELFSectionForGlobal(
  778. Ctx, GO, Kind, Mang, TM, EmitUniqueSection, Flags,
  779. NextUniqueID, LinkedToSym);
  780. assert(Section->getLinkedToSymbol() == LinkedToSym);
  781. return Section;
  782. }
  783. MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
  784. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  785. unsigned Flags = getELFSectionFlags(Kind);
  786. // If we have -ffunction-section or -fdata-section then we should emit the
  787. // global value to a uniqued section specifically for it.
  788. bool EmitUniqueSection = false;
  789. if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
  790. if (Kind.isText())
  791. EmitUniqueSection = TM.getFunctionSections();
  792. else
  793. EmitUniqueSection = TM.getDataSections();
  794. }
  795. EmitUniqueSection |= GO->hasComdat();
  796. return selectELFSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
  797. Used.count(GO), EmitUniqueSection, Flags,
  798. &NextUniqueID);
  799. }
  800. MCSection *TargetLoweringObjectFileELF::getUniqueSectionForFunction(
  801. const Function &F, const TargetMachine &TM) const {
  802. SectionKind Kind = SectionKind::getText();
  803. unsigned Flags = getELFSectionFlags(Kind);
  804. // If the function's section names is pre-determined via pragma or a
  805. // section attribute, call selectExplicitSectionGlobal.
  806. if (F.hasSection() || F.hasFnAttribute("implicit-section-name"))
  807. return selectExplicitSectionGlobal(
  808. &F, Kind, TM, getContext(), getMangler(), NextUniqueID,
  809. Used.count(&F), /* ForceUnique = */true);
  810. else
  811. return selectELFSectionForGlobal(
  812. getContext(), &F, Kind, getMangler(), TM, Used.count(&F),
  813. /*EmitUniqueSection=*/true, Flags, &NextUniqueID);
  814. }
  815. MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
  816. const Function &F, const TargetMachine &TM) const {
  817. // If the function can be removed, produce a unique section so that
  818. // the table doesn't prevent the removal.
  819. const Comdat *C = F.getComdat();
  820. bool EmitUniqueSection = TM.getFunctionSections() || C;
  821. if (!EmitUniqueSection)
  822. return ReadOnlySection;
  823. return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
  824. getMangler(), TM, EmitUniqueSection,
  825. ELF::SHF_ALLOC, &NextUniqueID,
  826. /* AssociatedSymbol */ nullptr);
  827. }
  828. MCSection *TargetLoweringObjectFileELF::getSectionForLSDA(
  829. const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
  830. // If neither COMDAT nor function sections, use the monolithic LSDA section.
  831. // Re-use this path if LSDASection is null as in the Arm EHABI.
  832. if (!LSDASection || (!F.hasComdat() && !TM.getFunctionSections()))
  833. return LSDASection;
  834. const auto *LSDA = cast<MCSectionELF>(LSDASection);
  835. unsigned Flags = LSDA->getFlags();
  836. const MCSymbolELF *LinkedToSym = nullptr;
  837. StringRef Group;
  838. bool IsComdat = false;
  839. if (const Comdat *C = getELFComdat(&F)) {
  840. Flags |= ELF::SHF_GROUP;
  841. Group = C->getName();
  842. IsComdat = C->getSelectionKind() == Comdat::Any;
  843. }
  844. // Use SHF_LINK_ORDER to facilitate --gc-sections if we can use GNU ld>=2.36
  845. // or LLD, which support mixed SHF_LINK_ORDER & non-SHF_LINK_ORDER.
  846. if (TM.getFunctionSections() &&
  847. (getContext().getAsmInfo()->useIntegratedAssembler() &&
  848. getContext().getAsmInfo()->binutilsIsAtLeast(2, 36))) {
  849. Flags |= ELF::SHF_LINK_ORDER;
  850. LinkedToSym = cast<MCSymbolELF>(&FnSym);
  851. }
  852. // Append the function name as the suffix like GCC, assuming
  853. // -funique-section-names applies to .gcc_except_table sections.
  854. return getContext().getELFSection(
  855. (TM.getUniqueSectionNames() ? LSDA->getName() + "." + F.getName()
  856. : LSDA->getName()),
  857. LSDA->getType(), Flags, 0, Group, IsComdat, MCSection::NonUniqueID,
  858. LinkedToSym);
  859. }
  860. bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
  861. bool UsesLabelDifference, const Function &F) const {
  862. // We can always create relative relocations, so use another section
  863. // that can be marked non-executable.
  864. return false;
  865. }
  866. /// Given a mergeable constant with the specified size and relocation
  867. /// information, return a section that it should be placed in.
  868. MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
  869. const DataLayout &DL, SectionKind Kind, const Constant *C,
  870. Align &Alignment) const {
  871. if (Kind.isMergeableConst4() && MergeableConst4Section)
  872. return MergeableConst4Section;
  873. if (Kind.isMergeableConst8() && MergeableConst8Section)
  874. return MergeableConst8Section;
  875. if (Kind.isMergeableConst16() && MergeableConst16Section)
  876. return MergeableConst16Section;
  877. if (Kind.isMergeableConst32() && MergeableConst32Section)
  878. return MergeableConst32Section;
  879. if (Kind.isReadOnly())
  880. return ReadOnlySection;
  881. assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
  882. return DataRelROSection;
  883. }
  884. /// Returns a unique section for the given machine basic block.
  885. MCSection *TargetLoweringObjectFileELF::getSectionForMachineBasicBlock(
  886. const Function &F, const MachineBasicBlock &MBB,
  887. const TargetMachine &TM) const {
  888. assert(MBB.isBeginSection() && "Basic block does not start a section!");
  889. unsigned UniqueID = MCContext::GenericSectionID;
  890. // For cold sections use the .text.split. prefix along with the parent
  891. // function name. All cold blocks for the same function go to the same
  892. // section. Similarly all exception blocks are grouped by symbol name
  893. // under the .text.eh prefix. For regular sections, we either use a unique
  894. // name, or a unique ID for the section.
  895. SmallString<128> Name;
  896. if (MBB.getSectionID() == MBBSectionID::ColdSectionID) {
  897. Name += BBSectionsColdTextPrefix;
  898. Name += MBB.getParent()->getName();
  899. } else if (MBB.getSectionID() == MBBSectionID::ExceptionSectionID) {
  900. Name += ".text.eh.";
  901. Name += MBB.getParent()->getName();
  902. } else {
  903. Name += MBB.getParent()->getSection()->getName();
  904. if (TM.getUniqueBasicBlockSectionNames()) {
  905. if (!Name.endswith("."))
  906. Name += ".";
  907. Name += MBB.getSymbol()->getName();
  908. } else {
  909. UniqueID = NextUniqueID++;
  910. }
  911. }
  912. unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_EXECINSTR;
  913. std::string GroupName;
  914. if (F.hasComdat()) {
  915. Flags |= ELF::SHF_GROUP;
  916. GroupName = F.getComdat()->getName().str();
  917. }
  918. return getContext().getELFSection(Name, ELF::SHT_PROGBITS, Flags,
  919. 0 /* Entry Size */, GroupName,
  920. F.hasComdat(), UniqueID, nullptr);
  921. }
  922. static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
  923. bool IsCtor, unsigned Priority,
  924. const MCSymbol *KeySym) {
  925. std::string Name;
  926. unsigned Type;
  927. unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
  928. StringRef Comdat = KeySym ? KeySym->getName() : "";
  929. if (KeySym)
  930. Flags |= ELF::SHF_GROUP;
  931. if (UseInitArray) {
  932. if (IsCtor) {
  933. Type = ELF::SHT_INIT_ARRAY;
  934. Name = ".init_array";
  935. } else {
  936. Type = ELF::SHT_FINI_ARRAY;
  937. Name = ".fini_array";
  938. }
  939. if (Priority != 65535) {
  940. Name += '.';
  941. Name += utostr(Priority);
  942. }
  943. } else {
  944. // The default scheme is .ctor / .dtor, so we have to invert the priority
  945. // numbering.
  946. if (IsCtor)
  947. Name = ".ctors";
  948. else
  949. Name = ".dtors";
  950. if (Priority != 65535)
  951. raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
  952. Type = ELF::SHT_PROGBITS;
  953. }
  954. return Ctx.getELFSection(Name, Type, Flags, 0, Comdat, /*IsComdat=*/true);
  955. }
  956. MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
  957. unsigned Priority, const MCSymbol *KeySym) const {
  958. return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
  959. KeySym);
  960. }
  961. MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
  962. unsigned Priority, const MCSymbol *KeySym) const {
  963. return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
  964. KeySym);
  965. }
  966. const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
  967. const GlobalValue *LHS, const GlobalValue *RHS,
  968. const TargetMachine &TM) const {
  969. // We may only use a PLT-relative relocation to refer to unnamed_addr
  970. // functions.
  971. if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
  972. return nullptr;
  973. // Basic correctness checks.
  974. if (LHS->getType()->getPointerAddressSpace() != 0 ||
  975. RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
  976. RHS->isThreadLocal())
  977. return nullptr;
  978. return MCBinaryExpr::createSub(
  979. MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
  980. getContext()),
  981. MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
  982. }
  983. const MCExpr *TargetLoweringObjectFileELF::lowerDSOLocalEquivalent(
  984. const DSOLocalEquivalent *Equiv, const TargetMachine &TM) const {
  985. assert(supportDSOLocalEquivalentLowering());
  986. const auto *GV = Equiv->getGlobalValue();
  987. // A PLT entry is not needed for dso_local globals.
  988. if (GV->isDSOLocal() || GV->isImplicitDSOLocal())
  989. return MCSymbolRefExpr::create(TM.getSymbol(GV), getContext());
  990. return MCSymbolRefExpr::create(TM.getSymbol(GV), PLTRelativeVariantKind,
  991. getContext());
  992. }
  993. MCSection *TargetLoweringObjectFileELF::getSectionForCommandLines() const {
  994. // Use ".GCC.command.line" since this feature is to support clang's
  995. // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the
  996. // same name.
  997. return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS,
  998. ELF::SHF_MERGE | ELF::SHF_STRINGS, 1);
  999. }
  1000. void
  1001. TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
  1002. UseInitArray = UseInitArray_;
  1003. MCContext &Ctx = getContext();
  1004. if (!UseInitArray) {
  1005. StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
  1006. ELF::SHF_ALLOC | ELF::SHF_WRITE);
  1007. StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
  1008. ELF::SHF_ALLOC | ELF::SHF_WRITE);
  1009. return;
  1010. }
  1011. StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
  1012. ELF::SHF_WRITE | ELF::SHF_ALLOC);
  1013. StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
  1014. ELF::SHF_WRITE | ELF::SHF_ALLOC);
  1015. }
  1016. //===----------------------------------------------------------------------===//
  1017. // MachO
  1018. //===----------------------------------------------------------------------===//
  1019. TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO() {
  1020. SupportIndirectSymViaGOTPCRel = true;
  1021. }
  1022. void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
  1023. const TargetMachine &TM) {
  1024. TargetLoweringObjectFile::Initialize(Ctx, TM);
  1025. if (TM.getRelocationModel() == Reloc::Static) {
  1026. StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
  1027. SectionKind::getData());
  1028. StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
  1029. SectionKind::getData());
  1030. } else {
  1031. StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
  1032. MachO::S_MOD_INIT_FUNC_POINTERS,
  1033. SectionKind::getData());
  1034. StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
  1035. MachO::S_MOD_TERM_FUNC_POINTERS,
  1036. SectionKind::getData());
  1037. }
  1038. PersonalityEncoding =
  1039. dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  1040. LSDAEncoding = dwarf::DW_EH_PE_pcrel;
  1041. TTypeEncoding =
  1042. dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  1043. }
  1044. void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer,
  1045. Module &M) const {
  1046. // Emit the linker options if present.
  1047. if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
  1048. for (const auto *Option : LinkerOptions->operands()) {
  1049. SmallVector<std::string, 4> StrOptions;
  1050. for (const auto &Piece : cast<MDNode>(Option)->operands())
  1051. StrOptions.push_back(std::string(cast<MDString>(Piece)->getString()));
  1052. Streamer.emitLinkerOptions(StrOptions);
  1053. }
  1054. }
  1055. unsigned VersionVal = 0;
  1056. unsigned ImageInfoFlags = 0;
  1057. StringRef SectionVal;
  1058. GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
  1059. emitCGProfileMetadata(Streamer, M);
  1060. // The section is mandatory. If we don't have it, then we don't have GC info.
  1061. if (SectionVal.empty())
  1062. return;
  1063. StringRef Segment, Section;
  1064. unsigned TAA = 0, StubSize = 0;
  1065. bool TAAParsed;
  1066. if (Error E = MCSectionMachO::ParseSectionSpecifier(
  1067. SectionVal, Segment, Section, TAA, TAAParsed, StubSize)) {
  1068. // If invalid, report the error with report_fatal_error.
  1069. report_fatal_error("Invalid section specifier '" + Section +
  1070. "': " + toString(std::move(E)) + ".");
  1071. }
  1072. // Get the section.
  1073. MCSectionMachO *S = getContext().getMachOSection(
  1074. Segment, Section, TAA, StubSize, SectionKind::getData());
  1075. Streamer.SwitchSection(S);
  1076. Streamer.emitLabel(getContext().
  1077. getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
  1078. Streamer.emitInt32(VersionVal);
  1079. Streamer.emitInt32(ImageInfoFlags);
  1080. Streamer.AddBlankLine();
  1081. }
  1082. static void checkMachOComdat(const GlobalValue *GV) {
  1083. const Comdat *C = GV->getComdat();
  1084. if (!C)
  1085. return;
  1086. report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
  1087. "' cannot be lowered.");
  1088. }
  1089. MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
  1090. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1091. StringRef SectionName = GO->getSection();
  1092. const Function *F = dyn_cast<Function>(GO);
  1093. if (F && F->hasFnAttribute("implicit-section-name")) {
  1094. SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
  1095. }
  1096. // Parse the section specifier and create it if valid.
  1097. StringRef Segment, Section;
  1098. unsigned TAA = 0, StubSize = 0;
  1099. bool TAAParsed;
  1100. checkMachOComdat(GO);
  1101. if (Error E = MCSectionMachO::ParseSectionSpecifier(
  1102. SectionName, Segment, Section, TAA, TAAParsed, StubSize)) {
  1103. // If invalid, report the error with report_fatal_error.
  1104. report_fatal_error("Global variable '" + GO->getName() +
  1105. "' has an invalid section specifier '" +
  1106. GO->getSection() + "': " + toString(std::move(E)) + ".");
  1107. }
  1108. // Get the section.
  1109. MCSectionMachO *S =
  1110. getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
  1111. // If TAA wasn't set by ParseSectionSpecifier() above,
  1112. // use the value returned by getMachOSection() as a default.
  1113. if (!TAAParsed)
  1114. TAA = S->getTypeAndAttributes();
  1115. // Okay, now that we got the section, verify that the TAA & StubSize agree.
  1116. // If the user declared multiple globals with different section flags, we need
  1117. // to reject it here.
  1118. if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
  1119. // If invalid, report the error with report_fatal_error.
  1120. report_fatal_error("Global variable '" + GO->getName() +
  1121. "' section type or attributes does not match previous"
  1122. " section specifier");
  1123. }
  1124. return S;
  1125. }
  1126. MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
  1127. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1128. checkMachOComdat(GO);
  1129. // Handle thread local data.
  1130. if (Kind.isThreadBSS()) return TLSBSSSection;
  1131. if (Kind.isThreadData()) return TLSDataSection;
  1132. if (Kind.isText())
  1133. return GO->isWeakForLinker() ? TextCoalSection : TextSection;
  1134. // If this is weak/linkonce, put this in a coalescable section, either in text
  1135. // or data depending on if it is writable.
  1136. if (GO->isWeakForLinker()) {
  1137. if (Kind.isReadOnly())
  1138. return ConstTextCoalSection;
  1139. if (Kind.isReadOnlyWithRel())
  1140. return ConstDataCoalSection;
  1141. return DataCoalSection;
  1142. }
  1143. // FIXME: Alignment check should be handled by section classifier.
  1144. if (Kind.isMergeable1ByteCString() &&
  1145. GO->getParent()->getDataLayout().getPreferredAlign(
  1146. cast<GlobalVariable>(GO)) < Align(32))
  1147. return CStringSection;
  1148. // Do not put 16-bit arrays in the UString section if they have an
  1149. // externally visible label, this runs into issues with certain linker
  1150. // versions.
  1151. if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
  1152. GO->getParent()->getDataLayout().getPreferredAlign(
  1153. cast<GlobalVariable>(GO)) < Align(32))
  1154. return UStringSection;
  1155. // With MachO only variables whose corresponding symbol starts with 'l' or
  1156. // 'L' can be merged, so we only try merging GVs with private linkage.
  1157. if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
  1158. if (Kind.isMergeableConst4())
  1159. return FourByteConstantSection;
  1160. if (Kind.isMergeableConst8())
  1161. return EightByteConstantSection;
  1162. if (Kind.isMergeableConst16())
  1163. return SixteenByteConstantSection;
  1164. }
  1165. // Otherwise, if it is readonly, but not something we can specially optimize,
  1166. // just drop it in .const.
  1167. if (Kind.isReadOnly())
  1168. return ReadOnlySection;
  1169. // If this is marked const, put it into a const section. But if the dynamic
  1170. // linker needs to write to it, put it in the data segment.
  1171. if (Kind.isReadOnlyWithRel())
  1172. return ConstDataSection;
  1173. // Put zero initialized globals with strong external linkage in the
  1174. // DATA, __common section with the .zerofill directive.
  1175. if (Kind.isBSSExtern())
  1176. return DataCommonSection;
  1177. // Put zero initialized globals with local linkage in __DATA,__bss directive
  1178. // with the .zerofill directive (aka .lcomm).
  1179. if (Kind.isBSSLocal())
  1180. return DataBSSSection;
  1181. // Otherwise, just drop the variable in the normal data section.
  1182. return DataSection;
  1183. }
  1184. MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
  1185. const DataLayout &DL, SectionKind Kind, const Constant *C,
  1186. Align &Alignment) const {
  1187. // If this constant requires a relocation, we have to put it in the data
  1188. // segment, not in the text segment.
  1189. if (Kind.isData() || Kind.isReadOnlyWithRel())
  1190. return ConstDataSection;
  1191. if (Kind.isMergeableConst4())
  1192. return FourByteConstantSection;
  1193. if (Kind.isMergeableConst8())
  1194. return EightByteConstantSection;
  1195. if (Kind.isMergeableConst16())
  1196. return SixteenByteConstantSection;
  1197. return ReadOnlySection; // .const
  1198. }
  1199. const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
  1200. const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
  1201. MachineModuleInfo *MMI, MCStreamer &Streamer) const {
  1202. // The mach-o version of this method defaults to returning a stub reference.
  1203. if (Encoding & DW_EH_PE_indirect) {
  1204. MachineModuleInfoMachO &MachOMMI =
  1205. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  1206. MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
  1207. // Add information about the stub reference to MachOMMI so that the stub
  1208. // gets emitted by the asmprinter.
  1209. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
  1210. if (!StubSym.getPointer()) {
  1211. MCSymbol *Sym = TM.getSymbol(GV);
  1212. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  1213. }
  1214. return TargetLoweringObjectFile::
  1215. getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
  1216. Encoding & ~DW_EH_PE_indirect, Streamer);
  1217. }
  1218. return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
  1219. MMI, Streamer);
  1220. }
  1221. MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
  1222. const GlobalValue *GV, const TargetMachine &TM,
  1223. MachineModuleInfo *MMI) const {
  1224. // The mach-o version of this method defaults to returning a stub reference.
  1225. MachineModuleInfoMachO &MachOMMI =
  1226. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  1227. MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
  1228. // Add information about the stub reference to MachOMMI so that the stub
  1229. // gets emitted by the asmprinter.
  1230. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
  1231. if (!StubSym.getPointer()) {
  1232. MCSymbol *Sym = TM.getSymbol(GV);
  1233. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  1234. }
  1235. return SSym;
  1236. }
  1237. const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
  1238. const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV,
  1239. int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const {
  1240. // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
  1241. // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
  1242. // through a non_lazy_ptr stub instead. One advantage is that it allows the
  1243. // computation of deltas to final external symbols. Example:
  1244. //
  1245. // _extgotequiv:
  1246. // .long _extfoo
  1247. //
  1248. // _delta:
  1249. // .long _extgotequiv-_delta
  1250. //
  1251. // is transformed to:
  1252. //
  1253. // _delta:
  1254. // .long L_extfoo$non_lazy_ptr-(_delta+0)
  1255. //
  1256. // .section __IMPORT,__pointers,non_lazy_symbol_pointers
  1257. // L_extfoo$non_lazy_ptr:
  1258. // .indirect_symbol _extfoo
  1259. // .long 0
  1260. //
  1261. // The indirect symbol table (and sections of non_lazy_symbol_pointers type)
  1262. // may point to both local (same translation unit) and global (other
  1263. // translation units) symbols. Example:
  1264. //
  1265. // .section __DATA,__pointers,non_lazy_symbol_pointers
  1266. // L1:
  1267. // .indirect_symbol _myGlobal
  1268. // .long 0
  1269. // L2:
  1270. // .indirect_symbol _myLocal
  1271. // .long _myLocal
  1272. //
  1273. // If the symbol is local, instead of the symbol's index, the assembler
  1274. // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table.
  1275. // Then the linker will notice the constant in the table and will look at the
  1276. // content of the symbol.
  1277. MachineModuleInfoMachO &MachOMMI =
  1278. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  1279. MCContext &Ctx = getContext();
  1280. // The offset must consider the original displacement from the base symbol
  1281. // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
  1282. Offset = -MV.getConstant();
  1283. const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
  1284. // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
  1285. // non_lazy_ptr stubs.
  1286. SmallString<128> Name;
  1287. StringRef Suffix = "$non_lazy_ptr";
  1288. Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
  1289. Name += Sym->getName();
  1290. Name += Suffix;
  1291. MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
  1292. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
  1293. if (!StubSym.getPointer())
  1294. StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym),
  1295. !GV->hasLocalLinkage());
  1296. const MCExpr *BSymExpr =
  1297. MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
  1298. const MCExpr *LHS =
  1299. MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
  1300. if (!Offset)
  1301. return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
  1302. const MCExpr *RHS =
  1303. MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
  1304. return MCBinaryExpr::createSub(LHS, RHS, Ctx);
  1305. }
  1306. static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
  1307. const MCSection &Section) {
  1308. if (!AsmInfo.isSectionAtomizableBySymbols(Section))
  1309. return true;
  1310. // FIXME: we should be able to use private labels for sections that can't be
  1311. // dead-stripped (there's no issue with blocking atomization there), but `ld
  1312. // -r` sometimes drops the no_dead_strip attribute from sections so for safety
  1313. // we don't allow it.
  1314. return false;
  1315. }
  1316. void TargetLoweringObjectFileMachO::getNameWithPrefix(
  1317. SmallVectorImpl<char> &OutName, const GlobalValue *GV,
  1318. const TargetMachine &TM) const {
  1319. bool CannotUsePrivateLabel = true;
  1320. if (auto *GO = GV->getAliaseeObject()) {
  1321. SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
  1322. const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
  1323. CannotUsePrivateLabel =
  1324. !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
  1325. }
  1326. getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
  1327. }
  1328. //===----------------------------------------------------------------------===//
  1329. // COFF
  1330. //===----------------------------------------------------------------------===//
  1331. static unsigned
  1332. getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
  1333. unsigned Flags = 0;
  1334. bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
  1335. if (K.isMetadata())
  1336. Flags |=
  1337. COFF::IMAGE_SCN_MEM_DISCARDABLE;
  1338. else if (K.isText())
  1339. Flags |=
  1340. COFF::IMAGE_SCN_MEM_EXECUTE |
  1341. COFF::IMAGE_SCN_MEM_READ |
  1342. COFF::IMAGE_SCN_CNT_CODE |
  1343. (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
  1344. else if (K.isBSS())
  1345. Flags |=
  1346. COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
  1347. COFF::IMAGE_SCN_MEM_READ |
  1348. COFF::IMAGE_SCN_MEM_WRITE;
  1349. else if (K.isThreadLocal())
  1350. Flags |=
  1351. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1352. COFF::IMAGE_SCN_MEM_READ |
  1353. COFF::IMAGE_SCN_MEM_WRITE;
  1354. else if (K.isReadOnly() || K.isReadOnlyWithRel())
  1355. Flags |=
  1356. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1357. COFF::IMAGE_SCN_MEM_READ;
  1358. else if (K.isWriteable())
  1359. Flags |=
  1360. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1361. COFF::IMAGE_SCN_MEM_READ |
  1362. COFF::IMAGE_SCN_MEM_WRITE;
  1363. return Flags;
  1364. }
  1365. static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
  1366. const Comdat *C = GV->getComdat();
  1367. assert(C && "expected GV to have a Comdat!");
  1368. StringRef ComdatGVName = C->getName();
  1369. const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
  1370. if (!ComdatGV)
  1371. report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
  1372. "' does not exist.");
  1373. if (ComdatGV->getComdat() != C)
  1374. report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
  1375. "' is not a key for its COMDAT.");
  1376. return ComdatGV;
  1377. }
  1378. static int getSelectionForCOFF(const GlobalValue *GV) {
  1379. if (const Comdat *C = GV->getComdat()) {
  1380. const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
  1381. if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
  1382. ComdatKey = GA->getAliaseeObject();
  1383. if (ComdatKey == GV) {
  1384. switch (C->getSelectionKind()) {
  1385. case Comdat::Any:
  1386. return COFF::IMAGE_COMDAT_SELECT_ANY;
  1387. case Comdat::ExactMatch:
  1388. return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
  1389. case Comdat::Largest:
  1390. return COFF::IMAGE_COMDAT_SELECT_LARGEST;
  1391. case Comdat::NoDeduplicate:
  1392. return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
  1393. case Comdat::SameSize:
  1394. return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
  1395. }
  1396. } else {
  1397. return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
  1398. }
  1399. }
  1400. return 0;
  1401. }
  1402. MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
  1403. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1404. int Selection = 0;
  1405. unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
  1406. StringRef Name = GO->getSection();
  1407. StringRef COMDATSymName = "";
  1408. if (GO->hasComdat()) {
  1409. Selection = getSelectionForCOFF(GO);
  1410. const GlobalValue *ComdatGV;
  1411. if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
  1412. ComdatGV = getComdatGVForCOFF(GO);
  1413. else
  1414. ComdatGV = GO;
  1415. if (!ComdatGV->hasPrivateLinkage()) {
  1416. MCSymbol *Sym = TM.getSymbol(ComdatGV);
  1417. COMDATSymName = Sym->getName();
  1418. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  1419. } else {
  1420. Selection = 0;
  1421. }
  1422. }
  1423. return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
  1424. Selection);
  1425. }
  1426. static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
  1427. if (Kind.isText())
  1428. return ".text";
  1429. if (Kind.isBSS())
  1430. return ".bss";
  1431. if (Kind.isThreadLocal())
  1432. return ".tls$";
  1433. if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
  1434. return ".rdata";
  1435. return ".data";
  1436. }
  1437. MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
  1438. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1439. // If we have -ffunction-sections then we should emit the global value to a
  1440. // uniqued section specifically for it.
  1441. bool EmitUniquedSection;
  1442. if (Kind.isText())
  1443. EmitUniquedSection = TM.getFunctionSections();
  1444. else
  1445. EmitUniquedSection = TM.getDataSections();
  1446. if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
  1447. SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind);
  1448. unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
  1449. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  1450. int Selection = getSelectionForCOFF(GO);
  1451. if (!Selection)
  1452. Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
  1453. const GlobalValue *ComdatGV;
  1454. if (GO->hasComdat())
  1455. ComdatGV = getComdatGVForCOFF(GO);
  1456. else
  1457. ComdatGV = GO;
  1458. unsigned UniqueID = MCContext::GenericSectionID;
  1459. if (EmitUniquedSection)
  1460. UniqueID = NextUniqueID++;
  1461. if (!ComdatGV->hasPrivateLinkage()) {
  1462. MCSymbol *Sym = TM.getSymbol(ComdatGV);
  1463. StringRef COMDATSymName = Sym->getName();
  1464. if (const auto *F = dyn_cast<Function>(GO))
  1465. if (Optional<StringRef> Prefix = F->getSectionPrefix())
  1466. raw_svector_ostream(Name) << '$' << *Prefix;
  1467. // Append "$symbol" to the section name *before* IR-level mangling is
  1468. // applied when targetting mingw. This is what GCC does, and the ld.bfd
  1469. // COFF linker will not properly handle comdats otherwise.
  1470. if (getContext().getTargetTriple().isWindowsGNUEnvironment())
  1471. raw_svector_ostream(Name) << '$' << ComdatGV->getName();
  1472. return getContext().getCOFFSection(Name, Characteristics, Kind,
  1473. COMDATSymName, Selection, UniqueID);
  1474. } else {
  1475. SmallString<256> TmpData;
  1476. getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
  1477. return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
  1478. Selection, UniqueID);
  1479. }
  1480. }
  1481. if (Kind.isText())
  1482. return TextSection;
  1483. if (Kind.isThreadLocal())
  1484. return TLSDataSection;
  1485. if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
  1486. return ReadOnlySection;
  1487. // Note: we claim that common symbols are put in BSSSection, but they are
  1488. // really emitted with the magic .comm directive, which creates a symbol table
  1489. // entry but not a section.
  1490. if (Kind.isBSS() || Kind.isCommon())
  1491. return BSSSection;
  1492. return DataSection;
  1493. }
  1494. void TargetLoweringObjectFileCOFF::getNameWithPrefix(
  1495. SmallVectorImpl<char> &OutName, const GlobalValue *GV,
  1496. const TargetMachine &TM) const {
  1497. bool CannotUsePrivateLabel = false;
  1498. if (GV->hasPrivateLinkage() &&
  1499. ((isa<Function>(GV) && TM.getFunctionSections()) ||
  1500. (isa<GlobalVariable>(GV) && TM.getDataSections())))
  1501. CannotUsePrivateLabel = true;
  1502. getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
  1503. }
  1504. MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
  1505. const Function &F, const TargetMachine &TM) const {
  1506. // If the function can be removed, produce a unique section so that
  1507. // the table doesn't prevent the removal.
  1508. const Comdat *C = F.getComdat();
  1509. bool EmitUniqueSection = TM.getFunctionSections() || C;
  1510. if (!EmitUniqueSection)
  1511. return ReadOnlySection;
  1512. // FIXME: we should produce a symbol for F instead.
  1513. if (F.hasPrivateLinkage())
  1514. return ReadOnlySection;
  1515. MCSymbol *Sym = TM.getSymbol(&F);
  1516. StringRef COMDATSymName = Sym->getName();
  1517. SectionKind Kind = SectionKind::getReadOnly();
  1518. StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind);
  1519. unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
  1520. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  1521. unsigned UniqueID = NextUniqueID++;
  1522. return getContext().getCOFFSection(
  1523. SecName, Characteristics, Kind, COMDATSymName,
  1524. COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
  1525. }
  1526. void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer,
  1527. Module &M) const {
  1528. emitLinkerDirectives(Streamer, M);
  1529. unsigned Version = 0;
  1530. unsigned Flags = 0;
  1531. StringRef Section;
  1532. GetObjCImageInfo(M, Version, Flags, Section);
  1533. if (!Section.empty()) {
  1534. auto &C = getContext();
  1535. auto *S = C.getCOFFSection(Section,
  1536. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1537. COFF::IMAGE_SCN_MEM_READ,
  1538. SectionKind::getReadOnly());
  1539. Streamer.SwitchSection(S);
  1540. Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
  1541. Streamer.emitInt32(Version);
  1542. Streamer.emitInt32(Flags);
  1543. Streamer.AddBlankLine();
  1544. }
  1545. emitCGProfileMetadata(Streamer, M);
  1546. }
  1547. void TargetLoweringObjectFileCOFF::emitLinkerDirectives(
  1548. MCStreamer &Streamer, Module &M) const {
  1549. if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
  1550. // Emit the linker options to the linker .drectve section. According to the
  1551. // spec, this section is a space-separated string containing flags for
  1552. // linker.
  1553. MCSection *Sec = getDrectveSection();
  1554. Streamer.SwitchSection(Sec);
  1555. for (const auto *Option : LinkerOptions->operands()) {
  1556. for (const auto &Piece : cast<MDNode>(Option)->operands()) {
  1557. // Lead with a space for consistency with our dllexport implementation.
  1558. std::string Directive(" ");
  1559. Directive.append(std::string(cast<MDString>(Piece)->getString()));
  1560. Streamer.emitBytes(Directive);
  1561. }
  1562. }
  1563. }
  1564. // Emit /EXPORT: flags for each exported global as necessary.
  1565. std::string Flags;
  1566. for (const GlobalValue &GV : M.global_values()) {
  1567. raw_string_ostream OS(Flags);
  1568. emitLinkerFlagsForGlobalCOFF(OS, &GV, getContext().getTargetTriple(),
  1569. getMangler());
  1570. OS.flush();
  1571. if (!Flags.empty()) {
  1572. Streamer.SwitchSection(getDrectveSection());
  1573. Streamer.emitBytes(Flags);
  1574. }
  1575. Flags.clear();
  1576. }
  1577. // Emit /INCLUDE: flags for each used global as necessary.
  1578. if (const auto *LU = M.getNamedGlobal("llvm.used")) {
  1579. assert(LU->hasInitializer() && "expected llvm.used to have an initializer");
  1580. assert(isa<ArrayType>(LU->getValueType()) &&
  1581. "expected llvm.used to be an array type");
  1582. if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
  1583. for (const Value *Op : A->operands()) {
  1584. const auto *GV = cast<GlobalValue>(Op->stripPointerCasts());
  1585. // Global symbols with internal or private linkage are not visible to
  1586. // the linker, and thus would cause an error when the linker tried to
  1587. // preserve the symbol due to the `/include:` directive.
  1588. if (GV->hasLocalLinkage())
  1589. continue;
  1590. raw_string_ostream OS(Flags);
  1591. emitLinkerFlagsForUsedCOFF(OS, GV, getContext().getTargetTriple(),
  1592. getMangler());
  1593. OS.flush();
  1594. if (!Flags.empty()) {
  1595. Streamer.SwitchSection(getDrectveSection());
  1596. Streamer.emitBytes(Flags);
  1597. }
  1598. Flags.clear();
  1599. }
  1600. }
  1601. }
  1602. }
  1603. void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
  1604. const TargetMachine &TM) {
  1605. TargetLoweringObjectFile::Initialize(Ctx, TM);
  1606. this->TM = &TM;
  1607. const Triple &T = TM.getTargetTriple();
  1608. if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
  1609. StaticCtorSection =
  1610. Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1611. COFF::IMAGE_SCN_MEM_READ,
  1612. SectionKind::getReadOnly());
  1613. StaticDtorSection =
  1614. Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1615. COFF::IMAGE_SCN_MEM_READ,
  1616. SectionKind::getReadOnly());
  1617. } else {
  1618. StaticCtorSection = Ctx.getCOFFSection(
  1619. ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1620. COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
  1621. SectionKind::getData());
  1622. StaticDtorSection = Ctx.getCOFFSection(
  1623. ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1624. COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
  1625. SectionKind::getData());
  1626. }
  1627. }
  1628. static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx,
  1629. const Triple &T, bool IsCtor,
  1630. unsigned Priority,
  1631. const MCSymbol *KeySym,
  1632. MCSectionCOFF *Default) {
  1633. if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
  1634. // If the priority is the default, use .CRT$XCU, possibly associative.
  1635. if (Priority == 65535)
  1636. return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
  1637. // Otherwise, we need to compute a new section name. Low priorities should
  1638. // run earlier. The linker will sort sections ASCII-betically, and we need a
  1639. // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
  1640. // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
  1641. // low priorities need to sort before 'L', since the CRT uses that
  1642. // internally, so we use ".CRT$XCA00001" for them.
  1643. SmallString<24> Name;
  1644. raw_svector_ostream OS(Name);
  1645. OS << ".CRT$X" << (IsCtor ? "C" : "T") <<
  1646. (Priority < 200 ? 'A' : 'T') << format("%05u", Priority);
  1647. MCSectionCOFF *Sec = Ctx.getCOFFSection(
  1648. Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
  1649. SectionKind::getReadOnly());
  1650. return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0);
  1651. }
  1652. std::string Name = IsCtor ? ".ctors" : ".dtors";
  1653. if (Priority != 65535)
  1654. raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
  1655. return Ctx.getAssociativeCOFFSection(
  1656. Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1657. COFF::IMAGE_SCN_MEM_READ |
  1658. COFF::IMAGE_SCN_MEM_WRITE,
  1659. SectionKind::getData()),
  1660. KeySym, 0);
  1661. }
  1662. MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
  1663. unsigned Priority, const MCSymbol *KeySym) const {
  1664. return getCOFFStaticStructorSection(
  1665. getContext(), getContext().getTargetTriple(), true, Priority, KeySym,
  1666. cast<MCSectionCOFF>(StaticCtorSection));
  1667. }
  1668. MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
  1669. unsigned Priority, const MCSymbol *KeySym) const {
  1670. return getCOFFStaticStructorSection(
  1671. getContext(), getContext().getTargetTriple(), false, Priority, KeySym,
  1672. cast<MCSectionCOFF>(StaticDtorSection));
  1673. }
  1674. const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference(
  1675. const GlobalValue *LHS, const GlobalValue *RHS,
  1676. const TargetMachine &TM) const {
  1677. const Triple &T = TM.getTargetTriple();
  1678. if (T.isOSCygMing())
  1679. return nullptr;
  1680. // Our symbols should exist in address space zero, cowardly no-op if
  1681. // otherwise.
  1682. if (LHS->getType()->getPointerAddressSpace() != 0 ||
  1683. RHS->getType()->getPointerAddressSpace() != 0)
  1684. return nullptr;
  1685. // Both ptrtoint instructions must wrap global objects:
  1686. // - Only global variables are eligible for image relative relocations.
  1687. // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
  1688. // We expect __ImageBase to be a global variable without a section, externally
  1689. // defined.
  1690. //
  1691. // It should look something like this: @__ImageBase = external constant i8
  1692. if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
  1693. LHS->isThreadLocal() || RHS->isThreadLocal() ||
  1694. RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
  1695. cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
  1696. return nullptr;
  1697. return MCSymbolRefExpr::create(TM.getSymbol(LHS),
  1698. MCSymbolRefExpr::VK_COFF_IMGREL32,
  1699. getContext());
  1700. }
  1701. static std::string APIntToHexString(const APInt &AI) {
  1702. unsigned Width = (AI.getBitWidth() / 8) * 2;
  1703. std::string HexString = toString(AI, 16, /*Signed=*/false);
  1704. llvm::transform(HexString, HexString.begin(), tolower);
  1705. unsigned Size = HexString.size();
  1706. assert(Width >= Size && "hex string is too large!");
  1707. HexString.insert(HexString.begin(), Width - Size, '0');
  1708. return HexString;
  1709. }
  1710. static std::string scalarConstantToHexString(const Constant *C) {
  1711. Type *Ty = C->getType();
  1712. if (isa<UndefValue>(C)) {
  1713. return APIntToHexString(APInt::getZero(Ty->getPrimitiveSizeInBits()));
  1714. } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
  1715. return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
  1716. } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
  1717. return APIntToHexString(CI->getValue());
  1718. } else {
  1719. unsigned NumElements;
  1720. if (auto *VTy = dyn_cast<VectorType>(Ty))
  1721. NumElements = cast<FixedVectorType>(VTy)->getNumElements();
  1722. else
  1723. NumElements = Ty->getArrayNumElements();
  1724. std::string HexString;
  1725. for (int I = NumElements - 1, E = -1; I != E; --I)
  1726. HexString += scalarConstantToHexString(C->getAggregateElement(I));
  1727. return HexString;
  1728. }
  1729. }
  1730. MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant(
  1731. const DataLayout &DL, SectionKind Kind, const Constant *C,
  1732. Align &Alignment) const {
  1733. if (Kind.isMergeableConst() && C &&
  1734. getContext().getAsmInfo()->hasCOFFComdatConstants()) {
  1735. // This creates comdat sections with the given symbol name, but unless
  1736. // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
  1737. // will be created with a null storage class, which makes GNU binutils
  1738. // error out.
  1739. const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1740. COFF::IMAGE_SCN_MEM_READ |
  1741. COFF::IMAGE_SCN_LNK_COMDAT;
  1742. std::string COMDATSymName;
  1743. if (Kind.isMergeableConst4()) {
  1744. if (Alignment <= 4) {
  1745. COMDATSymName = "__real@" + scalarConstantToHexString(C);
  1746. Alignment = Align(4);
  1747. }
  1748. } else if (Kind.isMergeableConst8()) {
  1749. if (Alignment <= 8) {
  1750. COMDATSymName = "__real@" + scalarConstantToHexString(C);
  1751. Alignment = Align(8);
  1752. }
  1753. } else if (Kind.isMergeableConst16()) {
  1754. // FIXME: These may not be appropriate for non-x86 architectures.
  1755. if (Alignment <= 16) {
  1756. COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
  1757. Alignment = Align(16);
  1758. }
  1759. } else if (Kind.isMergeableConst32()) {
  1760. if (Alignment <= 32) {
  1761. COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
  1762. Alignment = Align(32);
  1763. }
  1764. }
  1765. if (!COMDATSymName.empty())
  1766. return getContext().getCOFFSection(".rdata", Characteristics, Kind,
  1767. COMDATSymName,
  1768. COFF::IMAGE_COMDAT_SELECT_ANY);
  1769. }
  1770. return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C,
  1771. Alignment);
  1772. }
  1773. //===----------------------------------------------------------------------===//
  1774. // Wasm
  1775. //===----------------------------------------------------------------------===//
  1776. static const Comdat *getWasmComdat(const GlobalValue *GV) {
  1777. const Comdat *C = GV->getComdat();
  1778. if (!C)
  1779. return nullptr;
  1780. if (C->getSelectionKind() != Comdat::Any)
  1781. report_fatal_error("WebAssembly COMDATs only support "
  1782. "SelectionKind::Any, '" + C->getName() + "' cannot be "
  1783. "lowered.");
  1784. return C;
  1785. }
  1786. static unsigned getWasmSectionFlags(SectionKind K) {
  1787. unsigned Flags = 0;
  1788. if (K.isThreadLocal())
  1789. Flags |= wasm::WASM_SEG_FLAG_TLS;
  1790. if (K.isMergeableCString())
  1791. Flags |= wasm::WASM_SEG_FLAG_STRINGS;
  1792. // TODO(sbc): Add suport for K.isMergeableConst()
  1793. return Flags;
  1794. }
  1795. MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
  1796. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1797. // We don't support explict section names for functions in the wasm object
  1798. // format. Each function has to be in its own unique section.
  1799. if (isa<Function>(GO)) {
  1800. return SelectSectionForGlobal(GO, Kind, TM);
  1801. }
  1802. StringRef Name = GO->getSection();
  1803. // Certain data sections we treat as named custom sections rather than
  1804. // segments within the data section.
  1805. // This could be avoided if all data segements (the wasm sense) were
  1806. // represented as their own sections (in the llvm sense).
  1807. // TODO(sbc): https://github.com/WebAssembly/tool-conventions/issues/138
  1808. if (Name == ".llvmcmd" || Name == ".llvmbc")
  1809. Kind = SectionKind::getMetadata();
  1810. StringRef Group = "";
  1811. if (const Comdat *C = getWasmComdat(GO)) {
  1812. Group = C->getName();
  1813. }
  1814. unsigned Flags = getWasmSectionFlags(Kind);
  1815. MCSectionWasm *Section = getContext().getWasmSection(
  1816. Name, Kind, Flags, Group, MCContext::GenericSectionID);
  1817. return Section;
  1818. }
  1819. static MCSectionWasm *selectWasmSectionForGlobal(
  1820. MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
  1821. const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
  1822. StringRef Group = "";
  1823. if (const Comdat *C = getWasmComdat(GO)) {
  1824. Group = C->getName();
  1825. }
  1826. bool UniqueSectionNames = TM.getUniqueSectionNames();
  1827. SmallString<128> Name = getSectionPrefixForGlobal(Kind);
  1828. if (const auto *F = dyn_cast<Function>(GO)) {
  1829. const auto &OptionalPrefix = F->getSectionPrefix();
  1830. if (OptionalPrefix)
  1831. raw_svector_ostream(Name) << '.' << *OptionalPrefix;
  1832. }
  1833. if (EmitUniqueSection && UniqueSectionNames) {
  1834. Name.push_back('.');
  1835. TM.getNameWithPrefix(Name, GO, Mang, true);
  1836. }
  1837. unsigned UniqueID = MCContext::GenericSectionID;
  1838. if (EmitUniqueSection && !UniqueSectionNames) {
  1839. UniqueID = *NextUniqueID;
  1840. (*NextUniqueID)++;
  1841. }
  1842. unsigned Flags = getWasmSectionFlags(Kind);
  1843. return Ctx.getWasmSection(Name, Kind, Flags, Group, UniqueID);
  1844. }
  1845. MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
  1846. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1847. if (Kind.isCommon())
  1848. report_fatal_error("mergable sections not supported yet on wasm");
  1849. // If we have -ffunction-section or -fdata-section then we should emit the
  1850. // global value to a uniqued section specifically for it.
  1851. bool EmitUniqueSection = false;
  1852. if (Kind.isText())
  1853. EmitUniqueSection = TM.getFunctionSections();
  1854. else
  1855. EmitUniqueSection = TM.getDataSections();
  1856. EmitUniqueSection |= GO->hasComdat();
  1857. return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
  1858. EmitUniqueSection, &NextUniqueID);
  1859. }
  1860. bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
  1861. bool UsesLabelDifference, const Function &F) const {
  1862. // We can always create relative relocations, so use another section
  1863. // that can be marked non-executable.
  1864. return false;
  1865. }
  1866. const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
  1867. const GlobalValue *LHS, const GlobalValue *RHS,
  1868. const TargetMachine &TM) const {
  1869. // We may only use a PLT-relative relocation to refer to unnamed_addr
  1870. // functions.
  1871. if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
  1872. return nullptr;
  1873. // Basic correctness checks.
  1874. if (LHS->getType()->getPointerAddressSpace() != 0 ||
  1875. RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
  1876. RHS->isThreadLocal())
  1877. return nullptr;
  1878. return MCBinaryExpr::createSub(
  1879. MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
  1880. getContext()),
  1881. MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
  1882. }
  1883. void TargetLoweringObjectFileWasm::InitializeWasm() {
  1884. StaticCtorSection =
  1885. getContext().getWasmSection(".init_array", SectionKind::getData());
  1886. // We don't use PersonalityEncoding and LSDAEncoding because we don't emit
  1887. // .cfi directives. We use TTypeEncoding to encode typeinfo global variables.
  1888. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  1889. }
  1890. MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection(
  1891. unsigned Priority, const MCSymbol *KeySym) const {
  1892. return Priority == UINT16_MAX ?
  1893. StaticCtorSection :
  1894. getContext().getWasmSection(".init_array." + utostr(Priority),
  1895. SectionKind::getData());
  1896. }
  1897. MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection(
  1898. unsigned Priority, const MCSymbol *KeySym) const {
  1899. llvm_unreachable("@llvm.global_dtors should have been lowered already");
  1900. return nullptr;
  1901. }
  1902. //===----------------------------------------------------------------------===//
  1903. // XCOFF
  1904. //===----------------------------------------------------------------------===//
  1905. bool TargetLoweringObjectFileXCOFF::ShouldEmitEHBlock(
  1906. const MachineFunction *MF) {
  1907. if (!MF->getLandingPads().empty())
  1908. return true;
  1909. const Function &F = MF->getFunction();
  1910. if (!F.hasPersonalityFn() || !F.needsUnwindTableEntry())
  1911. return false;
  1912. const GlobalValue *Per =
  1913. dyn_cast<GlobalValue>(F.getPersonalityFn()->stripPointerCasts());
  1914. assert(Per && "Personality routine is not a GlobalValue type.");
  1915. if (isNoOpWithoutInvoke(classifyEHPersonality(Per)))
  1916. return false;
  1917. return true;
  1918. }
  1919. bool TargetLoweringObjectFileXCOFF::ShouldSetSSPCanaryBitInTB(
  1920. const MachineFunction *MF) {
  1921. const Function &F = MF->getFunction();
  1922. if (!F.hasStackProtectorFnAttr())
  1923. return false;
  1924. // FIXME: check presence of canary word
  1925. // There are cases that the stack protectors are not really inserted even if
  1926. // the attributes are on.
  1927. return true;
  1928. }
  1929. MCSymbol *
  1930. TargetLoweringObjectFileXCOFF::getEHInfoTableSymbol(const MachineFunction *MF) {
  1931. return MF->getMMI().getContext().getOrCreateSymbol(
  1932. "__ehinfo." + Twine(MF->getFunctionNumber()));
  1933. }
  1934. MCSymbol *
  1935. TargetLoweringObjectFileXCOFF::getTargetSymbol(const GlobalValue *GV,
  1936. const TargetMachine &TM) const {
  1937. // We always use a qualname symbol for a GV that represents
  1938. // a declaration, a function descriptor, or a common symbol.
  1939. // If a GV represents a GlobalVariable and -fdata-sections is enabled, we
  1940. // also return a qualname so that a label symbol could be avoided.
  1941. // It is inherently ambiguous when the GO represents the address of a
  1942. // function, as the GO could either represent a function descriptor or a
  1943. // function entry point. We choose to always return a function descriptor
  1944. // here.
  1945. if (const GlobalObject *GO = dyn_cast<GlobalObject>(GV)) {
  1946. if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
  1947. if (GVar->hasAttribute("toc-data"))
  1948. return cast<MCSectionXCOFF>(
  1949. SectionForGlobal(GVar, SectionKind::getData(), TM))
  1950. ->getQualNameSymbol();
  1951. if (GO->isDeclarationForLinker())
  1952. return cast<MCSectionXCOFF>(getSectionForExternalReference(GO, TM))
  1953. ->getQualNameSymbol();
  1954. SectionKind GOKind = getKindForGlobal(GO, TM);
  1955. if (GOKind.isText())
  1956. return cast<MCSectionXCOFF>(
  1957. getSectionForFunctionDescriptor(cast<Function>(GO), TM))
  1958. ->getQualNameSymbol();
  1959. if ((TM.getDataSections() && !GO->hasSection()) || GO->hasCommonLinkage() ||
  1960. GOKind.isBSSLocal() || GOKind.isThreadBSSLocal())
  1961. return cast<MCSectionXCOFF>(SectionForGlobal(GO, GOKind, TM))
  1962. ->getQualNameSymbol();
  1963. }
  1964. // For all other cases, fall back to getSymbol to return the unqualified name.
  1965. return nullptr;
  1966. }
  1967. MCSection *TargetLoweringObjectFileXCOFF::getExplicitSectionGlobal(
  1968. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1969. if (!GO->hasSection())
  1970. report_fatal_error("#pragma clang section is not yet supported");
  1971. StringRef SectionName = GO->getSection();
  1972. // Handle the XCOFF::TD case first, then deal with the rest.
  1973. if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
  1974. if (GVar->hasAttribute("toc-data"))
  1975. return getContext().getXCOFFSection(
  1976. SectionName, Kind,
  1977. XCOFF::CsectProperties(/*MappingClass*/ XCOFF::XMC_TD, XCOFF::XTY_SD),
  1978. /* MultiSymbolsAllowed*/ true);
  1979. XCOFF::StorageMappingClass MappingClass;
  1980. if (Kind.isText())
  1981. MappingClass = XCOFF::XMC_PR;
  1982. else if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS())
  1983. MappingClass = XCOFF::XMC_RW;
  1984. else if (Kind.isReadOnly())
  1985. MappingClass = XCOFF::XMC_RO;
  1986. else
  1987. report_fatal_error("XCOFF other section types not yet implemented.");
  1988. return getContext().getXCOFFSection(
  1989. SectionName, Kind, XCOFF::CsectProperties(MappingClass, XCOFF::XTY_SD),
  1990. /* MultiSymbolsAllowed*/ true);
  1991. }
  1992. MCSection *TargetLoweringObjectFileXCOFF::getSectionForExternalReference(
  1993. const GlobalObject *GO, const TargetMachine &TM) const {
  1994. assert(GO->isDeclarationForLinker() &&
  1995. "Tried to get ER section for a defined global.");
  1996. SmallString<128> Name;
  1997. getNameWithPrefix(Name, GO, TM);
  1998. XCOFF::StorageMappingClass SMC =
  1999. isa<Function>(GO) ? XCOFF::XMC_DS : XCOFF::XMC_UA;
  2000. if (GO->isThreadLocal())
  2001. SMC = XCOFF::XMC_UL;
  2002. // Externals go into a csect of type ER.
  2003. return getContext().getXCOFFSection(
  2004. Name, SectionKind::getMetadata(),
  2005. XCOFF::CsectProperties(SMC, XCOFF::XTY_ER));
  2006. }
  2007. MCSection *TargetLoweringObjectFileXCOFF::SelectSectionForGlobal(
  2008. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  2009. // Handle the XCOFF::TD case first, then deal with the rest.
  2010. if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
  2011. if (GVar->hasAttribute("toc-data")) {
  2012. SmallString<128> Name;
  2013. getNameWithPrefix(Name, GO, TM);
  2014. return getContext().getXCOFFSection(
  2015. Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TD, XCOFF::XTY_SD),
  2016. /* MultiSymbolsAllowed*/ true);
  2017. }
  2018. // Common symbols go into a csect with matching name which will get mapped
  2019. // into the .bss section.
  2020. // Zero-initialized local TLS symbols go into a csect with matching name which
  2021. // will get mapped into the .tbss section.
  2022. if (Kind.isBSSLocal() || GO->hasCommonLinkage() || Kind.isThreadBSSLocal()) {
  2023. SmallString<128> Name;
  2024. getNameWithPrefix(Name, GO, TM);
  2025. XCOFF::StorageMappingClass SMC = Kind.isBSSLocal() ? XCOFF::XMC_BS
  2026. : Kind.isCommon() ? XCOFF::XMC_RW
  2027. : XCOFF::XMC_UL;
  2028. return getContext().getXCOFFSection(
  2029. Name, Kind, XCOFF::CsectProperties(SMC, XCOFF::XTY_CM));
  2030. }
  2031. if (Kind.isMergeableCString()) {
  2032. Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign(
  2033. cast<GlobalVariable>(GO));
  2034. unsigned EntrySize = getEntrySizeForKind(Kind);
  2035. std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
  2036. SmallString<128> Name;
  2037. Name = SizeSpec + utostr(Alignment.value());
  2038. if (TM.getDataSections())
  2039. getNameWithPrefix(Name, GO, TM);
  2040. return getContext().getXCOFFSection(
  2041. Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD),
  2042. /* MultiSymbolsAllowed*/ !TM.getDataSections());
  2043. }
  2044. if (Kind.isText()) {
  2045. if (TM.getFunctionSections()) {
  2046. return cast<MCSymbolXCOFF>(getFunctionEntryPointSymbol(GO, TM))
  2047. ->getRepresentedCsect();
  2048. }
  2049. return TextSection;
  2050. }
  2051. // TODO: We may put Kind.isReadOnlyWithRel() under option control, because
  2052. // user may want to have read-only data with relocations placed into a
  2053. // read-only section by the compiler.
  2054. // For BSS kind, zero initialized data must be emitted to the .data section
  2055. // because external linkage control sections that get mapped to the .bss
  2056. // section will be linked as tentative defintions, which is only appropriate
  2057. // for SectionKind::Common.
  2058. if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS()) {
  2059. if (TM.getDataSections()) {
  2060. SmallString<128> Name;
  2061. getNameWithPrefix(Name, GO, TM);
  2062. return getContext().getXCOFFSection(
  2063. Name, SectionKind::getData(),
  2064. XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD));
  2065. }
  2066. return DataSection;
  2067. }
  2068. if (Kind.isReadOnly()) {
  2069. if (TM.getDataSections()) {
  2070. SmallString<128> Name;
  2071. getNameWithPrefix(Name, GO, TM);
  2072. return getContext().getXCOFFSection(
  2073. Name, SectionKind::getReadOnly(),
  2074. XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD));
  2075. }
  2076. return ReadOnlySection;
  2077. }
  2078. // External/weak TLS data and initialized local TLS data are not eligible
  2079. // to be put into common csect. If data sections are enabled, thread
  2080. // data are emitted into separate sections. Otherwise, thread data
  2081. // are emitted into the .tdata section.
  2082. if (Kind.isThreadLocal()) {
  2083. if (TM.getDataSections()) {
  2084. SmallString<128> Name;
  2085. getNameWithPrefix(Name, GO, TM);
  2086. return getContext().getXCOFFSection(
  2087. Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TL, XCOFF::XTY_SD));
  2088. }
  2089. return TLSDataSection;
  2090. }
  2091. report_fatal_error("XCOFF other section types not yet implemented.");
  2092. }
  2093. MCSection *TargetLoweringObjectFileXCOFF::getSectionForJumpTable(
  2094. const Function &F, const TargetMachine &TM) const {
  2095. assert (!F.getComdat() && "Comdat not supported on XCOFF.");
  2096. if (!TM.getFunctionSections())
  2097. return ReadOnlySection;
  2098. // If the function can be removed, produce a unique section so that
  2099. // the table doesn't prevent the removal.
  2100. SmallString<128> NameStr(".rodata.jmp..");
  2101. getNameWithPrefix(NameStr, &F, TM);
  2102. return getContext().getXCOFFSection(
  2103. NameStr, SectionKind::getReadOnly(),
  2104. XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD));
  2105. }
  2106. bool TargetLoweringObjectFileXCOFF::shouldPutJumpTableInFunctionSection(
  2107. bool UsesLabelDifference, const Function &F) const {
  2108. return false;
  2109. }
  2110. /// Given a mergeable constant with the specified size and relocation
  2111. /// information, return a section that it should be placed in.
  2112. MCSection *TargetLoweringObjectFileXCOFF::getSectionForConstant(
  2113. const DataLayout &DL, SectionKind Kind, const Constant *C,
  2114. Align &Alignment) const {
  2115. // TODO: Enable emiting constant pool to unique sections when we support it.
  2116. if (Alignment > Align(16))
  2117. report_fatal_error("Alignments greater than 16 not yet supported.");
  2118. if (Alignment == Align(8)) {
  2119. assert(ReadOnly8Section && "Section should always be initialized.");
  2120. return ReadOnly8Section;
  2121. }
  2122. if (Alignment == Align(16)) {
  2123. assert(ReadOnly16Section && "Section should always be initialized.");
  2124. return ReadOnly16Section;
  2125. }
  2126. return ReadOnlySection;
  2127. }
  2128. void TargetLoweringObjectFileXCOFF::Initialize(MCContext &Ctx,
  2129. const TargetMachine &TgtM) {
  2130. TargetLoweringObjectFile::Initialize(Ctx, TgtM);
  2131. TTypeEncoding =
  2132. dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_datarel |
  2133. (TgtM.getTargetTriple().isArch32Bit() ? dwarf::DW_EH_PE_sdata4
  2134. : dwarf::DW_EH_PE_sdata8);
  2135. PersonalityEncoding = 0;
  2136. LSDAEncoding = 0;
  2137. CallSiteEncoding = dwarf::DW_EH_PE_udata4;
  2138. }
  2139. MCSection *TargetLoweringObjectFileXCOFF::getStaticCtorSection(
  2140. unsigned Priority, const MCSymbol *KeySym) const {
  2141. report_fatal_error("no static constructor section on AIX");
  2142. }
  2143. MCSection *TargetLoweringObjectFileXCOFF::getStaticDtorSection(
  2144. unsigned Priority, const MCSymbol *KeySym) const {
  2145. report_fatal_error("no static destructor section on AIX");
  2146. }
  2147. const MCExpr *TargetLoweringObjectFileXCOFF::lowerRelativeReference(
  2148. const GlobalValue *LHS, const GlobalValue *RHS,
  2149. const TargetMachine &TM) const {
  2150. /* Not implemented yet, but don't crash, return nullptr. */
  2151. return nullptr;
  2152. }
  2153. XCOFF::StorageClass
  2154. TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(const GlobalValue *GV) {
  2155. assert(!isa<GlobalIFunc>(GV) && "GlobalIFunc is not supported on AIX.");
  2156. switch (GV->getLinkage()) {
  2157. case GlobalValue::InternalLinkage:
  2158. case GlobalValue::PrivateLinkage:
  2159. return XCOFF::C_HIDEXT;
  2160. case GlobalValue::ExternalLinkage:
  2161. case GlobalValue::CommonLinkage:
  2162. case GlobalValue::AvailableExternallyLinkage:
  2163. return XCOFF::C_EXT;
  2164. case GlobalValue::ExternalWeakLinkage:
  2165. case GlobalValue::LinkOnceAnyLinkage:
  2166. case GlobalValue::LinkOnceODRLinkage:
  2167. case GlobalValue::WeakAnyLinkage:
  2168. case GlobalValue::WeakODRLinkage:
  2169. return XCOFF::C_WEAKEXT;
  2170. case GlobalValue::AppendingLinkage:
  2171. report_fatal_error(
  2172. "There is no mapping that implements AppendingLinkage for XCOFF.");
  2173. }
  2174. llvm_unreachable("Unknown linkage type!");
  2175. }
  2176. MCSymbol *TargetLoweringObjectFileXCOFF::getFunctionEntryPointSymbol(
  2177. const GlobalValue *Func, const TargetMachine &TM) const {
  2178. assert((isa<Function>(Func) ||
  2179. (isa<GlobalAlias>(Func) &&
  2180. isa_and_nonnull<Function>(
  2181. cast<GlobalAlias>(Func)->getAliaseeObject()))) &&
  2182. "Func must be a function or an alias which has a function as base "
  2183. "object.");
  2184. SmallString<128> NameStr;
  2185. NameStr.push_back('.');
  2186. getNameWithPrefix(NameStr, Func, TM);
  2187. // When -function-sections is enabled and explicit section is not specified,
  2188. // it's not necessary to emit function entry point label any more. We will use
  2189. // function entry point csect instead. And for function delcarations, the
  2190. // undefined symbols gets treated as csect with XTY_ER property.
  2191. if (((TM.getFunctionSections() && !Func->hasSection()) ||
  2192. Func->isDeclaration()) &&
  2193. isa<Function>(Func)) {
  2194. return getContext()
  2195. .getXCOFFSection(
  2196. NameStr, SectionKind::getText(),
  2197. XCOFF::CsectProperties(XCOFF::XMC_PR, Func->isDeclaration()
  2198. ? XCOFF::XTY_ER
  2199. : XCOFF::XTY_SD))
  2200. ->getQualNameSymbol();
  2201. }
  2202. return getContext().getOrCreateSymbol(NameStr);
  2203. }
  2204. MCSection *TargetLoweringObjectFileXCOFF::getSectionForFunctionDescriptor(
  2205. const Function *F, const TargetMachine &TM) const {
  2206. SmallString<128> NameStr;
  2207. getNameWithPrefix(NameStr, F, TM);
  2208. return getContext().getXCOFFSection(
  2209. NameStr, SectionKind::getData(),
  2210. XCOFF::CsectProperties(XCOFF::XMC_DS, XCOFF::XTY_SD));
  2211. }
  2212. MCSection *TargetLoweringObjectFileXCOFF::getSectionForTOCEntry(
  2213. const MCSymbol *Sym, const TargetMachine &TM) const {
  2214. // Use TE storage-mapping class when large code model is enabled so that
  2215. // the chance of needing -bbigtoc is decreased.
  2216. return getContext().getXCOFFSection(
  2217. cast<MCSymbolXCOFF>(Sym)->getSymbolTableName(), SectionKind::getData(),
  2218. XCOFF::CsectProperties(
  2219. TM.getCodeModel() == CodeModel::Large ? XCOFF::XMC_TE : XCOFF::XMC_TC,
  2220. XCOFF::XTY_SD));
  2221. }
  2222. //===----------------------------------------------------------------------===//
  2223. // GOFF
  2224. //===----------------------------------------------------------------------===//
  2225. TargetLoweringObjectFileGOFF::TargetLoweringObjectFileGOFF() {}
  2226. MCSection *TargetLoweringObjectFileGOFF::getExplicitSectionGlobal(
  2227. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  2228. return SelectSectionForGlobal(GO, Kind, TM);
  2229. }
  2230. MCSection *TargetLoweringObjectFileGOFF::SelectSectionForGlobal(
  2231. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  2232. auto *Symbol = TM.getSymbol(GO);
  2233. if (Kind.isBSS())
  2234. return getContext().getGOFFSection(Symbol->getName(),
  2235. SectionKind::getBSS());
  2236. return getContext().getObjectFileInfo()->getTextSection();
  2237. }