MCMachOStreamer.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. //===- MCMachOStreamer.cpp - MachO Streamer -------------------------------===//
  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. #include "llvm/ADT/DenseMap.h"
  9. #include "llvm/ADT/SmallString.h"
  10. #include "llvm/ADT/SmallVector.h"
  11. #include "llvm/ADT/StringRef.h"
  12. #include "llvm/MC/MCAsmBackend.h"
  13. #include "llvm/MC/MCAssembler.h"
  14. #include "llvm/MC/MCCodeEmitter.h"
  15. #include "llvm/MC/MCContext.h"
  16. #include "llvm/MC/MCDirectives.h"
  17. #include "llvm/MC/MCExpr.h"
  18. #include "llvm/MC/MCFixup.h"
  19. #include "llvm/MC/MCFragment.h"
  20. #include "llvm/MC/MCLinkerOptimizationHint.h"
  21. #include "llvm/MC/MCObjectFileInfo.h"
  22. #include "llvm/MC/MCObjectStreamer.h"
  23. #include "llvm/MC/MCObjectWriter.h"
  24. #include "llvm/MC/MCSection.h"
  25. #include "llvm/MC/MCSectionMachO.h"
  26. #include "llvm/MC/MCSymbol.h"
  27. #include "llvm/MC/MCSymbolMachO.h"
  28. #include "llvm/MC/MCValue.h"
  29. #include "llvm/MC/SectionKind.h"
  30. #include "llvm/MC/TargetRegistry.h"
  31. #include "llvm/Support/Casting.h"
  32. #include "llvm/Support/ErrorHandling.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include <cassert>
  35. #include <vector>
  36. namespace llvm {
  37. class MCInst;
  38. class MCStreamer;
  39. class MCSubtargetInfo;
  40. class Triple;
  41. } // namespace llvm
  42. using namespace llvm;
  43. namespace {
  44. class MCMachOStreamer : public MCObjectStreamer {
  45. private:
  46. /// LabelSections - true if each section change should emit a linker local
  47. /// label for use in relocations for assembler local references. Obviates the
  48. /// need for local relocations. False by default.
  49. bool LabelSections;
  50. bool DWARFMustBeAtTheEnd;
  51. bool CreatedADWARFSection;
  52. /// HasSectionLabel - map of which sections have already had a non-local
  53. /// label emitted to them. Used so we don't emit extraneous linker local
  54. /// labels in the middle of the section.
  55. DenseMap<const MCSection*, bool> HasSectionLabel;
  56. void emitInstToData(const MCInst &Inst, const MCSubtargetInfo &STI) override;
  57. void emitDataRegion(DataRegionData::KindTy Kind);
  58. void emitDataRegionEnd();
  59. public:
  60. MCMachOStreamer(MCContext &Context, std::unique_ptr<MCAsmBackend> MAB,
  61. std::unique_ptr<MCObjectWriter> OW,
  62. std::unique_ptr<MCCodeEmitter> Emitter,
  63. bool DWARFMustBeAtTheEnd, bool label)
  64. : MCObjectStreamer(Context, std::move(MAB), std::move(OW),
  65. std::move(Emitter)),
  66. LabelSections(label), DWARFMustBeAtTheEnd(DWARFMustBeAtTheEnd),
  67. CreatedADWARFSection(false) {}
  68. /// state management
  69. void reset() override {
  70. CreatedADWARFSection = false;
  71. HasSectionLabel.clear();
  72. MCObjectStreamer::reset();
  73. }
  74. /// @name MCStreamer Interface
  75. /// @{
  76. void changeSection(MCSection *Sect, const MCExpr *Subsect) override;
  77. void emitLabel(MCSymbol *Symbol, SMLoc Loc = SMLoc()) override;
  78. void emitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
  79. void emitEHSymAttributes(const MCSymbol *Symbol, MCSymbol *EHSymbol) override;
  80. void emitAssemblerFlag(MCAssemblerFlag Flag) override;
  81. void emitLinkerOptions(ArrayRef<std::string> Options) override;
  82. void emitDataRegion(MCDataRegionType Kind) override;
  83. void emitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor,
  84. unsigned Update, VersionTuple SDKVersion) override;
  85. void emitBuildVersion(unsigned Platform, unsigned Major, unsigned Minor,
  86. unsigned Update, VersionTuple SDKVersion) override;
  87. void emitDarwinTargetVariantBuildVersion(unsigned Platform, unsigned Major,
  88. unsigned Minor, unsigned Update,
  89. VersionTuple SDKVersion) override;
  90. void emitThumbFunc(MCSymbol *Func) override;
  91. bool emitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
  92. void emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
  93. void emitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
  94. Align ByteAlignment) override;
  95. void emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
  96. Align ByteAlignment) override;
  97. void emitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
  98. uint64_t Size = 0, Align ByteAlignment = Align(1),
  99. SMLoc Loc = SMLoc()) override;
  100. void emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
  101. Align ByteAlignment = Align(1)) override;
  102. void emitIdent(StringRef IdentString) override {
  103. llvm_unreachable("macho doesn't support this directive");
  104. }
  105. void emitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override {
  106. getAssembler().getLOHContainer().addDirective(Kind, Args);
  107. }
  108. void emitCGProfileEntry(const MCSymbolRefExpr *From,
  109. const MCSymbolRefExpr *To, uint64_t Count) override {
  110. if (!From->getSymbol().isTemporary() && !To->getSymbol().isTemporary())
  111. getAssembler().CGProfile.push_back({From, To, Count});
  112. }
  113. void finishImpl() override;
  114. void finalizeCGProfileEntry(const MCSymbolRefExpr *&SRE);
  115. void finalizeCGProfile();
  116. void createAddrSigSection();
  117. };
  118. } // end anonymous namespace.
  119. static bool canGoAfterDWARF(const MCSectionMachO &MSec) {
  120. // These sections are created by the assembler itself after the end of
  121. // the .s file.
  122. StringRef SegName = MSec.getSegmentName();
  123. StringRef SecName = MSec.getName();
  124. if (SegName == "__LD" && SecName == "__compact_unwind")
  125. return true;
  126. if (SegName == "__IMPORT") {
  127. if (SecName == "__jump_table")
  128. return true;
  129. if (SecName == "__pointers")
  130. return true;
  131. }
  132. if (SegName == "__TEXT" && SecName == "__eh_frame")
  133. return true;
  134. if (SegName == "__DATA" && (SecName == "__nl_symbol_ptr" ||
  135. SecName == "__thread_ptr"))
  136. return true;
  137. if (SegName == "__LLVM" && SecName == "__cg_profile")
  138. return true;
  139. return false;
  140. }
  141. void MCMachOStreamer::changeSection(MCSection *Section,
  142. const MCExpr *Subsection) {
  143. // Change the section normally.
  144. bool Created = changeSectionImpl(Section, Subsection);
  145. const MCSectionMachO &MSec = *cast<MCSectionMachO>(Section);
  146. StringRef SegName = MSec.getSegmentName();
  147. if (SegName == "__DWARF")
  148. CreatedADWARFSection = true;
  149. else if (Created && DWARFMustBeAtTheEnd && !canGoAfterDWARF(MSec))
  150. assert(!CreatedADWARFSection && "Creating regular section after DWARF");
  151. // Output a linker-local symbol so we don't need section-relative local
  152. // relocations. The linker hates us when we do that.
  153. if (LabelSections && !HasSectionLabel[Section] &&
  154. !Section->getBeginSymbol()) {
  155. MCSymbol *Label = getContext().createLinkerPrivateTempSymbol();
  156. Section->setBeginSymbol(Label);
  157. HasSectionLabel[Section] = true;
  158. }
  159. }
  160. void MCMachOStreamer::emitEHSymAttributes(const MCSymbol *Symbol,
  161. MCSymbol *EHSymbol) {
  162. getAssembler().registerSymbol(*Symbol);
  163. if (Symbol->isExternal())
  164. emitSymbolAttribute(EHSymbol, MCSA_Global);
  165. if (cast<MCSymbolMachO>(Symbol)->isWeakDefinition())
  166. emitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
  167. if (Symbol->isPrivateExtern())
  168. emitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
  169. }
  170. void MCMachOStreamer::emitLabel(MCSymbol *Symbol, SMLoc Loc) {
  171. // We have to create a new fragment if this is an atom defining symbol,
  172. // fragments cannot span atoms.
  173. if (getAssembler().isSymbolLinkerVisible(*Symbol))
  174. insert(new MCDataFragment());
  175. MCObjectStreamer::emitLabel(Symbol, Loc);
  176. // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
  177. // to clear the weak reference and weak definition bits too, but the
  178. // implementation was buggy. For now we just try to match 'as', for
  179. // diffability.
  180. //
  181. // FIXME: Cleanup this code, these bits should be emitted based on semantic
  182. // properties, not on the order of definition, etc.
  183. cast<MCSymbolMachO>(Symbol)->clearReferenceType();
  184. }
  185. void MCMachOStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
  186. MCValue Res;
  187. if (Value->evaluateAsRelocatable(Res, nullptr, nullptr)) {
  188. if (const MCSymbolRefExpr *SymAExpr = Res.getSymA()) {
  189. const MCSymbol &SymA = SymAExpr->getSymbol();
  190. if (!Res.getSymB() && (SymA.getName() == "" || Res.getConstant() != 0))
  191. cast<MCSymbolMachO>(Symbol)->setAltEntry();
  192. }
  193. }
  194. MCObjectStreamer::emitAssignment(Symbol, Value);
  195. }
  196. void MCMachOStreamer::emitDataRegion(DataRegionData::KindTy Kind) {
  197. // Create a temporary label to mark the start of the data region.
  198. MCSymbol *Start = getContext().createTempSymbol();
  199. emitLabel(Start);
  200. // Record the region for the object writer to use.
  201. DataRegionData Data = { Kind, Start, nullptr };
  202. std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
  203. Regions.push_back(Data);
  204. }
  205. void MCMachOStreamer::emitDataRegionEnd() {
  206. std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
  207. assert(!Regions.empty() && "Mismatched .end_data_region!");
  208. DataRegionData &Data = Regions.back();
  209. assert(!Data.End && "Mismatched .end_data_region!");
  210. // Create a temporary label to mark the end of the data region.
  211. Data.End = getContext().createTempSymbol();
  212. emitLabel(Data.End);
  213. }
  214. void MCMachOStreamer::emitAssemblerFlag(MCAssemblerFlag Flag) {
  215. // Let the target do whatever target specific stuff it needs to do.
  216. getAssembler().getBackend().handleAssemblerFlag(Flag);
  217. // Do any generic stuff we need to do.
  218. switch (Flag) {
  219. case MCAF_SyntaxUnified: return; // no-op here.
  220. case MCAF_Code16: return; // Change parsing mode; no-op here.
  221. case MCAF_Code32: return; // Change parsing mode; no-op here.
  222. case MCAF_Code64: return; // Change parsing mode; no-op here.
  223. case MCAF_SubsectionsViaSymbols:
  224. getAssembler().setSubsectionsViaSymbols(true);
  225. return;
  226. }
  227. }
  228. void MCMachOStreamer::emitLinkerOptions(ArrayRef<std::string> Options) {
  229. getAssembler().getLinkerOptions().push_back(Options);
  230. }
  231. void MCMachOStreamer::emitDataRegion(MCDataRegionType Kind) {
  232. switch (Kind) {
  233. case MCDR_DataRegion:
  234. emitDataRegion(DataRegionData::Data);
  235. return;
  236. case MCDR_DataRegionJT8:
  237. emitDataRegion(DataRegionData::JumpTable8);
  238. return;
  239. case MCDR_DataRegionJT16:
  240. emitDataRegion(DataRegionData::JumpTable16);
  241. return;
  242. case MCDR_DataRegionJT32:
  243. emitDataRegion(DataRegionData::JumpTable32);
  244. return;
  245. case MCDR_DataRegionEnd:
  246. emitDataRegionEnd();
  247. return;
  248. }
  249. }
  250. void MCMachOStreamer::emitVersionMin(MCVersionMinType Kind, unsigned Major,
  251. unsigned Minor, unsigned Update,
  252. VersionTuple SDKVersion) {
  253. getAssembler().setVersionMin(Kind, Major, Minor, Update, SDKVersion);
  254. }
  255. void MCMachOStreamer::emitBuildVersion(unsigned Platform, unsigned Major,
  256. unsigned Minor, unsigned Update,
  257. VersionTuple SDKVersion) {
  258. getAssembler().setBuildVersion((MachO::PlatformType)Platform, Major, Minor,
  259. Update, SDKVersion);
  260. }
  261. void MCMachOStreamer::emitDarwinTargetVariantBuildVersion(
  262. unsigned Platform, unsigned Major, unsigned Minor, unsigned Update,
  263. VersionTuple SDKVersion) {
  264. getAssembler().setDarwinTargetVariantBuildVersion(
  265. (MachO::PlatformType)Platform, Major, Minor, Update, SDKVersion);
  266. }
  267. void MCMachOStreamer::emitThumbFunc(MCSymbol *Symbol) {
  268. // Remember that the function is a thumb function. Fixup and relocation
  269. // values will need adjusted.
  270. getAssembler().setIsThumbFunc(Symbol);
  271. cast<MCSymbolMachO>(Symbol)->setThumbFunc();
  272. }
  273. bool MCMachOStreamer::emitSymbolAttribute(MCSymbol *Sym,
  274. MCSymbolAttr Attribute) {
  275. MCSymbolMachO *Symbol = cast<MCSymbolMachO>(Sym);
  276. // Indirect symbols are handled differently, to match how 'as' handles
  277. // them. This makes writing matching .o files easier.
  278. if (Attribute == MCSA_IndirectSymbol) {
  279. // Note that we intentionally cannot use the symbol data here; this is
  280. // important for matching the string table that 'as' generates.
  281. IndirectSymbolData ISD;
  282. ISD.Symbol = Symbol;
  283. ISD.Section = getCurrentSectionOnly();
  284. getAssembler().getIndirectSymbols().push_back(ISD);
  285. return true;
  286. }
  287. // Adding a symbol attribute always introduces the symbol, note that an
  288. // important side effect of calling registerSymbol here is to register
  289. // the symbol with the assembler.
  290. getAssembler().registerSymbol(*Symbol);
  291. // The implementation of symbol attributes is designed to match 'as', but it
  292. // leaves much to desired. It doesn't really make sense to arbitrarily add and
  293. // remove flags, but 'as' allows this (in particular, see .desc).
  294. //
  295. // In the future it might be worth trying to make these operations more well
  296. // defined.
  297. switch (Attribute) {
  298. case MCSA_Invalid:
  299. case MCSA_ELF_TypeFunction:
  300. case MCSA_ELF_TypeIndFunction:
  301. case MCSA_ELF_TypeObject:
  302. case MCSA_ELF_TypeTLS:
  303. case MCSA_ELF_TypeCommon:
  304. case MCSA_ELF_TypeNoType:
  305. case MCSA_ELF_TypeGnuUniqueObject:
  306. case MCSA_Extern:
  307. case MCSA_Hidden:
  308. case MCSA_IndirectSymbol:
  309. case MCSA_Internal:
  310. case MCSA_Protected:
  311. case MCSA_Weak:
  312. case MCSA_Local:
  313. case MCSA_LGlobal:
  314. case MCSA_Exported:
  315. case MCSA_Memtag:
  316. return false;
  317. case MCSA_Global:
  318. Symbol->setExternal(true);
  319. // This effectively clears the undefined lazy bit, in Darwin 'as', although
  320. // it isn't very consistent because it implements this as part of symbol
  321. // lookup.
  322. //
  323. // FIXME: Cleanup this code, these bits should be emitted based on semantic
  324. // properties, not on the order of definition, etc.
  325. Symbol->setReferenceTypeUndefinedLazy(false);
  326. break;
  327. case MCSA_LazyReference:
  328. // FIXME: This requires -dynamic.
  329. Symbol->setNoDeadStrip();
  330. if (Symbol->isUndefined())
  331. Symbol->setReferenceTypeUndefinedLazy(true);
  332. break;
  333. // Since .reference sets the no dead strip bit, it is equivalent to
  334. // .no_dead_strip in practice.
  335. case MCSA_Reference:
  336. case MCSA_NoDeadStrip:
  337. Symbol->setNoDeadStrip();
  338. break;
  339. case MCSA_SymbolResolver:
  340. Symbol->setSymbolResolver();
  341. break;
  342. case MCSA_AltEntry:
  343. Symbol->setAltEntry();
  344. break;
  345. case MCSA_PrivateExtern:
  346. Symbol->setExternal(true);
  347. Symbol->setPrivateExtern(true);
  348. break;
  349. case MCSA_WeakReference:
  350. // FIXME: This requires -dynamic.
  351. if (Symbol->isUndefined())
  352. Symbol->setWeakReference();
  353. break;
  354. case MCSA_WeakDefinition:
  355. // FIXME: 'as' enforces that this is defined and global. The manual claims
  356. // it has to be in a coalesced section, but this isn't enforced.
  357. Symbol->setWeakDefinition();
  358. break;
  359. case MCSA_WeakDefAutoPrivate:
  360. Symbol->setWeakDefinition();
  361. Symbol->setWeakReference();
  362. break;
  363. case MCSA_Cold:
  364. Symbol->setCold();
  365. break;
  366. }
  367. return true;
  368. }
  369. void MCMachOStreamer::emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
  370. // Encode the 'desc' value into the lowest implementation defined bits.
  371. getAssembler().registerSymbol(*Symbol);
  372. cast<MCSymbolMachO>(Symbol)->setDesc(DescValue);
  373. }
  374. void MCMachOStreamer::emitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
  375. Align ByteAlignment) {
  376. // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
  377. assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
  378. getAssembler().registerSymbol(*Symbol);
  379. Symbol->setExternal(true);
  380. Symbol->setCommon(Size, ByteAlignment);
  381. }
  382. void MCMachOStreamer::emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
  383. Align ByteAlignment) {
  384. // '.lcomm' is equivalent to '.zerofill'.
  385. return emitZerofill(getContext().getObjectFileInfo()->getDataBSSSection(),
  386. Symbol, Size, ByteAlignment);
  387. }
  388. void MCMachOStreamer::emitZerofill(MCSection *Section, MCSymbol *Symbol,
  389. uint64_t Size, Align ByteAlignment,
  390. SMLoc Loc) {
  391. // On darwin all virtual sections have zerofill type. Disallow the usage of
  392. // .zerofill in non-virtual functions. If something similar is needed, use
  393. // .space or .zero.
  394. if (!Section->isVirtualSection()) {
  395. getContext().reportError(
  396. Loc, "The usage of .zerofill is restricted to sections of "
  397. "ZEROFILL type. Use .zero or .space instead.");
  398. return; // Early returning here shouldn't harm. EmitZeros should work on any
  399. // section.
  400. }
  401. pushSection();
  402. switchSection(Section);
  403. // The symbol may not be present, which only creates the section.
  404. if (Symbol) {
  405. emitValueToAlignment(ByteAlignment, 0, 1, 0);
  406. emitLabel(Symbol);
  407. emitZeros(Size);
  408. }
  409. popSection();
  410. }
  411. // This should always be called with the thread local bss section. Like the
  412. // .zerofill directive this doesn't actually switch sections on us.
  413. void MCMachOStreamer::emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
  414. uint64_t Size, Align ByteAlignment) {
  415. emitZerofill(Section, Symbol, Size, ByteAlignment);
  416. }
  417. void MCMachOStreamer::emitInstToData(const MCInst &Inst,
  418. const MCSubtargetInfo &STI) {
  419. MCDataFragment *DF = getOrCreateDataFragment();
  420. SmallVector<MCFixup, 4> Fixups;
  421. SmallString<256> Code;
  422. raw_svector_ostream VecOS(Code);
  423. getAssembler().getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
  424. // Add the fixups and data.
  425. for (MCFixup &Fixup : Fixups) {
  426. Fixup.setOffset(Fixup.getOffset() + DF->getContents().size());
  427. DF->getFixups().push_back(Fixup);
  428. }
  429. DF->setHasInstructions(STI);
  430. DF->getContents().append(Code.begin(), Code.end());
  431. }
  432. void MCMachOStreamer::finishImpl() {
  433. emitFrames(&getAssembler().getBackend());
  434. // We have to set the fragment atom associations so we can relax properly for
  435. // Mach-O.
  436. // First, scan the symbol table to build a lookup table from fragments to
  437. // defining symbols.
  438. DenseMap<const MCFragment *, const MCSymbol *> DefiningSymbolMap;
  439. for (const MCSymbol &Symbol : getAssembler().symbols()) {
  440. if (getAssembler().isSymbolLinkerVisible(Symbol) && Symbol.isInSection() &&
  441. !Symbol.isVariable()) {
  442. // An atom defining symbol should never be internal to a fragment.
  443. assert(Symbol.getOffset() == 0 &&
  444. "Invalid offset in atom defining symbol!");
  445. DefiningSymbolMap[Symbol.getFragment()] = &Symbol;
  446. }
  447. }
  448. // Set the fragment atom associations by tracking the last seen atom defining
  449. // symbol.
  450. for (MCSection &Sec : getAssembler()) {
  451. const MCSymbol *CurrentAtom = nullptr;
  452. for (MCFragment &Frag : Sec) {
  453. if (const MCSymbol *Symbol = DefiningSymbolMap.lookup(&Frag))
  454. CurrentAtom = Symbol;
  455. Frag.setAtom(CurrentAtom);
  456. }
  457. }
  458. finalizeCGProfile();
  459. createAddrSigSection();
  460. this->MCObjectStreamer::finishImpl();
  461. }
  462. void MCMachOStreamer::finalizeCGProfileEntry(const MCSymbolRefExpr *&SRE) {
  463. const MCSymbol *S = &SRE->getSymbol();
  464. bool Created;
  465. getAssembler().registerSymbol(*S, &Created);
  466. if (Created)
  467. S->setExternal(true);
  468. }
  469. void MCMachOStreamer::finalizeCGProfile() {
  470. MCAssembler &Asm = getAssembler();
  471. if (Asm.CGProfile.empty())
  472. return;
  473. for (MCAssembler::CGProfileEntry &E : Asm.CGProfile) {
  474. finalizeCGProfileEntry(E.From);
  475. finalizeCGProfileEntry(E.To);
  476. }
  477. // We can't write the section out until symbol indices are finalized which
  478. // doesn't happen until after section layout. We need to create the section
  479. // and set its size now so that it's accounted for in layout.
  480. MCSection *CGProfileSection = Asm.getContext().getMachOSection(
  481. "__LLVM", "__cg_profile", 0, SectionKind::getMetadata());
  482. Asm.registerSection(*CGProfileSection);
  483. auto *Frag = new MCDataFragment(CGProfileSection);
  484. // For each entry, reserve space for 2 32-bit indices and a 64-bit count.
  485. size_t SectionBytes =
  486. Asm.CGProfile.size() * (2 * sizeof(uint32_t) + sizeof(uint64_t));
  487. Frag->getContents().resize(SectionBytes);
  488. }
  489. MCStreamer *llvm::createMachOStreamer(MCContext &Context,
  490. std::unique_ptr<MCAsmBackend> &&MAB,
  491. std::unique_ptr<MCObjectWriter> &&OW,
  492. std::unique_ptr<MCCodeEmitter> &&CE,
  493. bool RelaxAll, bool DWARFMustBeAtTheEnd,
  494. bool LabelSections) {
  495. MCMachOStreamer *S =
  496. new MCMachOStreamer(Context, std::move(MAB), std::move(OW), std::move(CE),
  497. DWARFMustBeAtTheEnd, LabelSections);
  498. const Triple &Target = Context.getTargetTriple();
  499. S->emitVersionForTarget(
  500. Target, Context.getObjectFileInfo()->getSDKVersion(),
  501. Context.getObjectFileInfo()->getDarwinTargetVariantTriple(),
  502. Context.getObjectFileInfo()->getDarwinTargetVariantSDKVersion());
  503. if (RelaxAll)
  504. S->getAssembler().setRelaxAll(true);
  505. return S;
  506. }
  507. // The AddrSig section uses a series of relocations to refer to the symbols that
  508. // should be considered address-significant. The only interesting content of
  509. // these relocations is their symbol; the type, length etc will be ignored by
  510. // the linker. The reason we are not referring to the symbol indices directly is
  511. // that those indices will be invalidated by tools that update the symbol table.
  512. // Symbol relocations OTOH will have their indices updated by e.g. llvm-strip.
  513. void MCMachOStreamer::createAddrSigSection() {
  514. MCAssembler &Asm = getAssembler();
  515. MCObjectWriter &writer = Asm.getWriter();
  516. if (!writer.getEmitAddrsigSection())
  517. return;
  518. // Create the AddrSig section and first data fragment here as its layout needs
  519. // to be computed immediately after in order for it to be exported correctly.
  520. MCSection *AddrSigSection =
  521. Asm.getContext().getObjectFileInfo()->getAddrSigSection();
  522. Asm.registerSection(*AddrSigSection);
  523. auto *Frag = new MCDataFragment(AddrSigSection);
  524. // We will generate a series of pointer-sized symbol relocations at offset
  525. // 0x0. Set the section size to be large enough to contain a single pointer
  526. // (instead of emitting a zero-sized section) so these relocations are
  527. // technically valid, even though we don't expect these relocations to
  528. // actually be applied by the linker.
  529. Frag->getContents().resize(8);
  530. }