MCStreamer.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  1. //===- lib/MC/MCStreamer.cpp - Streaming Machine Code Output --------------===//
  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/MC/MCStreamer.h"
  9. #include "llvm/ADT/SmallString.h"
  10. #include "llvm/ADT/StringRef.h"
  11. #include "llvm/ADT/Twine.h"
  12. #include "llvm/BinaryFormat/COFF.h"
  13. #include "llvm/BinaryFormat/MachO.h"
  14. #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
  15. #include "llvm/MC/MCAsmBackend.h"
  16. #include "llvm/MC/MCAsmInfo.h"
  17. #include "llvm/MC/MCCodeView.h"
  18. #include "llvm/MC/MCContext.h"
  19. #include "llvm/MC/MCDwarf.h"
  20. #include "llvm/MC/MCExpr.h"
  21. #include "llvm/MC/MCInst.h"
  22. #include "llvm/MC/MCInstPrinter.h"
  23. #include "llvm/MC/MCObjectFileInfo.h"
  24. #include "llvm/MC/MCPseudoProbe.h"
  25. #include "llvm/MC/MCRegister.h"
  26. #include "llvm/MC/MCRegisterInfo.h"
  27. #include "llvm/MC/MCSection.h"
  28. #include "llvm/MC/MCSectionCOFF.h"
  29. #include "llvm/MC/MCSymbol.h"
  30. #include "llvm/MC/MCWin64EH.h"
  31. #include "llvm/MC/MCWinEH.h"
  32. #include "llvm/Support/Casting.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. #include "llvm/Support/LEB128.h"
  35. #include "llvm/Support/MathExtras.h"
  36. #include "llvm/Support/raw_ostream.h"
  37. #include <cassert>
  38. #include <cstdint>
  39. #include <cstdlib>
  40. #include <optional>
  41. #include <utility>
  42. using namespace llvm;
  43. MCTargetStreamer::MCTargetStreamer(MCStreamer &S) : Streamer(S) {
  44. S.setTargetStreamer(this);
  45. }
  46. // Pin the vtables to this file.
  47. MCTargetStreamer::~MCTargetStreamer() = default;
  48. void MCTargetStreamer::emitLabel(MCSymbol *Symbol) {}
  49. void MCTargetStreamer::finish() {}
  50. void MCTargetStreamer::emitConstantPools() {}
  51. void MCTargetStreamer::changeSection(const MCSection *CurSection,
  52. MCSection *Section,
  53. const MCExpr *Subsection,
  54. raw_ostream &OS) {
  55. Section->printSwitchToSection(*Streamer.getContext().getAsmInfo(),
  56. Streamer.getContext().getTargetTriple(), OS,
  57. Subsection);
  58. }
  59. void MCTargetStreamer::emitDwarfFileDirective(StringRef Directive) {
  60. Streamer.emitRawText(Directive);
  61. }
  62. void MCTargetStreamer::emitValue(const MCExpr *Value) {
  63. SmallString<128> Str;
  64. raw_svector_ostream OS(Str);
  65. Value->print(OS, Streamer.getContext().getAsmInfo());
  66. Streamer.emitRawText(OS.str());
  67. }
  68. void MCTargetStreamer::emitRawBytes(StringRef Data) {
  69. const MCAsmInfo *MAI = Streamer.getContext().getAsmInfo();
  70. const char *Directive = MAI->getData8bitsDirective();
  71. for (const unsigned char C : Data.bytes()) {
  72. SmallString<128> Str;
  73. raw_svector_ostream OS(Str);
  74. OS << Directive << (unsigned)C;
  75. Streamer.emitRawText(OS.str());
  76. }
  77. }
  78. void MCTargetStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {}
  79. MCStreamer::MCStreamer(MCContext &Ctx)
  80. : Context(Ctx), CurrentWinFrameInfo(nullptr),
  81. CurrentProcWinFrameInfoStartIndex(0), UseAssemblerInfoForParsing(false) {
  82. SectionStack.push_back(std::pair<MCSectionSubPair, MCSectionSubPair>());
  83. }
  84. MCStreamer::~MCStreamer() = default;
  85. void MCStreamer::reset() {
  86. DwarfFrameInfos.clear();
  87. CurrentWinFrameInfo = nullptr;
  88. WinFrameInfos.clear();
  89. SymbolOrdering.clear();
  90. SectionStack.clear();
  91. SectionStack.push_back(std::pair<MCSectionSubPair, MCSectionSubPair>());
  92. }
  93. raw_ostream &MCStreamer::getCommentOS() {
  94. // By default, discard comments.
  95. return nulls();
  96. }
  97. unsigned MCStreamer::getNumFrameInfos() { return DwarfFrameInfos.size(); }
  98. ArrayRef<MCDwarfFrameInfo> MCStreamer::getDwarfFrameInfos() const {
  99. return DwarfFrameInfos;
  100. }
  101. void MCStreamer::emitRawComment(const Twine &T, bool TabPrefix) {}
  102. void MCStreamer::addExplicitComment(const Twine &T) {}
  103. void MCStreamer::emitExplicitComments() {}
  104. void MCStreamer::generateCompactUnwindEncodings(MCAsmBackend *MAB) {
  105. for (auto &FI : DwarfFrameInfos)
  106. FI.CompactUnwindEncoding =
  107. (MAB ? MAB->generateCompactUnwindEncoding(FI.Instructions) : 0);
  108. }
  109. /// EmitIntValue - Special case of EmitValue that avoids the client having to
  110. /// pass in a MCExpr for constant integers.
  111. void MCStreamer::emitIntValue(uint64_t Value, unsigned Size) {
  112. assert(1 <= Size && Size <= 8 && "Invalid size");
  113. assert((isUIntN(8 * Size, Value) || isIntN(8 * Size, Value)) &&
  114. "Invalid size");
  115. const bool IsLittleEndian = Context.getAsmInfo()->isLittleEndian();
  116. uint64_t Swapped = support::endian::byte_swap(
  117. Value, IsLittleEndian ? support::little : support::big);
  118. unsigned Index = IsLittleEndian ? 0 : 8 - Size;
  119. emitBytes(StringRef(reinterpret_cast<char *>(&Swapped) + Index, Size));
  120. }
  121. void MCStreamer::emitIntValue(APInt Value) {
  122. if (Value.getNumWords() == 1) {
  123. emitIntValue(Value.getLimitedValue(), Value.getBitWidth() / 8);
  124. return;
  125. }
  126. const bool IsLittleEndianTarget = Context.getAsmInfo()->isLittleEndian();
  127. const bool ShouldSwap = sys::IsLittleEndianHost != IsLittleEndianTarget;
  128. const APInt Swapped = ShouldSwap ? Value.byteSwap() : Value;
  129. const unsigned Size = Value.getBitWidth() / 8;
  130. SmallString<10> Tmp;
  131. Tmp.resize(Size);
  132. StoreIntToMemory(Swapped, reinterpret_cast<uint8_t *>(Tmp.data()), Size);
  133. emitBytes(Tmp.str());
  134. }
  135. /// EmitULEB128IntValue - Special case of EmitULEB128Value that avoids the
  136. /// client having to pass in a MCExpr for constant integers.
  137. unsigned MCStreamer::emitULEB128IntValue(uint64_t Value, unsigned PadTo) {
  138. SmallString<128> Tmp;
  139. raw_svector_ostream OSE(Tmp);
  140. encodeULEB128(Value, OSE, PadTo);
  141. emitBytes(OSE.str());
  142. return Tmp.size();
  143. }
  144. /// EmitSLEB128IntValue - Special case of EmitSLEB128Value that avoids the
  145. /// client having to pass in a MCExpr for constant integers.
  146. unsigned MCStreamer::emitSLEB128IntValue(int64_t Value) {
  147. SmallString<128> Tmp;
  148. raw_svector_ostream OSE(Tmp);
  149. encodeSLEB128(Value, OSE);
  150. emitBytes(OSE.str());
  151. return Tmp.size();
  152. }
  153. void MCStreamer::emitValue(const MCExpr *Value, unsigned Size, SMLoc Loc) {
  154. emitValueImpl(Value, Size, Loc);
  155. }
  156. void MCStreamer::emitSymbolValue(const MCSymbol *Sym, unsigned Size,
  157. bool IsSectionRelative) {
  158. assert((!IsSectionRelative || Size == 4) &&
  159. "SectionRelative value requires 4-bytes");
  160. if (!IsSectionRelative)
  161. emitValueImpl(MCSymbolRefExpr::create(Sym, getContext()), Size);
  162. else
  163. emitCOFFSecRel32(Sym, /*Offset=*/0);
  164. }
  165. void MCStreamer::emitDTPRel64Value(const MCExpr *Value) {
  166. report_fatal_error("unsupported directive in streamer");
  167. }
  168. void MCStreamer::emitDTPRel32Value(const MCExpr *Value) {
  169. report_fatal_error("unsupported directive in streamer");
  170. }
  171. void MCStreamer::emitTPRel64Value(const MCExpr *Value) {
  172. report_fatal_error("unsupported directive in streamer");
  173. }
  174. void MCStreamer::emitTPRel32Value(const MCExpr *Value) {
  175. report_fatal_error("unsupported directive in streamer");
  176. }
  177. void MCStreamer::emitGPRel64Value(const MCExpr *Value) {
  178. report_fatal_error("unsupported directive in streamer");
  179. }
  180. void MCStreamer::emitGPRel32Value(const MCExpr *Value) {
  181. report_fatal_error("unsupported directive in streamer");
  182. }
  183. /// Emit NumBytes bytes worth of the value specified by FillValue.
  184. /// This implements directives such as '.space'.
  185. void MCStreamer::emitFill(uint64_t NumBytes, uint8_t FillValue) {
  186. emitFill(*MCConstantExpr::create(NumBytes, getContext()), FillValue);
  187. }
  188. void llvm::MCStreamer::emitNops(int64_t NumBytes, int64_t ControlledNopLen,
  189. llvm::SMLoc, const MCSubtargetInfo& STI) {}
  190. /// The implementation in this class just redirects to emitFill.
  191. void MCStreamer::emitZeros(uint64_t NumBytes) { emitFill(NumBytes, 0); }
  192. Expected<unsigned> MCStreamer::tryEmitDwarfFileDirective(
  193. unsigned FileNo, StringRef Directory, StringRef Filename,
  194. std::optional<MD5::MD5Result> Checksum, std::optional<StringRef> Source,
  195. unsigned CUID) {
  196. return getContext().getDwarfFile(Directory, Filename, FileNo, Checksum,
  197. Source, CUID);
  198. }
  199. void MCStreamer::emitDwarfFile0Directive(StringRef Directory,
  200. StringRef Filename,
  201. std::optional<MD5::MD5Result> Checksum,
  202. std::optional<StringRef> Source,
  203. unsigned CUID) {
  204. getContext().setMCLineTableRootFile(CUID, Directory, Filename, Checksum,
  205. Source);
  206. }
  207. void MCStreamer::emitCFIBKeyFrame() {
  208. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  209. if (!CurFrame)
  210. return;
  211. CurFrame->IsBKeyFrame = true;
  212. }
  213. void MCStreamer::emitCFIMTETaggedFrame() {
  214. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  215. if (!CurFrame)
  216. return;
  217. CurFrame->IsMTETaggedFrame = true;
  218. }
  219. void MCStreamer::emitDwarfLocDirective(unsigned FileNo, unsigned Line,
  220. unsigned Column, unsigned Flags,
  221. unsigned Isa, unsigned Discriminator,
  222. StringRef FileName) {
  223. getContext().setCurrentDwarfLoc(FileNo, Line, Column, Flags, Isa,
  224. Discriminator);
  225. }
  226. MCSymbol *MCStreamer::getDwarfLineTableSymbol(unsigned CUID) {
  227. MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
  228. if (!Table.getLabel()) {
  229. StringRef Prefix = Context.getAsmInfo()->getPrivateGlobalPrefix();
  230. Table.setLabel(
  231. Context.getOrCreateSymbol(Prefix + "line_table_start" + Twine(CUID)));
  232. }
  233. return Table.getLabel();
  234. }
  235. bool MCStreamer::hasUnfinishedDwarfFrameInfo() {
  236. return !DwarfFrameInfos.empty() && !DwarfFrameInfos.back().End;
  237. }
  238. MCDwarfFrameInfo *MCStreamer::getCurrentDwarfFrameInfo() {
  239. if (!hasUnfinishedDwarfFrameInfo()) {
  240. getContext().reportError(getStartTokLoc(),
  241. "this directive must appear between "
  242. ".cfi_startproc and .cfi_endproc directives");
  243. return nullptr;
  244. }
  245. return &DwarfFrameInfos.back();
  246. }
  247. bool MCStreamer::emitCVFileDirective(unsigned FileNo, StringRef Filename,
  248. ArrayRef<uint8_t> Checksum,
  249. unsigned ChecksumKind) {
  250. return getContext().getCVContext().addFile(*this, FileNo, Filename, Checksum,
  251. ChecksumKind);
  252. }
  253. bool MCStreamer::emitCVFuncIdDirective(unsigned FunctionId) {
  254. return getContext().getCVContext().recordFunctionId(FunctionId);
  255. }
  256. bool MCStreamer::emitCVInlineSiteIdDirective(unsigned FunctionId,
  257. unsigned IAFunc, unsigned IAFile,
  258. unsigned IALine, unsigned IACol,
  259. SMLoc Loc) {
  260. if (getContext().getCVContext().getCVFunctionInfo(IAFunc) == nullptr) {
  261. getContext().reportError(Loc, "parent function id not introduced by "
  262. ".cv_func_id or .cv_inline_site_id");
  263. return true;
  264. }
  265. return getContext().getCVContext().recordInlinedCallSiteId(
  266. FunctionId, IAFunc, IAFile, IALine, IACol);
  267. }
  268. void MCStreamer::emitCVLocDirective(unsigned FunctionId, unsigned FileNo,
  269. unsigned Line, unsigned Column,
  270. bool PrologueEnd, bool IsStmt,
  271. StringRef FileName, SMLoc Loc) {}
  272. bool MCStreamer::checkCVLocSection(unsigned FuncId, unsigned FileNo,
  273. SMLoc Loc) {
  274. CodeViewContext &CVC = getContext().getCVContext();
  275. MCCVFunctionInfo *FI = CVC.getCVFunctionInfo(FuncId);
  276. if (!FI) {
  277. getContext().reportError(
  278. Loc, "function id not introduced by .cv_func_id or .cv_inline_site_id");
  279. return false;
  280. }
  281. // Track the section
  282. if (FI->Section == nullptr)
  283. FI->Section = getCurrentSectionOnly();
  284. else if (FI->Section != getCurrentSectionOnly()) {
  285. getContext().reportError(
  286. Loc,
  287. "all .cv_loc directives for a function must be in the same section");
  288. return false;
  289. }
  290. return true;
  291. }
  292. void MCStreamer::emitCVLinetableDirective(unsigned FunctionId,
  293. const MCSymbol *Begin,
  294. const MCSymbol *End) {}
  295. void MCStreamer::emitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
  296. unsigned SourceFileId,
  297. unsigned SourceLineNum,
  298. const MCSymbol *FnStartSym,
  299. const MCSymbol *FnEndSym) {}
  300. /// Only call this on endian-specific types like ulittle16_t and little32_t, or
  301. /// structs composed of them.
  302. template <typename T>
  303. static void copyBytesForDefRange(SmallString<20> &BytePrefix,
  304. codeview::SymbolKind SymKind,
  305. const T &DefRangeHeader) {
  306. BytePrefix.resize(2 + sizeof(T));
  307. codeview::ulittle16_t SymKindLE = codeview::ulittle16_t(SymKind);
  308. memcpy(&BytePrefix[0], &SymKindLE, 2);
  309. memcpy(&BytePrefix[2], &DefRangeHeader, sizeof(T));
  310. }
  311. void MCStreamer::emitCVDefRangeDirective(
  312. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
  313. StringRef FixedSizePortion) {}
  314. void MCStreamer::emitCVDefRangeDirective(
  315. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
  316. codeview::DefRangeRegisterRelHeader DRHdr) {
  317. SmallString<20> BytePrefix;
  318. copyBytesForDefRange(BytePrefix, codeview::S_DEFRANGE_REGISTER_REL, DRHdr);
  319. emitCVDefRangeDirective(Ranges, BytePrefix);
  320. }
  321. void MCStreamer::emitCVDefRangeDirective(
  322. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
  323. codeview::DefRangeSubfieldRegisterHeader DRHdr) {
  324. SmallString<20> BytePrefix;
  325. copyBytesForDefRange(BytePrefix, codeview::S_DEFRANGE_SUBFIELD_REGISTER,
  326. DRHdr);
  327. emitCVDefRangeDirective(Ranges, BytePrefix);
  328. }
  329. void MCStreamer::emitCVDefRangeDirective(
  330. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
  331. codeview::DefRangeRegisterHeader DRHdr) {
  332. SmallString<20> BytePrefix;
  333. copyBytesForDefRange(BytePrefix, codeview::S_DEFRANGE_REGISTER, DRHdr);
  334. emitCVDefRangeDirective(Ranges, BytePrefix);
  335. }
  336. void MCStreamer::emitCVDefRangeDirective(
  337. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
  338. codeview::DefRangeFramePointerRelHeader DRHdr) {
  339. SmallString<20> BytePrefix;
  340. copyBytesForDefRange(BytePrefix, codeview::S_DEFRANGE_FRAMEPOINTER_REL,
  341. DRHdr);
  342. emitCVDefRangeDirective(Ranges, BytePrefix);
  343. }
  344. void MCStreamer::emitEHSymAttributes(const MCSymbol *Symbol,
  345. MCSymbol *EHSymbol) {
  346. }
  347. void MCStreamer::initSections(bool NoExecStack, const MCSubtargetInfo &STI) {
  348. switchSection(getContext().getObjectFileInfo()->getTextSection());
  349. }
  350. void MCStreamer::assignFragment(MCSymbol *Symbol, MCFragment *Fragment) {
  351. assert(Fragment);
  352. Symbol->setFragment(Fragment);
  353. // As we emit symbols into a section, track the order so that they can
  354. // be sorted upon later. Zero is reserved to mean 'unemitted'.
  355. SymbolOrdering[Symbol] = 1 + SymbolOrdering.size();
  356. }
  357. void MCStreamer::emitLabel(MCSymbol *Symbol, SMLoc Loc) {
  358. Symbol->redefineIfPossible();
  359. if (!Symbol->isUndefined() || Symbol->isVariable())
  360. return getContext().reportError(Loc, "symbol '" + Twine(Symbol->getName()) +
  361. "' is already defined");
  362. assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
  363. assert(getCurrentSectionOnly() && "Cannot emit before setting section!");
  364. assert(!Symbol->getFragment() && "Unexpected fragment on symbol data!");
  365. assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
  366. Symbol->setFragment(&getCurrentSectionOnly()->getDummyFragment());
  367. MCTargetStreamer *TS = getTargetStreamer();
  368. if (TS)
  369. TS->emitLabel(Symbol);
  370. }
  371. void MCStreamer::emitConditionalAssignment(MCSymbol *Symbol,
  372. const MCExpr *Value) {}
  373. void MCStreamer::emitCFISections(bool EH, bool Debug) {}
  374. void MCStreamer::emitCFIStartProc(bool IsSimple, SMLoc Loc) {
  375. if (hasUnfinishedDwarfFrameInfo())
  376. return getContext().reportError(
  377. Loc, "starting new .cfi frame before finishing the previous one");
  378. MCDwarfFrameInfo Frame;
  379. Frame.IsSimple = IsSimple;
  380. emitCFIStartProcImpl(Frame);
  381. const MCAsmInfo* MAI = Context.getAsmInfo();
  382. if (MAI) {
  383. for (const MCCFIInstruction& Inst : MAI->getInitialFrameState()) {
  384. if (Inst.getOperation() == MCCFIInstruction::OpDefCfa ||
  385. Inst.getOperation() == MCCFIInstruction::OpDefCfaRegister ||
  386. Inst.getOperation() == MCCFIInstruction::OpLLVMDefAspaceCfa) {
  387. Frame.CurrentCfaRegister = Inst.getRegister();
  388. }
  389. }
  390. }
  391. DwarfFrameInfos.push_back(Frame);
  392. }
  393. void MCStreamer::emitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
  394. }
  395. void MCStreamer::emitCFIEndProc() {
  396. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  397. if (!CurFrame)
  398. return;
  399. emitCFIEndProcImpl(*CurFrame);
  400. }
  401. void MCStreamer::emitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
  402. // Put a dummy non-null value in Frame.End to mark that this frame has been
  403. // closed.
  404. Frame.End = (MCSymbol *)1;
  405. }
  406. MCSymbol *MCStreamer::emitCFILabel() {
  407. // Return a dummy non-null value so that label fields appear filled in when
  408. // generating textual assembly.
  409. return (MCSymbol *)1;
  410. }
  411. void MCStreamer::emitCFIDefCfa(int64_t Register, int64_t Offset) {
  412. MCSymbol *Label = emitCFILabel();
  413. MCCFIInstruction Instruction =
  414. MCCFIInstruction::cfiDefCfa(Label, Register, Offset);
  415. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  416. if (!CurFrame)
  417. return;
  418. CurFrame->Instructions.push_back(Instruction);
  419. CurFrame->CurrentCfaRegister = static_cast<unsigned>(Register);
  420. }
  421. void MCStreamer::emitCFIDefCfaOffset(int64_t Offset) {
  422. MCSymbol *Label = emitCFILabel();
  423. MCCFIInstruction Instruction =
  424. MCCFIInstruction::cfiDefCfaOffset(Label, Offset);
  425. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  426. if (!CurFrame)
  427. return;
  428. CurFrame->Instructions.push_back(Instruction);
  429. }
  430. void MCStreamer::emitCFIAdjustCfaOffset(int64_t Adjustment) {
  431. MCSymbol *Label = emitCFILabel();
  432. MCCFIInstruction Instruction =
  433. MCCFIInstruction::createAdjustCfaOffset(Label, Adjustment);
  434. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  435. if (!CurFrame)
  436. return;
  437. CurFrame->Instructions.push_back(Instruction);
  438. }
  439. void MCStreamer::emitCFIDefCfaRegister(int64_t Register) {
  440. MCSymbol *Label = emitCFILabel();
  441. MCCFIInstruction Instruction =
  442. MCCFIInstruction::createDefCfaRegister(Label, Register);
  443. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  444. if (!CurFrame)
  445. return;
  446. CurFrame->Instructions.push_back(Instruction);
  447. CurFrame->CurrentCfaRegister = static_cast<unsigned>(Register);
  448. }
  449. void MCStreamer::emitCFILLVMDefAspaceCfa(int64_t Register, int64_t Offset,
  450. int64_t AddressSpace) {
  451. MCSymbol *Label = emitCFILabel();
  452. MCCFIInstruction Instruction = MCCFIInstruction::createLLVMDefAspaceCfa(
  453. Label, Register, Offset, AddressSpace);
  454. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  455. if (!CurFrame)
  456. return;
  457. CurFrame->Instructions.push_back(Instruction);
  458. CurFrame->CurrentCfaRegister = static_cast<unsigned>(Register);
  459. }
  460. void MCStreamer::emitCFIOffset(int64_t Register, int64_t Offset) {
  461. MCSymbol *Label = emitCFILabel();
  462. MCCFIInstruction Instruction =
  463. MCCFIInstruction::createOffset(Label, Register, Offset);
  464. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  465. if (!CurFrame)
  466. return;
  467. CurFrame->Instructions.push_back(Instruction);
  468. }
  469. void MCStreamer::emitCFIRelOffset(int64_t Register, int64_t Offset) {
  470. MCSymbol *Label = emitCFILabel();
  471. MCCFIInstruction Instruction =
  472. MCCFIInstruction::createRelOffset(Label, Register, Offset);
  473. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  474. if (!CurFrame)
  475. return;
  476. CurFrame->Instructions.push_back(Instruction);
  477. }
  478. void MCStreamer::emitCFIPersonality(const MCSymbol *Sym,
  479. unsigned Encoding) {
  480. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  481. if (!CurFrame)
  482. return;
  483. CurFrame->Personality = Sym;
  484. CurFrame->PersonalityEncoding = Encoding;
  485. }
  486. void MCStreamer::emitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
  487. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  488. if (!CurFrame)
  489. return;
  490. CurFrame->Lsda = Sym;
  491. CurFrame->LsdaEncoding = Encoding;
  492. }
  493. void MCStreamer::emitCFIRememberState() {
  494. MCSymbol *Label = emitCFILabel();
  495. MCCFIInstruction Instruction = MCCFIInstruction::createRememberState(Label);
  496. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  497. if (!CurFrame)
  498. return;
  499. CurFrame->Instructions.push_back(Instruction);
  500. }
  501. void MCStreamer::emitCFIRestoreState() {
  502. // FIXME: Error if there is no matching cfi_remember_state.
  503. MCSymbol *Label = emitCFILabel();
  504. MCCFIInstruction Instruction = MCCFIInstruction::createRestoreState(Label);
  505. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  506. if (!CurFrame)
  507. return;
  508. CurFrame->Instructions.push_back(Instruction);
  509. }
  510. void MCStreamer::emitCFISameValue(int64_t Register) {
  511. MCSymbol *Label = emitCFILabel();
  512. MCCFIInstruction Instruction =
  513. MCCFIInstruction::createSameValue(Label, Register);
  514. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  515. if (!CurFrame)
  516. return;
  517. CurFrame->Instructions.push_back(Instruction);
  518. }
  519. void MCStreamer::emitCFIRestore(int64_t Register) {
  520. MCSymbol *Label = emitCFILabel();
  521. MCCFIInstruction Instruction =
  522. MCCFIInstruction::createRestore(Label, Register);
  523. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  524. if (!CurFrame)
  525. return;
  526. CurFrame->Instructions.push_back(Instruction);
  527. }
  528. void MCStreamer::emitCFIEscape(StringRef Values) {
  529. MCSymbol *Label = emitCFILabel();
  530. MCCFIInstruction Instruction = MCCFIInstruction::createEscape(Label, Values);
  531. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  532. if (!CurFrame)
  533. return;
  534. CurFrame->Instructions.push_back(Instruction);
  535. }
  536. void MCStreamer::emitCFIGnuArgsSize(int64_t Size) {
  537. MCSymbol *Label = emitCFILabel();
  538. MCCFIInstruction Instruction =
  539. MCCFIInstruction::createGnuArgsSize(Label, Size);
  540. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  541. if (!CurFrame)
  542. return;
  543. CurFrame->Instructions.push_back(Instruction);
  544. }
  545. void MCStreamer::emitCFISignalFrame() {
  546. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  547. if (!CurFrame)
  548. return;
  549. CurFrame->IsSignalFrame = true;
  550. }
  551. void MCStreamer::emitCFIUndefined(int64_t Register) {
  552. MCSymbol *Label = emitCFILabel();
  553. MCCFIInstruction Instruction =
  554. MCCFIInstruction::createUndefined(Label, Register);
  555. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  556. if (!CurFrame)
  557. return;
  558. CurFrame->Instructions.push_back(Instruction);
  559. }
  560. void MCStreamer::emitCFIRegister(int64_t Register1, int64_t Register2) {
  561. MCSymbol *Label = emitCFILabel();
  562. MCCFIInstruction Instruction =
  563. MCCFIInstruction::createRegister(Label, Register1, Register2);
  564. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  565. if (!CurFrame)
  566. return;
  567. CurFrame->Instructions.push_back(Instruction);
  568. }
  569. void MCStreamer::emitCFIWindowSave() {
  570. MCSymbol *Label = emitCFILabel();
  571. MCCFIInstruction Instruction =
  572. MCCFIInstruction::createWindowSave(Label);
  573. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  574. if (!CurFrame)
  575. return;
  576. CurFrame->Instructions.push_back(Instruction);
  577. }
  578. void MCStreamer::emitCFINegateRAState() {
  579. MCSymbol *Label = emitCFILabel();
  580. MCCFIInstruction Instruction = MCCFIInstruction::createNegateRAState(Label);
  581. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  582. if (!CurFrame)
  583. return;
  584. CurFrame->Instructions.push_back(Instruction);
  585. }
  586. void MCStreamer::emitCFIReturnColumn(int64_t Register) {
  587. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  588. if (!CurFrame)
  589. return;
  590. CurFrame->RAReg = Register;
  591. }
  592. WinEH::FrameInfo *MCStreamer::EnsureValidWinFrameInfo(SMLoc Loc) {
  593. const MCAsmInfo *MAI = Context.getAsmInfo();
  594. if (!MAI->usesWindowsCFI()) {
  595. getContext().reportError(
  596. Loc, ".seh_* directives are not supported on this target");
  597. return nullptr;
  598. }
  599. if (!CurrentWinFrameInfo || CurrentWinFrameInfo->End) {
  600. getContext().reportError(
  601. Loc, ".seh_ directive must appear within an active frame");
  602. return nullptr;
  603. }
  604. return CurrentWinFrameInfo;
  605. }
  606. void MCStreamer::emitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) {
  607. const MCAsmInfo *MAI = Context.getAsmInfo();
  608. if (!MAI->usesWindowsCFI())
  609. return getContext().reportError(
  610. Loc, ".seh_* directives are not supported on this target");
  611. if (CurrentWinFrameInfo && !CurrentWinFrameInfo->End)
  612. getContext().reportError(
  613. Loc, "Starting a function before ending the previous one!");
  614. MCSymbol *StartProc = emitCFILabel();
  615. CurrentProcWinFrameInfoStartIndex = WinFrameInfos.size();
  616. WinFrameInfos.emplace_back(
  617. std::make_unique<WinEH::FrameInfo>(Symbol, StartProc));
  618. CurrentWinFrameInfo = WinFrameInfos.back().get();
  619. CurrentWinFrameInfo->TextSection = getCurrentSectionOnly();
  620. }
  621. void MCStreamer::emitWinCFIEndProc(SMLoc Loc) {
  622. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  623. if (!CurFrame)
  624. return;
  625. if (CurFrame->ChainedParent)
  626. getContext().reportError(Loc, "Not all chained regions terminated!");
  627. MCSymbol *Label = emitCFILabel();
  628. CurFrame->End = Label;
  629. if (!CurFrame->FuncletOrFuncEnd)
  630. CurFrame->FuncletOrFuncEnd = CurFrame->End;
  631. for (size_t I = CurrentProcWinFrameInfoStartIndex, E = WinFrameInfos.size();
  632. I != E; ++I)
  633. emitWindowsUnwindTables(WinFrameInfos[I].get());
  634. switchSection(CurFrame->TextSection);
  635. }
  636. void MCStreamer::emitWinCFIFuncletOrFuncEnd(SMLoc Loc) {
  637. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  638. if (!CurFrame)
  639. return;
  640. if (CurFrame->ChainedParent)
  641. getContext().reportError(Loc, "Not all chained regions terminated!");
  642. MCSymbol *Label = emitCFILabel();
  643. CurFrame->FuncletOrFuncEnd = Label;
  644. }
  645. void MCStreamer::emitWinCFIStartChained(SMLoc Loc) {
  646. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  647. if (!CurFrame)
  648. return;
  649. MCSymbol *StartProc = emitCFILabel();
  650. WinFrameInfos.emplace_back(std::make_unique<WinEH::FrameInfo>(
  651. CurFrame->Function, StartProc, CurFrame));
  652. CurrentWinFrameInfo = WinFrameInfos.back().get();
  653. CurrentWinFrameInfo->TextSection = getCurrentSectionOnly();
  654. }
  655. void MCStreamer::emitWinCFIEndChained(SMLoc Loc) {
  656. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  657. if (!CurFrame)
  658. return;
  659. if (!CurFrame->ChainedParent)
  660. return getContext().reportError(
  661. Loc, "End of a chained region outside a chained region!");
  662. MCSymbol *Label = emitCFILabel();
  663. CurFrame->End = Label;
  664. CurrentWinFrameInfo = const_cast<WinEH::FrameInfo *>(CurFrame->ChainedParent);
  665. }
  666. void MCStreamer::emitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except,
  667. SMLoc Loc) {
  668. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  669. if (!CurFrame)
  670. return;
  671. if (CurFrame->ChainedParent)
  672. return getContext().reportError(
  673. Loc, "Chained unwind areas can't have handlers!");
  674. CurFrame->ExceptionHandler = Sym;
  675. if (!Except && !Unwind)
  676. getContext().reportError(Loc, "Don't know what kind of handler this is!");
  677. if (Unwind)
  678. CurFrame->HandlesUnwind = true;
  679. if (Except)
  680. CurFrame->HandlesExceptions = true;
  681. }
  682. void MCStreamer::emitWinEHHandlerData(SMLoc Loc) {
  683. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  684. if (!CurFrame)
  685. return;
  686. if (CurFrame->ChainedParent)
  687. getContext().reportError(Loc, "Chained unwind areas can't have handlers!");
  688. }
  689. void MCStreamer::emitCGProfileEntry(const MCSymbolRefExpr *From,
  690. const MCSymbolRefExpr *To, uint64_t Count) {
  691. }
  692. static MCSection *getWinCFISection(MCContext &Context, unsigned *NextWinCFIID,
  693. MCSection *MainCFISec,
  694. const MCSection *TextSec) {
  695. // If this is the main .text section, use the main unwind info section.
  696. if (TextSec == Context.getObjectFileInfo()->getTextSection())
  697. return MainCFISec;
  698. const auto *TextSecCOFF = cast<MCSectionCOFF>(TextSec);
  699. auto *MainCFISecCOFF = cast<MCSectionCOFF>(MainCFISec);
  700. unsigned UniqueID = TextSecCOFF->getOrAssignWinCFISectionID(NextWinCFIID);
  701. // If this section is COMDAT, this unwind section should be COMDAT associative
  702. // with its group.
  703. const MCSymbol *KeySym = nullptr;
  704. if (TextSecCOFF->getCharacteristics() & COFF::IMAGE_SCN_LNK_COMDAT) {
  705. KeySym = TextSecCOFF->getCOMDATSymbol();
  706. // In a GNU environment, we can't use associative comdats. Instead, do what
  707. // GCC does, which is to make plain comdat selectany section named like
  708. // ".[px]data$_Z3foov".
  709. if (!Context.getAsmInfo()->hasCOFFAssociativeComdats()) {
  710. std::string SectionName = (MainCFISecCOFF->getName() + "$" +
  711. TextSecCOFF->getName().split('$').second)
  712. .str();
  713. return Context.getCOFFSection(
  714. SectionName,
  715. MainCFISecCOFF->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT,
  716. MainCFISecCOFF->getKind(), "", COFF::IMAGE_COMDAT_SELECT_ANY);
  717. }
  718. }
  719. return Context.getAssociativeCOFFSection(MainCFISecCOFF, KeySym, UniqueID);
  720. }
  721. MCSection *MCStreamer::getAssociatedPDataSection(const MCSection *TextSec) {
  722. return getWinCFISection(getContext(), &NextWinCFIID,
  723. getContext().getObjectFileInfo()->getPDataSection(),
  724. TextSec);
  725. }
  726. MCSection *MCStreamer::getAssociatedXDataSection(const MCSection *TextSec) {
  727. return getWinCFISection(getContext(), &NextWinCFIID,
  728. getContext().getObjectFileInfo()->getXDataSection(),
  729. TextSec);
  730. }
  731. void MCStreamer::emitSyntaxDirective() {}
  732. static unsigned encodeSEHRegNum(MCContext &Ctx, MCRegister Reg) {
  733. return Ctx.getRegisterInfo()->getSEHRegNum(Reg);
  734. }
  735. void MCStreamer::emitWinCFIPushReg(MCRegister Register, SMLoc Loc) {
  736. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  737. if (!CurFrame)
  738. return;
  739. MCSymbol *Label = emitCFILabel();
  740. WinEH::Instruction Inst = Win64EH::Instruction::PushNonVol(
  741. Label, encodeSEHRegNum(Context, Register));
  742. CurFrame->Instructions.push_back(Inst);
  743. }
  744. void MCStreamer::emitWinCFISetFrame(MCRegister Register, unsigned Offset,
  745. SMLoc Loc) {
  746. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  747. if (!CurFrame)
  748. return;
  749. if (CurFrame->LastFrameInst >= 0)
  750. return getContext().reportError(
  751. Loc, "frame register and offset can be set at most once");
  752. if (Offset & 0x0F)
  753. return getContext().reportError(Loc, "offset is not a multiple of 16");
  754. if (Offset > 240)
  755. return getContext().reportError(
  756. Loc, "frame offset must be less than or equal to 240");
  757. MCSymbol *Label = emitCFILabel();
  758. WinEH::Instruction Inst = Win64EH::Instruction::SetFPReg(
  759. Label, encodeSEHRegNum(getContext(), Register), Offset);
  760. CurFrame->LastFrameInst = CurFrame->Instructions.size();
  761. CurFrame->Instructions.push_back(Inst);
  762. }
  763. void MCStreamer::emitWinCFIAllocStack(unsigned Size, SMLoc Loc) {
  764. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  765. if (!CurFrame)
  766. return;
  767. if (Size == 0)
  768. return getContext().reportError(Loc,
  769. "stack allocation size must be non-zero");
  770. if (Size & 7)
  771. return getContext().reportError(
  772. Loc, "stack allocation size is not a multiple of 8");
  773. MCSymbol *Label = emitCFILabel();
  774. WinEH::Instruction Inst = Win64EH::Instruction::Alloc(Label, Size);
  775. CurFrame->Instructions.push_back(Inst);
  776. }
  777. void MCStreamer::emitWinCFISaveReg(MCRegister Register, unsigned Offset,
  778. SMLoc Loc) {
  779. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  780. if (!CurFrame)
  781. return;
  782. if (Offset & 7)
  783. return getContext().reportError(
  784. Loc, "register save offset is not 8 byte aligned");
  785. MCSymbol *Label = emitCFILabel();
  786. WinEH::Instruction Inst = Win64EH::Instruction::SaveNonVol(
  787. Label, encodeSEHRegNum(Context, Register), Offset);
  788. CurFrame->Instructions.push_back(Inst);
  789. }
  790. void MCStreamer::emitWinCFISaveXMM(MCRegister Register, unsigned Offset,
  791. SMLoc Loc) {
  792. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  793. if (!CurFrame)
  794. return;
  795. if (Offset & 0x0F)
  796. return getContext().reportError(Loc, "offset is not a multiple of 16");
  797. MCSymbol *Label = emitCFILabel();
  798. WinEH::Instruction Inst = Win64EH::Instruction::SaveXMM(
  799. Label, encodeSEHRegNum(Context, Register), Offset);
  800. CurFrame->Instructions.push_back(Inst);
  801. }
  802. void MCStreamer::emitWinCFIPushFrame(bool Code, SMLoc Loc) {
  803. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  804. if (!CurFrame)
  805. return;
  806. if (!CurFrame->Instructions.empty())
  807. return getContext().reportError(
  808. Loc, "If present, PushMachFrame must be the first UOP");
  809. MCSymbol *Label = emitCFILabel();
  810. WinEH::Instruction Inst = Win64EH::Instruction::PushMachFrame(Label, Code);
  811. CurFrame->Instructions.push_back(Inst);
  812. }
  813. void MCStreamer::emitWinCFIEndProlog(SMLoc Loc) {
  814. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  815. if (!CurFrame)
  816. return;
  817. MCSymbol *Label = emitCFILabel();
  818. CurFrame->PrologEnd = Label;
  819. }
  820. void MCStreamer::emitCOFFSafeSEH(MCSymbol const *Symbol) {}
  821. void MCStreamer::emitCOFFSymbolIndex(MCSymbol const *Symbol) {}
  822. void MCStreamer::emitCOFFSectionIndex(MCSymbol const *Symbol) {}
  823. void MCStreamer::emitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) {}
  824. void MCStreamer::emitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset) {}
  825. /// EmitRawText - If this file is backed by an assembly streamer, this dumps
  826. /// the specified string in the output .s file. This capability is
  827. /// indicated by the hasRawTextSupport() predicate.
  828. void MCStreamer::emitRawTextImpl(StringRef String) {
  829. // This is not llvm_unreachable for the sake of out of tree backend
  830. // developers who may not have assembly streamers and should serve as a
  831. // reminder to not accidentally call EmitRawText in the absence of such.
  832. report_fatal_error("EmitRawText called on an MCStreamer that doesn't support "
  833. "it (target backend is likely missing an AsmStreamer "
  834. "implementation)");
  835. }
  836. void MCStreamer::emitRawText(const Twine &T) {
  837. SmallString<128> Str;
  838. emitRawTextImpl(T.toStringRef(Str));
  839. }
  840. void MCStreamer::emitWindowsUnwindTables() {}
  841. void MCStreamer::emitWindowsUnwindTables(WinEH::FrameInfo *Frame) {}
  842. void MCStreamer::finish(SMLoc EndLoc) {
  843. if ((!DwarfFrameInfos.empty() && !DwarfFrameInfos.back().End) ||
  844. (!WinFrameInfos.empty() && !WinFrameInfos.back()->End)) {
  845. getContext().reportError(EndLoc, "Unfinished frame!");
  846. return;
  847. }
  848. MCTargetStreamer *TS = getTargetStreamer();
  849. if (TS)
  850. TS->finish();
  851. finishImpl();
  852. }
  853. void MCStreamer::maybeEmitDwarf64Mark() {
  854. if (Context.getDwarfFormat() != dwarf::DWARF64)
  855. return;
  856. AddComment("DWARF64 Mark");
  857. emitInt32(dwarf::DW_LENGTH_DWARF64);
  858. }
  859. void MCStreamer::emitDwarfUnitLength(uint64_t Length, const Twine &Comment) {
  860. assert(Context.getDwarfFormat() == dwarf::DWARF64 ||
  861. Length <= dwarf::DW_LENGTH_lo_reserved);
  862. maybeEmitDwarf64Mark();
  863. AddComment(Comment);
  864. emitIntValue(Length, dwarf::getDwarfOffsetByteSize(Context.getDwarfFormat()));
  865. }
  866. MCSymbol *MCStreamer::emitDwarfUnitLength(const Twine &Prefix,
  867. const Twine &Comment) {
  868. maybeEmitDwarf64Mark();
  869. AddComment(Comment);
  870. MCSymbol *Lo = Context.createTempSymbol(Prefix + "_start");
  871. MCSymbol *Hi = Context.createTempSymbol(Prefix + "_end");
  872. emitAbsoluteSymbolDiff(
  873. Hi, Lo, dwarf::getDwarfOffsetByteSize(Context.getDwarfFormat()));
  874. // emit the begin symbol after we generate the length field.
  875. emitLabel(Lo);
  876. // Return the Hi symbol to the caller.
  877. return Hi;
  878. }
  879. void MCStreamer::emitDwarfLineStartLabel(MCSymbol *StartSym) {
  880. // Set the value of the symbol, as we are at the start of the line table.
  881. emitLabel(StartSym);
  882. }
  883. void MCStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
  884. visitUsedExpr(*Value);
  885. Symbol->setVariableValue(Value);
  886. MCTargetStreamer *TS = getTargetStreamer();
  887. if (TS)
  888. TS->emitAssignment(Symbol, Value);
  889. }
  890. void MCTargetStreamer::prettyPrintAsm(MCInstPrinter &InstPrinter,
  891. uint64_t Address, const MCInst &Inst,
  892. const MCSubtargetInfo &STI,
  893. raw_ostream &OS) {
  894. InstPrinter.printInst(&Inst, Address, "", STI, OS);
  895. }
  896. void MCStreamer::visitUsedSymbol(const MCSymbol &Sym) {
  897. }
  898. void MCStreamer::visitUsedExpr(const MCExpr &Expr) {
  899. switch (Expr.getKind()) {
  900. case MCExpr::Target:
  901. cast<MCTargetExpr>(Expr).visitUsedExpr(*this);
  902. break;
  903. case MCExpr::Constant:
  904. break;
  905. case MCExpr::Binary: {
  906. const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
  907. visitUsedExpr(*BE.getLHS());
  908. visitUsedExpr(*BE.getRHS());
  909. break;
  910. }
  911. case MCExpr::SymbolRef:
  912. visitUsedSymbol(cast<MCSymbolRefExpr>(Expr).getSymbol());
  913. break;
  914. case MCExpr::Unary:
  915. visitUsedExpr(*cast<MCUnaryExpr>(Expr).getSubExpr());
  916. break;
  917. }
  918. }
  919. void MCStreamer::emitInstruction(const MCInst &Inst, const MCSubtargetInfo &) {
  920. // Scan for values.
  921. for (unsigned i = Inst.getNumOperands(); i--;)
  922. if (Inst.getOperand(i).isExpr())
  923. visitUsedExpr(*Inst.getOperand(i).getExpr());
  924. }
  925. void MCStreamer::emitPseudoProbe(uint64_t Guid, uint64_t Index, uint64_t Type,
  926. uint64_t Attr,
  927. const MCPseudoProbeInlineStack &InlineStack,
  928. MCSymbol *FnSym) {
  929. auto &Context = getContext();
  930. // Create a symbol at in the current section for use in the probe.
  931. MCSymbol *ProbeSym = Context.createTempSymbol();
  932. // Set the value of the symbol to use for the MCPseudoProbe.
  933. emitLabel(ProbeSym);
  934. // Create a (local) probe entry with the symbol.
  935. MCPseudoProbe Probe(ProbeSym, Guid, Index, Type, Attr);
  936. // Add the probe entry to this section's entries.
  937. Context.getMCPseudoProbeTable().getProbeSections().addPseudoProbe(
  938. FnSym, Probe, InlineStack);
  939. }
  940. void MCStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo,
  941. unsigned Size) {
  942. // Get the Hi-Lo expression.
  943. const MCExpr *Diff =
  944. MCBinaryExpr::createSub(MCSymbolRefExpr::create(Hi, Context),
  945. MCSymbolRefExpr::create(Lo, Context), Context);
  946. const MCAsmInfo *MAI = Context.getAsmInfo();
  947. if (!MAI->doesSetDirectiveSuppressReloc()) {
  948. emitValue(Diff, Size);
  949. return;
  950. }
  951. // Otherwise, emit with .set (aka assignment).
  952. MCSymbol *SetLabel = Context.createTempSymbol("set");
  953. emitAssignment(SetLabel, Diff);
  954. emitSymbolValue(SetLabel, Size);
  955. }
  956. void MCStreamer::emitAbsoluteSymbolDiffAsULEB128(const MCSymbol *Hi,
  957. const MCSymbol *Lo) {
  958. // Get the Hi-Lo expression.
  959. const MCExpr *Diff =
  960. MCBinaryExpr::createSub(MCSymbolRefExpr::create(Hi, Context),
  961. MCSymbolRefExpr::create(Lo, Context), Context);
  962. emitULEB128Value(Diff);
  963. }
  964. void MCStreamer::emitAssemblerFlag(MCAssemblerFlag Flag) {}
  965. void MCStreamer::emitThumbFunc(MCSymbol *Func) {}
  966. void MCStreamer::emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
  967. void MCStreamer::beginCOFFSymbolDef(const MCSymbol *Symbol) {
  968. llvm_unreachable("this directive only supported on COFF targets");
  969. }
  970. void MCStreamer::endCOFFSymbolDef() {
  971. llvm_unreachable("this directive only supported on COFF targets");
  972. }
  973. void MCStreamer::emitFileDirective(StringRef Filename) {}
  974. void MCStreamer::emitFileDirective(StringRef Filename, StringRef CompilerVerion,
  975. StringRef TimeStamp, StringRef Description) {
  976. }
  977. void MCStreamer::emitCOFFSymbolStorageClass(int StorageClass) {
  978. llvm_unreachable("this directive only supported on COFF targets");
  979. }
  980. void MCStreamer::emitCOFFSymbolType(int Type) {
  981. llvm_unreachable("this directive only supported on COFF targets");
  982. }
  983. void MCStreamer::emitXCOFFLocalCommonSymbol(MCSymbol *LabelSym, uint64_t Size,
  984. MCSymbol *CsectSym,
  985. Align Alignment) {
  986. llvm_unreachable("this directive only supported on XCOFF targets");
  987. }
  988. void MCStreamer::emitXCOFFSymbolLinkageWithVisibility(MCSymbol *Symbol,
  989. MCSymbolAttr Linkage,
  990. MCSymbolAttr Visibility) {
  991. llvm_unreachable("emitXCOFFSymbolLinkageWithVisibility is only supported on "
  992. "XCOFF targets");
  993. }
  994. void MCStreamer::emitXCOFFRenameDirective(const MCSymbol *Name,
  995. StringRef Rename) {
  996. llvm_unreachable("emitXCOFFRenameDirective is only supported on "
  997. "XCOFF targets");
  998. }
  999. void MCStreamer::emitXCOFFRefDirective(StringRef Name) {
  1000. llvm_unreachable("emitXCOFFRefDirective is only supported on XCOFF targets");
  1001. }
  1002. void MCStreamer::emitXCOFFExceptDirective(const MCSymbol *Symbol,
  1003. const MCSymbol *Trap,
  1004. unsigned Lang, unsigned Reason,
  1005. unsigned FunctionSize,
  1006. bool hasDebug) {
  1007. report_fatal_error("emitXCOFFExceptDirective is only supported on "
  1008. "XCOFF targets");
  1009. }
  1010. void MCStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
  1011. void MCStreamer::emitELFSymverDirective(const MCSymbol *OriginalSym,
  1012. StringRef Name, bool KeepOriginalSym) {}
  1013. void MCStreamer::emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
  1014. Align ByteAlignment) {}
  1015. void MCStreamer::emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
  1016. uint64_t Size, Align ByteAlignment) {}
  1017. void MCStreamer::changeSection(MCSection *, const MCExpr *) {}
  1018. void MCStreamer::emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
  1019. void MCStreamer::emitBytes(StringRef Data) {}
  1020. void MCStreamer::emitBinaryData(StringRef Data) { emitBytes(Data); }
  1021. void MCStreamer::emitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc) {
  1022. visitUsedExpr(*Value);
  1023. }
  1024. void MCStreamer::emitULEB128Value(const MCExpr *Value) {}
  1025. void MCStreamer::emitSLEB128Value(const MCExpr *Value) {}
  1026. void MCStreamer::emitFill(const MCExpr &NumBytes, uint64_t Value, SMLoc Loc) {}
  1027. void MCStreamer::emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr,
  1028. SMLoc Loc) {}
  1029. void MCStreamer::emitValueToAlignment(Align Alignment, int64_t Value,
  1030. unsigned ValueSize,
  1031. unsigned MaxBytesToEmit) {}
  1032. void MCStreamer::emitCodeAlignment(Align Alignment, const MCSubtargetInfo *STI,
  1033. unsigned MaxBytesToEmit) {}
  1034. void MCStreamer::emitValueToOffset(const MCExpr *Offset, unsigned char Value,
  1035. SMLoc Loc) {}
  1036. void MCStreamer::emitBundleAlignMode(Align Alignment) {}
  1037. void MCStreamer::emitBundleLock(bool AlignToEnd) {}
  1038. void MCStreamer::finishImpl() {}
  1039. void MCStreamer::emitBundleUnlock() {}
  1040. void MCStreamer::switchSection(MCSection *Section, const MCExpr *Subsection) {
  1041. assert(Section && "Cannot switch to a null section!");
  1042. MCSectionSubPair curSection = SectionStack.back().first;
  1043. SectionStack.back().second = curSection;
  1044. if (MCSectionSubPair(Section, Subsection) != curSection) {
  1045. changeSection(Section, Subsection);
  1046. SectionStack.back().first = MCSectionSubPair(Section, Subsection);
  1047. assert(!Section->hasEnded() && "Section already ended");
  1048. MCSymbol *Sym = Section->getBeginSymbol();
  1049. if (Sym && !Sym->isInSection())
  1050. emitLabel(Sym);
  1051. }
  1052. }
  1053. MCSymbol *MCStreamer::endSection(MCSection *Section) {
  1054. // TODO: keep track of the last subsection so that this symbol appears in the
  1055. // correct place.
  1056. MCSymbol *Sym = Section->getEndSymbol(Context);
  1057. if (Sym->isInSection())
  1058. return Sym;
  1059. switchSection(Section);
  1060. emitLabel(Sym);
  1061. return Sym;
  1062. }
  1063. static VersionTuple
  1064. targetVersionOrMinimumSupportedOSVersion(const Triple &Target,
  1065. VersionTuple TargetVersion) {
  1066. VersionTuple Min = Target.getMinimumSupportedOSVersion();
  1067. return !Min.empty() && Min > TargetVersion ? Min : TargetVersion;
  1068. }
  1069. static MCVersionMinType
  1070. getMachoVersionMinLoadCommandType(const Triple &Target) {
  1071. assert(Target.isOSDarwin() && "expected a darwin OS");
  1072. switch (Target.getOS()) {
  1073. case Triple::MacOSX:
  1074. case Triple::Darwin:
  1075. return MCVM_OSXVersionMin;
  1076. case Triple::IOS:
  1077. assert(!Target.isMacCatalystEnvironment() &&
  1078. "mac Catalyst should use LC_BUILD_VERSION");
  1079. return MCVM_IOSVersionMin;
  1080. case Triple::TvOS:
  1081. return MCVM_TvOSVersionMin;
  1082. case Triple::WatchOS:
  1083. return MCVM_WatchOSVersionMin;
  1084. default:
  1085. break;
  1086. }
  1087. llvm_unreachable("unexpected OS type");
  1088. }
  1089. static VersionTuple getMachoBuildVersionSupportedOS(const Triple &Target) {
  1090. assert(Target.isOSDarwin() && "expected a darwin OS");
  1091. switch (Target.getOS()) {
  1092. case Triple::MacOSX:
  1093. case Triple::Darwin:
  1094. return VersionTuple(10, 14);
  1095. case Triple::IOS:
  1096. // Mac Catalyst always uses the build version load command.
  1097. if (Target.isMacCatalystEnvironment())
  1098. return VersionTuple();
  1099. [[fallthrough]];
  1100. case Triple::TvOS:
  1101. return VersionTuple(12);
  1102. case Triple::WatchOS:
  1103. return VersionTuple(5);
  1104. case Triple::DriverKit:
  1105. // DriverKit always uses the build version load command.
  1106. return VersionTuple();
  1107. default:
  1108. break;
  1109. }
  1110. llvm_unreachable("unexpected OS type");
  1111. }
  1112. static MachO::PlatformType
  1113. getMachoBuildVersionPlatformType(const Triple &Target) {
  1114. assert(Target.isOSDarwin() && "expected a darwin OS");
  1115. switch (Target.getOS()) {
  1116. case Triple::MacOSX:
  1117. case Triple::Darwin:
  1118. return MachO::PLATFORM_MACOS;
  1119. case Triple::IOS:
  1120. if (Target.isMacCatalystEnvironment())
  1121. return MachO::PLATFORM_MACCATALYST;
  1122. return Target.isSimulatorEnvironment() ? MachO::PLATFORM_IOSSIMULATOR
  1123. : MachO::PLATFORM_IOS;
  1124. case Triple::TvOS:
  1125. return Target.isSimulatorEnvironment() ? MachO::PLATFORM_TVOSSIMULATOR
  1126. : MachO::PLATFORM_TVOS;
  1127. case Triple::WatchOS:
  1128. return Target.isSimulatorEnvironment() ? MachO::PLATFORM_WATCHOSSIMULATOR
  1129. : MachO::PLATFORM_WATCHOS;
  1130. case Triple::DriverKit:
  1131. return MachO::PLATFORM_DRIVERKIT;
  1132. default:
  1133. break;
  1134. }
  1135. llvm_unreachable("unexpected OS type");
  1136. }
  1137. void MCStreamer::emitVersionForTarget(
  1138. const Triple &Target, const VersionTuple &SDKVersion,
  1139. const Triple *DarwinTargetVariantTriple,
  1140. const VersionTuple &DarwinTargetVariantSDKVersion) {
  1141. if (!Target.isOSBinFormatMachO() || !Target.isOSDarwin())
  1142. return;
  1143. // Do we even know the version?
  1144. if (Target.getOSMajorVersion() == 0)
  1145. return;
  1146. VersionTuple Version;
  1147. switch (Target.getOS()) {
  1148. case Triple::MacOSX:
  1149. case Triple::Darwin:
  1150. Target.getMacOSXVersion(Version);
  1151. break;
  1152. case Triple::IOS:
  1153. case Triple::TvOS:
  1154. Version = Target.getiOSVersion();
  1155. break;
  1156. case Triple::WatchOS:
  1157. Version = Target.getWatchOSVersion();
  1158. break;
  1159. case Triple::DriverKit:
  1160. Version = Target.getDriverKitVersion();
  1161. break;
  1162. default:
  1163. llvm_unreachable("unexpected OS type");
  1164. }
  1165. assert(Version.getMajor() != 0 && "A non-zero major version is expected");
  1166. auto LinkedTargetVersion =
  1167. targetVersionOrMinimumSupportedOSVersion(Target, Version);
  1168. auto BuildVersionOSVersion = getMachoBuildVersionSupportedOS(Target);
  1169. bool ShouldEmitBuildVersion = false;
  1170. if (BuildVersionOSVersion.empty() ||
  1171. LinkedTargetVersion >= BuildVersionOSVersion) {
  1172. if (Target.isMacCatalystEnvironment() && DarwinTargetVariantTriple &&
  1173. DarwinTargetVariantTriple->isMacOSX()) {
  1174. emitVersionForTarget(*DarwinTargetVariantTriple,
  1175. DarwinTargetVariantSDKVersion,
  1176. /*DarwinTargetVariantTriple=*/nullptr,
  1177. /*DarwinTargetVariantSDKVersion=*/VersionTuple());
  1178. emitDarwinTargetVariantBuildVersion(
  1179. getMachoBuildVersionPlatformType(Target),
  1180. LinkedTargetVersion.getMajor(),
  1181. LinkedTargetVersion.getMinor().value_or(0),
  1182. LinkedTargetVersion.getSubminor().value_or(0), SDKVersion);
  1183. return;
  1184. }
  1185. emitBuildVersion(getMachoBuildVersionPlatformType(Target),
  1186. LinkedTargetVersion.getMajor(),
  1187. LinkedTargetVersion.getMinor().value_or(0),
  1188. LinkedTargetVersion.getSubminor().value_or(0), SDKVersion);
  1189. ShouldEmitBuildVersion = true;
  1190. }
  1191. if (const Triple *TVT = DarwinTargetVariantTriple) {
  1192. if (Target.isMacOSX() && TVT->isMacCatalystEnvironment()) {
  1193. auto TVLinkedTargetVersion =
  1194. targetVersionOrMinimumSupportedOSVersion(*TVT, TVT->getiOSVersion());
  1195. emitDarwinTargetVariantBuildVersion(
  1196. getMachoBuildVersionPlatformType(*TVT),
  1197. TVLinkedTargetVersion.getMajor(),
  1198. TVLinkedTargetVersion.getMinor().value_or(0),
  1199. TVLinkedTargetVersion.getSubminor().value_or(0),
  1200. DarwinTargetVariantSDKVersion);
  1201. }
  1202. }
  1203. if (ShouldEmitBuildVersion)
  1204. return;
  1205. emitVersionMin(getMachoVersionMinLoadCommandType(Target),
  1206. LinkedTargetVersion.getMajor(),
  1207. LinkedTargetVersion.getMinor().value_or(0),
  1208. LinkedTargetVersion.getSubminor().value_or(0), SDKVersion);
  1209. }