MCStreamer.cpp 48 KB

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