TargetLoweringObjectFileImpl.cpp 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902
  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/CodeGen/MachineModuleInfo.h"
  24. #include "llvm/CodeGen/MachineModuleInfoImpls.h"
  25. #include "llvm/IR/Comdat.h"
  26. #include "llvm/IR/Constants.h"
  27. #include "llvm/IR/DataLayout.h"
  28. #include "llvm/IR/DerivedTypes.h"
  29. #include "llvm/IR/Function.h"
  30. #include "llvm/IR/GlobalAlias.h"
  31. #include "llvm/IR/GlobalObject.h"
  32. #include "llvm/IR/GlobalValue.h"
  33. #include "llvm/IR/GlobalVariable.h"
  34. #include "llvm/IR/Mangler.h"
  35. #include "llvm/IR/Metadata.h"
  36. #include "llvm/IR/Module.h"
  37. #include "llvm/IR/Type.h"
  38. #include "llvm/MC/MCAsmInfo.h"
  39. #include "llvm/MC/MCContext.h"
  40. #include "llvm/MC/MCExpr.h"
  41. #include "llvm/MC/MCSectionCOFF.h"
  42. #include "llvm/MC/MCSectionELF.h"
  43. #include "llvm/MC/MCSectionMachO.h"
  44. #include "llvm/MC/MCSectionWasm.h"
  45. #include "llvm/MC/MCSectionXCOFF.h"
  46. #include "llvm/MC/MCStreamer.h"
  47. #include "llvm/MC/MCSymbol.h"
  48. #include "llvm/MC/MCSymbolELF.h"
  49. #include "llvm/MC/MCValue.h"
  50. #include "llvm/MC/SectionKind.h"
  51. #include "llvm/ProfileData/InstrProf.h"
  52. #include "llvm/Support/Casting.h"
  53. #include "llvm/Support/CodeGen.h"
  54. #include "llvm/Support/Format.h"
  55. #include "llvm/Support/ErrorHandling.h"
  56. #include "llvm/Support/raw_ostream.h"
  57. #include "llvm/Target/TargetMachine.h"
  58. #include <cassert>
  59. #include <string>
  60. using namespace llvm;
  61. using namespace dwarf;
  62. static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
  63. StringRef &Section) {
  64. SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
  65. M.getModuleFlagsMetadata(ModuleFlags);
  66. for (const auto &MFE: ModuleFlags) {
  67. // Ignore flags with 'Require' behaviour.
  68. if (MFE.Behavior == Module::Require)
  69. continue;
  70. StringRef Key = MFE.Key->getString();
  71. if (Key == "Objective-C Image Info Version") {
  72. Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
  73. } else if (Key == "Objective-C Garbage Collection" ||
  74. Key == "Objective-C GC Only" ||
  75. Key == "Objective-C Is Simulated" ||
  76. Key == "Objective-C Class Properties" ||
  77. Key == "Objective-C Image Swift Version") {
  78. Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
  79. } else if (Key == "Objective-C Image Info Section") {
  80. Section = cast<MDString>(MFE.Val)->getString();
  81. }
  82. }
  83. }
  84. //===----------------------------------------------------------------------===//
  85. // ELF
  86. //===----------------------------------------------------------------------===//
  87. void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
  88. const TargetMachine &TgtM) {
  89. TargetLoweringObjectFile::Initialize(Ctx, TgtM);
  90. TM = &TgtM;
  91. CodeModel::Model CM = TgtM.getCodeModel();
  92. switch (TgtM.getTargetTriple().getArch()) {
  93. case Triple::arm:
  94. case Triple::armeb:
  95. case Triple::thumb:
  96. case Triple::thumbeb:
  97. if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM)
  98. break;
  99. // Fallthrough if not using EHABI
  100. LLVM_FALLTHROUGH;
  101. case Triple::ppc:
  102. case Triple::x86:
  103. PersonalityEncoding = isPositionIndependent()
  104. ? dwarf::DW_EH_PE_indirect |
  105. dwarf::DW_EH_PE_pcrel |
  106. dwarf::DW_EH_PE_sdata4
  107. : dwarf::DW_EH_PE_absptr;
  108. LSDAEncoding = isPositionIndependent()
  109. ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4
  110. : dwarf::DW_EH_PE_absptr;
  111. TTypeEncoding = isPositionIndependent()
  112. ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  113. dwarf::DW_EH_PE_sdata4
  114. : dwarf::DW_EH_PE_absptr;
  115. break;
  116. case Triple::x86_64:
  117. if (isPositionIndependent()) {
  118. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  119. ((CM == CodeModel::Small || CM == CodeModel::Medium)
  120. ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
  121. LSDAEncoding = dwarf::DW_EH_PE_pcrel |
  122. (CM == CodeModel::Small
  123. ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
  124. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  125. ((CM == CodeModel::Small || CM == CodeModel::Medium)
  126. ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4);
  127. } else {
  128. PersonalityEncoding =
  129. (CM == CodeModel::Small || CM == CodeModel::Medium)
  130. ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
  131. LSDAEncoding = (CM == CodeModel::Small)
  132. ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
  133. TTypeEncoding = (CM == CodeModel::Small)
  134. ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
  135. }
  136. break;
  137. case Triple::hexagon:
  138. PersonalityEncoding = dwarf::DW_EH_PE_absptr;
  139. LSDAEncoding = dwarf::DW_EH_PE_absptr;
  140. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  141. if (isPositionIndependent()) {
  142. PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
  143. LSDAEncoding |= dwarf::DW_EH_PE_pcrel;
  144. TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
  145. }
  146. break;
  147. case Triple::aarch64:
  148. case Triple::aarch64_be:
  149. case Triple::aarch64_32:
  150. // The small model guarantees static code/data size < 4GB, but not where it
  151. // will be in memory. Most of these could end up >2GB away so even a signed
  152. // pc-relative 32-bit address is insufficient, theoretically.
  153. if (isPositionIndependent()) {
  154. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  155. dwarf::DW_EH_PE_sdata8;
  156. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8;
  157. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  158. dwarf::DW_EH_PE_sdata8;
  159. } else {
  160. PersonalityEncoding = dwarf::DW_EH_PE_absptr;
  161. LSDAEncoding = dwarf::DW_EH_PE_absptr;
  162. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  163. }
  164. break;
  165. case Triple::lanai:
  166. LSDAEncoding = dwarf::DW_EH_PE_absptr;
  167. PersonalityEncoding = dwarf::DW_EH_PE_absptr;
  168. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  169. break;
  170. case Triple::mips:
  171. case Triple::mipsel:
  172. case Triple::mips64:
  173. case Triple::mips64el:
  174. // MIPS uses indirect pointer to refer personality functions and types, so
  175. // that the eh_frame section can be read-only. DW.ref.personality will be
  176. // generated for relocation.
  177. PersonalityEncoding = dwarf::DW_EH_PE_indirect;
  178. // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
  179. // identify N64 from just a triple.
  180. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  181. dwarf::DW_EH_PE_sdata4;
  182. // We don't support PC-relative LSDA references in GAS so we use the default
  183. // DW_EH_PE_absptr for those.
  184. // FreeBSD must be explicit about the data size and using pcrel since it's
  185. // assembler/linker won't do the automatic conversion that the Linux tools
  186. // do.
  187. if (TgtM.getTargetTriple().isOSFreeBSD()) {
  188. PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  189. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  190. }
  191. break;
  192. case Triple::ppc64:
  193. case Triple::ppc64le:
  194. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  195. dwarf::DW_EH_PE_udata8;
  196. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8;
  197. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  198. dwarf::DW_EH_PE_udata8;
  199. break;
  200. case Triple::sparcel:
  201. case Triple::sparc:
  202. if (isPositionIndependent()) {
  203. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  204. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  205. dwarf::DW_EH_PE_sdata4;
  206. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  207. dwarf::DW_EH_PE_sdata4;
  208. } else {
  209. LSDAEncoding = dwarf::DW_EH_PE_absptr;
  210. PersonalityEncoding = dwarf::DW_EH_PE_absptr;
  211. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  212. }
  213. CallSiteEncoding = dwarf::DW_EH_PE_udata4;
  214. break;
  215. case Triple::riscv32:
  216. case Triple::riscv64:
  217. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  218. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  219. dwarf::DW_EH_PE_sdata4;
  220. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  221. dwarf::DW_EH_PE_sdata4;
  222. CallSiteEncoding = dwarf::DW_EH_PE_udata4;
  223. break;
  224. case Triple::sparcv9:
  225. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  226. if (isPositionIndependent()) {
  227. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  228. dwarf::DW_EH_PE_sdata4;
  229. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  230. dwarf::DW_EH_PE_sdata4;
  231. } else {
  232. PersonalityEncoding = dwarf::DW_EH_PE_absptr;
  233. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  234. }
  235. break;
  236. case Triple::systemz:
  237. // All currently-defined code models guarantee that 4-byte PC-relative
  238. // values will be in range.
  239. if (isPositionIndependent()) {
  240. PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  241. dwarf::DW_EH_PE_sdata4;
  242. LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  243. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
  244. dwarf::DW_EH_PE_sdata4;
  245. } else {
  246. PersonalityEncoding = dwarf::DW_EH_PE_absptr;
  247. LSDAEncoding = dwarf::DW_EH_PE_absptr;
  248. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  249. }
  250. break;
  251. default:
  252. break;
  253. }
  254. }
  255. void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer,
  256. Module &M) const {
  257. auto &C = getContext();
  258. if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
  259. auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
  260. ELF::SHF_EXCLUDE);
  261. Streamer.SwitchSection(S);
  262. for (const auto &Operand : LinkerOptions->operands()) {
  263. if (cast<MDNode>(Operand)->getNumOperands() != 2)
  264. report_fatal_error("invalid llvm.linker.options");
  265. for (const auto &Option : cast<MDNode>(Operand)->operands()) {
  266. Streamer.EmitBytes(cast<MDString>(Option)->getString());
  267. Streamer.EmitIntValue(0, 1);
  268. }
  269. }
  270. }
  271. if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) {
  272. auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES,
  273. ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, "");
  274. Streamer.SwitchSection(S);
  275. for (const auto &Operand : DependentLibraries->operands()) {
  276. Streamer.EmitBytes(
  277. cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString());
  278. Streamer.EmitIntValue(0, 1);
  279. }
  280. }
  281. unsigned Version = 0;
  282. unsigned Flags = 0;
  283. StringRef Section;
  284. GetObjCImageInfo(M, Version, Flags, Section);
  285. if (!Section.empty()) {
  286. auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
  287. Streamer.SwitchSection(S);
  288. Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
  289. Streamer.EmitIntValue(Version, 4);
  290. Streamer.EmitIntValue(Flags, 4);
  291. Streamer.AddBlankLine();
  292. }
  293. SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
  294. M.getModuleFlagsMetadata(ModuleFlags);
  295. MDNode *CFGProfile = nullptr;
  296. for (const auto &MFE : ModuleFlags) {
  297. StringRef Key = MFE.Key->getString();
  298. if (Key == "CG Profile") {
  299. CFGProfile = cast<MDNode>(MFE.Val);
  300. break;
  301. }
  302. }
  303. if (!CFGProfile)
  304. return;
  305. auto GetSym = [this](const MDOperand &MDO) -> MCSymbol * {
  306. if (!MDO)
  307. return nullptr;
  308. auto V = cast<ValueAsMetadata>(MDO);
  309. const Function *F = cast<Function>(V->getValue());
  310. return TM->getSymbol(F);
  311. };
  312. for (const auto &Edge : CFGProfile->operands()) {
  313. MDNode *E = cast<MDNode>(Edge);
  314. const MCSymbol *From = GetSym(E->getOperand(0));
  315. const MCSymbol *To = GetSym(E->getOperand(1));
  316. // Skip null functions. This can happen if functions are dead stripped after
  317. // the CGProfile pass has been run.
  318. if (!From || !To)
  319. continue;
  320. uint64_t Count = cast<ConstantAsMetadata>(E->getOperand(2))
  321. ->getValue()
  322. ->getUniqueInteger()
  323. .getZExtValue();
  324. Streamer.emitCGProfileEntry(
  325. MCSymbolRefExpr::create(From, MCSymbolRefExpr::VK_None, C),
  326. MCSymbolRefExpr::create(To, MCSymbolRefExpr::VK_None, C), Count);
  327. }
  328. }
  329. MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
  330. const GlobalValue *GV, const TargetMachine &TM,
  331. MachineModuleInfo *MMI) const {
  332. unsigned Encoding = getPersonalityEncoding();
  333. if ((Encoding & 0x80) == DW_EH_PE_indirect)
  334. return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
  335. TM.getSymbol(GV)->getName());
  336. if ((Encoding & 0x70) == DW_EH_PE_absptr)
  337. return TM.getSymbol(GV);
  338. report_fatal_error("We do not support this DWARF encoding yet!");
  339. }
  340. void TargetLoweringObjectFileELF::emitPersonalityValue(
  341. MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
  342. SmallString<64> NameData("DW.ref.");
  343. NameData += Sym->getName();
  344. MCSymbolELF *Label =
  345. cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
  346. Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
  347. Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
  348. unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
  349. MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
  350. ELF::SHT_PROGBITS, Flags, 0);
  351. unsigned Size = DL.getPointerSize();
  352. Streamer.SwitchSection(Sec);
  353. Streamer.EmitValueToAlignment(DL.getPointerABIAlignment(0));
  354. Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
  355. const MCExpr *E = MCConstantExpr::create(Size, getContext());
  356. Streamer.emitELFSize(Label, E);
  357. Streamer.EmitLabel(Label);
  358. Streamer.EmitSymbolValue(Sym, Size);
  359. }
  360. const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
  361. const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
  362. MachineModuleInfo *MMI, MCStreamer &Streamer) const {
  363. if (Encoding & DW_EH_PE_indirect) {
  364. MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
  365. MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
  366. // Add information about the stub reference to ELFMMI so that the stub
  367. // gets emitted by the asmprinter.
  368. MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
  369. if (!StubSym.getPointer()) {
  370. MCSymbol *Sym = TM.getSymbol(GV);
  371. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  372. }
  373. return TargetLoweringObjectFile::
  374. getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
  375. Encoding & ~DW_EH_PE_indirect, Streamer);
  376. }
  377. return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
  378. MMI, Streamer);
  379. }
  380. static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
  381. // N.B.: The defaults used in here are not the same ones used in MC.
  382. // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
  383. // both gas and MC will produce a section with no flags. Given
  384. // section(".eh_frame") gcc will produce:
  385. //
  386. // .section .eh_frame,"a",@progbits
  387. if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
  388. /*AddSegmentInfo=*/false))
  389. return SectionKind::getMetadata();
  390. if (Name.empty() || Name[0] != '.') return K;
  391. // Default implementation based on some magic section names.
  392. if (Name == ".bss" ||
  393. Name.startswith(".bss.") ||
  394. Name.startswith(".gnu.linkonce.b.") ||
  395. Name.startswith(".llvm.linkonce.b.") ||
  396. Name == ".sbss" ||
  397. Name.startswith(".sbss.") ||
  398. Name.startswith(".gnu.linkonce.sb.") ||
  399. Name.startswith(".llvm.linkonce.sb."))
  400. return SectionKind::getBSS();
  401. if (Name == ".tdata" ||
  402. Name.startswith(".tdata.") ||
  403. Name.startswith(".gnu.linkonce.td.") ||
  404. Name.startswith(".llvm.linkonce.td."))
  405. return SectionKind::getThreadData();
  406. if (Name == ".tbss" ||
  407. Name.startswith(".tbss.") ||
  408. Name.startswith(".gnu.linkonce.tb.") ||
  409. Name.startswith(".llvm.linkonce.tb."))
  410. return SectionKind::getThreadBSS();
  411. return K;
  412. }
  413. static unsigned getELFSectionType(StringRef Name, SectionKind K) {
  414. // Use SHT_NOTE for section whose name starts with ".note" to allow
  415. // emitting ELF notes from C variable declaration.
  416. // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
  417. if (Name.startswith(".note"))
  418. return ELF::SHT_NOTE;
  419. if (Name == ".init_array")
  420. return ELF::SHT_INIT_ARRAY;
  421. if (Name == ".fini_array")
  422. return ELF::SHT_FINI_ARRAY;
  423. if (Name == ".preinit_array")
  424. return ELF::SHT_PREINIT_ARRAY;
  425. if (K.isBSS() || K.isThreadBSS())
  426. return ELF::SHT_NOBITS;
  427. return ELF::SHT_PROGBITS;
  428. }
  429. static unsigned getELFSectionFlags(SectionKind K) {
  430. unsigned Flags = 0;
  431. if (!K.isMetadata())
  432. Flags |= ELF::SHF_ALLOC;
  433. if (K.isText())
  434. Flags |= ELF::SHF_EXECINSTR;
  435. if (K.isExecuteOnly())
  436. Flags |= ELF::SHF_ARM_PURECODE;
  437. if (K.isWriteable())
  438. Flags |= ELF::SHF_WRITE;
  439. if (K.isThreadLocal())
  440. Flags |= ELF::SHF_TLS;
  441. if (K.isMergeableCString() || K.isMergeableConst())
  442. Flags |= ELF::SHF_MERGE;
  443. if (K.isMergeableCString())
  444. Flags |= ELF::SHF_STRINGS;
  445. return Flags;
  446. }
  447. static const Comdat *getELFComdat(const GlobalValue *GV) {
  448. const Comdat *C = GV->getComdat();
  449. if (!C)
  450. return nullptr;
  451. if (C->getSelectionKind() != Comdat::Any)
  452. report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
  453. C->getName() + "' cannot be lowered.");
  454. return C;
  455. }
  456. static const MCSymbolELF *getAssociatedSymbol(const GlobalObject *GO,
  457. const TargetMachine &TM) {
  458. MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
  459. if (!MD)
  460. return nullptr;
  461. const MDOperand &Op = MD->getOperand(0);
  462. if (!Op.get())
  463. return nullptr;
  464. auto *VM = dyn_cast<ValueAsMetadata>(Op);
  465. if (!VM)
  466. report_fatal_error("MD_associated operand is not ValueAsMetadata");
  467. auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue());
  468. return OtherGV ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV)) : nullptr;
  469. }
  470. static unsigned getEntrySizeForKind(SectionKind Kind) {
  471. if (Kind.isMergeable1ByteCString())
  472. return 1;
  473. else if (Kind.isMergeable2ByteCString())
  474. return 2;
  475. else if (Kind.isMergeable4ByteCString())
  476. return 4;
  477. else if (Kind.isMergeableConst4())
  478. return 4;
  479. else if (Kind.isMergeableConst8())
  480. return 8;
  481. else if (Kind.isMergeableConst16())
  482. return 16;
  483. else if (Kind.isMergeableConst32())
  484. return 32;
  485. else {
  486. // We shouldn't have mergeable C strings or mergeable constants that we
  487. // didn't handle above.
  488. assert(!Kind.isMergeableCString() && "unknown string width");
  489. assert(!Kind.isMergeableConst() && "unknown data width");
  490. return 0;
  491. }
  492. }
  493. MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
  494. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  495. StringRef SectionName = GO->getSection();
  496. // Check if '#pragma clang section' name is applicable.
  497. // Note that pragma directive overrides -ffunction-section, -fdata-section
  498. // and so section name is exactly as user specified and not uniqued.
  499. const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
  500. if (GV && GV->hasImplicitSection()) {
  501. auto Attrs = GV->getAttributes();
  502. if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
  503. SectionName = Attrs.getAttribute("bss-section").getValueAsString();
  504. } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
  505. SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
  506. } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
  507. SectionName = Attrs.getAttribute("data-section").getValueAsString();
  508. }
  509. }
  510. const Function *F = dyn_cast<Function>(GO);
  511. if (F && F->hasFnAttribute("implicit-section-name")) {
  512. SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
  513. }
  514. // Infer section flags from the section name if we can.
  515. Kind = getELFKindForNamedSection(SectionName, Kind);
  516. StringRef Group = "";
  517. unsigned Flags = getELFSectionFlags(Kind);
  518. if (const Comdat *C = getELFComdat(GO)) {
  519. Group = C->getName();
  520. Flags |= ELF::SHF_GROUP;
  521. }
  522. // A section can have at most one associated section. Put each global with
  523. // MD_associated in a unique section.
  524. unsigned UniqueID = MCContext::GenericSectionID;
  525. const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
  526. if (AssociatedSymbol) {
  527. UniqueID = NextUniqueID++;
  528. Flags |= ELF::SHF_LINK_ORDER;
  529. }
  530. MCSectionELF *Section = getContext().getELFSection(
  531. SectionName, getELFSectionType(SectionName, Kind), Flags,
  532. getEntrySizeForKind(Kind), Group, UniqueID, AssociatedSymbol);
  533. // Make sure that we did not get some other section with incompatible sh_link.
  534. // This should not be possible due to UniqueID code above.
  535. assert(Section->getAssociatedSymbol() == AssociatedSymbol &&
  536. "Associated symbol mismatch between sections");
  537. return Section;
  538. }
  539. /// Return the section prefix name used by options FunctionsSections and
  540. /// DataSections.
  541. static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
  542. if (Kind.isText())
  543. return ".text";
  544. if (Kind.isReadOnly())
  545. return ".rodata";
  546. if (Kind.isBSS())
  547. return ".bss";
  548. if (Kind.isThreadData())
  549. return ".tdata";
  550. if (Kind.isThreadBSS())
  551. return ".tbss";
  552. if (Kind.isData())
  553. return ".data";
  554. assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
  555. return ".data.rel.ro";
  556. }
  557. static MCSectionELF *selectELFSectionForGlobal(
  558. MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
  559. const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
  560. unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
  561. StringRef Group = "";
  562. if (const Comdat *C = getELFComdat(GO)) {
  563. Flags |= ELF::SHF_GROUP;
  564. Group = C->getName();
  565. }
  566. // Get the section entry size based on the kind.
  567. unsigned EntrySize = getEntrySizeForKind(Kind);
  568. SmallString<128> Name;
  569. if (Kind.isMergeableCString()) {
  570. // We also need alignment here.
  571. // FIXME: this is getting the alignment of the character, not the
  572. // alignment of the global!
  573. unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment(
  574. cast<GlobalVariable>(GO));
  575. std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
  576. Name = SizeSpec + utostr(Align);
  577. } else if (Kind.isMergeableConst()) {
  578. Name = ".rodata.cst";
  579. Name += utostr(EntrySize);
  580. } else {
  581. Name = getSectionPrefixForGlobal(Kind);
  582. }
  583. if (const auto *F = dyn_cast<Function>(GO)) {
  584. const auto &OptionalPrefix = F->getSectionPrefix();
  585. if (OptionalPrefix)
  586. Name += *OptionalPrefix;
  587. }
  588. unsigned UniqueID = MCContext::GenericSectionID;
  589. if (EmitUniqueSection) {
  590. if (TM.getUniqueSectionNames()) {
  591. Name.push_back('.');
  592. TM.getNameWithPrefix(Name, GO, Mang, true /*MayAlwaysUsePrivate*/);
  593. } else {
  594. UniqueID = *NextUniqueID;
  595. (*NextUniqueID)++;
  596. }
  597. }
  598. // Use 0 as the unique ID for execute-only text.
  599. if (Kind.isExecuteOnly())
  600. UniqueID = 0;
  601. return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
  602. EntrySize, Group, UniqueID, AssociatedSymbol);
  603. }
  604. MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
  605. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  606. unsigned Flags = getELFSectionFlags(Kind);
  607. // If we have -ffunction-section or -fdata-section then we should emit the
  608. // global value to a uniqued section specifically for it.
  609. bool EmitUniqueSection = false;
  610. if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
  611. if (Kind.isText())
  612. EmitUniqueSection = TM.getFunctionSections();
  613. else
  614. EmitUniqueSection = TM.getDataSections();
  615. }
  616. EmitUniqueSection |= GO->hasComdat();
  617. const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
  618. if (AssociatedSymbol) {
  619. EmitUniqueSection = true;
  620. Flags |= ELF::SHF_LINK_ORDER;
  621. }
  622. MCSectionELF *Section = selectELFSectionForGlobal(
  623. getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
  624. &NextUniqueID, AssociatedSymbol);
  625. assert(Section->getAssociatedSymbol() == AssociatedSymbol);
  626. return Section;
  627. }
  628. MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
  629. const Function &F, const TargetMachine &TM) const {
  630. // If the function can be removed, produce a unique section so that
  631. // the table doesn't prevent the removal.
  632. const Comdat *C = F.getComdat();
  633. bool EmitUniqueSection = TM.getFunctionSections() || C;
  634. if (!EmitUniqueSection)
  635. return ReadOnlySection;
  636. return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
  637. getMangler(), TM, EmitUniqueSection,
  638. ELF::SHF_ALLOC, &NextUniqueID,
  639. /* AssociatedSymbol */ nullptr);
  640. }
  641. bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
  642. bool UsesLabelDifference, const Function &F) const {
  643. // We can always create relative relocations, so use another section
  644. // that can be marked non-executable.
  645. return false;
  646. }
  647. /// Given a mergeable constant with the specified size and relocation
  648. /// information, return a section that it should be placed in.
  649. MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
  650. const DataLayout &DL, SectionKind Kind, const Constant *C,
  651. unsigned &Align) const {
  652. if (Kind.isMergeableConst4() && MergeableConst4Section)
  653. return MergeableConst4Section;
  654. if (Kind.isMergeableConst8() && MergeableConst8Section)
  655. return MergeableConst8Section;
  656. if (Kind.isMergeableConst16() && MergeableConst16Section)
  657. return MergeableConst16Section;
  658. if (Kind.isMergeableConst32() && MergeableConst32Section)
  659. return MergeableConst32Section;
  660. if (Kind.isReadOnly())
  661. return ReadOnlySection;
  662. assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
  663. return DataRelROSection;
  664. }
  665. static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
  666. bool IsCtor, unsigned Priority,
  667. const MCSymbol *KeySym) {
  668. std::string Name;
  669. unsigned Type;
  670. unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
  671. StringRef COMDAT = KeySym ? KeySym->getName() : "";
  672. if (KeySym)
  673. Flags |= ELF::SHF_GROUP;
  674. if (UseInitArray) {
  675. if (IsCtor) {
  676. Type = ELF::SHT_INIT_ARRAY;
  677. Name = ".init_array";
  678. } else {
  679. Type = ELF::SHT_FINI_ARRAY;
  680. Name = ".fini_array";
  681. }
  682. if (Priority != 65535) {
  683. Name += '.';
  684. Name += utostr(Priority);
  685. }
  686. } else {
  687. // The default scheme is .ctor / .dtor, so we have to invert the priority
  688. // numbering.
  689. if (IsCtor)
  690. Name = ".ctors";
  691. else
  692. Name = ".dtors";
  693. if (Priority != 65535)
  694. raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
  695. Type = ELF::SHT_PROGBITS;
  696. }
  697. return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
  698. }
  699. MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
  700. unsigned Priority, const MCSymbol *KeySym) const {
  701. return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
  702. KeySym);
  703. }
  704. MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
  705. unsigned Priority, const MCSymbol *KeySym) const {
  706. return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
  707. KeySym);
  708. }
  709. const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
  710. const GlobalValue *LHS, const GlobalValue *RHS,
  711. const TargetMachine &TM) const {
  712. // We may only use a PLT-relative relocation to refer to unnamed_addr
  713. // functions.
  714. if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
  715. return nullptr;
  716. // Basic sanity checks.
  717. if (LHS->getType()->getPointerAddressSpace() != 0 ||
  718. RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
  719. RHS->isThreadLocal())
  720. return nullptr;
  721. return MCBinaryExpr::createSub(
  722. MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
  723. getContext()),
  724. MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
  725. }
  726. MCSection *TargetLoweringObjectFileELF::getSectionForCommandLines() const {
  727. // Use ".GCC.command.line" since this feature is to support clang's
  728. // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the
  729. // same name.
  730. return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS,
  731. ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, "");
  732. }
  733. void
  734. TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
  735. UseInitArray = UseInitArray_;
  736. MCContext &Ctx = getContext();
  737. if (!UseInitArray) {
  738. StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
  739. ELF::SHF_ALLOC | ELF::SHF_WRITE);
  740. StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
  741. ELF::SHF_ALLOC | ELF::SHF_WRITE);
  742. return;
  743. }
  744. StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
  745. ELF::SHF_WRITE | ELF::SHF_ALLOC);
  746. StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
  747. ELF::SHF_WRITE | ELF::SHF_ALLOC);
  748. }
  749. //===----------------------------------------------------------------------===//
  750. // MachO
  751. //===----------------------------------------------------------------------===//
  752. TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
  753. : TargetLoweringObjectFile() {
  754. SupportIndirectSymViaGOTPCRel = true;
  755. }
  756. void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
  757. const TargetMachine &TM) {
  758. TargetLoweringObjectFile::Initialize(Ctx, TM);
  759. if (TM.getRelocationModel() == Reloc::Static) {
  760. StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
  761. SectionKind::getData());
  762. StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
  763. SectionKind::getData());
  764. } else {
  765. StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
  766. MachO::S_MOD_INIT_FUNC_POINTERS,
  767. SectionKind::getData());
  768. StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
  769. MachO::S_MOD_TERM_FUNC_POINTERS,
  770. SectionKind::getData());
  771. }
  772. PersonalityEncoding =
  773. dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  774. LSDAEncoding = dwarf::DW_EH_PE_pcrel;
  775. TTypeEncoding =
  776. dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
  777. }
  778. void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer,
  779. Module &M) const {
  780. // Emit the linker options if present.
  781. if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
  782. for (const auto &Option : LinkerOptions->operands()) {
  783. SmallVector<std::string, 4> StrOptions;
  784. for (const auto &Piece : cast<MDNode>(Option)->operands())
  785. StrOptions.push_back(cast<MDString>(Piece)->getString());
  786. Streamer.EmitLinkerOptions(StrOptions);
  787. }
  788. }
  789. unsigned VersionVal = 0;
  790. unsigned ImageInfoFlags = 0;
  791. StringRef SectionVal;
  792. GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
  793. // The section is mandatory. If we don't have it, then we don't have GC info.
  794. if (SectionVal.empty())
  795. return;
  796. StringRef Segment, Section;
  797. unsigned TAA = 0, StubSize = 0;
  798. bool TAAParsed;
  799. std::string ErrorCode =
  800. MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
  801. TAA, TAAParsed, StubSize);
  802. if (!ErrorCode.empty())
  803. // If invalid, report the error with report_fatal_error.
  804. report_fatal_error("Invalid section specifier '" + Section + "': " +
  805. ErrorCode + ".");
  806. // Get the section.
  807. MCSectionMachO *S = getContext().getMachOSection(
  808. Segment, Section, TAA, StubSize, SectionKind::getData());
  809. Streamer.SwitchSection(S);
  810. Streamer.EmitLabel(getContext().
  811. getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
  812. Streamer.EmitIntValue(VersionVal, 4);
  813. Streamer.EmitIntValue(ImageInfoFlags, 4);
  814. Streamer.AddBlankLine();
  815. }
  816. static void checkMachOComdat(const GlobalValue *GV) {
  817. const Comdat *C = GV->getComdat();
  818. if (!C)
  819. return;
  820. report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
  821. "' cannot be lowered.");
  822. }
  823. MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
  824. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  825. // Parse the section specifier and create it if valid.
  826. StringRef Segment, Section;
  827. unsigned TAA = 0, StubSize = 0;
  828. bool TAAParsed;
  829. checkMachOComdat(GO);
  830. std::string ErrorCode =
  831. MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
  832. TAA, TAAParsed, StubSize);
  833. if (!ErrorCode.empty()) {
  834. // If invalid, report the error with report_fatal_error.
  835. report_fatal_error("Global variable '" + GO->getName() +
  836. "' has an invalid section specifier '" +
  837. GO->getSection() + "': " + ErrorCode + ".");
  838. }
  839. // Get the section.
  840. MCSectionMachO *S =
  841. getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
  842. // If TAA wasn't set by ParseSectionSpecifier() above,
  843. // use the value returned by getMachOSection() as a default.
  844. if (!TAAParsed)
  845. TAA = S->getTypeAndAttributes();
  846. // Okay, now that we got the section, verify that the TAA & StubSize agree.
  847. // If the user declared multiple globals with different section flags, we need
  848. // to reject it here.
  849. if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
  850. // If invalid, report the error with report_fatal_error.
  851. report_fatal_error("Global variable '" + GO->getName() +
  852. "' section type or attributes does not match previous"
  853. " section specifier");
  854. }
  855. return S;
  856. }
  857. MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
  858. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  859. checkMachOComdat(GO);
  860. // Handle thread local data.
  861. if (Kind.isThreadBSS()) return TLSBSSSection;
  862. if (Kind.isThreadData()) return TLSDataSection;
  863. if (Kind.isText())
  864. return GO->isWeakForLinker() ? TextCoalSection : TextSection;
  865. // If this is weak/linkonce, put this in a coalescable section, either in text
  866. // or data depending on if it is writable.
  867. if (GO->isWeakForLinker()) {
  868. if (Kind.isReadOnly())
  869. return ConstTextCoalSection;
  870. if (Kind.isReadOnlyWithRel())
  871. return ConstDataCoalSection;
  872. return DataCoalSection;
  873. }
  874. // FIXME: Alignment check should be handled by section classifier.
  875. if (Kind.isMergeable1ByteCString() &&
  876. GO->getParent()->getDataLayout().getPreferredAlignment(
  877. cast<GlobalVariable>(GO)) < 32)
  878. return CStringSection;
  879. // Do not put 16-bit arrays in the UString section if they have an
  880. // externally visible label, this runs into issues with certain linker
  881. // versions.
  882. if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
  883. GO->getParent()->getDataLayout().getPreferredAlignment(
  884. cast<GlobalVariable>(GO)) < 32)
  885. return UStringSection;
  886. // With MachO only variables whose corresponding symbol starts with 'l' or
  887. // 'L' can be merged, so we only try merging GVs with private linkage.
  888. if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
  889. if (Kind.isMergeableConst4())
  890. return FourByteConstantSection;
  891. if (Kind.isMergeableConst8())
  892. return EightByteConstantSection;
  893. if (Kind.isMergeableConst16())
  894. return SixteenByteConstantSection;
  895. }
  896. // Otherwise, if it is readonly, but not something we can specially optimize,
  897. // just drop it in .const.
  898. if (Kind.isReadOnly())
  899. return ReadOnlySection;
  900. // If this is marked const, put it into a const section. But if the dynamic
  901. // linker needs to write to it, put it in the data segment.
  902. if (Kind.isReadOnlyWithRel())
  903. return ConstDataSection;
  904. // Put zero initialized globals with strong external linkage in the
  905. // DATA, __common section with the .zerofill directive.
  906. if (Kind.isBSSExtern())
  907. return DataCommonSection;
  908. // Put zero initialized globals with local linkage in __DATA,__bss directive
  909. // with the .zerofill directive (aka .lcomm).
  910. if (Kind.isBSSLocal())
  911. return DataBSSSection;
  912. // Otherwise, just drop the variable in the normal data section.
  913. return DataSection;
  914. }
  915. MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
  916. const DataLayout &DL, SectionKind Kind, const Constant *C,
  917. unsigned &Align) const {
  918. // If this constant requires a relocation, we have to put it in the data
  919. // segment, not in the text segment.
  920. if (Kind.isData() || Kind.isReadOnlyWithRel())
  921. return ConstDataSection;
  922. if (Kind.isMergeableConst4())
  923. return FourByteConstantSection;
  924. if (Kind.isMergeableConst8())
  925. return EightByteConstantSection;
  926. if (Kind.isMergeableConst16())
  927. return SixteenByteConstantSection;
  928. return ReadOnlySection; // .const
  929. }
  930. const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
  931. const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
  932. MachineModuleInfo *MMI, MCStreamer &Streamer) const {
  933. // The mach-o version of this method defaults to returning a stub reference.
  934. if (Encoding & DW_EH_PE_indirect) {
  935. MachineModuleInfoMachO &MachOMMI =
  936. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  937. MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
  938. // Add information about the stub reference to MachOMMI so that the stub
  939. // gets emitted by the asmprinter.
  940. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
  941. if (!StubSym.getPointer()) {
  942. MCSymbol *Sym = TM.getSymbol(GV);
  943. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  944. }
  945. return TargetLoweringObjectFile::
  946. getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
  947. Encoding & ~DW_EH_PE_indirect, Streamer);
  948. }
  949. return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
  950. MMI, Streamer);
  951. }
  952. MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
  953. const GlobalValue *GV, const TargetMachine &TM,
  954. MachineModuleInfo *MMI) const {
  955. // The mach-o version of this method defaults to returning a stub reference.
  956. MachineModuleInfoMachO &MachOMMI =
  957. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  958. MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
  959. // Add information about the stub reference to MachOMMI so that the stub
  960. // gets emitted by the asmprinter.
  961. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
  962. if (!StubSym.getPointer()) {
  963. MCSymbol *Sym = TM.getSymbol(GV);
  964. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  965. }
  966. return SSym;
  967. }
  968. const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
  969. const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV,
  970. int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const {
  971. // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
  972. // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
  973. // through a non_lazy_ptr stub instead. One advantage is that it allows the
  974. // computation of deltas to final external symbols. Example:
  975. //
  976. // _extgotequiv:
  977. // .long _extfoo
  978. //
  979. // _delta:
  980. // .long _extgotequiv-_delta
  981. //
  982. // is transformed to:
  983. //
  984. // _delta:
  985. // .long L_extfoo$non_lazy_ptr-(_delta+0)
  986. //
  987. // .section __IMPORT,__pointers,non_lazy_symbol_pointers
  988. // L_extfoo$non_lazy_ptr:
  989. // .indirect_symbol _extfoo
  990. // .long 0
  991. //
  992. // The indirect symbol table (and sections of non_lazy_symbol_pointers type)
  993. // may point to both local (same translation unit) and global (other
  994. // translation units) symbols. Example:
  995. //
  996. // .section __DATA,__pointers,non_lazy_symbol_pointers
  997. // L1:
  998. // .indirect_symbol _myGlobal
  999. // .long 0
  1000. // L2:
  1001. // .indirect_symbol _myLocal
  1002. // .long _myLocal
  1003. //
  1004. // If the symbol is local, instead of the symbol's index, the assembler
  1005. // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table.
  1006. // Then the linker will notice the constant in the table and will look at the
  1007. // content of the symbol.
  1008. MachineModuleInfoMachO &MachOMMI =
  1009. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  1010. MCContext &Ctx = getContext();
  1011. // The offset must consider the original displacement from the base symbol
  1012. // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
  1013. Offset = -MV.getConstant();
  1014. const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
  1015. // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
  1016. // non_lazy_ptr stubs.
  1017. SmallString<128> Name;
  1018. StringRef Suffix = "$non_lazy_ptr";
  1019. Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
  1020. Name += Sym->getName();
  1021. Name += Suffix;
  1022. MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
  1023. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
  1024. if (!StubSym.getPointer())
  1025. StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym),
  1026. !GV->hasLocalLinkage());
  1027. const MCExpr *BSymExpr =
  1028. MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
  1029. const MCExpr *LHS =
  1030. MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
  1031. if (!Offset)
  1032. return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
  1033. const MCExpr *RHS =
  1034. MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
  1035. return MCBinaryExpr::createSub(LHS, RHS, Ctx);
  1036. }
  1037. static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
  1038. const MCSection &Section) {
  1039. if (!AsmInfo.isSectionAtomizableBySymbols(Section))
  1040. return true;
  1041. // If it is not dead stripped, it is safe to use private labels.
  1042. const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
  1043. if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
  1044. return true;
  1045. return false;
  1046. }
  1047. void TargetLoweringObjectFileMachO::getNameWithPrefix(
  1048. SmallVectorImpl<char> &OutName, const GlobalValue *GV,
  1049. const TargetMachine &TM) const {
  1050. bool CannotUsePrivateLabel = true;
  1051. if (auto *GO = GV->getBaseObject()) {
  1052. SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
  1053. const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
  1054. CannotUsePrivateLabel =
  1055. !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
  1056. }
  1057. getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
  1058. }
  1059. //===----------------------------------------------------------------------===//
  1060. // COFF
  1061. //===----------------------------------------------------------------------===//
  1062. static unsigned
  1063. getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
  1064. unsigned Flags = 0;
  1065. bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
  1066. if (K.isMetadata())
  1067. Flags |=
  1068. COFF::IMAGE_SCN_MEM_DISCARDABLE;
  1069. else if (K.isText())
  1070. Flags |=
  1071. COFF::IMAGE_SCN_MEM_EXECUTE |
  1072. COFF::IMAGE_SCN_MEM_READ |
  1073. COFF::IMAGE_SCN_CNT_CODE |
  1074. (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
  1075. else if (K.isBSS())
  1076. Flags |=
  1077. COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
  1078. COFF::IMAGE_SCN_MEM_READ |
  1079. COFF::IMAGE_SCN_MEM_WRITE;
  1080. else if (K.isThreadLocal())
  1081. Flags |=
  1082. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1083. COFF::IMAGE_SCN_MEM_READ |
  1084. COFF::IMAGE_SCN_MEM_WRITE;
  1085. else if (K.isReadOnly() || K.isReadOnlyWithRel())
  1086. Flags |=
  1087. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1088. COFF::IMAGE_SCN_MEM_READ;
  1089. else if (K.isWriteable())
  1090. Flags |=
  1091. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1092. COFF::IMAGE_SCN_MEM_READ |
  1093. COFF::IMAGE_SCN_MEM_WRITE;
  1094. return Flags;
  1095. }
  1096. static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
  1097. const Comdat *C = GV->getComdat();
  1098. assert(C && "expected GV to have a Comdat!");
  1099. StringRef ComdatGVName = C->getName();
  1100. const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
  1101. if (!ComdatGV)
  1102. report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
  1103. "' does not exist.");
  1104. if (ComdatGV->getComdat() != C)
  1105. report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
  1106. "' is not a key for its COMDAT.");
  1107. return ComdatGV;
  1108. }
  1109. static int getSelectionForCOFF(const GlobalValue *GV) {
  1110. if (const Comdat *C = GV->getComdat()) {
  1111. const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
  1112. if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
  1113. ComdatKey = GA->getBaseObject();
  1114. if (ComdatKey == GV) {
  1115. switch (C->getSelectionKind()) {
  1116. case Comdat::Any:
  1117. return COFF::IMAGE_COMDAT_SELECT_ANY;
  1118. case Comdat::ExactMatch:
  1119. return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
  1120. case Comdat::Largest:
  1121. return COFF::IMAGE_COMDAT_SELECT_LARGEST;
  1122. case Comdat::NoDuplicates:
  1123. return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
  1124. case Comdat::SameSize:
  1125. return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
  1126. }
  1127. } else {
  1128. return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
  1129. }
  1130. }
  1131. return 0;
  1132. }
  1133. MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
  1134. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1135. int Selection = 0;
  1136. unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
  1137. StringRef Name = GO->getSection();
  1138. StringRef COMDATSymName = "";
  1139. if (GO->hasComdat()) {
  1140. Selection = getSelectionForCOFF(GO);
  1141. const GlobalValue *ComdatGV;
  1142. if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
  1143. ComdatGV = getComdatGVForCOFF(GO);
  1144. else
  1145. ComdatGV = GO;
  1146. if (!ComdatGV->hasPrivateLinkage()) {
  1147. MCSymbol *Sym = TM.getSymbol(ComdatGV);
  1148. COMDATSymName = Sym->getName();
  1149. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  1150. } else {
  1151. Selection = 0;
  1152. }
  1153. }
  1154. return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
  1155. Selection);
  1156. }
  1157. static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
  1158. if (Kind.isText())
  1159. return ".text";
  1160. if (Kind.isBSS())
  1161. return ".bss";
  1162. if (Kind.isThreadLocal())
  1163. return ".tls$";
  1164. if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
  1165. return ".rdata";
  1166. return ".data";
  1167. }
  1168. MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
  1169. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1170. // If we have -ffunction-sections then we should emit the global value to a
  1171. // uniqued section specifically for it.
  1172. bool EmitUniquedSection;
  1173. if (Kind.isText())
  1174. EmitUniquedSection = TM.getFunctionSections();
  1175. else
  1176. EmitUniquedSection = TM.getDataSections();
  1177. if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
  1178. SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind);
  1179. unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
  1180. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  1181. int Selection = getSelectionForCOFF(GO);
  1182. if (!Selection)
  1183. Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
  1184. const GlobalValue *ComdatGV;
  1185. if (GO->hasComdat())
  1186. ComdatGV = getComdatGVForCOFF(GO);
  1187. else
  1188. ComdatGV = GO;
  1189. unsigned UniqueID = MCContext::GenericSectionID;
  1190. if (EmitUniquedSection)
  1191. UniqueID = NextUniqueID++;
  1192. if (!ComdatGV->hasPrivateLinkage()) {
  1193. MCSymbol *Sym = TM.getSymbol(ComdatGV);
  1194. StringRef COMDATSymName = Sym->getName();
  1195. // Append "$symbol" to the section name *before* IR-level mangling is
  1196. // applied when targetting mingw. This is what GCC does, and the ld.bfd
  1197. // COFF linker will not properly handle comdats otherwise.
  1198. if (getTargetTriple().isWindowsGNUEnvironment())
  1199. raw_svector_ostream(Name) << '$' << ComdatGV->getName();
  1200. return getContext().getCOFFSection(Name, Characteristics, Kind,
  1201. COMDATSymName, Selection, UniqueID);
  1202. } else {
  1203. SmallString<256> TmpData;
  1204. getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
  1205. return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
  1206. Selection, UniqueID);
  1207. }
  1208. }
  1209. if (Kind.isText())
  1210. return TextSection;
  1211. if (Kind.isThreadLocal())
  1212. return TLSDataSection;
  1213. if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
  1214. return ReadOnlySection;
  1215. // Note: we claim that common symbols are put in BSSSection, but they are
  1216. // really emitted with the magic .comm directive, which creates a symbol table
  1217. // entry but not a section.
  1218. if (Kind.isBSS() || Kind.isCommon())
  1219. return BSSSection;
  1220. return DataSection;
  1221. }
  1222. void TargetLoweringObjectFileCOFF::getNameWithPrefix(
  1223. SmallVectorImpl<char> &OutName, const GlobalValue *GV,
  1224. const TargetMachine &TM) const {
  1225. bool CannotUsePrivateLabel = false;
  1226. if (GV->hasPrivateLinkage() &&
  1227. ((isa<Function>(GV) && TM.getFunctionSections()) ||
  1228. (isa<GlobalVariable>(GV) && TM.getDataSections())))
  1229. CannotUsePrivateLabel = true;
  1230. getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
  1231. }
  1232. MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
  1233. const Function &F, const TargetMachine &TM) const {
  1234. // If the function can be removed, produce a unique section so that
  1235. // the table doesn't prevent the removal.
  1236. const Comdat *C = F.getComdat();
  1237. bool EmitUniqueSection = TM.getFunctionSections() || C;
  1238. if (!EmitUniqueSection)
  1239. return ReadOnlySection;
  1240. // FIXME: we should produce a symbol for F instead.
  1241. if (F.hasPrivateLinkage())
  1242. return ReadOnlySection;
  1243. MCSymbol *Sym = TM.getSymbol(&F);
  1244. StringRef COMDATSymName = Sym->getName();
  1245. SectionKind Kind = SectionKind::getReadOnly();
  1246. StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind);
  1247. unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
  1248. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  1249. unsigned UniqueID = NextUniqueID++;
  1250. return getContext().getCOFFSection(
  1251. SecName, Characteristics, Kind, COMDATSymName,
  1252. COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
  1253. }
  1254. void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer,
  1255. Module &M) const {
  1256. if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
  1257. // Emit the linker options to the linker .drectve section. According to the
  1258. // spec, this section is a space-separated string containing flags for
  1259. // linker.
  1260. MCSection *Sec = getDrectveSection();
  1261. Streamer.SwitchSection(Sec);
  1262. for (const auto &Option : LinkerOptions->operands()) {
  1263. for (const auto &Piece : cast<MDNode>(Option)->operands()) {
  1264. // Lead with a space for consistency with our dllexport implementation.
  1265. std::string Directive(" ");
  1266. Directive.append(cast<MDString>(Piece)->getString());
  1267. Streamer.EmitBytes(Directive);
  1268. }
  1269. }
  1270. }
  1271. unsigned Version = 0;
  1272. unsigned Flags = 0;
  1273. StringRef Section;
  1274. GetObjCImageInfo(M, Version, Flags, Section);
  1275. if (Section.empty())
  1276. return;
  1277. auto &C = getContext();
  1278. auto *S = C.getCOFFSection(
  1279. Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
  1280. SectionKind::getReadOnly());
  1281. Streamer.SwitchSection(S);
  1282. Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
  1283. Streamer.EmitIntValue(Version, 4);
  1284. Streamer.EmitIntValue(Flags, 4);
  1285. Streamer.AddBlankLine();
  1286. }
  1287. void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
  1288. const TargetMachine &TM) {
  1289. TargetLoweringObjectFile::Initialize(Ctx, TM);
  1290. const Triple &T = TM.getTargetTriple();
  1291. if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
  1292. StaticCtorSection =
  1293. Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1294. COFF::IMAGE_SCN_MEM_READ,
  1295. SectionKind::getReadOnly());
  1296. StaticDtorSection =
  1297. Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1298. COFF::IMAGE_SCN_MEM_READ,
  1299. SectionKind::getReadOnly());
  1300. } else {
  1301. StaticCtorSection = Ctx.getCOFFSection(
  1302. ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1303. COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
  1304. SectionKind::getData());
  1305. StaticDtorSection = Ctx.getCOFFSection(
  1306. ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1307. COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
  1308. SectionKind::getData());
  1309. }
  1310. }
  1311. static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx,
  1312. const Triple &T, bool IsCtor,
  1313. unsigned Priority,
  1314. const MCSymbol *KeySym,
  1315. MCSectionCOFF *Default) {
  1316. if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
  1317. // If the priority is the default, use .CRT$XCU, possibly associative.
  1318. if (Priority == 65535)
  1319. return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
  1320. // Otherwise, we need to compute a new section name. Low priorities should
  1321. // run earlier. The linker will sort sections ASCII-betically, and we need a
  1322. // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
  1323. // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
  1324. // low priorities need to sort before 'L', since the CRT uses that
  1325. // internally, so we use ".CRT$XCA00001" for them.
  1326. SmallString<24> Name;
  1327. raw_svector_ostream OS(Name);
  1328. OS << ".CRT$X" << (IsCtor ? "C" : "T") <<
  1329. (Priority < 200 ? 'A' : 'T') << format("%05u", Priority);
  1330. MCSectionCOFF *Sec = Ctx.getCOFFSection(
  1331. Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
  1332. SectionKind::getReadOnly());
  1333. return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0);
  1334. }
  1335. std::string Name = IsCtor ? ".ctors" : ".dtors";
  1336. if (Priority != 65535)
  1337. raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
  1338. return Ctx.getAssociativeCOFFSection(
  1339. Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1340. COFF::IMAGE_SCN_MEM_READ |
  1341. COFF::IMAGE_SCN_MEM_WRITE,
  1342. SectionKind::getData()),
  1343. KeySym, 0);
  1344. }
  1345. MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
  1346. unsigned Priority, const MCSymbol *KeySym) const {
  1347. return getCOFFStaticStructorSection(getContext(), getTargetTriple(), true,
  1348. Priority, KeySym,
  1349. cast<MCSectionCOFF>(StaticCtorSection));
  1350. }
  1351. MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
  1352. unsigned Priority, const MCSymbol *KeySym) const {
  1353. return getCOFFStaticStructorSection(getContext(), getTargetTriple(), false,
  1354. Priority, KeySym,
  1355. cast<MCSectionCOFF>(StaticDtorSection));
  1356. }
  1357. void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
  1358. raw_ostream &OS, const GlobalValue *GV) const {
  1359. emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler());
  1360. }
  1361. void TargetLoweringObjectFileCOFF::emitLinkerFlagsForUsed(
  1362. raw_ostream &OS, const GlobalValue *GV) const {
  1363. emitLinkerFlagsForUsedCOFF(OS, GV, getTargetTriple(), getMangler());
  1364. }
  1365. const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference(
  1366. const GlobalValue *LHS, const GlobalValue *RHS,
  1367. const TargetMachine &TM) const {
  1368. const Triple &T = TM.getTargetTriple();
  1369. if (T.isOSCygMing())
  1370. return nullptr;
  1371. // Our symbols should exist in address space zero, cowardly no-op if
  1372. // otherwise.
  1373. if (LHS->getType()->getPointerAddressSpace() != 0 ||
  1374. RHS->getType()->getPointerAddressSpace() != 0)
  1375. return nullptr;
  1376. // Both ptrtoint instructions must wrap global objects:
  1377. // - Only global variables are eligible for image relative relocations.
  1378. // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
  1379. // We expect __ImageBase to be a global variable without a section, externally
  1380. // defined.
  1381. //
  1382. // It should look something like this: @__ImageBase = external constant i8
  1383. if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
  1384. LHS->isThreadLocal() || RHS->isThreadLocal() ||
  1385. RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
  1386. cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
  1387. return nullptr;
  1388. return MCSymbolRefExpr::create(TM.getSymbol(LHS),
  1389. MCSymbolRefExpr::VK_COFF_IMGREL32,
  1390. getContext());
  1391. }
  1392. static std::string APIntToHexString(const APInt &AI) {
  1393. unsigned Width = (AI.getBitWidth() / 8) * 2;
  1394. std::string HexString = AI.toString(16, /*Signed=*/false);
  1395. transform(HexString.begin(), HexString.end(), HexString.begin(), tolower);
  1396. unsigned Size = HexString.size();
  1397. assert(Width >= Size && "hex string is too large!");
  1398. HexString.insert(HexString.begin(), Width - Size, '0');
  1399. return HexString;
  1400. }
  1401. static std::string scalarConstantToHexString(const Constant *C) {
  1402. Type *Ty = C->getType();
  1403. if (isa<UndefValue>(C)) {
  1404. return APIntToHexString(APInt::getNullValue(Ty->getPrimitiveSizeInBits()));
  1405. } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
  1406. return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
  1407. } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
  1408. return APIntToHexString(CI->getValue());
  1409. } else {
  1410. unsigned NumElements;
  1411. if (isa<VectorType>(Ty))
  1412. NumElements = Ty->getVectorNumElements();
  1413. else
  1414. NumElements = Ty->getArrayNumElements();
  1415. std::string HexString;
  1416. for (int I = NumElements - 1, E = -1; I != E; --I)
  1417. HexString += scalarConstantToHexString(C->getAggregateElement(I));
  1418. return HexString;
  1419. }
  1420. }
  1421. MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant(
  1422. const DataLayout &DL, SectionKind Kind, const Constant *C,
  1423. unsigned &Align) const {
  1424. if (Kind.isMergeableConst() && C &&
  1425. getContext().getAsmInfo()->hasCOFFComdatConstants()) {
  1426. // This creates comdat sections with the given symbol name, but unless
  1427. // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
  1428. // will be created with a null storage class, which makes GNU binutils
  1429. // error out.
  1430. const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  1431. COFF::IMAGE_SCN_MEM_READ |
  1432. COFF::IMAGE_SCN_LNK_COMDAT;
  1433. std::string COMDATSymName;
  1434. if (Kind.isMergeableConst4()) {
  1435. if (Align <= 4) {
  1436. COMDATSymName = "__real@" + scalarConstantToHexString(C);
  1437. Align = 4;
  1438. }
  1439. } else if (Kind.isMergeableConst8()) {
  1440. if (Align <= 8) {
  1441. COMDATSymName = "__real@" + scalarConstantToHexString(C);
  1442. Align = 8;
  1443. }
  1444. } else if (Kind.isMergeableConst16()) {
  1445. // FIXME: These may not be appropriate for non-x86 architectures.
  1446. if (Align <= 16) {
  1447. COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
  1448. Align = 16;
  1449. }
  1450. } else if (Kind.isMergeableConst32()) {
  1451. if (Align <= 32) {
  1452. COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
  1453. Align = 32;
  1454. }
  1455. }
  1456. if (!COMDATSymName.empty())
  1457. return getContext().getCOFFSection(".rdata", Characteristics, Kind,
  1458. COMDATSymName,
  1459. COFF::IMAGE_COMDAT_SELECT_ANY);
  1460. }
  1461. return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C, Align);
  1462. }
  1463. //===----------------------------------------------------------------------===//
  1464. // Wasm
  1465. //===----------------------------------------------------------------------===//
  1466. static const Comdat *getWasmComdat(const GlobalValue *GV) {
  1467. const Comdat *C = GV->getComdat();
  1468. if (!C)
  1469. return nullptr;
  1470. if (C->getSelectionKind() != Comdat::Any)
  1471. report_fatal_error("WebAssembly COMDATs only support "
  1472. "SelectionKind::Any, '" + C->getName() + "' cannot be "
  1473. "lowered.");
  1474. return C;
  1475. }
  1476. static SectionKind getWasmKindForNamedSection(StringRef Name, SectionKind K) {
  1477. // If we're told we have function data, then use that.
  1478. if (K.isText())
  1479. return SectionKind::getText();
  1480. // Otherwise, ignore whatever section type the generic impl detected and use
  1481. // a plain data section.
  1482. return SectionKind::getData();
  1483. }
  1484. MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
  1485. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1486. // We don't support explict section names for functions in the wasm object
  1487. // format. Each function has to be in its own unique section.
  1488. if (isa<Function>(GO)) {
  1489. return SelectSectionForGlobal(GO, Kind, TM);
  1490. }
  1491. StringRef Name = GO->getSection();
  1492. Kind = getWasmKindForNamedSection(Name, Kind);
  1493. StringRef Group = "";
  1494. if (const Comdat *C = getWasmComdat(GO)) {
  1495. Group = C->getName();
  1496. }
  1497. MCSectionWasm* Section =
  1498. getContext().getWasmSection(Name, Kind, Group,
  1499. MCContext::GenericSectionID);
  1500. return Section;
  1501. }
  1502. static MCSectionWasm *selectWasmSectionForGlobal(
  1503. MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
  1504. const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
  1505. StringRef Group = "";
  1506. if (const Comdat *C = getWasmComdat(GO)) {
  1507. Group = C->getName();
  1508. }
  1509. bool UniqueSectionNames = TM.getUniqueSectionNames();
  1510. SmallString<128> Name = getSectionPrefixForGlobal(Kind);
  1511. if (const auto *F = dyn_cast<Function>(GO)) {
  1512. const auto &OptionalPrefix = F->getSectionPrefix();
  1513. if (OptionalPrefix)
  1514. Name += *OptionalPrefix;
  1515. }
  1516. if (EmitUniqueSection && UniqueSectionNames) {
  1517. Name.push_back('.');
  1518. TM.getNameWithPrefix(Name, GO, Mang, true);
  1519. }
  1520. unsigned UniqueID = MCContext::GenericSectionID;
  1521. if (EmitUniqueSection && !UniqueSectionNames) {
  1522. UniqueID = *NextUniqueID;
  1523. (*NextUniqueID)++;
  1524. }
  1525. return Ctx.getWasmSection(Name, Kind, Group, UniqueID);
  1526. }
  1527. MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
  1528. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1529. if (Kind.isCommon())
  1530. report_fatal_error("mergable sections not supported yet on wasm");
  1531. // If we have -ffunction-section or -fdata-section then we should emit the
  1532. // global value to a uniqued section specifically for it.
  1533. bool EmitUniqueSection = false;
  1534. if (Kind.isText())
  1535. EmitUniqueSection = TM.getFunctionSections();
  1536. else
  1537. EmitUniqueSection = TM.getDataSections();
  1538. EmitUniqueSection |= GO->hasComdat();
  1539. return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
  1540. EmitUniqueSection, &NextUniqueID);
  1541. }
  1542. bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
  1543. bool UsesLabelDifference, const Function &F) const {
  1544. // We can always create relative relocations, so use another section
  1545. // that can be marked non-executable.
  1546. return false;
  1547. }
  1548. const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
  1549. const GlobalValue *LHS, const GlobalValue *RHS,
  1550. const TargetMachine &TM) const {
  1551. // We may only use a PLT-relative relocation to refer to unnamed_addr
  1552. // functions.
  1553. if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
  1554. return nullptr;
  1555. // Basic sanity checks.
  1556. if (LHS->getType()->getPointerAddressSpace() != 0 ||
  1557. RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
  1558. RHS->isThreadLocal())
  1559. return nullptr;
  1560. return MCBinaryExpr::createSub(
  1561. MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
  1562. getContext()),
  1563. MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
  1564. }
  1565. void TargetLoweringObjectFileWasm::InitializeWasm() {
  1566. StaticCtorSection =
  1567. getContext().getWasmSection(".init_array", SectionKind::getData());
  1568. // We don't use PersonalityEncoding and LSDAEncoding because we don't emit
  1569. // .cfi directives. We use TTypeEncoding to encode typeinfo global variables.
  1570. TTypeEncoding = dwarf::DW_EH_PE_absptr;
  1571. }
  1572. MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection(
  1573. unsigned Priority, const MCSymbol *KeySym) const {
  1574. return Priority == UINT16_MAX ?
  1575. StaticCtorSection :
  1576. getContext().getWasmSection(".init_array." + utostr(Priority),
  1577. SectionKind::getData());
  1578. }
  1579. MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection(
  1580. unsigned Priority, const MCSymbol *KeySym) const {
  1581. llvm_unreachable("@llvm.global_dtors should have been lowered already");
  1582. return nullptr;
  1583. }
  1584. //===----------------------------------------------------------------------===//
  1585. // XCOFF
  1586. //===----------------------------------------------------------------------===//
  1587. MCSection *TargetLoweringObjectFileXCOFF::getExplicitSectionGlobal(
  1588. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1589. report_fatal_error("XCOFF explicit sections not yet implemented.");
  1590. }
  1591. MCSection *TargetLoweringObjectFileXCOFF::SelectSectionForGlobal(
  1592. const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
  1593. assert(!TM.getFunctionSections() && !TM.getDataSections() &&
  1594. "XCOFF unique sections not yet implemented.");
  1595. // Common symbols go into a csect with matching name which will get mapped
  1596. // into the .bss section.
  1597. if (Kind.isBSSLocal() || Kind.isCommon()) {
  1598. SmallString<128> Name;
  1599. getNameWithPrefix(Name, GO, TM);
  1600. XCOFF::StorageClass SC =
  1601. TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
  1602. return getContext().getXCOFFSection(
  1603. Name, Kind.isBSSLocal() ? XCOFF::XMC_BS : XCOFF::XMC_RW, XCOFF::XTY_CM,
  1604. SC, Kind, /* BeginSymbolName */ nullptr);
  1605. }
  1606. if (Kind.isText())
  1607. return TextSection;
  1608. if (Kind.isData())
  1609. return DataSection;
  1610. report_fatal_error("XCOFF other section types not yet implemented.");
  1611. }
  1612. bool TargetLoweringObjectFileXCOFF::shouldPutJumpTableInFunctionSection(
  1613. bool UsesLabelDifference, const Function &F) const {
  1614. report_fatal_error("TLOF XCOFF not yet implemented.");
  1615. }
  1616. void TargetLoweringObjectFileXCOFF::Initialize(MCContext &Ctx,
  1617. const TargetMachine &TgtM) {
  1618. TargetLoweringObjectFile::Initialize(Ctx, TgtM);
  1619. TTypeEncoding = 0;
  1620. PersonalityEncoding = 0;
  1621. LSDAEncoding = 0;
  1622. }
  1623. MCSection *TargetLoweringObjectFileXCOFF::getStaticCtorSection(
  1624. unsigned Priority, const MCSymbol *KeySym) const {
  1625. report_fatal_error("XCOFF ctor section not yet implemented.");
  1626. }
  1627. MCSection *TargetLoweringObjectFileXCOFF::getStaticDtorSection(
  1628. unsigned Priority, const MCSymbol *KeySym) const {
  1629. report_fatal_error("XCOFF dtor section not yet implemented.");
  1630. }
  1631. const MCExpr *TargetLoweringObjectFileXCOFF::lowerRelativeReference(
  1632. const GlobalValue *LHS, const GlobalValue *RHS,
  1633. const TargetMachine &TM) const {
  1634. report_fatal_error("XCOFF not yet implemented.");
  1635. }
  1636. XCOFF::StorageClass TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(
  1637. const GlobalObject *GO) {
  1638. switch (GO->getLinkage()) {
  1639. case GlobalValue::InternalLinkage:
  1640. return XCOFF::C_HIDEXT;
  1641. case GlobalValue::ExternalLinkage:
  1642. case GlobalValue::CommonLinkage:
  1643. return XCOFF::C_EXT;
  1644. case GlobalValue::ExternalWeakLinkage:
  1645. return XCOFF::C_WEAKEXT;
  1646. default:
  1647. report_fatal_error(
  1648. "Unhandled linkage when mapping linkage to StorageClass.");
  1649. }
  1650. }