MCAsmStreamer.cpp 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513
  1. //===- lib/MC/MCAsmStreamer.cpp - Text Assembly Output ----------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "llvm/ADT/Optional.h"
  9. #include "llvm/ADT/STLExtras.h"
  10. #include "llvm/ADT/SmallString.h"
  11. #include "llvm/ADT/StringExtras.h"
  12. #include "llvm/ADT/Twine.h"
  13. #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
  14. #include "llvm/MC/MCAsmBackend.h"
  15. #include "llvm/MC/MCAsmInfo.h"
  16. #include "llvm/MC/MCAssembler.h"
  17. #include "llvm/MC/MCCodeEmitter.h"
  18. #include "llvm/MC/MCCodeView.h"
  19. #include "llvm/MC/MCContext.h"
  20. #include "llvm/MC/MCExpr.h"
  21. #include "llvm/MC/MCFixupKindInfo.h"
  22. #include "llvm/MC/MCInst.h"
  23. #include "llvm/MC/MCInstPrinter.h"
  24. #include "llvm/MC/MCObjectFileInfo.h"
  25. #include "llvm/MC/MCObjectWriter.h"
  26. #include "llvm/MC/MCPseudoProbe.h"
  27. #include "llvm/MC/MCRegister.h"
  28. #include "llvm/MC/MCRegisterInfo.h"
  29. #include "llvm/MC/MCSectionMachO.h"
  30. #include "llvm/MC/MCStreamer.h"
  31. #include "llvm/MC/MCSymbolXCOFF.h"
  32. #include "llvm/MC/TargetRegistry.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. #include "llvm/Support/Format.h"
  35. #include "llvm/Support/FormattedStream.h"
  36. #include "llvm/Support/LEB128.h"
  37. #include "llvm/Support/MathExtras.h"
  38. #include "llvm/Support/Path.h"
  39. #include <cctype>
  40. using namespace llvm;
  41. namespace {
  42. class MCAsmStreamer final : public MCStreamer {
  43. std::unique_ptr<formatted_raw_ostream> OSOwner;
  44. formatted_raw_ostream &OS;
  45. const MCAsmInfo *MAI;
  46. std::unique_ptr<MCInstPrinter> InstPrinter;
  47. std::unique_ptr<MCAssembler> Assembler;
  48. SmallString<128> ExplicitCommentToEmit;
  49. SmallString<128> CommentToEmit;
  50. raw_svector_ostream CommentStream;
  51. raw_null_ostream NullStream;
  52. unsigned IsVerboseAsm : 1;
  53. unsigned ShowInst : 1;
  54. unsigned UseDwarfDirectory : 1;
  55. void EmitRegisterName(int64_t Register);
  56. void PrintQuotedString(StringRef Data, raw_ostream &OS) const;
  57. void printDwarfFileDirective(unsigned FileNo, StringRef Directory,
  58. StringRef Filename,
  59. Optional<MD5::MD5Result> Checksum,
  60. Optional<StringRef> Source,
  61. bool UseDwarfDirectory,
  62. raw_svector_ostream &OS) const;
  63. void emitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override;
  64. void emitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override;
  65. public:
  66. MCAsmStreamer(MCContext &Context, std::unique_ptr<formatted_raw_ostream> os,
  67. bool isVerboseAsm, bool useDwarfDirectory,
  68. MCInstPrinter *printer, std::unique_ptr<MCCodeEmitter> emitter,
  69. std::unique_ptr<MCAsmBackend> asmbackend, bool showInst)
  70. : MCStreamer(Context), OSOwner(std::move(os)), OS(*OSOwner),
  71. MAI(Context.getAsmInfo()), InstPrinter(printer),
  72. Assembler(std::make_unique<MCAssembler>(
  73. Context, std::move(asmbackend), std::move(emitter),
  74. (asmbackend) ? asmbackend->createObjectWriter(NullStream)
  75. : nullptr)),
  76. CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
  77. ShowInst(showInst), UseDwarfDirectory(useDwarfDirectory) {
  78. assert(InstPrinter);
  79. if (IsVerboseAsm)
  80. InstPrinter->setCommentStream(CommentStream);
  81. if (Assembler->getBackendPtr())
  82. setAllowAutoPadding(Assembler->getBackend().allowAutoPadding());
  83. Context.setUseNamesOnTempLabels(true);
  84. }
  85. MCAssembler &getAssembler() { return *Assembler; }
  86. MCAssembler *getAssemblerPtr() override { return nullptr; }
  87. inline void EmitEOL() {
  88. // Dump Explicit Comments here.
  89. emitExplicitComments();
  90. // If we don't have any comments, just emit a \n.
  91. if (!IsVerboseAsm) {
  92. OS << '\n';
  93. return;
  94. }
  95. EmitCommentsAndEOL();
  96. }
  97. void emitSyntaxDirective() override;
  98. void EmitCommentsAndEOL();
  99. /// Return true if this streamer supports verbose assembly at all.
  100. bool isVerboseAsm() const override { return IsVerboseAsm; }
  101. /// Do we support EmitRawText?
  102. bool hasRawTextSupport() const override { return true; }
  103. /// Add a comment that can be emitted to the generated .s file to make the
  104. /// output of the compiler more readable. This only affects the MCAsmStreamer
  105. /// and only when verbose assembly output is enabled.
  106. void AddComment(const Twine &T, bool EOL = true) override;
  107. /// Add a comment showing the encoding of an instruction.
  108. void AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &);
  109. /// Return a raw_ostream that comments can be written to.
  110. /// Unlike AddComment, you are required to terminate comments with \n if you
  111. /// use this method.
  112. raw_ostream &GetCommentOS() override {
  113. if (!IsVerboseAsm)
  114. return nulls(); // Discard comments unless in verbose asm mode.
  115. return CommentStream;
  116. }
  117. void emitRawComment(const Twine &T, bool TabPrefix = true) override;
  118. void addExplicitComment(const Twine &T) override;
  119. void emitExplicitComments() override;
  120. /// Emit a blank line to a .s file to pretty it up.
  121. void AddBlankLine() override {
  122. EmitEOL();
  123. }
  124. /// @name MCStreamer Interface
  125. /// @{
  126. void changeSection(MCSection *Section, const MCExpr *Subsection) override;
  127. void emitELFSymverDirective(const MCSymbol *OriginalSym, StringRef Name,
  128. bool KeepOriginalSym) override;
  129. void emitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override;
  130. void emitGNUAttribute(unsigned Tag, unsigned Value) override;
  131. StringRef getMnemonic(MCInst &MI) override {
  132. return InstPrinter->getMnemonic(&MI).first;
  133. }
  134. void emitLabel(MCSymbol *Symbol, SMLoc Loc = SMLoc()) override;
  135. void emitAssemblerFlag(MCAssemblerFlag Flag) override;
  136. void emitLinkerOptions(ArrayRef<std::string> Options) override;
  137. void emitDataRegion(MCDataRegionType Kind) override;
  138. void emitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor,
  139. unsigned Update, VersionTuple SDKVersion) override;
  140. void emitBuildVersion(unsigned Platform, unsigned Major, unsigned Minor,
  141. unsigned Update, VersionTuple SDKVersion) override;
  142. void emitDarwinTargetVariantBuildVersion(unsigned Platform, unsigned Major,
  143. unsigned Minor, unsigned Update,
  144. VersionTuple SDKVersion) override;
  145. void emitThumbFunc(MCSymbol *Func) override;
  146. void emitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
  147. void emitConditionalAssignment(MCSymbol *Symbol,
  148. const MCExpr *Value) override;
  149. void emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override;
  150. bool emitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
  151. void emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
  152. void BeginCOFFSymbolDef(const MCSymbol *Symbol) override;
  153. void EmitCOFFSymbolStorageClass(int StorageClass) override;
  154. void EmitCOFFSymbolType(int Type) override;
  155. void EndCOFFSymbolDef() override;
  156. void EmitCOFFSafeSEH(MCSymbol const *Symbol) override;
  157. void EmitCOFFSymbolIndex(MCSymbol const *Symbol) override;
  158. void EmitCOFFSectionIndex(MCSymbol const *Symbol) override;
  159. void EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) override;
  160. void EmitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset) override;
  161. void emitXCOFFLocalCommonSymbol(MCSymbol *LabelSym, uint64_t Size,
  162. MCSymbol *CsectSym,
  163. unsigned ByteAlign) override;
  164. void emitXCOFFSymbolLinkageWithVisibility(MCSymbol *Symbol,
  165. MCSymbolAttr Linakge,
  166. MCSymbolAttr Visibility) override;
  167. void emitXCOFFRenameDirective(const MCSymbol *Name,
  168. StringRef Rename) override;
  169. void emitELFSize(MCSymbol *Symbol, const MCExpr *Value) override;
  170. void emitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
  171. unsigned ByteAlignment) override;
  172. /// Emit a local common (.lcomm) symbol.
  173. ///
  174. /// @param Symbol - The common symbol to emit.
  175. /// @param Size - The size of the common symbol.
  176. /// @param ByteAlignment - The alignment of the common symbol in bytes.
  177. void emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
  178. unsigned ByteAlignment) override;
  179. void emitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
  180. uint64_t Size = 0, unsigned ByteAlignment = 0,
  181. SMLoc Loc = SMLoc()) override;
  182. void emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
  183. unsigned ByteAlignment = 0) override;
  184. void emitBinaryData(StringRef Data) override;
  185. void emitBytes(StringRef Data) override;
  186. void emitValueImpl(const MCExpr *Value, unsigned Size,
  187. SMLoc Loc = SMLoc()) override;
  188. void emitIntValue(uint64_t Value, unsigned Size) override;
  189. void emitIntValueInHex(uint64_t Value, unsigned Size) override;
  190. void emitIntValueInHexWithPadding(uint64_t Value, unsigned Size) override;
  191. void emitULEB128Value(const MCExpr *Value) override;
  192. void emitSLEB128Value(const MCExpr *Value) override;
  193. void emitDTPRel32Value(const MCExpr *Value) override;
  194. void emitDTPRel64Value(const MCExpr *Value) override;
  195. void emitTPRel32Value(const MCExpr *Value) override;
  196. void emitTPRel64Value(const MCExpr *Value) override;
  197. void emitGPRel64Value(const MCExpr *Value) override;
  198. void emitGPRel32Value(const MCExpr *Value) override;
  199. void emitFill(const MCExpr &NumBytes, uint64_t FillValue,
  200. SMLoc Loc = SMLoc()) override;
  201. void emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr,
  202. SMLoc Loc = SMLoc()) override;
  203. void emitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
  204. unsigned ValueSize = 1,
  205. unsigned MaxBytesToEmit = 0) override;
  206. void emitCodeAlignment(unsigned ByteAlignment, const MCSubtargetInfo *STI,
  207. unsigned MaxBytesToEmit = 0) override;
  208. void emitValueToOffset(const MCExpr *Offset,
  209. unsigned char Value,
  210. SMLoc Loc) override;
  211. void emitFileDirective(StringRef Filename) override;
  212. void emitFileDirective(StringRef Filename, StringRef CompilerVerion,
  213. StringRef TimeStamp, StringRef Description) override;
  214. Expected<unsigned> tryEmitDwarfFileDirective(unsigned FileNo,
  215. StringRef Directory,
  216. StringRef Filename,
  217. Optional<MD5::MD5Result> Checksum = None,
  218. Optional<StringRef> Source = None,
  219. unsigned CUID = 0) override;
  220. void emitDwarfFile0Directive(StringRef Directory, StringRef Filename,
  221. Optional<MD5::MD5Result> Checksum,
  222. Optional<StringRef> Source,
  223. unsigned CUID = 0) override;
  224. void emitDwarfLocDirective(unsigned FileNo, unsigned Line, unsigned Column,
  225. unsigned Flags, unsigned Isa,
  226. unsigned Discriminator,
  227. StringRef FileName) override;
  228. MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override;
  229. bool EmitCVFileDirective(unsigned FileNo, StringRef Filename,
  230. ArrayRef<uint8_t> Checksum,
  231. unsigned ChecksumKind) override;
  232. bool EmitCVFuncIdDirective(unsigned FuncId) override;
  233. bool EmitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc,
  234. unsigned IAFile, unsigned IALine,
  235. unsigned IACol, SMLoc Loc) override;
  236. void emitCVLocDirective(unsigned FunctionId, unsigned FileNo, unsigned Line,
  237. unsigned Column, bool PrologueEnd, bool IsStmt,
  238. StringRef FileName, SMLoc Loc) override;
  239. void emitCVLinetableDirective(unsigned FunctionId, const MCSymbol *FnStart,
  240. const MCSymbol *FnEnd) override;
  241. void emitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
  242. unsigned SourceFileId,
  243. unsigned SourceLineNum,
  244. const MCSymbol *FnStartSym,
  245. const MCSymbol *FnEndSym) override;
  246. void PrintCVDefRangePrefix(
  247. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges);
  248. void emitCVDefRangeDirective(
  249. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
  250. codeview::DefRangeRegisterRelHeader DRHdr) override;
  251. void emitCVDefRangeDirective(
  252. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
  253. codeview::DefRangeSubfieldRegisterHeader DRHdr) override;
  254. void emitCVDefRangeDirective(
  255. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
  256. codeview::DefRangeRegisterHeader DRHdr) override;
  257. void emitCVDefRangeDirective(
  258. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
  259. codeview::DefRangeFramePointerRelHeader DRHdr) override;
  260. void emitCVStringTableDirective() override;
  261. void emitCVFileChecksumsDirective() override;
  262. void emitCVFileChecksumOffsetDirective(unsigned FileNo) override;
  263. void EmitCVFPOData(const MCSymbol *ProcSym, SMLoc L) override;
  264. void emitIdent(StringRef IdentString) override;
  265. void emitCFIBKeyFrame() override;
  266. void emitCFISections(bool EH, bool Debug) override;
  267. void emitCFIDefCfa(int64_t Register, int64_t Offset) override;
  268. void emitCFIDefCfaOffset(int64_t Offset) override;
  269. void emitCFIDefCfaRegister(int64_t Register) override;
  270. void emitCFILLVMDefAspaceCfa(int64_t Register, int64_t Offset,
  271. int64_t AddressSpace) override;
  272. void emitCFIOffset(int64_t Register, int64_t Offset) override;
  273. void emitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override;
  274. void emitCFILsda(const MCSymbol *Sym, unsigned Encoding) override;
  275. void emitCFIRememberState() override;
  276. void emitCFIRestoreState() override;
  277. void emitCFIRestore(int64_t Register) override;
  278. void emitCFISameValue(int64_t Register) override;
  279. void emitCFIRelOffset(int64_t Register, int64_t Offset) override;
  280. void emitCFIAdjustCfaOffset(int64_t Adjustment) override;
  281. void emitCFIEscape(StringRef Values) override;
  282. void emitCFIGnuArgsSize(int64_t Size) override;
  283. void emitCFISignalFrame() override;
  284. void emitCFIUndefined(int64_t Register) override;
  285. void emitCFIRegister(int64_t Register1, int64_t Register2) override;
  286. void emitCFIWindowSave() override;
  287. void emitCFINegateRAState() override;
  288. void emitCFIReturnColumn(int64_t Register) override;
  289. void EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) override;
  290. void EmitWinCFIEndProc(SMLoc Loc) override;
  291. void EmitWinCFIFuncletOrFuncEnd(SMLoc Loc) override;
  292. void EmitWinCFIStartChained(SMLoc Loc) override;
  293. void EmitWinCFIEndChained(SMLoc Loc) override;
  294. void EmitWinCFIPushReg(MCRegister Register, SMLoc Loc) override;
  295. void EmitWinCFISetFrame(MCRegister Register, unsigned Offset,
  296. SMLoc Loc) override;
  297. void EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) override;
  298. void EmitWinCFISaveReg(MCRegister Register, unsigned Offset,
  299. SMLoc Loc) override;
  300. void EmitWinCFISaveXMM(MCRegister Register, unsigned Offset,
  301. SMLoc Loc) override;
  302. void EmitWinCFIPushFrame(bool Code, SMLoc Loc) override;
  303. void EmitWinCFIEndProlog(SMLoc Loc) override;
  304. void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except,
  305. SMLoc Loc) override;
  306. void EmitWinEHHandlerData(SMLoc Loc) override;
  307. void emitCGProfileEntry(const MCSymbolRefExpr *From,
  308. const MCSymbolRefExpr *To, uint64_t Count) override;
  309. void emitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) override;
  310. void emitPseudoProbe(uint64_t Guid, uint64_t Index, uint64_t Type,
  311. uint64_t Attr,
  312. const MCPseudoProbeInlineStack &InlineStack) override;
  313. void emitBundleAlignMode(unsigned AlignPow2) override;
  314. void emitBundleLock(bool AlignToEnd) override;
  315. void emitBundleUnlock() override;
  316. Optional<std::pair<bool, std::string>>
  317. emitRelocDirective(const MCExpr &Offset, StringRef Name, const MCExpr *Expr,
  318. SMLoc Loc, const MCSubtargetInfo &STI) override;
  319. void emitAddrsig() override;
  320. void emitAddrsigSym(const MCSymbol *Sym) override;
  321. /// If this file is backed by an assembly streamer, this dumps the specified
  322. /// string in the output .s file. This capability is indicated by the
  323. /// hasRawTextSupport() predicate.
  324. void emitRawTextImpl(StringRef String) override;
  325. void finishImpl() override;
  326. void emitDwarfUnitLength(uint64_t Length, const Twine &Comment) override;
  327. MCSymbol *emitDwarfUnitLength(const Twine &Prefix,
  328. const Twine &Comment) override;
  329. void emitDwarfLineStartLabel(MCSymbol *StartSym) override;
  330. void emitDwarfLineEndEntry(MCSection *Section, MCSymbol *LastLabel) override;
  331. void emitDwarfAdvanceLineAddr(int64_t LineDelta, const MCSymbol *LastLabel,
  332. const MCSymbol *Label,
  333. unsigned PointerSize) override;
  334. void doFinalizationAtSectionEnd(MCSection *Section) override;
  335. };
  336. } // end anonymous namespace.
  337. void MCAsmStreamer::AddComment(const Twine &T, bool EOL) {
  338. if (!IsVerboseAsm) return;
  339. T.toVector(CommentToEmit);
  340. if (EOL)
  341. CommentToEmit.push_back('\n'); // Place comment in a new line.
  342. }
  343. void MCAsmStreamer::EmitCommentsAndEOL() {
  344. if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
  345. OS << '\n';
  346. return;
  347. }
  348. StringRef Comments = CommentToEmit;
  349. assert(Comments.back() == '\n' &&
  350. "Comment array not newline terminated");
  351. do {
  352. // Emit a line of comments.
  353. OS.PadToColumn(MAI->getCommentColumn());
  354. size_t Position = Comments.find('\n');
  355. OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
  356. Comments = Comments.substr(Position+1);
  357. } while (!Comments.empty());
  358. CommentToEmit.clear();
  359. }
  360. static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
  361. assert(Bytes > 0 && Bytes <= 8 && "Invalid size!");
  362. return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
  363. }
  364. void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
  365. if (TabPrefix)
  366. OS << '\t';
  367. OS << MAI->getCommentString() << T;
  368. EmitEOL();
  369. }
  370. void MCAsmStreamer::addExplicitComment(const Twine &T) {
  371. StringRef c = T.getSingleStringRef();
  372. if (c.equals(StringRef(MAI->getSeparatorString())))
  373. return;
  374. if (c.startswith(StringRef("//"))) {
  375. ExplicitCommentToEmit.append("\t");
  376. ExplicitCommentToEmit.append(MAI->getCommentString());
  377. // drop //
  378. ExplicitCommentToEmit.append(c.slice(2, c.size()).str());
  379. } else if (c.startswith(StringRef("/*"))) {
  380. size_t p = 2, len = c.size() - 2;
  381. // emit each line in comment as separate newline.
  382. do {
  383. size_t newp = std::min(len, c.find_first_of("\r\n", p));
  384. ExplicitCommentToEmit.append("\t");
  385. ExplicitCommentToEmit.append(MAI->getCommentString());
  386. ExplicitCommentToEmit.append(c.slice(p, newp).str());
  387. // If we have another line in this comment add line
  388. if (newp < len)
  389. ExplicitCommentToEmit.append("\n");
  390. p = newp + 1;
  391. } while (p < len);
  392. } else if (c.startswith(StringRef(MAI->getCommentString()))) {
  393. ExplicitCommentToEmit.append("\t");
  394. ExplicitCommentToEmit.append(c.str());
  395. } else if (c.front() == '#') {
  396. ExplicitCommentToEmit.append("\t");
  397. ExplicitCommentToEmit.append(MAI->getCommentString());
  398. ExplicitCommentToEmit.append(c.slice(1, c.size()).str());
  399. } else
  400. assert(false && "Unexpected Assembly Comment");
  401. // full line comments immediately output
  402. if (c.back() == '\n')
  403. emitExplicitComments();
  404. }
  405. void MCAsmStreamer::emitExplicitComments() {
  406. StringRef Comments = ExplicitCommentToEmit;
  407. if (!Comments.empty())
  408. OS << Comments;
  409. ExplicitCommentToEmit.clear();
  410. }
  411. void MCAsmStreamer::changeSection(MCSection *Section,
  412. const MCExpr *Subsection) {
  413. assert(Section && "Cannot switch to a null section!");
  414. if (MCTargetStreamer *TS = getTargetStreamer()) {
  415. TS->changeSection(getCurrentSectionOnly(), Section, Subsection, OS);
  416. } else {
  417. Section->PrintSwitchToSection(*MAI, getContext().getTargetTriple(), OS,
  418. Subsection);
  419. }
  420. }
  421. void MCAsmStreamer::emitELFSymverDirective(const MCSymbol *OriginalSym,
  422. StringRef Name,
  423. bool KeepOriginalSym) {
  424. OS << ".symver ";
  425. OriginalSym->print(OS, MAI);
  426. OS << ", " << Name;
  427. if (!KeepOriginalSym && !Name.contains("@@@"))
  428. OS << ", remove";
  429. EmitEOL();
  430. }
  431. void MCAsmStreamer::emitLabel(MCSymbol *Symbol, SMLoc Loc) {
  432. MCStreamer::emitLabel(Symbol, Loc);
  433. Symbol->print(OS, MAI);
  434. OS << MAI->getLabelSuffix();
  435. EmitEOL();
  436. }
  437. void MCAsmStreamer::emitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {
  438. StringRef str = MCLOHIdToName(Kind);
  439. #ifndef NDEBUG
  440. int NbArgs = MCLOHIdToNbArgs(Kind);
  441. assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!");
  442. assert(str != "" && "Invalid LOH name");
  443. #endif
  444. OS << "\t" << MCLOHDirectiveName() << " " << str << "\t";
  445. bool IsFirst = true;
  446. for (const MCSymbol *Arg : Args) {
  447. if (!IsFirst)
  448. OS << ", ";
  449. IsFirst = false;
  450. Arg->print(OS, MAI);
  451. }
  452. EmitEOL();
  453. }
  454. void MCAsmStreamer::emitGNUAttribute(unsigned Tag, unsigned Value) {
  455. OS << "\t.gnu_attribute " << Tag << ", " << Value << "\n";
  456. }
  457. void MCAsmStreamer::emitAssemblerFlag(MCAssemblerFlag Flag) {
  458. switch (Flag) {
  459. case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
  460. case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
  461. case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
  462. case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
  463. case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
  464. }
  465. EmitEOL();
  466. }
  467. void MCAsmStreamer::emitLinkerOptions(ArrayRef<std::string> Options) {
  468. assert(!Options.empty() && "At least one option is required!");
  469. OS << "\t.linker_option \"" << Options[0] << '"';
  470. for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
  471. ie = Options.end(); it != ie; ++it) {
  472. OS << ", " << '"' << *it << '"';
  473. }
  474. EmitEOL();
  475. }
  476. void MCAsmStreamer::emitDataRegion(MCDataRegionType Kind) {
  477. if (!MAI->doesSupportDataRegionDirectives())
  478. return;
  479. switch (Kind) {
  480. case MCDR_DataRegion: OS << "\t.data_region"; break;
  481. case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
  482. case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
  483. case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
  484. case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
  485. }
  486. EmitEOL();
  487. }
  488. static const char *getVersionMinDirective(MCVersionMinType Type) {
  489. switch (Type) {
  490. case MCVM_WatchOSVersionMin: return ".watchos_version_min";
  491. case MCVM_TvOSVersionMin: return ".tvos_version_min";
  492. case MCVM_IOSVersionMin: return ".ios_version_min";
  493. case MCVM_OSXVersionMin: return ".macosx_version_min";
  494. }
  495. llvm_unreachable("Invalid MC version min type");
  496. }
  497. static void EmitSDKVersionSuffix(raw_ostream &OS,
  498. const VersionTuple &SDKVersion) {
  499. if (SDKVersion.empty())
  500. return;
  501. OS << '\t' << "sdk_version " << SDKVersion.getMajor();
  502. if (auto Minor = SDKVersion.getMinor()) {
  503. OS << ", " << *Minor;
  504. if (auto Subminor = SDKVersion.getSubminor()) {
  505. OS << ", " << *Subminor;
  506. }
  507. }
  508. }
  509. void MCAsmStreamer::emitVersionMin(MCVersionMinType Type, unsigned Major,
  510. unsigned Minor, unsigned Update,
  511. VersionTuple SDKVersion) {
  512. OS << '\t' << getVersionMinDirective(Type) << ' ' << Major << ", " << Minor;
  513. if (Update)
  514. OS << ", " << Update;
  515. EmitSDKVersionSuffix(OS, SDKVersion);
  516. EmitEOL();
  517. }
  518. static const char *getPlatformName(MachO::PlatformType Type) {
  519. switch (Type) {
  520. case MachO::PLATFORM_UNKNOWN: /* silence warning*/
  521. break;
  522. case MachO::PLATFORM_MACOS: return "macos";
  523. case MachO::PLATFORM_IOS: return "ios";
  524. case MachO::PLATFORM_TVOS: return "tvos";
  525. case MachO::PLATFORM_WATCHOS: return "watchos";
  526. case MachO::PLATFORM_BRIDGEOS: return "bridgeos";
  527. case MachO::PLATFORM_MACCATALYST: return "macCatalyst";
  528. case MachO::PLATFORM_IOSSIMULATOR: return "iossimulator";
  529. case MachO::PLATFORM_TVOSSIMULATOR: return "tvossimulator";
  530. case MachO::PLATFORM_WATCHOSSIMULATOR: return "watchossimulator";
  531. case MachO::PLATFORM_DRIVERKIT: return "driverkit";
  532. }
  533. llvm_unreachable("Invalid Mach-O platform type");
  534. }
  535. void MCAsmStreamer::emitBuildVersion(unsigned Platform, unsigned Major,
  536. unsigned Minor, unsigned Update,
  537. VersionTuple SDKVersion) {
  538. const char *PlatformName = getPlatformName((MachO::PlatformType)Platform);
  539. OS << "\t.build_version " << PlatformName << ", " << Major << ", " << Minor;
  540. if (Update)
  541. OS << ", " << Update;
  542. EmitSDKVersionSuffix(OS, SDKVersion);
  543. EmitEOL();
  544. }
  545. void MCAsmStreamer::emitDarwinTargetVariantBuildVersion(
  546. unsigned Platform, unsigned Major, unsigned Minor, unsigned Update,
  547. VersionTuple SDKVersion) {
  548. emitBuildVersion(Platform, Major, Minor, Update, SDKVersion);
  549. }
  550. void MCAsmStreamer::emitThumbFunc(MCSymbol *Func) {
  551. // This needs to emit to a temporary string to get properly quoted
  552. // MCSymbols when they have spaces in them.
  553. OS << "\t.thumb_func";
  554. // Only Mach-O hasSubsectionsViaSymbols()
  555. if (MAI->hasSubsectionsViaSymbols()) {
  556. OS << '\t';
  557. Func->print(OS, MAI);
  558. }
  559. EmitEOL();
  560. }
  561. void MCAsmStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
  562. // Do not emit a .set on inlined target assignments.
  563. bool EmitSet = true;
  564. if (auto *E = dyn_cast<MCTargetExpr>(Value))
  565. if (E->inlineAssignedExpr())
  566. EmitSet = false;
  567. if (EmitSet) {
  568. OS << ".set ";
  569. Symbol->print(OS, MAI);
  570. OS << ", ";
  571. Value->print(OS, MAI);
  572. EmitEOL();
  573. }
  574. MCStreamer::emitAssignment(Symbol, Value);
  575. }
  576. void MCAsmStreamer::emitConditionalAssignment(MCSymbol *Symbol,
  577. const MCExpr *Value) {
  578. OS << ".lto_set_conditional ";
  579. Symbol->print(OS, MAI);
  580. OS << ", ";
  581. Value->print(OS, MAI);
  582. EmitEOL();
  583. }
  584. void MCAsmStreamer::emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
  585. OS << ".weakref ";
  586. Alias->print(OS, MAI);
  587. OS << ", ";
  588. Symbol->print(OS, MAI);
  589. EmitEOL();
  590. }
  591. bool MCAsmStreamer::emitSymbolAttribute(MCSymbol *Symbol,
  592. MCSymbolAttr Attribute) {
  593. switch (Attribute) {
  594. case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
  595. case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
  596. case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
  597. case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
  598. case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
  599. case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
  600. case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
  601. case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
  602. if (!MAI->hasDotTypeDotSizeDirective())
  603. return false; // Symbol attribute not supported
  604. OS << "\t.type\t";
  605. Symbol->print(OS, MAI);
  606. OS << ',' << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
  607. switch (Attribute) {
  608. default: return false;
  609. case MCSA_ELF_TypeFunction: OS << "function"; break;
  610. case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
  611. case MCSA_ELF_TypeObject: OS << "object"; break;
  612. case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
  613. case MCSA_ELF_TypeCommon: OS << "common"; break;
  614. case MCSA_ELF_TypeNoType: OS << "notype"; break;
  615. case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
  616. }
  617. EmitEOL();
  618. return true;
  619. case MCSA_Global: // .globl/.global
  620. OS << MAI->getGlobalDirective();
  621. break;
  622. case MCSA_LGlobal: OS << "\t.lglobl\t"; break;
  623. case MCSA_Hidden: OS << "\t.hidden\t"; break;
  624. case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
  625. case MCSA_Internal: OS << "\t.internal\t"; break;
  626. case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
  627. case MCSA_Local: OS << "\t.local\t"; break;
  628. case MCSA_NoDeadStrip:
  629. if (!MAI->hasNoDeadStrip())
  630. return false;
  631. OS << "\t.no_dead_strip\t";
  632. break;
  633. case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
  634. case MCSA_AltEntry: OS << "\t.alt_entry\t"; break;
  635. case MCSA_PrivateExtern:
  636. OS << "\t.private_extern\t";
  637. break;
  638. case MCSA_Protected: OS << "\t.protected\t"; break;
  639. case MCSA_Reference: OS << "\t.reference\t"; break;
  640. case MCSA_Extern:
  641. OS << "\t.extern\t";
  642. break;
  643. case MCSA_Weak: OS << MAI->getWeakDirective(); break;
  644. case MCSA_WeakDefinition:
  645. OS << "\t.weak_definition\t";
  646. break;
  647. // .weak_reference
  648. case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
  649. case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
  650. case MCSA_Cold:
  651. // Assemblers currently do not support a .cold directive.
  652. return false;
  653. }
  654. Symbol->print(OS, MAI);
  655. EmitEOL();
  656. return true;
  657. }
  658. void MCAsmStreamer::emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
  659. OS << ".desc" << ' ';
  660. Symbol->print(OS, MAI);
  661. OS << ',' << DescValue;
  662. EmitEOL();
  663. }
  664. void MCAsmStreamer::emitSyntaxDirective() {
  665. if (MAI->getAssemblerDialect() == 1) {
  666. OS << "\t.intel_syntax noprefix";
  667. EmitEOL();
  668. }
  669. // FIXME: Currently emit unprefix'ed registers.
  670. // The intel_syntax directive has one optional argument
  671. // with may have a value of prefix or noprefix.
  672. }
  673. void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
  674. OS << "\t.def\t";
  675. Symbol->print(OS, MAI);
  676. OS << ';';
  677. EmitEOL();
  678. }
  679. void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
  680. OS << "\t.scl\t" << StorageClass << ';';
  681. EmitEOL();
  682. }
  683. void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
  684. OS << "\t.type\t" << Type << ';';
  685. EmitEOL();
  686. }
  687. void MCAsmStreamer::EndCOFFSymbolDef() {
  688. OS << "\t.endef";
  689. EmitEOL();
  690. }
  691. void MCAsmStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {
  692. OS << "\t.safeseh\t";
  693. Symbol->print(OS, MAI);
  694. EmitEOL();
  695. }
  696. void MCAsmStreamer::EmitCOFFSymbolIndex(MCSymbol const *Symbol) {
  697. OS << "\t.symidx\t";
  698. Symbol->print(OS, MAI);
  699. EmitEOL();
  700. }
  701. void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
  702. OS << "\t.secidx\t";
  703. Symbol->print(OS, MAI);
  704. EmitEOL();
  705. }
  706. void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) {
  707. OS << "\t.secrel32\t";
  708. Symbol->print(OS, MAI);
  709. if (Offset != 0)
  710. OS << '+' << Offset;
  711. EmitEOL();
  712. }
  713. void MCAsmStreamer::EmitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset) {
  714. OS << "\t.rva\t";
  715. Symbol->print(OS, MAI);
  716. if (Offset > 0)
  717. OS << '+' << Offset;
  718. else if (Offset < 0)
  719. OS << '-' << -Offset;
  720. EmitEOL();
  721. }
  722. // We need an XCOFF-specific version of this directive as the AIX syntax
  723. // requires a QualName argument identifying the csect name and storage mapping
  724. // class to appear before the alignment if we are specifying it.
  725. void MCAsmStreamer::emitXCOFFLocalCommonSymbol(MCSymbol *LabelSym,
  726. uint64_t Size,
  727. MCSymbol *CsectSym,
  728. unsigned ByteAlignment) {
  729. assert(MAI->getLCOMMDirectiveAlignmentType() == LCOMM::Log2Alignment &&
  730. "We only support writing log base-2 alignment format with XCOFF.");
  731. assert(isPowerOf2_32(ByteAlignment) && "Alignment must be a power of 2.");
  732. OS << "\t.lcomm\t";
  733. LabelSym->print(OS, MAI);
  734. OS << ',' << Size << ',';
  735. CsectSym->print(OS, MAI);
  736. OS << ',' << Log2_32(ByteAlignment);
  737. EmitEOL();
  738. // Print symbol's rename (original name contains invalid character(s)) if
  739. // there is one.
  740. MCSymbolXCOFF *XSym = cast<MCSymbolXCOFF>(CsectSym);
  741. if (XSym->hasRename())
  742. emitXCOFFRenameDirective(XSym, XSym->getSymbolTableName());
  743. }
  744. void MCAsmStreamer::emitXCOFFSymbolLinkageWithVisibility(
  745. MCSymbol *Symbol, MCSymbolAttr Linkage, MCSymbolAttr Visibility) {
  746. switch (Linkage) {
  747. case MCSA_Global:
  748. OS << MAI->getGlobalDirective();
  749. break;
  750. case MCSA_Weak:
  751. OS << MAI->getWeakDirective();
  752. break;
  753. case MCSA_Extern:
  754. OS << "\t.extern\t";
  755. break;
  756. case MCSA_LGlobal:
  757. OS << "\t.lglobl\t";
  758. break;
  759. default:
  760. report_fatal_error("unhandled linkage type");
  761. }
  762. Symbol->print(OS, MAI);
  763. switch (Visibility) {
  764. case MCSA_Invalid:
  765. // Nothing to do.
  766. break;
  767. case MCSA_Hidden:
  768. OS << ",hidden";
  769. break;
  770. case MCSA_Protected:
  771. OS << ",protected";
  772. break;
  773. default:
  774. report_fatal_error("unexpected value for Visibility type");
  775. }
  776. EmitEOL();
  777. // Print symbol's rename (original name contains invalid character(s)) if
  778. // there is one.
  779. if (cast<MCSymbolXCOFF>(Symbol)->hasRename())
  780. emitXCOFFRenameDirective(Symbol,
  781. cast<MCSymbolXCOFF>(Symbol)->getSymbolTableName());
  782. }
  783. void MCAsmStreamer::emitXCOFFRenameDirective(const MCSymbol *Name,
  784. StringRef Rename) {
  785. OS << "\t.rename\t";
  786. Name->print(OS, MAI);
  787. const char DQ = '"';
  788. OS << ',' << DQ;
  789. for (char C : Rename) {
  790. // To escape a double quote character, the character should be doubled.
  791. if (C == DQ)
  792. OS << DQ;
  793. OS << C;
  794. }
  795. OS << DQ;
  796. EmitEOL();
  797. }
  798. void MCAsmStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
  799. assert(MAI->hasDotTypeDotSizeDirective());
  800. OS << "\t.size\t";
  801. Symbol->print(OS, MAI);
  802. OS << ", ";
  803. Value->print(OS, MAI);
  804. EmitEOL();
  805. }
  806. void MCAsmStreamer::emitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
  807. unsigned ByteAlignment) {
  808. OS << "\t.comm\t";
  809. Symbol->print(OS, MAI);
  810. OS << ',' << Size;
  811. if (ByteAlignment != 0) {
  812. if (MAI->getCOMMDirectiveAlignmentIsInBytes())
  813. OS << ',' << ByteAlignment;
  814. else
  815. OS << ',' << Log2_32(ByteAlignment);
  816. }
  817. EmitEOL();
  818. // Print symbol's rename (original name contains invalid character(s)) if
  819. // there is one.
  820. MCSymbolXCOFF *XSym = dyn_cast<MCSymbolXCOFF>(Symbol);
  821. if (XSym && XSym->hasRename())
  822. emitXCOFFRenameDirective(XSym, XSym->getSymbolTableName());
  823. }
  824. void MCAsmStreamer::emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
  825. unsigned ByteAlign) {
  826. OS << "\t.lcomm\t";
  827. Symbol->print(OS, MAI);
  828. OS << ',' << Size;
  829. if (ByteAlign > 1) {
  830. switch (MAI->getLCOMMDirectiveAlignmentType()) {
  831. case LCOMM::NoAlignment:
  832. llvm_unreachable("alignment not supported on .lcomm!");
  833. case LCOMM::ByteAlignment:
  834. OS << ',' << ByteAlign;
  835. break;
  836. case LCOMM::Log2Alignment:
  837. assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
  838. OS << ',' << Log2_32(ByteAlign);
  839. break;
  840. }
  841. }
  842. EmitEOL();
  843. }
  844. void MCAsmStreamer::emitZerofill(MCSection *Section, MCSymbol *Symbol,
  845. uint64_t Size, unsigned ByteAlignment,
  846. SMLoc Loc) {
  847. if (Symbol)
  848. AssignFragment(Symbol, &Section->getDummyFragment());
  849. // Note: a .zerofill directive does not switch sections.
  850. OS << ".zerofill ";
  851. assert(Section->getVariant() == MCSection::SV_MachO &&
  852. ".zerofill is a Mach-O specific directive");
  853. // This is a mach-o specific directive.
  854. const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
  855. OS << MOSection->getSegmentName() << "," << MOSection->getName();
  856. if (Symbol) {
  857. OS << ',';
  858. Symbol->print(OS, MAI);
  859. OS << ',' << Size;
  860. if (ByteAlignment != 0)
  861. OS << ',' << Log2_32(ByteAlignment);
  862. }
  863. EmitEOL();
  864. }
  865. // .tbss sym, size, align
  866. // This depends that the symbol has already been mangled from the original,
  867. // e.g. _a.
  868. void MCAsmStreamer::emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
  869. uint64_t Size, unsigned ByteAlignment) {
  870. AssignFragment(Symbol, &Section->getDummyFragment());
  871. assert(Symbol && "Symbol shouldn't be NULL!");
  872. // Instead of using the Section we'll just use the shortcut.
  873. assert(Section->getVariant() == MCSection::SV_MachO &&
  874. ".zerofill is a Mach-O specific directive");
  875. // This is a mach-o specific directive and section.
  876. OS << ".tbss ";
  877. Symbol->print(OS, MAI);
  878. OS << ", " << Size;
  879. // Output align if we have it. We default to 1 so don't bother printing
  880. // that.
  881. if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
  882. EmitEOL();
  883. }
  884. static inline bool isPrintableString(StringRef Data) {
  885. const auto BeginPtr = Data.begin(), EndPtr = Data.end();
  886. for (const unsigned char C : make_range(BeginPtr, EndPtr - 1)) {
  887. if (!isPrint(C))
  888. return false;
  889. }
  890. return isPrint(Data.back()) || Data.back() == 0;
  891. }
  892. static inline char toOctal(int X) { return (X&7)+'0'; }
  893. static void PrintByteList(StringRef Data, raw_ostream &OS,
  894. MCAsmInfo::AsmCharLiteralSyntax ACLS) {
  895. assert(!Data.empty() && "Cannot generate an empty list.");
  896. const auto printCharacterInOctal = [&OS](unsigned char C) {
  897. OS << '0';
  898. OS << toOctal(C >> 6);
  899. OS << toOctal(C >> 3);
  900. OS << toOctal(C >> 0);
  901. };
  902. const auto printOneCharacterFor = [printCharacterInOctal](
  903. auto printOnePrintingCharacter) {
  904. return [printCharacterInOctal, printOnePrintingCharacter](unsigned char C) {
  905. if (isPrint(C)) {
  906. printOnePrintingCharacter(static_cast<char>(C));
  907. return;
  908. }
  909. printCharacterInOctal(C);
  910. };
  911. };
  912. const auto printCharacterList = [Data, &OS](const auto &printOneCharacter) {
  913. const auto BeginPtr = Data.begin(), EndPtr = Data.end();
  914. for (const unsigned char C : make_range(BeginPtr, EndPtr - 1)) {
  915. printOneCharacter(C);
  916. OS << ',';
  917. }
  918. printOneCharacter(*(EndPtr - 1));
  919. };
  920. switch (ACLS) {
  921. case MCAsmInfo::ACLS_Unknown:
  922. printCharacterList(printCharacterInOctal);
  923. return;
  924. case MCAsmInfo::ACLS_SingleQuotePrefix:
  925. printCharacterList(printOneCharacterFor([&OS](char C) {
  926. const char AsmCharLitBuf[2] = {'\'', C};
  927. OS << StringRef(AsmCharLitBuf, sizeof(AsmCharLitBuf));
  928. }));
  929. return;
  930. }
  931. llvm_unreachable("Invalid AsmCharLiteralSyntax value!");
  932. }
  933. void MCAsmStreamer::PrintQuotedString(StringRef Data, raw_ostream &OS) const {
  934. OS << '"';
  935. if (MAI->hasPairedDoubleQuoteStringConstants()) {
  936. for (unsigned char C : Data) {
  937. if (C == '"')
  938. OS << "\"\"";
  939. else
  940. OS << (char)C;
  941. }
  942. } else {
  943. for (unsigned char C : Data) {
  944. if (C == '"' || C == '\\') {
  945. OS << '\\' << (char)C;
  946. continue;
  947. }
  948. if (isPrint((unsigned char)C)) {
  949. OS << (char)C;
  950. continue;
  951. }
  952. switch (C) {
  953. case '\b':
  954. OS << "\\b";
  955. break;
  956. case '\f':
  957. OS << "\\f";
  958. break;
  959. case '\n':
  960. OS << "\\n";
  961. break;
  962. case '\r':
  963. OS << "\\r";
  964. break;
  965. case '\t':
  966. OS << "\\t";
  967. break;
  968. default:
  969. OS << '\\';
  970. OS << toOctal(C >> 6);
  971. OS << toOctal(C >> 3);
  972. OS << toOctal(C >> 0);
  973. break;
  974. }
  975. }
  976. }
  977. OS << '"';
  978. }
  979. void MCAsmStreamer::emitBytes(StringRef Data) {
  980. assert(getCurrentSectionOnly() &&
  981. "Cannot emit contents before setting section!");
  982. if (Data.empty()) return;
  983. const auto emitAsString = [this](StringRef Data) {
  984. // If the data ends with 0 and the target supports .asciz, use it, otherwise
  985. // use .ascii or a byte-list directive
  986. if (MAI->getAscizDirective() && Data.back() == 0) {
  987. OS << MAI->getAscizDirective();
  988. Data = Data.substr(0, Data.size() - 1);
  989. } else if (LLVM_LIKELY(MAI->getAsciiDirective())) {
  990. OS << MAI->getAsciiDirective();
  991. } else if (MAI->hasPairedDoubleQuoteStringConstants() &&
  992. isPrintableString(Data)) {
  993. // For target with DoubleQuoteString constants, .string and .byte are used
  994. // as replacement of .asciz and .ascii.
  995. assert(MAI->getPlainStringDirective() &&
  996. "hasPairedDoubleQuoteStringConstants target must support "
  997. "PlainString Directive");
  998. assert(MAI->getByteListDirective() &&
  999. "hasPairedDoubleQuoteStringConstants target must support ByteList "
  1000. "Directive");
  1001. if (Data.back() == 0) {
  1002. OS << MAI->getPlainStringDirective();
  1003. Data = Data.substr(0, Data.size() - 1);
  1004. } else {
  1005. OS << MAI->getByteListDirective();
  1006. }
  1007. } else if (MAI->getByteListDirective()) {
  1008. OS << MAI->getByteListDirective();
  1009. PrintByteList(Data, OS, MAI->characterLiteralSyntax());
  1010. EmitEOL();
  1011. return true;
  1012. } else {
  1013. return false;
  1014. }
  1015. PrintQuotedString(Data, OS);
  1016. EmitEOL();
  1017. return true;
  1018. };
  1019. if (Data.size() != 1 && emitAsString(Data))
  1020. return;
  1021. // Only single byte is provided or no ascii, asciz, or byte-list directives
  1022. // are applicable. Emit as vector of individual 8bits data elements.
  1023. if (MCTargetStreamer *TS = getTargetStreamer()) {
  1024. TS->emitRawBytes(Data);
  1025. return;
  1026. }
  1027. const char *Directive = MAI->getData8bitsDirective();
  1028. for (const unsigned char C : Data.bytes()) {
  1029. OS << Directive << (unsigned)C;
  1030. EmitEOL();
  1031. }
  1032. }
  1033. void MCAsmStreamer::emitBinaryData(StringRef Data) {
  1034. // This is binary data. Print it in a grid of hex bytes for readability.
  1035. const size_t Cols = 4;
  1036. for (size_t I = 0, EI = alignTo(Data.size(), Cols); I < EI; I += Cols) {
  1037. size_t J = I, EJ = std::min(I + Cols, Data.size());
  1038. assert(EJ > 0);
  1039. OS << MAI->getData8bitsDirective();
  1040. for (; J < EJ - 1; ++J)
  1041. OS << format("0x%02x", uint8_t(Data[J])) << ", ";
  1042. OS << format("0x%02x", uint8_t(Data[J]));
  1043. EmitEOL();
  1044. }
  1045. }
  1046. void MCAsmStreamer::emitIntValue(uint64_t Value, unsigned Size) {
  1047. emitValue(MCConstantExpr::create(Value, getContext()), Size);
  1048. }
  1049. void MCAsmStreamer::emitIntValueInHex(uint64_t Value, unsigned Size) {
  1050. emitValue(MCConstantExpr::create(Value, getContext(), true), Size);
  1051. }
  1052. void MCAsmStreamer::emitIntValueInHexWithPadding(uint64_t Value,
  1053. unsigned Size) {
  1054. emitValue(MCConstantExpr::create(Value, getContext(), true, Size), Size);
  1055. }
  1056. void MCAsmStreamer::emitValueImpl(const MCExpr *Value, unsigned Size,
  1057. SMLoc Loc) {
  1058. assert(Size <= 8 && "Invalid size");
  1059. assert(getCurrentSectionOnly() &&
  1060. "Cannot emit contents before setting section!");
  1061. const char *Directive = nullptr;
  1062. switch (Size) {
  1063. default: break;
  1064. case 1: Directive = MAI->getData8bitsDirective(); break;
  1065. case 2: Directive = MAI->getData16bitsDirective(); break;
  1066. case 4: Directive = MAI->getData32bitsDirective(); break;
  1067. case 8: Directive = MAI->getData64bitsDirective(); break;
  1068. }
  1069. if (!Directive) {
  1070. int64_t IntValue;
  1071. if (!Value->evaluateAsAbsolute(IntValue))
  1072. report_fatal_error("Don't know how to emit this value.");
  1073. // We couldn't handle the requested integer size so we fallback by breaking
  1074. // the request down into several, smaller, integers.
  1075. // Since sizes greater or equal to "Size" are invalid, we use the greatest
  1076. // power of 2 that is less than "Size" as our largest piece of granularity.
  1077. bool IsLittleEndian = MAI->isLittleEndian();
  1078. for (unsigned Emitted = 0; Emitted != Size;) {
  1079. unsigned Remaining = Size - Emitted;
  1080. // The size of our partial emission must be a power of two less than
  1081. // Size.
  1082. unsigned EmissionSize = PowerOf2Floor(std::min(Remaining, Size - 1));
  1083. // Calculate the byte offset of our partial emission taking into account
  1084. // the endianness of the target.
  1085. unsigned ByteOffset =
  1086. IsLittleEndian ? Emitted : (Remaining - EmissionSize);
  1087. uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
  1088. // We truncate our partial emission to fit within the bounds of the
  1089. // emission domain. This produces nicer output and silences potential
  1090. // truncation warnings when round tripping through another assembler.
  1091. uint64_t Shift = 64 - EmissionSize * 8;
  1092. assert(Shift < static_cast<uint64_t>(
  1093. std::numeric_limits<unsigned long long>::digits) &&
  1094. "undefined behavior");
  1095. ValueToEmit &= ~0ULL >> Shift;
  1096. emitIntValue(ValueToEmit, EmissionSize);
  1097. Emitted += EmissionSize;
  1098. }
  1099. return;
  1100. }
  1101. assert(Directive && "Invalid size for machine code value!");
  1102. OS << Directive;
  1103. if (MCTargetStreamer *TS = getTargetStreamer()) {
  1104. TS->emitValue(Value);
  1105. } else {
  1106. Value->print(OS, MAI);
  1107. EmitEOL();
  1108. }
  1109. }
  1110. void MCAsmStreamer::emitULEB128Value(const MCExpr *Value) {
  1111. int64_t IntValue;
  1112. if (Value->evaluateAsAbsolute(IntValue)) {
  1113. emitULEB128IntValue(IntValue);
  1114. return;
  1115. }
  1116. OS << "\t.uleb128 ";
  1117. Value->print(OS, MAI);
  1118. EmitEOL();
  1119. }
  1120. void MCAsmStreamer::emitSLEB128Value(const MCExpr *Value) {
  1121. int64_t IntValue;
  1122. if (Value->evaluateAsAbsolute(IntValue)) {
  1123. emitSLEB128IntValue(IntValue);
  1124. return;
  1125. }
  1126. OS << "\t.sleb128 ";
  1127. Value->print(OS, MAI);
  1128. EmitEOL();
  1129. }
  1130. void MCAsmStreamer::emitDTPRel64Value(const MCExpr *Value) {
  1131. assert(MAI->getDTPRel64Directive() != nullptr);
  1132. OS << MAI->getDTPRel64Directive();
  1133. Value->print(OS, MAI);
  1134. EmitEOL();
  1135. }
  1136. void MCAsmStreamer::emitDTPRel32Value(const MCExpr *Value) {
  1137. assert(MAI->getDTPRel32Directive() != nullptr);
  1138. OS << MAI->getDTPRel32Directive();
  1139. Value->print(OS, MAI);
  1140. EmitEOL();
  1141. }
  1142. void MCAsmStreamer::emitTPRel64Value(const MCExpr *Value) {
  1143. assert(MAI->getTPRel64Directive() != nullptr);
  1144. OS << MAI->getTPRel64Directive();
  1145. Value->print(OS, MAI);
  1146. EmitEOL();
  1147. }
  1148. void MCAsmStreamer::emitTPRel32Value(const MCExpr *Value) {
  1149. assert(MAI->getTPRel32Directive() != nullptr);
  1150. OS << MAI->getTPRel32Directive();
  1151. Value->print(OS, MAI);
  1152. EmitEOL();
  1153. }
  1154. void MCAsmStreamer::emitGPRel64Value(const MCExpr *Value) {
  1155. assert(MAI->getGPRel64Directive() != nullptr);
  1156. OS << MAI->getGPRel64Directive();
  1157. Value->print(OS, MAI);
  1158. EmitEOL();
  1159. }
  1160. void MCAsmStreamer::emitGPRel32Value(const MCExpr *Value) {
  1161. assert(MAI->getGPRel32Directive() != nullptr);
  1162. OS << MAI->getGPRel32Directive();
  1163. Value->print(OS, MAI);
  1164. EmitEOL();
  1165. }
  1166. void MCAsmStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue,
  1167. SMLoc Loc) {
  1168. int64_t IntNumBytes;
  1169. const bool IsAbsolute = NumBytes.evaluateAsAbsolute(IntNumBytes);
  1170. if (IsAbsolute && IntNumBytes == 0)
  1171. return;
  1172. if (const char *ZeroDirective = MAI->getZeroDirective()) {
  1173. if (MAI->doesZeroDirectiveSupportNonZeroValue() || FillValue == 0) {
  1174. // FIXME: Emit location directives
  1175. OS << ZeroDirective;
  1176. NumBytes.print(OS, MAI);
  1177. if (FillValue != 0)
  1178. OS << ',' << (int)FillValue;
  1179. EmitEOL();
  1180. } else {
  1181. if (!IsAbsolute)
  1182. report_fatal_error(
  1183. "Cannot emit non-absolute expression lengths of fill.");
  1184. for (int i = 0; i < IntNumBytes; ++i) {
  1185. OS << MAI->getData8bitsDirective() << (int)FillValue;
  1186. EmitEOL();
  1187. }
  1188. }
  1189. return;
  1190. }
  1191. MCStreamer::emitFill(NumBytes, FillValue);
  1192. }
  1193. void MCAsmStreamer::emitFill(const MCExpr &NumValues, int64_t Size,
  1194. int64_t Expr, SMLoc Loc) {
  1195. // FIXME: Emit location directives
  1196. OS << "\t.fill\t";
  1197. NumValues.print(OS, MAI);
  1198. OS << ", " << Size << ", 0x";
  1199. OS.write_hex(truncateToSize(Expr, 4));
  1200. EmitEOL();
  1201. }
  1202. void MCAsmStreamer::emitValueToAlignment(unsigned ByteAlignment, int64_t Value,
  1203. unsigned ValueSize,
  1204. unsigned MaxBytesToEmit) {
  1205. if (MAI->useDotAlignForAlignment()) {
  1206. if (!isPowerOf2_32(ByteAlignment))
  1207. report_fatal_error("Only power-of-two alignments are supported "
  1208. "with .align.");
  1209. OS << "\t.align\t";
  1210. OS << Log2_32(ByteAlignment);
  1211. EmitEOL();
  1212. return;
  1213. }
  1214. // Some assemblers don't support non-power of two alignments, so we always
  1215. // emit alignments as a power of two if possible.
  1216. if (isPowerOf2_32(ByteAlignment)) {
  1217. switch (ValueSize) {
  1218. default:
  1219. llvm_unreachable("Invalid size for machine code value!");
  1220. case 1:
  1221. OS << "\t.p2align\t";
  1222. break;
  1223. case 2:
  1224. OS << ".p2alignw ";
  1225. break;
  1226. case 4:
  1227. OS << ".p2alignl ";
  1228. break;
  1229. case 8:
  1230. llvm_unreachable("Unsupported alignment size!");
  1231. }
  1232. OS << Log2_32(ByteAlignment);
  1233. if (Value || MaxBytesToEmit) {
  1234. OS << ", 0x";
  1235. OS.write_hex(truncateToSize(Value, ValueSize));
  1236. if (MaxBytesToEmit)
  1237. OS << ", " << MaxBytesToEmit;
  1238. }
  1239. EmitEOL();
  1240. return;
  1241. }
  1242. // Non-power of two alignment. This is not widely supported by assemblers.
  1243. // FIXME: Parameterize this based on MAI.
  1244. switch (ValueSize) {
  1245. default: llvm_unreachable("Invalid size for machine code value!");
  1246. case 1: OS << ".balign"; break;
  1247. case 2: OS << ".balignw"; break;
  1248. case 4: OS << ".balignl"; break;
  1249. case 8: llvm_unreachable("Unsupported alignment size!");
  1250. }
  1251. OS << ' ' << ByteAlignment;
  1252. OS << ", " << truncateToSize(Value, ValueSize);
  1253. if (MaxBytesToEmit)
  1254. OS << ", " << MaxBytesToEmit;
  1255. EmitEOL();
  1256. }
  1257. void MCAsmStreamer::emitCodeAlignment(unsigned ByteAlignment,
  1258. const MCSubtargetInfo *STI,
  1259. unsigned MaxBytesToEmit) {
  1260. // Emit with a text fill value.
  1261. emitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
  1262. 1, MaxBytesToEmit);
  1263. }
  1264. void MCAsmStreamer::emitValueToOffset(const MCExpr *Offset,
  1265. unsigned char Value,
  1266. SMLoc Loc) {
  1267. // FIXME: Verify that Offset is associated with the current section.
  1268. OS << ".org ";
  1269. Offset->print(OS, MAI);
  1270. OS << ", " << (unsigned)Value;
  1271. EmitEOL();
  1272. }
  1273. void MCAsmStreamer::emitFileDirective(StringRef Filename) {
  1274. assert(MAI->hasSingleParameterDotFile());
  1275. OS << "\t.file\t";
  1276. PrintQuotedString(Filename, OS);
  1277. EmitEOL();
  1278. }
  1279. void MCAsmStreamer::emitFileDirective(StringRef Filename,
  1280. StringRef CompilerVerion,
  1281. StringRef TimeStamp,
  1282. StringRef Description) {
  1283. assert(MAI->hasFourStringsDotFile());
  1284. OS << "\t.file\t";
  1285. PrintQuotedString(Filename, OS);
  1286. OS << ",";
  1287. if (!CompilerVerion.empty()) {
  1288. PrintQuotedString(CompilerVerion, OS);
  1289. }
  1290. if (!TimeStamp.empty()) {
  1291. OS << ",";
  1292. PrintQuotedString(TimeStamp, OS);
  1293. }
  1294. if (!Description.empty()) {
  1295. OS << ",";
  1296. PrintQuotedString(Description, OS);
  1297. }
  1298. EmitEOL();
  1299. }
  1300. void MCAsmStreamer::printDwarfFileDirective(
  1301. unsigned FileNo, StringRef Directory, StringRef Filename,
  1302. Optional<MD5::MD5Result> Checksum, Optional<StringRef> Source,
  1303. bool UseDwarfDirectory, raw_svector_ostream &OS) const {
  1304. SmallString<128> FullPathName;
  1305. if (!UseDwarfDirectory && !Directory.empty()) {
  1306. if (sys::path::is_absolute(Filename))
  1307. Directory = "";
  1308. else {
  1309. FullPathName = Directory;
  1310. sys::path::append(FullPathName, Filename);
  1311. Directory = "";
  1312. Filename = FullPathName;
  1313. }
  1314. }
  1315. OS << "\t.file\t" << FileNo << ' ';
  1316. if (!Directory.empty()) {
  1317. PrintQuotedString(Directory, OS);
  1318. OS << ' ';
  1319. }
  1320. PrintQuotedString(Filename, OS);
  1321. if (Checksum)
  1322. OS << " md5 0x" << Checksum->digest();
  1323. if (Source) {
  1324. OS << " source ";
  1325. PrintQuotedString(*Source, OS);
  1326. }
  1327. }
  1328. Expected<unsigned> MCAsmStreamer::tryEmitDwarfFileDirective(
  1329. unsigned FileNo, StringRef Directory, StringRef Filename,
  1330. Optional<MD5::MD5Result> Checksum, Optional<StringRef> Source, unsigned CUID) {
  1331. assert(CUID == 0 && "multiple CUs not supported by MCAsmStreamer");
  1332. MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
  1333. unsigned NumFiles = Table.getMCDwarfFiles().size();
  1334. Expected<unsigned> FileNoOrErr =
  1335. Table.tryGetFile(Directory, Filename, Checksum, Source,
  1336. getContext().getDwarfVersion(), FileNo);
  1337. if (!FileNoOrErr)
  1338. return FileNoOrErr.takeError();
  1339. FileNo = FileNoOrErr.get();
  1340. // Return early if this file is already emitted before or if target doesn't
  1341. // support .file directive.
  1342. if (NumFiles == Table.getMCDwarfFiles().size() ||
  1343. !MAI->usesDwarfFileAndLocDirectives())
  1344. return FileNo;
  1345. SmallString<128> Str;
  1346. raw_svector_ostream OS1(Str);
  1347. printDwarfFileDirective(FileNo, Directory, Filename, Checksum, Source,
  1348. UseDwarfDirectory, OS1);
  1349. if (MCTargetStreamer *TS = getTargetStreamer())
  1350. TS->emitDwarfFileDirective(OS1.str());
  1351. else
  1352. emitRawText(OS1.str());
  1353. return FileNo;
  1354. }
  1355. void MCAsmStreamer::emitDwarfFile0Directive(StringRef Directory,
  1356. StringRef Filename,
  1357. Optional<MD5::MD5Result> Checksum,
  1358. Optional<StringRef> Source,
  1359. unsigned CUID) {
  1360. assert(CUID == 0);
  1361. // .file 0 is new for DWARF v5.
  1362. if (getContext().getDwarfVersion() < 5)
  1363. return;
  1364. // Inform MCDwarf about the root file.
  1365. getContext().setMCLineTableRootFile(CUID, Directory, Filename, Checksum,
  1366. Source);
  1367. // Target doesn't support .loc/.file directives, return early.
  1368. if (!MAI->usesDwarfFileAndLocDirectives())
  1369. return;
  1370. SmallString<128> Str;
  1371. raw_svector_ostream OS1(Str);
  1372. printDwarfFileDirective(0, Directory, Filename, Checksum, Source,
  1373. UseDwarfDirectory, OS1);
  1374. if (MCTargetStreamer *TS = getTargetStreamer())
  1375. TS->emitDwarfFileDirective(OS1.str());
  1376. else
  1377. emitRawText(OS1.str());
  1378. }
  1379. void MCAsmStreamer::emitDwarfLocDirective(unsigned FileNo, unsigned Line,
  1380. unsigned Column, unsigned Flags,
  1381. unsigned Isa, unsigned Discriminator,
  1382. StringRef FileName) {
  1383. // If target doesn't support .loc/.file directive, we need to record the lines
  1384. // same way like we do in object mode.
  1385. if (!MAI->usesDwarfFileAndLocDirectives()) {
  1386. // In case we see two .loc directives in a row, make sure the
  1387. // first one gets a line entry.
  1388. MCDwarfLineEntry::make(this, getCurrentSectionOnly());
  1389. this->MCStreamer::emitDwarfLocDirective(FileNo, Line, Column, Flags, Isa,
  1390. Discriminator, FileName);
  1391. return;
  1392. }
  1393. OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
  1394. if (MAI->supportsExtendedDwarfLocDirective()) {
  1395. if (Flags & DWARF2_FLAG_BASIC_BLOCK)
  1396. OS << " basic_block";
  1397. if (Flags & DWARF2_FLAG_PROLOGUE_END)
  1398. OS << " prologue_end";
  1399. if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
  1400. OS << " epilogue_begin";
  1401. unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
  1402. if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
  1403. OS << " is_stmt ";
  1404. if (Flags & DWARF2_FLAG_IS_STMT)
  1405. OS << "1";
  1406. else
  1407. OS << "0";
  1408. }
  1409. if (Isa)
  1410. OS << " isa " << Isa;
  1411. if (Discriminator)
  1412. OS << " discriminator " << Discriminator;
  1413. }
  1414. if (IsVerboseAsm) {
  1415. OS.PadToColumn(MAI->getCommentColumn());
  1416. OS << MAI->getCommentString() << ' ' << FileName << ':'
  1417. << Line << ':' << Column;
  1418. }
  1419. EmitEOL();
  1420. this->MCStreamer::emitDwarfLocDirective(FileNo, Line, Column, Flags, Isa,
  1421. Discriminator, FileName);
  1422. }
  1423. MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) {
  1424. // Always use the zeroth line table, since asm syntax only supports one line
  1425. // table for now.
  1426. return MCStreamer::getDwarfLineTableSymbol(0);
  1427. }
  1428. bool MCAsmStreamer::EmitCVFileDirective(unsigned FileNo, StringRef Filename,
  1429. ArrayRef<uint8_t> Checksum,
  1430. unsigned ChecksumKind) {
  1431. if (!getContext().getCVContext().addFile(*this, FileNo, Filename, Checksum,
  1432. ChecksumKind))
  1433. return false;
  1434. OS << "\t.cv_file\t" << FileNo << ' ';
  1435. PrintQuotedString(Filename, OS);
  1436. if (!ChecksumKind) {
  1437. EmitEOL();
  1438. return true;
  1439. }
  1440. OS << ' ';
  1441. PrintQuotedString(toHex(Checksum), OS);
  1442. OS << ' ' << ChecksumKind;
  1443. EmitEOL();
  1444. return true;
  1445. }
  1446. bool MCAsmStreamer::EmitCVFuncIdDirective(unsigned FuncId) {
  1447. OS << "\t.cv_func_id " << FuncId << '\n';
  1448. return MCStreamer::EmitCVFuncIdDirective(FuncId);
  1449. }
  1450. bool MCAsmStreamer::EmitCVInlineSiteIdDirective(unsigned FunctionId,
  1451. unsigned IAFunc,
  1452. unsigned IAFile,
  1453. unsigned IALine, unsigned IACol,
  1454. SMLoc Loc) {
  1455. OS << "\t.cv_inline_site_id " << FunctionId << " within " << IAFunc
  1456. << " inlined_at " << IAFile << ' ' << IALine << ' ' << IACol << '\n';
  1457. return MCStreamer::EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
  1458. IALine, IACol, Loc);
  1459. }
  1460. void MCAsmStreamer::emitCVLocDirective(unsigned FunctionId, unsigned FileNo,
  1461. unsigned Line, unsigned Column,
  1462. bool PrologueEnd, bool IsStmt,
  1463. StringRef FileName, SMLoc Loc) {
  1464. // Validate the directive.
  1465. if (!checkCVLocSection(FunctionId, FileNo, Loc))
  1466. return;
  1467. OS << "\t.cv_loc\t" << FunctionId << " " << FileNo << " " << Line << " "
  1468. << Column;
  1469. if (PrologueEnd)
  1470. OS << " prologue_end";
  1471. if (IsStmt)
  1472. OS << " is_stmt 1";
  1473. if (IsVerboseAsm) {
  1474. OS.PadToColumn(MAI->getCommentColumn());
  1475. OS << MAI->getCommentString() << ' ' << FileName << ':' << Line << ':'
  1476. << Column;
  1477. }
  1478. EmitEOL();
  1479. }
  1480. void MCAsmStreamer::emitCVLinetableDirective(unsigned FunctionId,
  1481. const MCSymbol *FnStart,
  1482. const MCSymbol *FnEnd) {
  1483. OS << "\t.cv_linetable\t" << FunctionId << ", ";
  1484. FnStart->print(OS, MAI);
  1485. OS << ", ";
  1486. FnEnd->print(OS, MAI);
  1487. EmitEOL();
  1488. this->MCStreamer::emitCVLinetableDirective(FunctionId, FnStart, FnEnd);
  1489. }
  1490. void MCAsmStreamer::emitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
  1491. unsigned SourceFileId,
  1492. unsigned SourceLineNum,
  1493. const MCSymbol *FnStartSym,
  1494. const MCSymbol *FnEndSym) {
  1495. OS << "\t.cv_inline_linetable\t" << PrimaryFunctionId << ' ' << SourceFileId
  1496. << ' ' << SourceLineNum << ' ';
  1497. FnStartSym->print(OS, MAI);
  1498. OS << ' ';
  1499. FnEndSym->print(OS, MAI);
  1500. EmitEOL();
  1501. this->MCStreamer::emitCVInlineLinetableDirective(
  1502. PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym);
  1503. }
  1504. void MCAsmStreamer::PrintCVDefRangePrefix(
  1505. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges) {
  1506. OS << "\t.cv_def_range\t";
  1507. for (std::pair<const MCSymbol *, const MCSymbol *> Range : Ranges) {
  1508. OS << ' ';
  1509. Range.first->print(OS, MAI);
  1510. OS << ' ';
  1511. Range.second->print(OS, MAI);
  1512. }
  1513. }
  1514. void MCAsmStreamer::emitCVDefRangeDirective(
  1515. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
  1516. codeview::DefRangeRegisterRelHeader DRHdr) {
  1517. PrintCVDefRangePrefix(Ranges);
  1518. OS << ", reg_rel, ";
  1519. OS << DRHdr.Register << ", " << DRHdr.Flags << ", "
  1520. << DRHdr.BasePointerOffset;
  1521. EmitEOL();
  1522. }
  1523. void MCAsmStreamer::emitCVDefRangeDirective(
  1524. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
  1525. codeview::DefRangeSubfieldRegisterHeader DRHdr) {
  1526. PrintCVDefRangePrefix(Ranges);
  1527. OS << ", subfield_reg, ";
  1528. OS << DRHdr.Register << ", " << DRHdr.OffsetInParent;
  1529. EmitEOL();
  1530. }
  1531. void MCAsmStreamer::emitCVDefRangeDirective(
  1532. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
  1533. codeview::DefRangeRegisterHeader DRHdr) {
  1534. PrintCVDefRangePrefix(Ranges);
  1535. OS << ", reg, ";
  1536. OS << DRHdr.Register;
  1537. EmitEOL();
  1538. }
  1539. void MCAsmStreamer::emitCVDefRangeDirective(
  1540. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
  1541. codeview::DefRangeFramePointerRelHeader DRHdr) {
  1542. PrintCVDefRangePrefix(Ranges);
  1543. OS << ", frame_ptr_rel, ";
  1544. OS << DRHdr.Offset;
  1545. EmitEOL();
  1546. }
  1547. void MCAsmStreamer::emitCVStringTableDirective() {
  1548. OS << "\t.cv_stringtable";
  1549. EmitEOL();
  1550. }
  1551. void MCAsmStreamer::emitCVFileChecksumsDirective() {
  1552. OS << "\t.cv_filechecksums";
  1553. EmitEOL();
  1554. }
  1555. void MCAsmStreamer::emitCVFileChecksumOffsetDirective(unsigned FileNo) {
  1556. OS << "\t.cv_filechecksumoffset\t" << FileNo;
  1557. EmitEOL();
  1558. }
  1559. void MCAsmStreamer::EmitCVFPOData(const MCSymbol *ProcSym, SMLoc L) {
  1560. OS << "\t.cv_fpo_data\t";
  1561. ProcSym->print(OS, MAI);
  1562. EmitEOL();
  1563. }
  1564. void MCAsmStreamer::emitIdent(StringRef IdentString) {
  1565. assert(MAI->hasIdentDirective() && ".ident directive not supported");
  1566. OS << "\t.ident\t";
  1567. PrintQuotedString(IdentString, OS);
  1568. EmitEOL();
  1569. }
  1570. void MCAsmStreamer::emitCFISections(bool EH, bool Debug) {
  1571. MCStreamer::emitCFISections(EH, Debug);
  1572. OS << "\t.cfi_sections ";
  1573. if (EH) {
  1574. OS << ".eh_frame";
  1575. if (Debug)
  1576. OS << ", .debug_frame";
  1577. } else if (Debug) {
  1578. OS << ".debug_frame";
  1579. }
  1580. EmitEOL();
  1581. }
  1582. void MCAsmStreamer::emitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
  1583. OS << "\t.cfi_startproc";
  1584. if (Frame.IsSimple)
  1585. OS << " simple";
  1586. EmitEOL();
  1587. }
  1588. void MCAsmStreamer::emitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
  1589. MCStreamer::emitCFIEndProcImpl(Frame);
  1590. OS << "\t.cfi_endproc";
  1591. EmitEOL();
  1592. }
  1593. void MCAsmStreamer::EmitRegisterName(int64_t Register) {
  1594. if (!MAI->useDwarfRegNumForCFI()) {
  1595. // User .cfi_* directives can use arbitrary DWARF register numbers, not
  1596. // just ones that map to LLVM register numbers and have known names.
  1597. // Fall back to using the original number directly if no name is known.
  1598. const MCRegisterInfo *MRI = getContext().getRegisterInfo();
  1599. if (Optional<unsigned> LLVMRegister = MRI->getLLVMRegNum(Register, true)) {
  1600. InstPrinter->printRegName(OS, *LLVMRegister);
  1601. return;
  1602. }
  1603. }
  1604. OS << Register;
  1605. }
  1606. void MCAsmStreamer::emitCFIDefCfa(int64_t Register, int64_t Offset) {
  1607. MCStreamer::emitCFIDefCfa(Register, Offset);
  1608. OS << "\t.cfi_def_cfa ";
  1609. EmitRegisterName(Register);
  1610. OS << ", " << Offset;
  1611. EmitEOL();
  1612. }
  1613. void MCAsmStreamer::emitCFIDefCfaOffset(int64_t Offset) {
  1614. MCStreamer::emitCFIDefCfaOffset(Offset);
  1615. OS << "\t.cfi_def_cfa_offset " << Offset;
  1616. EmitEOL();
  1617. }
  1618. void MCAsmStreamer::emitCFILLVMDefAspaceCfa(int64_t Register, int64_t Offset,
  1619. int64_t AddressSpace) {
  1620. MCStreamer::emitCFILLVMDefAspaceCfa(Register, Offset, AddressSpace);
  1621. OS << "\t.cfi_llvm_def_aspace_cfa ";
  1622. EmitRegisterName(Register);
  1623. OS << ", " << Offset;
  1624. OS << ", " << AddressSpace;
  1625. EmitEOL();
  1626. }
  1627. static void PrintCFIEscape(llvm::formatted_raw_ostream &OS, StringRef Values) {
  1628. OS << "\t.cfi_escape ";
  1629. if (!Values.empty()) {
  1630. size_t e = Values.size() - 1;
  1631. for (size_t i = 0; i < e; ++i)
  1632. OS << format("0x%02x", uint8_t(Values[i])) << ", ";
  1633. OS << format("0x%02x", uint8_t(Values[e]));
  1634. }
  1635. }
  1636. void MCAsmStreamer::emitCFIEscape(StringRef Values) {
  1637. MCStreamer::emitCFIEscape(Values);
  1638. PrintCFIEscape(OS, Values);
  1639. EmitEOL();
  1640. }
  1641. void MCAsmStreamer::emitCFIGnuArgsSize(int64_t Size) {
  1642. MCStreamer::emitCFIGnuArgsSize(Size);
  1643. uint8_t Buffer[16] = { dwarf::DW_CFA_GNU_args_size };
  1644. unsigned Len = encodeULEB128(Size, Buffer + 1) + 1;
  1645. PrintCFIEscape(OS, StringRef((const char *)&Buffer[0], Len));
  1646. EmitEOL();
  1647. }
  1648. void MCAsmStreamer::emitCFIDefCfaRegister(int64_t Register) {
  1649. MCStreamer::emitCFIDefCfaRegister(Register);
  1650. OS << "\t.cfi_def_cfa_register ";
  1651. EmitRegisterName(Register);
  1652. EmitEOL();
  1653. }
  1654. void MCAsmStreamer::emitCFIOffset(int64_t Register, int64_t Offset) {
  1655. this->MCStreamer::emitCFIOffset(Register, Offset);
  1656. OS << "\t.cfi_offset ";
  1657. EmitRegisterName(Register);
  1658. OS << ", " << Offset;
  1659. EmitEOL();
  1660. }
  1661. void MCAsmStreamer::emitCFIPersonality(const MCSymbol *Sym,
  1662. unsigned Encoding) {
  1663. MCStreamer::emitCFIPersonality(Sym, Encoding);
  1664. OS << "\t.cfi_personality " << Encoding << ", ";
  1665. Sym->print(OS, MAI);
  1666. EmitEOL();
  1667. }
  1668. void MCAsmStreamer::emitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
  1669. MCStreamer::emitCFILsda(Sym, Encoding);
  1670. OS << "\t.cfi_lsda " << Encoding << ", ";
  1671. Sym->print(OS, MAI);
  1672. EmitEOL();
  1673. }
  1674. void MCAsmStreamer::emitCFIRememberState() {
  1675. MCStreamer::emitCFIRememberState();
  1676. OS << "\t.cfi_remember_state";
  1677. EmitEOL();
  1678. }
  1679. void MCAsmStreamer::emitCFIRestoreState() {
  1680. MCStreamer::emitCFIRestoreState();
  1681. OS << "\t.cfi_restore_state";
  1682. EmitEOL();
  1683. }
  1684. void MCAsmStreamer::emitCFIRestore(int64_t Register) {
  1685. MCStreamer::emitCFIRestore(Register);
  1686. OS << "\t.cfi_restore ";
  1687. EmitRegisterName(Register);
  1688. EmitEOL();
  1689. }
  1690. void MCAsmStreamer::emitCFISameValue(int64_t Register) {
  1691. MCStreamer::emitCFISameValue(Register);
  1692. OS << "\t.cfi_same_value ";
  1693. EmitRegisterName(Register);
  1694. EmitEOL();
  1695. }
  1696. void MCAsmStreamer::emitCFIRelOffset(int64_t Register, int64_t Offset) {
  1697. MCStreamer::emitCFIRelOffset(Register, Offset);
  1698. OS << "\t.cfi_rel_offset ";
  1699. EmitRegisterName(Register);
  1700. OS << ", " << Offset;
  1701. EmitEOL();
  1702. }
  1703. void MCAsmStreamer::emitCFIAdjustCfaOffset(int64_t Adjustment) {
  1704. MCStreamer::emitCFIAdjustCfaOffset(Adjustment);
  1705. OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
  1706. EmitEOL();
  1707. }
  1708. void MCAsmStreamer::emitCFISignalFrame() {
  1709. MCStreamer::emitCFISignalFrame();
  1710. OS << "\t.cfi_signal_frame";
  1711. EmitEOL();
  1712. }
  1713. void MCAsmStreamer::emitCFIUndefined(int64_t Register) {
  1714. MCStreamer::emitCFIUndefined(Register);
  1715. OS << "\t.cfi_undefined ";
  1716. EmitRegisterName(Register);
  1717. EmitEOL();
  1718. }
  1719. void MCAsmStreamer::emitCFIRegister(int64_t Register1, int64_t Register2) {
  1720. MCStreamer::emitCFIRegister(Register1, Register2);
  1721. OS << "\t.cfi_register ";
  1722. EmitRegisterName(Register1);
  1723. OS << ", ";
  1724. EmitRegisterName(Register2);
  1725. EmitEOL();
  1726. }
  1727. void MCAsmStreamer::emitCFIWindowSave() {
  1728. MCStreamer::emitCFIWindowSave();
  1729. OS << "\t.cfi_window_save";
  1730. EmitEOL();
  1731. }
  1732. void MCAsmStreamer::emitCFINegateRAState() {
  1733. MCStreamer::emitCFINegateRAState();
  1734. OS << "\t.cfi_negate_ra_state";
  1735. EmitEOL();
  1736. }
  1737. void MCAsmStreamer::emitCFIReturnColumn(int64_t Register) {
  1738. MCStreamer::emitCFIReturnColumn(Register);
  1739. OS << "\t.cfi_return_column ";
  1740. EmitRegisterName(Register);
  1741. EmitEOL();
  1742. }
  1743. void MCAsmStreamer::emitCFIBKeyFrame() {
  1744. MCStreamer::emitCFIBKeyFrame();
  1745. OS << "\t.cfi_b_key_frame";
  1746. EmitEOL();
  1747. }
  1748. void MCAsmStreamer::EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) {
  1749. MCStreamer::EmitWinCFIStartProc(Symbol, Loc);
  1750. OS << ".seh_proc ";
  1751. Symbol->print(OS, MAI);
  1752. EmitEOL();
  1753. }
  1754. void MCAsmStreamer::EmitWinCFIEndProc(SMLoc Loc) {
  1755. MCStreamer::EmitWinCFIEndProc(Loc);
  1756. OS << "\t.seh_endproc";
  1757. EmitEOL();
  1758. }
  1759. void MCAsmStreamer::EmitWinCFIFuncletOrFuncEnd(SMLoc Loc) {
  1760. MCStreamer::EmitWinCFIFuncletOrFuncEnd(Loc);
  1761. OS << "\t.seh_endfunclet";
  1762. EmitEOL();
  1763. }
  1764. void MCAsmStreamer::EmitWinCFIStartChained(SMLoc Loc) {
  1765. MCStreamer::EmitWinCFIStartChained(Loc);
  1766. OS << "\t.seh_startchained";
  1767. EmitEOL();
  1768. }
  1769. void MCAsmStreamer::EmitWinCFIEndChained(SMLoc Loc) {
  1770. MCStreamer::EmitWinCFIEndChained(Loc);
  1771. OS << "\t.seh_endchained";
  1772. EmitEOL();
  1773. }
  1774. void MCAsmStreamer::EmitWinEHHandler(const MCSymbol *Sym, bool Unwind,
  1775. bool Except, SMLoc Loc) {
  1776. MCStreamer::EmitWinEHHandler(Sym, Unwind, Except, Loc);
  1777. OS << "\t.seh_handler ";
  1778. Sym->print(OS, MAI);
  1779. if (Unwind)
  1780. OS << ", @unwind";
  1781. if (Except)
  1782. OS << ", @except";
  1783. EmitEOL();
  1784. }
  1785. void MCAsmStreamer::EmitWinEHHandlerData(SMLoc Loc) {
  1786. MCStreamer::EmitWinEHHandlerData(Loc);
  1787. // Switch sections. Don't call SwitchSection directly, because that will
  1788. // cause the section switch to be visible in the emitted assembly.
  1789. // We only do this so the section switch that terminates the handler
  1790. // data block is visible.
  1791. WinEH::FrameInfo *CurFrame = getCurrentWinFrameInfo();
  1792. // Do nothing if no frame is open. MCStreamer should've already reported an
  1793. // error.
  1794. if (!CurFrame)
  1795. return;
  1796. MCSection *TextSec = &CurFrame->Function->getSection();
  1797. MCSection *XData = getAssociatedXDataSection(TextSec);
  1798. SwitchSectionNoChange(XData);
  1799. OS << "\t.seh_handlerdata";
  1800. EmitEOL();
  1801. }
  1802. void MCAsmStreamer::EmitWinCFIPushReg(MCRegister Register, SMLoc Loc) {
  1803. MCStreamer::EmitWinCFIPushReg(Register, Loc);
  1804. OS << "\t.seh_pushreg ";
  1805. InstPrinter->printRegName(OS, Register);
  1806. EmitEOL();
  1807. }
  1808. void MCAsmStreamer::EmitWinCFISetFrame(MCRegister Register, unsigned Offset,
  1809. SMLoc Loc) {
  1810. MCStreamer::EmitWinCFISetFrame(Register, Offset, Loc);
  1811. OS << "\t.seh_setframe ";
  1812. InstPrinter->printRegName(OS, Register);
  1813. OS << ", " << Offset;
  1814. EmitEOL();
  1815. }
  1816. void MCAsmStreamer::EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) {
  1817. MCStreamer::EmitWinCFIAllocStack(Size, Loc);
  1818. OS << "\t.seh_stackalloc " << Size;
  1819. EmitEOL();
  1820. }
  1821. void MCAsmStreamer::EmitWinCFISaveReg(MCRegister Register, unsigned Offset,
  1822. SMLoc Loc) {
  1823. MCStreamer::EmitWinCFISaveReg(Register, Offset, Loc);
  1824. OS << "\t.seh_savereg ";
  1825. InstPrinter->printRegName(OS, Register);
  1826. OS << ", " << Offset;
  1827. EmitEOL();
  1828. }
  1829. void MCAsmStreamer::EmitWinCFISaveXMM(MCRegister Register, unsigned Offset,
  1830. SMLoc Loc) {
  1831. MCStreamer::EmitWinCFISaveXMM(Register, Offset, Loc);
  1832. OS << "\t.seh_savexmm ";
  1833. InstPrinter->printRegName(OS, Register);
  1834. OS << ", " << Offset;
  1835. EmitEOL();
  1836. }
  1837. void MCAsmStreamer::EmitWinCFIPushFrame(bool Code, SMLoc Loc) {
  1838. MCStreamer::EmitWinCFIPushFrame(Code, Loc);
  1839. OS << "\t.seh_pushframe";
  1840. if (Code)
  1841. OS << " @code";
  1842. EmitEOL();
  1843. }
  1844. void MCAsmStreamer::EmitWinCFIEndProlog(SMLoc Loc) {
  1845. MCStreamer::EmitWinCFIEndProlog(Loc);
  1846. OS << "\t.seh_endprologue";
  1847. EmitEOL();
  1848. }
  1849. void MCAsmStreamer::emitCGProfileEntry(const MCSymbolRefExpr *From,
  1850. const MCSymbolRefExpr *To,
  1851. uint64_t Count) {
  1852. OS << "\t.cg_profile ";
  1853. From->getSymbol().print(OS, MAI);
  1854. OS << ", ";
  1855. To->getSymbol().print(OS, MAI);
  1856. OS << ", " << Count;
  1857. EmitEOL();
  1858. }
  1859. void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
  1860. const MCSubtargetInfo &STI) {
  1861. raw_ostream &OS = GetCommentOS();
  1862. SmallString<256> Code;
  1863. SmallVector<MCFixup, 4> Fixups;
  1864. raw_svector_ostream VecOS(Code);
  1865. // If we have no code emitter, don't emit code.
  1866. if (!getAssembler().getEmitterPtr())
  1867. return;
  1868. getAssembler().getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
  1869. // If we are showing fixups, create symbolic markers in the encoded
  1870. // representation. We do this by making a per-bit map to the fixup item index,
  1871. // then trying to display it as nicely as possible.
  1872. SmallVector<uint8_t, 64> FixupMap;
  1873. FixupMap.resize(Code.size() * 8);
  1874. for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
  1875. FixupMap[i] = 0;
  1876. for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
  1877. MCFixup &F = Fixups[i];
  1878. const MCFixupKindInfo &Info =
  1879. getAssembler().getBackend().getFixupKindInfo(F.getKind());
  1880. for (unsigned j = 0; j != Info.TargetSize; ++j) {
  1881. unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
  1882. assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
  1883. FixupMap[Index] = 1 + i;
  1884. }
  1885. }
  1886. // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
  1887. // high order halfword of a 32-bit Thumb2 instruction is emitted first.
  1888. OS << "encoding: [";
  1889. for (unsigned i = 0, e = Code.size(); i != e; ++i) {
  1890. if (i)
  1891. OS << ',';
  1892. // See if all bits are the same map entry.
  1893. uint8_t MapEntry = FixupMap[i * 8 + 0];
  1894. for (unsigned j = 1; j != 8; ++j) {
  1895. if (FixupMap[i * 8 + j] == MapEntry)
  1896. continue;
  1897. MapEntry = uint8_t(~0U);
  1898. break;
  1899. }
  1900. if (MapEntry != uint8_t(~0U)) {
  1901. if (MapEntry == 0) {
  1902. OS << format("0x%02x", uint8_t(Code[i]));
  1903. } else {
  1904. if (Code[i]) {
  1905. // FIXME: Some of the 8 bits require fix up.
  1906. OS << format("0x%02x", uint8_t(Code[i])) << '\''
  1907. << char('A' + MapEntry - 1) << '\'';
  1908. } else
  1909. OS << char('A' + MapEntry - 1);
  1910. }
  1911. } else {
  1912. // Otherwise, write out in binary.
  1913. OS << "0b";
  1914. for (unsigned j = 8; j--;) {
  1915. unsigned Bit = (Code[i] >> j) & 1;
  1916. unsigned FixupBit;
  1917. if (MAI->isLittleEndian())
  1918. FixupBit = i * 8 + j;
  1919. else
  1920. FixupBit = i * 8 + (7-j);
  1921. if (uint8_t MapEntry = FixupMap[FixupBit]) {
  1922. assert(Bit == 0 && "Encoder wrote into fixed up bit!");
  1923. OS << char('A' + MapEntry - 1);
  1924. } else
  1925. OS << Bit;
  1926. }
  1927. }
  1928. }
  1929. OS << "]\n";
  1930. for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
  1931. MCFixup &F = Fixups[i];
  1932. const MCFixupKindInfo &Info =
  1933. getAssembler().getBackend().getFixupKindInfo(F.getKind());
  1934. OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
  1935. << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
  1936. }
  1937. }
  1938. void MCAsmStreamer::emitInstruction(const MCInst &Inst,
  1939. const MCSubtargetInfo &STI) {
  1940. assert(getCurrentSectionOnly() &&
  1941. "Cannot emit contents before setting section!");
  1942. if (!MAI->usesDwarfFileAndLocDirectives())
  1943. // Now that a machine instruction has been assembled into this section, make
  1944. // a line entry for any .loc directive that has been seen.
  1945. MCDwarfLineEntry::make(this, getCurrentSectionOnly());
  1946. // Show the encoding in a comment if we have a code emitter.
  1947. AddEncodingComment(Inst, STI);
  1948. // Show the MCInst if enabled.
  1949. if (ShowInst) {
  1950. Inst.dump_pretty(GetCommentOS(), InstPrinter.get(), "\n ");
  1951. GetCommentOS() << "\n";
  1952. }
  1953. if(getTargetStreamer())
  1954. getTargetStreamer()->prettyPrintAsm(*InstPrinter, 0, Inst, STI, OS);
  1955. else
  1956. InstPrinter->printInst(&Inst, 0, "", STI, OS);
  1957. StringRef Comments = CommentToEmit;
  1958. if (Comments.size() && Comments.back() != '\n')
  1959. GetCommentOS() << "\n";
  1960. EmitEOL();
  1961. }
  1962. void MCAsmStreamer::emitPseudoProbe(
  1963. uint64_t Guid, uint64_t Index, uint64_t Type, uint64_t Attr,
  1964. const MCPseudoProbeInlineStack &InlineStack) {
  1965. OS << "\t.pseudoprobe\t" << Guid << " " << Index << " " << Type << " "
  1966. << Attr;
  1967. // Emit inline stack like
  1968. // @ GUIDmain:3 @ GUIDCaller:1 @ GUIDDirectCaller:11
  1969. for (const auto &Site : InlineStack)
  1970. OS << " @ " << std::get<0>(Site) << ":" << std::get<1>(Site);
  1971. EmitEOL();
  1972. }
  1973. void MCAsmStreamer::emitBundleAlignMode(unsigned AlignPow2) {
  1974. OS << "\t.bundle_align_mode " << AlignPow2;
  1975. EmitEOL();
  1976. }
  1977. void MCAsmStreamer::emitBundleLock(bool AlignToEnd) {
  1978. OS << "\t.bundle_lock";
  1979. if (AlignToEnd)
  1980. OS << " align_to_end";
  1981. EmitEOL();
  1982. }
  1983. void MCAsmStreamer::emitBundleUnlock() {
  1984. OS << "\t.bundle_unlock";
  1985. EmitEOL();
  1986. }
  1987. Optional<std::pair<bool, std::string>>
  1988. MCAsmStreamer::emitRelocDirective(const MCExpr &Offset, StringRef Name,
  1989. const MCExpr *Expr, SMLoc,
  1990. const MCSubtargetInfo &STI) {
  1991. OS << "\t.reloc ";
  1992. Offset.print(OS, MAI);
  1993. OS << ", " << Name;
  1994. if (Expr) {
  1995. OS << ", ";
  1996. Expr->print(OS, MAI);
  1997. }
  1998. EmitEOL();
  1999. return None;
  2000. }
  2001. void MCAsmStreamer::emitAddrsig() {
  2002. OS << "\t.addrsig";
  2003. EmitEOL();
  2004. }
  2005. void MCAsmStreamer::emitAddrsigSym(const MCSymbol *Sym) {
  2006. OS << "\t.addrsig_sym ";
  2007. Sym->print(OS, MAI);
  2008. EmitEOL();
  2009. }
  2010. /// EmitRawText - If this file is backed by an assembly streamer, this dumps
  2011. /// the specified string in the output .s file. This capability is
  2012. /// indicated by the hasRawTextSupport() predicate.
  2013. void MCAsmStreamer::emitRawTextImpl(StringRef String) {
  2014. if (!String.empty() && String.back() == '\n')
  2015. String = String.substr(0, String.size()-1);
  2016. OS << String;
  2017. EmitEOL();
  2018. }
  2019. void MCAsmStreamer::finishImpl() {
  2020. // If we are generating dwarf for assembly source files dump out the sections.
  2021. if (getContext().getGenDwarfForAssembly())
  2022. MCGenDwarfInfo::Emit(this);
  2023. // Now it is time to emit debug line sections if target doesn't support .loc
  2024. // and .line directives.
  2025. if (!MAI->usesDwarfFileAndLocDirectives()) {
  2026. MCDwarfLineTable::emit(this, getAssembler().getDWARFLinetableParams());
  2027. return;
  2028. }
  2029. // Emit the label for the line table, if requested - since the rest of the
  2030. // line table will be defined by .loc/.file directives, and not emitted
  2031. // directly, the label is the only work required here.
  2032. const auto &Tables = getContext().getMCDwarfLineTables();
  2033. if (!Tables.empty()) {
  2034. assert(Tables.size() == 1 && "asm output only supports one line table");
  2035. if (auto *Label = Tables.begin()->second.getLabel()) {
  2036. SwitchSection(getContext().getObjectFileInfo()->getDwarfLineSection());
  2037. emitLabel(Label);
  2038. }
  2039. }
  2040. }
  2041. void MCAsmStreamer::emitDwarfUnitLength(uint64_t Length, const Twine &Comment) {
  2042. // If the assembler on some target fills in the DWARF unit length, we
  2043. // don't want to emit the length in the compiler. For example, the AIX
  2044. // assembler requires the assembly file with the unit length omitted from
  2045. // the debug section headers. In such cases, any label we placed occurs
  2046. // after the implied length field. We need to adjust the reference here
  2047. // to account for the offset introduced by the inserted length field.
  2048. if (!MAI->needsDwarfSectionSizeInHeader())
  2049. return;
  2050. MCStreamer::emitDwarfUnitLength(Length, Comment);
  2051. }
  2052. MCSymbol *MCAsmStreamer::emitDwarfUnitLength(const Twine &Prefix,
  2053. const Twine &Comment) {
  2054. // If the assembler on some target fills in the DWARF unit length, we
  2055. // don't want to emit the length in the compiler. For example, the AIX
  2056. // assembler requires the assembly file with the unit length omitted from
  2057. // the debug section headers. In such cases, any label we placed occurs
  2058. // after the implied length field. We need to adjust the reference here
  2059. // to account for the offset introduced by the inserted length field.
  2060. if (!MAI->needsDwarfSectionSizeInHeader())
  2061. return getContext().createTempSymbol(Prefix + "_end");
  2062. return MCStreamer::emitDwarfUnitLength(Prefix, Comment);
  2063. }
  2064. void MCAsmStreamer::emitDwarfLineStartLabel(MCSymbol *StartSym) {
  2065. // If the assembler on some target fills in the DWARF unit length, we
  2066. // don't want to emit the length in the compiler. For example, the AIX
  2067. // assembler requires the assembly file with the unit length omitted from
  2068. // the debug section headers. In such cases, any label we placed occurs
  2069. // after the implied length field. We need to adjust the reference here
  2070. // to account for the offset introduced by the inserted length field.
  2071. MCContext &Ctx = getContext();
  2072. if (!MAI->needsDwarfSectionSizeInHeader()) {
  2073. MCSymbol *DebugLineSymTmp = Ctx.createTempSymbol("debug_line_");
  2074. // Emit the symbol which does not contain the unit length field.
  2075. emitLabel(DebugLineSymTmp);
  2076. // Adjust the outer reference to account for the offset introduced by the
  2077. // inserted length field.
  2078. unsigned LengthFieldSize =
  2079. dwarf::getUnitLengthFieldByteSize(Ctx.getDwarfFormat());
  2080. const MCExpr *EntrySize = MCConstantExpr::create(LengthFieldSize, Ctx);
  2081. const MCExpr *OuterSym = MCBinaryExpr::createSub(
  2082. MCSymbolRefExpr::create(DebugLineSymTmp, Ctx), EntrySize, Ctx);
  2083. emitAssignment(StartSym, OuterSym);
  2084. return;
  2085. }
  2086. MCStreamer::emitDwarfLineStartLabel(StartSym);
  2087. }
  2088. void MCAsmStreamer::emitDwarfLineEndEntry(MCSection *Section,
  2089. MCSymbol *LastLabel) {
  2090. // If the targets write the raw debug line data for assembly output (We can
  2091. // not switch to Section and add the end symbol there for assembly output)
  2092. // we currently use the .text end label as any section end. This will not
  2093. // impact the debugability as we will jump to the caller of the last function
  2094. // in the section before we come into the .text end address.
  2095. assert(!MAI->usesDwarfFileAndLocDirectives() &&
  2096. ".loc should not be generated together with raw data!");
  2097. MCContext &Ctx = getContext();
  2098. // FIXME: use section end symbol as end of the Section. We need to consider
  2099. // the explicit sections and -ffunction-sections when we try to generate or
  2100. // find section end symbol for the Section.
  2101. MCSection *TextSection = Ctx.getObjectFileInfo()->getTextSection();
  2102. assert(TextSection->hasEnded() && ".text section is not end!");
  2103. MCSymbol *SectionEnd = TextSection->getEndSymbol(Ctx);
  2104. const MCAsmInfo *AsmInfo = Ctx.getAsmInfo();
  2105. emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
  2106. AsmInfo->getCodePointerSize());
  2107. }
  2108. // Generate DWARF line sections for assembly mode without .loc/.file
  2109. void MCAsmStreamer::emitDwarfAdvanceLineAddr(int64_t LineDelta,
  2110. const MCSymbol *LastLabel,
  2111. const MCSymbol *Label,
  2112. unsigned PointerSize) {
  2113. assert(!MAI->usesDwarfFileAndLocDirectives() &&
  2114. ".loc/.file don't need raw data in debug line section!");
  2115. // Set to new address.
  2116. AddComment("Set address to " + Label->getName());
  2117. emitIntValue(dwarf::DW_LNS_extended_op, 1);
  2118. emitULEB128IntValue(PointerSize + 1);
  2119. emitIntValue(dwarf::DW_LNE_set_address, 1);
  2120. emitSymbolValue(Label, PointerSize);
  2121. if (!LastLabel) {
  2122. // Emit the sequence for the LineDelta (from 1) and a zero address delta.
  2123. AddComment("Start sequence");
  2124. MCDwarfLineAddr::Emit(this, MCDwarfLineTableParams(), LineDelta, 0);
  2125. return;
  2126. }
  2127. // INT64_MAX is a signal of the end of the section. Emit DW_LNE_end_sequence
  2128. // for the end of the section.
  2129. if (LineDelta == INT64_MAX) {
  2130. AddComment("End sequence");
  2131. emitIntValue(dwarf::DW_LNS_extended_op, 1);
  2132. emitULEB128IntValue(1);
  2133. emitIntValue(dwarf::DW_LNE_end_sequence, 1);
  2134. return;
  2135. }
  2136. // Advance line.
  2137. AddComment("Advance line " + Twine(LineDelta));
  2138. emitIntValue(dwarf::DW_LNS_advance_line, 1);
  2139. emitSLEB128IntValue(LineDelta);
  2140. emitIntValue(dwarf::DW_LNS_copy, 1);
  2141. }
  2142. void MCAsmStreamer::doFinalizationAtSectionEnd(MCSection *Section) {
  2143. // Emit section end. This is used to tell the debug line section where the end
  2144. // is for a text section if we don't use .loc to represent the debug line.
  2145. if (MAI->usesDwarfFileAndLocDirectives())
  2146. return;
  2147. SwitchSectionNoChange(Section);
  2148. MCSymbol *Sym = getCurrentSectionOnly()->getEndSymbol(getContext());
  2149. if (!Sym->isInSection())
  2150. emitLabel(Sym);
  2151. }
  2152. MCStreamer *llvm::createAsmStreamer(MCContext &Context,
  2153. std::unique_ptr<formatted_raw_ostream> OS,
  2154. bool isVerboseAsm, bool useDwarfDirectory,
  2155. MCInstPrinter *IP,
  2156. std::unique_ptr<MCCodeEmitter> &&CE,
  2157. std::unique_ptr<MCAsmBackend> &&MAB,
  2158. bool ShowInst) {
  2159. return new MCAsmStreamer(Context, std::move(OS), isVerboseAsm,
  2160. useDwarfDirectory, IP, std::move(CE), std::move(MAB),
  2161. ShowInst);
  2162. }