LLVM  14.0.0git
AsmParser.cpp
Go to the documentation of this file.
1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This class implements a parser for assembly files similar to gas syntax.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/APFloat.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Twine.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCCodeView.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCDirectives.h"
31 #include "llvm/MC/MCDwarf.h"
32 #include "llvm/MC/MCExpr.h"
33 #include "llvm/MC/MCInstPrinter.h"
34 #include "llvm/MC/MCInstrDesc.h"
35 #include "llvm/MC/MCInstrInfo.h"
45 #include "llvm/MC/MCRegisterInfo.h"
46 #include "llvm/MC/MCSection.h"
47 #include "llvm/MC/MCStreamer.h"
48 #include "llvm/MC/MCSymbol.h"
50 #include "llvm/MC/MCValue.h"
51 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/MD5.h"
57 #include "llvm/Support/SMLoc.h"
58 #include "llvm/Support/SourceMgr.h"
60 #include <algorithm>
61 #include <cassert>
62 #include <cctype>
63 #include <climits>
64 #include <cstddef>
65 #include <cstdint>
66 #include <deque>
67 #include <memory>
68 #include <sstream>
69 #include <string>
70 #include <tuple>
71 #include <utility>
72 #include <vector>
73 
74 using namespace llvm;
75 
77 
79 
80 namespace {
81 
82 /// Helper types for tracking macro definitions.
83 typedef std::vector<AsmToken> MCAsmMacroArgument;
84 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
85 
86 /// Helper class for storing information about an active macro
87 /// instantiation.
88 struct MacroInstantiation {
89  /// The location of the instantiation.
90  SMLoc InstantiationLoc;
91 
92  /// The buffer where parsing should resume upon instantiation completion.
93  unsigned ExitBuffer;
94 
95  /// The location where parsing should resume upon instantiation completion.
96  SMLoc ExitLoc;
97 
98  /// The depth of TheCondStack at the start of the instantiation.
99  size_t CondStackDepth;
100 };
101 
102 struct ParseStatementInfo {
103  /// The parsed operands from the last parsed statement.
105 
106  /// The opcode from the last parsed instruction.
107  unsigned Opcode = ~0U;
108 
109  /// Was there an error parsing the inline assembly?
110  bool ParseError = false;
111 
112  SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr;
113 
114  ParseStatementInfo() = delete;
115  ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
116  : AsmRewrites(rewrites) {}
117 };
118 
119 /// The concrete assembly parser instance.
120 class AsmParser : public MCAsmParser {
121 private:
122  AsmLexer Lexer;
123  MCContext &Ctx;
124  MCStreamer &Out;
125  const MCAsmInfo &MAI;
126  SourceMgr &SrcMgr;
127  SourceMgr::DiagHandlerTy SavedDiagHandler;
128  void *SavedDiagContext;
129  std::unique_ptr<MCAsmParserExtension> PlatformParser;
130  SMLoc StartTokLoc;
131 
132  /// This is the current buffer index we're lexing from as managed by the
133  /// SourceMgr object.
134  unsigned CurBuffer;
135 
136  AsmCond TheCondState;
137  std::vector<AsmCond> TheCondStack;
138 
139  /// maps directive names to handler methods in parser
140  /// extensions. Extensions register themselves in this map by calling
141  /// addDirectiveHandler.
142  StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
143 
144  /// Stack of active macro instantiations.
145  std::vector<MacroInstantiation*> ActiveMacros;
146 
147  /// List of bodies of anonymous macros.
148  std::deque<MCAsmMacro> MacroLikeBodies;
149 
150  /// Boolean tracking whether macro substitution is enabled.
151  unsigned MacrosEnabledFlag : 1;
152 
153  /// Keeps track of how many .macro's have been instantiated.
154  unsigned NumOfMacroInstantiations;
155 
156  /// The values from the last parsed cpp hash file line comment if any.
157  struct CppHashInfoTy {
158  StringRef Filename;
159  int64_t LineNumber;
160  SMLoc Loc;
161  unsigned Buf;
162  CppHashInfoTy() : Filename(), LineNumber(0), Loc(), Buf(0) {}
163  };
164  CppHashInfoTy CppHashInfo;
165 
166  /// The filename from the first cpp hash file line comment, if any.
167  StringRef FirstCppHashFilename;
168 
169  /// List of forward directional labels for diagnosis at the end.
171 
172  SmallSet<StringRef, 2> LTODiscardSymbols;
173 
174  /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
175  unsigned AssemblerDialect = ~0U;
176 
177  /// is Darwin compatibility enabled?
178  bool IsDarwin = false;
179 
180  /// Are we parsing ms-style inline assembly?
181  bool ParsingMSInlineAsm = false;
182 
183  /// Did we already inform the user about inconsistent MD5 usage?
184  bool ReportedInconsistentMD5 = false;
185 
186  // Is alt macro mode enabled.
187  bool AltMacroMode = false;
188 
189 protected:
190  virtual bool parseStatement(ParseStatementInfo &Info,
192 
193  /// This routine uses the target specific ParseInstruction function to
194  /// parse an instruction into Operands, and then call the target specific
195  /// MatchAndEmit function to match and emit the instruction.
196  bool parseAndMatchAndEmitTargetInstruction(ParseStatementInfo &Info,
197  StringRef IDVal, AsmToken ID,
198  SMLoc IDLoc);
199 
200  /// Should we emit DWARF describing this assembler source? (Returns false if
201  /// the source has .file directives, which means we don't want to generate
202  /// info describing the assembler source itself.)
203  bool enabledGenDwarfForAssembly();
204 
205 public:
206  AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
207  const MCAsmInfo &MAI, unsigned CB);
208  AsmParser(const AsmParser &) = delete;
209  AsmParser &operator=(const AsmParser &) = delete;
210  ~AsmParser() override;
211 
212  bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
213 
214  void addDirectiveHandler(StringRef Directive,
215  ExtensionDirectiveHandler Handler) override {
216  ExtensionDirectiveMap[Directive] = Handler;
217  }
218 
219  void addAliasForDirective(StringRef Directive, StringRef Alias) override {
220  DirectiveKindMap[Directive.lower()] = DirectiveKindMap[Alias.lower()];
221  }
222 
223  /// @name MCAsmParser Interface
224  /// {
225 
226  SourceMgr &getSourceManager() override { return SrcMgr; }
227  MCAsmLexer &getLexer() override { return Lexer; }
228  MCContext &getContext() override { return Ctx; }
229  MCStreamer &getStreamer() override { return Out; }
230 
231  CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
232 
233  unsigned getAssemblerDialect() override {
234  if (AssemblerDialect == ~0U)
235  return MAI.getAssemblerDialect();
236  else
237  return AssemblerDialect;
238  }
239  void setAssemblerDialect(unsigned i) override {
240  AssemblerDialect = i;
241  }
242 
243  void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
244  bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
245  bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
246 
247  const AsmToken &Lex() override;
248 
249  void setParsingMSInlineAsm(bool V) override {
250  ParsingMSInlineAsm = V;
251  // When parsing MS inline asm, we must lex 0b1101 and 0ABCH as binary and
252  // hex integer literals.
253  Lexer.setLexMasmIntegers(V);
254  }
255  bool isParsingMSInlineAsm() override { return ParsingMSInlineAsm; }
256 
257  bool discardLTOSymbol(StringRef Name) const override {
258  return LTODiscardSymbols.contains(Name);
259  }
260 
261  bool parseMSInlineAsm(std::string &AsmString, unsigned &NumOutputs,
262  unsigned &NumInputs,
263  SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
264  SmallVectorImpl<std::string> &Constraints,
266  const MCInstrInfo *MII, const MCInstPrinter *IP,
267  MCAsmParserSemaCallback &SI) override;
268 
269  bool parseExpression(const MCExpr *&Res);
270  bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
271  bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc,
272  AsmTypeInfo *TypeInfo) override;
273  bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
274  bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
275  SMLoc &EndLoc) override;
276  bool parseAbsoluteExpression(int64_t &Res) override;
277 
278  /// Parse a floating point expression using the float \p Semantics
279  /// and set \p Res to the value.
280  bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
281 
282  /// Parse an identifier or string (as a quoted identifier)
283  /// and set \p Res to the identifier contents.
284  bool parseIdentifier(StringRef &Res) override;
285  void eatToEndOfStatement() override;
286 
287  bool checkForValidSection() override;
288 
289  /// }
290 
291 private:
292  bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
293  bool parseCppHashLineFilenameComment(SMLoc L, bool SaveLocInfo = true);
294 
295  void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
296  ArrayRef<MCAsmMacroParameter> Parameters);
297  bool expandMacro(raw_svector_ostream &OS, StringRef Body,
299  ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
300  SMLoc L);
301 
302  /// Are macros enabled in the parser?
303  bool areMacrosEnabled() {return MacrosEnabledFlag;}
304 
305  /// Control a flag in the parser that enables or disables macros.
306  void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
307 
308  /// Are we inside a macro instantiation?
309  bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
310 
311  /// Handle entry to macro instantiation.
312  ///
313  /// \param M The macro.
314  /// \param NameLoc Instantiation location.
315  bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
316 
317  /// Handle exit from macro instantiation.
318  void handleMacroExit();
319 
320  /// Extract AsmTokens for a macro argument.
321  bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
322 
323  /// Parse all macro arguments for a given macro.
324  bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
325 
326  void printMacroInstantiations();
327  void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
328  SMRange Range = None) const {
329  ArrayRef<SMRange> Ranges(Range);
330  SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
331  }
332  static void DiagHandler(const SMDiagnostic &Diag, void *Context);
333 
334  /// Enter the specified file. This returns true on failure.
335  bool enterIncludeFile(const std::string &Filename);
336 
337  /// Process the specified file for the .incbin directive.
338  /// This returns true on failure.
339  bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
340  const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
341 
342  /// Reset the current lexer position to that given by \p Loc. The
343  /// current token is not set; clients should ensure Lex() is called
344  /// subsequently.
345  ///
346  /// \param InBuffer If not 0, should be the known buffer id that contains the
347  /// location.
348  void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
349 
350  /// Parse up to the end of statement and a return the contents from the
351  /// current token until the end of the statement; the current token on exit
352  /// will be either the EndOfStatement or EOF.
353  StringRef parseStringToEndOfStatement() override;
354 
355  /// Parse until the end of a statement or a comma is encountered,
356  /// return the contents from the current token up to the end or comma.
357  StringRef parseStringToComma();
358 
359  bool parseAssignment(StringRef Name, bool allow_redef,
360  bool NoDeadStrip = false);
361 
362  unsigned getBinOpPrecedence(AsmToken::TokenKind K,
364 
365  bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
366  bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
367  bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
368 
369  bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
370 
371  bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
372  bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
373 
374  // Generic (target and platform independent) directive parsing.
375  enum DirectiveKind {
376  DK_NO_DIRECTIVE, // Placeholder
377  DK_SET,
378  DK_EQU,
379  DK_EQUIV,
380  DK_ASCII,
381  DK_ASCIZ,
382  DK_STRING,
383  DK_BYTE,
384  DK_SHORT,
385  DK_RELOC,
386  DK_VALUE,
387  DK_2BYTE,
388  DK_LONG,
389  DK_INT,
390  DK_4BYTE,
391  DK_QUAD,
392  DK_8BYTE,
393  DK_OCTA,
394  DK_DC,
395  DK_DC_A,
396  DK_DC_B,
397  DK_DC_D,
398  DK_DC_L,
399  DK_DC_S,
400  DK_DC_W,
401  DK_DC_X,
402  DK_DCB,
403  DK_DCB_B,
404  DK_DCB_D,
405  DK_DCB_L,
406  DK_DCB_S,
407  DK_DCB_W,
408  DK_DCB_X,
409  DK_DS,
410  DK_DS_B,
411  DK_DS_D,
412  DK_DS_L,
413  DK_DS_P,
414  DK_DS_S,
415  DK_DS_W,
416  DK_DS_X,
417  DK_SINGLE,
418  DK_FLOAT,
419  DK_DOUBLE,
420  DK_ALIGN,
421  DK_ALIGN32,
422  DK_BALIGN,
423  DK_BALIGNW,
424  DK_BALIGNL,
425  DK_P2ALIGN,
426  DK_P2ALIGNW,
427  DK_P2ALIGNL,
428  DK_ORG,
429  DK_FILL,
430  DK_ENDR,
431  DK_BUNDLE_ALIGN_MODE,
432  DK_BUNDLE_LOCK,
433  DK_BUNDLE_UNLOCK,
434  DK_ZERO,
435  DK_EXTERN,
436  DK_GLOBL,
437  DK_GLOBAL,
438  DK_LAZY_REFERENCE,
439  DK_NO_DEAD_STRIP,
440  DK_SYMBOL_RESOLVER,
441  DK_PRIVATE_EXTERN,
442  DK_REFERENCE,
443  DK_WEAK_DEFINITION,
444  DK_WEAK_REFERENCE,
445  DK_WEAK_DEF_CAN_BE_HIDDEN,
446  DK_COLD,
447  DK_COMM,
448  DK_COMMON,
449  DK_LCOMM,
450  DK_ABORT,
451  DK_INCLUDE,
452  DK_INCBIN,
453  DK_CODE16,
454  DK_CODE16GCC,
455  DK_REPT,
456  DK_IRP,
457  DK_IRPC,
458  DK_IF,
459  DK_IFEQ,
460  DK_IFGE,
461  DK_IFGT,
462  DK_IFLE,
463  DK_IFLT,
464  DK_IFNE,
465  DK_IFB,
466  DK_IFNB,
467  DK_IFC,
468  DK_IFEQS,
469  DK_IFNC,
470  DK_IFNES,
471  DK_IFDEF,
472  DK_IFNDEF,
473  DK_IFNOTDEF,
474  DK_ELSEIF,
475  DK_ELSE,
476  DK_ENDIF,
477  DK_SPACE,
478  DK_SKIP,
479  DK_FILE,
480  DK_LINE,
481  DK_LOC,
482  DK_STABS,
483  DK_CV_FILE,
484  DK_CV_FUNC_ID,
485  DK_CV_INLINE_SITE_ID,
486  DK_CV_LOC,
487  DK_CV_LINETABLE,
488  DK_CV_INLINE_LINETABLE,
489  DK_CV_DEF_RANGE,
490  DK_CV_STRINGTABLE,
491  DK_CV_STRING,
492  DK_CV_FILECHECKSUMS,
493  DK_CV_FILECHECKSUM_OFFSET,
494  DK_CV_FPO_DATA,
495  DK_CFI_SECTIONS,
496  DK_CFI_STARTPROC,
497  DK_CFI_ENDPROC,
498  DK_CFI_DEF_CFA,
499  DK_CFI_DEF_CFA_OFFSET,
500  DK_CFI_ADJUST_CFA_OFFSET,
501  DK_CFI_DEF_CFA_REGISTER,
502  DK_CFI_LLVM_DEF_ASPACE_CFA,
503  DK_CFI_OFFSET,
504  DK_CFI_REL_OFFSET,
505  DK_CFI_PERSONALITY,
506  DK_CFI_LSDA,
507  DK_CFI_REMEMBER_STATE,
508  DK_CFI_RESTORE_STATE,
509  DK_CFI_SAME_VALUE,
510  DK_CFI_RESTORE,
511  DK_CFI_ESCAPE,
512  DK_CFI_RETURN_COLUMN,
513  DK_CFI_SIGNAL_FRAME,
514  DK_CFI_UNDEFINED,
515  DK_CFI_REGISTER,
516  DK_CFI_WINDOW_SAVE,
517  DK_CFI_B_KEY_FRAME,
518  DK_MACROS_ON,
519  DK_MACROS_OFF,
520  DK_ALTMACRO,
521  DK_NOALTMACRO,
522  DK_MACRO,
523  DK_EXITM,
524  DK_ENDM,
525  DK_ENDMACRO,
526  DK_PURGEM,
527  DK_SLEB128,
528  DK_ULEB128,
529  DK_ERR,
530  DK_ERROR,
531  DK_WARNING,
532  DK_PRINT,
533  DK_ADDRSIG,
534  DK_ADDRSIG_SYM,
535  DK_PSEUDO_PROBE,
536  DK_LTO_DISCARD,
537  DK_END
538  };
539 
540  /// Maps directive name --> DirectiveKind enum, for
541  /// directives parsed by this class.
542  StringMap<DirectiveKind> DirectiveKindMap;
543 
544  // Codeview def_range type parsing.
545  enum CVDefRangeType {
546  CVDR_DEFRANGE = 0, // Placeholder
547  CVDR_DEFRANGE_REGISTER,
548  CVDR_DEFRANGE_FRAMEPOINTER_REL,
549  CVDR_DEFRANGE_SUBFIELD_REGISTER,
550  CVDR_DEFRANGE_REGISTER_REL
551  };
552 
553  /// Maps Codeview def_range types --> CVDefRangeType enum, for
554  /// Codeview def_range types parsed by this class.
555  StringMap<CVDefRangeType> CVDefRangeTypeMap;
556 
557  // ".ascii", ".asciz", ".string"
558  bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
559  bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
560  bool parseDirectiveValue(StringRef IDVal,
561  unsigned Size); // ".byte", ".long", ...
562  bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
563  bool parseDirectiveRealValue(StringRef IDVal,
564  const fltSemantics &); // ".single", ...
565  bool parseDirectiveFill(); // ".fill"
566  bool parseDirectiveZero(); // ".zero"
567  // ".set", ".equ", ".equiv"
568  bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
569  bool parseDirectiveOrg(); // ".org"
570  // ".align{,32}", ".p2align{,w,l}"
571  bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
572 
573  // ".file", ".line", ".loc", ".stabs"
574  bool parseDirectiveFile(SMLoc DirectiveLoc);
575  bool parseDirectiveLine();
576  bool parseDirectiveLoc();
577  bool parseDirectiveStabs();
578 
579  // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
580  // ".cv_inline_linetable", ".cv_def_range", ".cv_string"
581  bool parseDirectiveCVFile();
582  bool parseDirectiveCVFuncId();
583  bool parseDirectiveCVInlineSiteId();
584  bool parseDirectiveCVLoc();
585  bool parseDirectiveCVLinetable();
586  bool parseDirectiveCVInlineLinetable();
587  bool parseDirectiveCVDefRange();
588  bool parseDirectiveCVString();
589  bool parseDirectiveCVStringTable();
590  bool parseDirectiveCVFileChecksums();
591  bool parseDirectiveCVFileChecksumOffset();
592  bool parseDirectiveCVFPOData();
593 
594  // .cfi directives
595  bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
596  bool parseDirectiveCFIWindowSave();
597  bool parseDirectiveCFISections();
598  bool parseDirectiveCFIStartProc();
599  bool parseDirectiveCFIEndProc();
600  bool parseDirectiveCFIDefCfaOffset();
601  bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
602  bool parseDirectiveCFIAdjustCfaOffset();
603  bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
604  bool parseDirectiveCFILLVMDefAspaceCfa(SMLoc DirectiveLoc);
605  bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
606  bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
607  bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
608  bool parseDirectiveCFIRememberState();
609  bool parseDirectiveCFIRestoreState();
610  bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
611  bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
612  bool parseDirectiveCFIEscape();
613  bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc);
614  bool parseDirectiveCFISignalFrame();
615  bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
616 
617  // macro directives
618  bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
619  bool parseDirectiveExitMacro(StringRef Directive);
620  bool parseDirectiveEndMacro(StringRef Directive);
621  bool parseDirectiveMacro(SMLoc DirectiveLoc);
622  bool parseDirectiveMacrosOnOff(StringRef Directive);
623  // alternate macro mode directives
624  bool parseDirectiveAltmacro(StringRef Directive);
625  // ".bundle_align_mode"
626  bool parseDirectiveBundleAlignMode();
627  // ".bundle_lock"
628  bool parseDirectiveBundleLock();
629  // ".bundle_unlock"
630  bool parseDirectiveBundleUnlock();
631 
632  // ".space", ".skip"
633  bool parseDirectiveSpace(StringRef IDVal);
634 
635  // ".dcb"
636  bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
637  bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
638  // ".ds"
639  bool parseDirectiveDS(StringRef IDVal, unsigned Size);
640 
641  // .sleb128 (Signed=true) and .uleb128 (Signed=false)
642  bool parseDirectiveLEB128(bool Signed);
643 
644  /// Parse a directive like ".globl" which
645  /// accepts a single symbol (which should be a label or an external).
646  bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
647 
648  bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
649 
650  bool parseDirectiveAbort(); // ".abort"
651  bool parseDirectiveInclude(); // ".include"
652  bool parseDirectiveIncbin(); // ".incbin"
653 
654  // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
655  bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
656  // ".ifb" or ".ifnb", depending on ExpectBlank.
657  bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
658  // ".ifc" or ".ifnc", depending on ExpectEqual.
659  bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
660  // ".ifeqs" or ".ifnes", depending on ExpectEqual.
661  bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
662  // ".ifdef" or ".ifndef", depending on expect_defined
663  bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
664  bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
665  bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
666  bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
667  bool parseEscapedString(std::string &Data) override;
668  bool parseAngleBracketString(std::string &Data) override;
669 
670  const MCExpr *applyModifierToExpr(const MCExpr *E,
672 
673  // Macro-like directives
674  MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
675  void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
676  raw_svector_ostream &OS);
677  bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
678  bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
679  bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
680  bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
681 
682  // "_emit" or "__emit"
683  bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
684  size_t Len);
685 
686  // "align"
687  bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
688 
689  // "end"
690  bool parseDirectiveEnd(SMLoc DirectiveLoc);
691 
692  // ".err" or ".error"
693  bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
694 
695  // ".warning"
696  bool parseDirectiveWarning(SMLoc DirectiveLoc);
697 
698  // .print <double-quotes-string>
699  bool parseDirectivePrint(SMLoc DirectiveLoc);
700 
701  // .pseudoprobe
702  bool parseDirectivePseudoProbe();
703 
704  // ".lto_discard"
705  bool parseDirectiveLTODiscard();
706 
707  // Directives to support address-significance tables.
708  bool parseDirectiveAddrsig();
709  bool parseDirectiveAddrsigSym();
710 
711  void initializeDirectiveKindMap();
712  void initializeCVDefRangeTypeMap();
713 };
714 
715 class HLASMAsmParser final : public AsmParser {
716 private:
717  MCAsmLexer &Lexer;
718  MCStreamer &Out;
719 
720  void lexLeadingSpaces() {
721  while (Lexer.is(AsmToken::Space))
722  Lexer.Lex();
723  }
724 
725  bool parseAsHLASMLabel(ParseStatementInfo &Info, MCAsmParserSemaCallback *SI);
726  bool parseAsMachineInstruction(ParseStatementInfo &Info,
728 
729 public:
730  HLASMAsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
731  const MCAsmInfo &MAI, unsigned CB = 0)
732  : AsmParser(SM, Ctx, Out, MAI, CB), Lexer(getLexer()), Out(Out) {
733  Lexer.setSkipSpace(false);
734  Lexer.setAllowHashInIdentifier(true);
735  Lexer.setLexHLASMIntegers(true);
736  Lexer.setLexHLASMStrings(true);
737  }
738 
739  ~HLASMAsmParser() { Lexer.setSkipSpace(true); }
740 
741  bool parseStatement(ParseStatementInfo &Info,
742  MCAsmParserSemaCallback *SI) override;
743 };
744 
745 } // end anonymous namespace
746 
747 namespace llvm {
748 
754 
755 } // end namespace llvm
756 
757 enum { DEFAULT_ADDRSPACE = 0 };
758 
759 AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
760  const MCAsmInfo &MAI, unsigned CB = 0)
761  : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
762  CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
763  HadError = false;
764  // Save the old handler.
765  SavedDiagHandler = SrcMgr.getDiagHandler();
766  SavedDiagContext = SrcMgr.getDiagContext();
767  // Set our own handler which calls the saved handler.
769  Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
770  // Make MCStreamer aware of the StartTokLoc for locations in diagnostics.
771  Out.setStartTokLocPtr(&StartTokLoc);
772 
773  // Initialize the platform / file format parser.
774  switch (Ctx.getObjectFileType()) {
775  case MCContext::IsCOFF:
776  PlatformParser.reset(createCOFFAsmParser());
777  break;
778  case MCContext::IsMachO:
779  PlatformParser.reset(createDarwinAsmParser());
780  IsDarwin = true;
781  break;
782  case MCContext::IsELF:
783  PlatformParser.reset(createELFAsmParser());
784  break;
785  case MCContext::IsGOFF:
786  report_fatal_error("GOFFAsmParser support not implemented yet");
787  case MCContext::IsWasm:
788  PlatformParser.reset(createWasmAsmParser());
789  break;
790  case MCContext::IsXCOFF:
791  PlatformParser.reset(createXCOFFAsmParser());
792  break;
793  }
794 
795  PlatformParser->Initialize(*this);
796  initializeDirectiveKindMap();
797  initializeCVDefRangeTypeMap();
798 
799  NumOfMacroInstantiations = 0;
800 }
801 
802 AsmParser::~AsmParser() {
803  assert((HadError || ActiveMacros.empty()) &&
804  "Unexpected active macro instantiation!");
805 
806  // Remove MCStreamer's reference to the parser SMLoc.
807  Out.setStartTokLocPtr(nullptr);
808  // Restore the saved diagnostics handler and context for use during
809  // finalization.
810  SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
811 }
812 
813 void AsmParser::printMacroInstantiations() {
814  // Print the active macro instantiation stack.
815  for (std::vector<MacroInstantiation *>::const_reverse_iterator
816  it = ActiveMacros.rbegin(),
817  ie = ActiveMacros.rend();
818  it != ie; ++it)
819  printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
820  "while in macro instantiation");
821 }
822 
823 void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
824  printPendingErrors();
825  printMessage(L, SourceMgr::DK_Note, Msg, Range);
826  printMacroInstantiations();
827 }
828 
829 bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
830  if(getTargetParser().getTargetOptions().MCNoWarn)
831  return false;
832  if (getTargetParser().getTargetOptions().MCFatalWarnings)
833  return Error(L, Msg, Range);
834  printMessage(L, SourceMgr::DK_Warning, Msg, Range);
835  printMacroInstantiations();
836  return false;
837 }
838 
839 bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
840  HadError = true;
841  printMessage(L, SourceMgr::DK_Error, Msg, Range);
842  printMacroInstantiations();
843  return true;
844 }
845 
846 bool AsmParser::enterIncludeFile(const std::string &Filename) {
847  std::string IncludedFile;
848  unsigned NewBuf =
849  SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
850  if (!NewBuf)
851  return true;
852 
853  CurBuffer = NewBuf;
854  Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
855  return false;
856 }
857 
858 /// Process the specified .incbin file by searching for it in the include paths
859 /// then just emitting the byte contents of the file to the streamer. This
860 /// returns true on failure.
861 bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
862  const MCExpr *Count, SMLoc Loc) {
863  std::string IncludedFile;
864  unsigned NewBuf =
865  SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
866  if (!NewBuf)
867  return true;
868 
869  // Pick up the bytes from the file and emit them.
870  StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
871  Bytes = Bytes.drop_front(Skip);
872  if (Count) {
873  int64_t Res;
874  if (!Count->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
875  return Error(Loc, "expected absolute expression");
876  if (Res < 0)
877  return Warning(Loc, "negative count has no effect");
878  Bytes = Bytes.take_front(Res);
879  }
880  getStreamer().emitBytes(Bytes);
881  return false;
882 }
883 
884 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
885  CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
886  Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
887  Loc.getPointer());
888 }
889 
890 const AsmToken &AsmParser::Lex() {
891  if (Lexer.getTok().is(AsmToken::Error))
892  Error(Lexer.getErrLoc(), Lexer.getErr());
893 
894  // if it's a end of statement with a comment in it
895  if (getTok().is(AsmToken::EndOfStatement)) {
896  // if this is a line comment output it.
897  if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
898  getTok().getString().front() != '\r' && MAI.preserveAsmComments())
899  Out.addExplicitComment(Twine(getTok().getString()));
900  }
901 
902  const AsmToken *tok = &Lexer.Lex();
903 
904  // Parse comments here to be deferred until end of next statement.
905  while (tok->is(AsmToken::Comment)) {
906  if (MAI.preserveAsmComments())
907  Out.addExplicitComment(Twine(tok->getString()));
908  tok = &Lexer.Lex();
909  }
910 
911  if (tok->is(AsmToken::Eof)) {
912  // If this is the end of an included file, pop the parent file off the
913  // include stack.
914  SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
915  if (ParentIncludeLoc != SMLoc()) {
916  jumpToLoc(ParentIncludeLoc);
917  return Lex();
918  }
919  }
920 
921  return *tok;
922 }
923 
924 bool AsmParser::enabledGenDwarfForAssembly() {
925  // Check whether the user specified -g.
926  if (!getContext().getGenDwarfForAssembly())
927  return false;
928  // If we haven't encountered any .file directives (which would imply that
929  // the assembler source was produced with debug info already) then emit one
930  // describing the assembler source file itself.
931  if (getContext().getGenDwarfFileNumber() == 0) {
932  // Use the first #line directive for this, if any. It's preprocessed, so
933  // there is no checksum, and of course no source directive.
934  if (!FirstCppHashFilename.empty())
935  getContext().setMCLineTableRootFile(/*CUID=*/0,
936  getContext().getCompilationDir(),
937  FirstCppHashFilename,
938  /*Cksum=*/None, /*Source=*/None);
939  const MCDwarfFile &RootFile =
940  getContext().getMCDwarfLineTable(/*CUID=*/0).getRootFile();
941  getContext().setGenDwarfFileNumber(getStreamer().emitDwarfFileDirective(
942  /*CUID=*/0, getContext().getCompilationDir(), RootFile.Name,
943  RootFile.Checksum, RootFile.Source));
944  }
945  return true;
946 }
947 
948 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
949  LTODiscardSymbols.clear();
950 
951  // Create the initial section, if requested.
952  if (!NoInitialTextSection)
953  Out.InitSections(false);
954 
955  // Prime the lexer.
956  Lex();
957 
958  HadError = false;
959  AsmCond StartingCondState = TheCondState;
960  SmallVector<AsmRewrite, 4> AsmStrRewrites;
961 
962  // If we are generating dwarf for assembly source files save the initial text
963  // section. (Don't use enabledGenDwarfForAssembly() here, as we aren't
964  // emitting any actual debug info yet and haven't had a chance to parse any
965  // embedded .file directives.)
966  if (getContext().getGenDwarfForAssembly()) {
967  MCSection *Sec = getStreamer().getCurrentSectionOnly();
968  if (!Sec->getBeginSymbol()) {
969  MCSymbol *SectionStartSym = getContext().createTempSymbol();
970  getStreamer().emitLabel(SectionStartSym);
971  Sec->setBeginSymbol(SectionStartSym);
972  }
973  bool InsertResult = getContext().addGenDwarfSection(Sec);
974  assert(InsertResult && ".text section should not have debug info yet");
975  (void)InsertResult;
976  }
977 
978  getTargetParser().onBeginOfFile();
979 
980  // While we have input, parse each statement.
981  while (Lexer.isNot(AsmToken::Eof)) {
982  ParseStatementInfo Info(&AsmStrRewrites);
983  bool Parsed = parseStatement(Info, nullptr);
984 
985  // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
986  // for printing ErrMsg via Lex() only if no (presumably better) parser error
987  // exists.
988  if (Parsed && !hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
989  Lex();
990  }
991 
992  // parseStatement returned true so may need to emit an error.
993  printPendingErrors();
994 
995  // Skipping to the next line if needed.
996  if (Parsed && !getLexer().isAtStartOfStatement())
997  eatToEndOfStatement();
998  }
999 
1000  getTargetParser().onEndOfFile();
1001  printPendingErrors();
1002 
1003  // All errors should have been emitted.
1004  assert(!hasPendingError() && "unexpected error from parseStatement");
1005 
1006  getTargetParser().flushPendingInstructions(getStreamer());
1007 
1008  if (TheCondState.TheCond != StartingCondState.TheCond ||
1009  TheCondState.Ignore != StartingCondState.Ignore)
1010  printError(getTok().getLoc(), "unmatched .ifs or .elses");
1011  // Check to see there are no empty DwarfFile slots.
1012  const auto &LineTables = getContext().getMCDwarfLineTables();
1013  if (!LineTables.empty()) {
1014  unsigned Index = 0;
1015  for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
1016  if (File.Name.empty() && Index != 0)
1017  printError(getTok().getLoc(), "unassigned file number: " +
1018  Twine(Index) +
1019  " for .file directives");
1020  ++Index;
1021  }
1022  }
1023 
1024  // Check to see that all assembler local symbols were actually defined.
1025  // Targets that don't do subsections via symbols may not want this, though,
1026  // so conservatively exclude them. Only do this if we're finalizing, though,
1027  // as otherwise we won't necessarilly have seen everything yet.
1028  if (!NoFinalize) {
1029  if (MAI.hasSubsectionsViaSymbols()) {
1030  for (const auto &TableEntry : getContext().getSymbols()) {
1031  MCSymbol *Sym = TableEntry.getValue();
1032  // Variable symbols may not be marked as defined, so check those
1033  // explicitly. If we know it's a variable, we have a definition for
1034  // the purposes of this check.
1035  if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
1036  // FIXME: We would really like to refer back to where the symbol was
1037  // first referenced for a source location. We need to add something
1038  // to track that. Currently, we just point to the end of the file.
1039  printError(getTok().getLoc(), "assembler local symbol '" +
1040  Sym->getName() + "' not defined");
1041  }
1042  }
1043 
1044  // Temporary symbols like the ones for directional jumps don't go in the
1045  // symbol table. They also need to be diagnosed in all (final) cases.
1046  for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
1047  if (std::get<2>(LocSym)->isUndefined()) {
1048  // Reset the state of any "# line file" directives we've seen to the
1049  // context as it was at the diagnostic site.
1050  CppHashInfo = std::get<1>(LocSym);
1051  printError(std::get<0>(LocSym), "directional label undefined");
1052  }
1053  }
1054  }
1055  // Finalize the output stream if there are no errors and if the client wants
1056  // us to.
1057  if (!HadError && !NoFinalize) {
1058  if (auto *TS = Out.getTargetStreamer())
1059  TS->emitConstantPools();
1060 
1061  Out.Finish(Lexer.getLoc());
1062  }
1063 
1064  return HadError || getContext().hadError();
1065 }
1066 
1067 bool AsmParser::checkForValidSection() {
1068  if (!ParsingMSInlineAsm && !getStreamer().getCurrentSectionOnly()) {
1069  Out.InitSections(false);
1070  return Error(getTok().getLoc(),
1071  "expected section directive before assembly directive");
1072  }
1073  return false;
1074 }
1075 
1076 /// Throw away the rest of the line for testing purposes.
1077 void AsmParser::eatToEndOfStatement() {
1078  while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
1079  Lexer.Lex();
1080 
1081  // Eat EOL.
1082  if (Lexer.is(AsmToken::EndOfStatement))
1083  Lexer.Lex();
1084 }
1085 
1086 StringRef AsmParser::parseStringToEndOfStatement() {
1087  const char *Start = getTok().getLoc().getPointer();
1088 
1089  while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
1090  Lexer.Lex();
1091 
1092  const char *End = getTok().getLoc().getPointer();
1093  return StringRef(Start, End - Start);
1094 }
1095 
1096 StringRef AsmParser::parseStringToComma() {
1097  const char *Start = getTok().getLoc().getPointer();
1098 
1099  while (Lexer.isNot(AsmToken::EndOfStatement) &&
1100  Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
1101  Lexer.Lex();
1102 
1103  const char *End = getTok().getLoc().getPointer();
1104  return StringRef(Start, End - Start);
1105 }
1106 
1107 /// Parse a paren expression and return it.
1108 /// NOTE: This assumes the leading '(' has already been consumed.
1109 ///
1110 /// parenexpr ::= expr)
1111 ///
1112 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1113  if (parseExpression(Res))
1114  return true;
1115  if (Lexer.isNot(AsmToken::RParen))
1116  return TokError("expected ')' in parentheses expression");
1117  EndLoc = Lexer.getTok().getEndLoc();
1118  Lex();
1119  return false;
1120 }
1121 
1122 /// Parse a bracket expression and return it.
1123 /// NOTE: This assumes the leading '[' has already been consumed.
1124 ///
1125 /// bracketexpr ::= expr]
1126 ///
1127 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1128  if (parseExpression(Res))
1129  return true;
1130  EndLoc = getTok().getEndLoc();
1131  if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
1132  return true;
1133  return false;
1134 }
1135 
1136 /// Parse a primary expression and return it.
1137 /// primaryexpr ::= (parenexpr
1138 /// primaryexpr ::= symbol
1139 /// primaryexpr ::= number
1140 /// primaryexpr ::= '.'
1141 /// primaryexpr ::= ~,+,- primaryexpr
1142 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc,
1143  AsmTypeInfo *TypeInfo) {
1144  SMLoc FirstTokenLoc = getLexer().getLoc();
1145  AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
1146  switch (FirstTokenKind) {
1147  default:
1148  return TokError("unknown token in expression");
1149  // If we have an error assume that we've already handled it.
1150  case AsmToken::Error:
1151  return true;
1152  case AsmToken::Exclaim:
1153  Lex(); // Eat the operator.
1154  if (parsePrimaryExpr(Res, EndLoc, TypeInfo))
1155  return true;
1156  Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
1157  return false;
1158  case AsmToken::Dollar:
1159  case AsmToken::Star:
1160  case AsmToken::At:
1161  case AsmToken::String:
1162  case AsmToken::Identifier: {
1164  if (parseIdentifier(Identifier)) {
1165  // We may have failed but '$'|'*' may be a valid token in context of
1166  // the current PC.
1167  if (getTok().is(AsmToken::Dollar) || getTok().is(AsmToken::Star)) {
1168  bool ShouldGenerateTempSymbol = false;
1169  if ((getTok().is(AsmToken::Dollar) && MAI.getDollarIsPC()) ||
1170  (getTok().is(AsmToken::Star) && MAI.getStarIsPC()))
1171  ShouldGenerateTempSymbol = true;
1172 
1173  if (!ShouldGenerateTempSymbol)
1174  return Error(FirstTokenLoc, "invalid token in expression");
1175 
1176  // Eat the '$'|'*' token.
1177  Lex();
1178  // This is either a '$'|'*' reference, which references the current PC.
1179  // Emit a temporary label to the streamer and refer to it.
1180  MCSymbol *Sym = Ctx.createTempSymbol();
1181  Out.emitLabel(Sym);
1182  Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
1183  getContext());
1184  EndLoc = FirstTokenLoc;
1185  return false;
1186  }
1187  }
1188  // Parse symbol variant
1189  std::pair<StringRef, StringRef> Split;
1190  if (!MAI.useParensForSymbolVariant()) {
1191  if (FirstTokenKind == AsmToken::String) {
1192  if (Lexer.is(AsmToken::At)) {
1193  Lex(); // eat @
1194  SMLoc AtLoc = getLexer().getLoc();
1195  StringRef VName;
1196  if (parseIdentifier(VName))
1197  return Error(AtLoc, "expected symbol variant after '@'");
1198 
1199  Split = std::make_pair(Identifier, VName);
1200  }
1201  } else {
1202  Split = Identifier.split('@');
1203  }
1204  } else if (Lexer.is(AsmToken::LParen)) {
1205  Lex(); // eat '('.
1206  StringRef VName;
1207  parseIdentifier(VName);
1208  // eat ')'.
1209  if (parseToken(AsmToken::RParen,
1210  "unexpected token in variant, expected ')'"))
1211  return true;
1212  Split = std::make_pair(Identifier, VName);
1213  }
1214 
1215  EndLoc = SMLoc::getFromPointer(Identifier.end());
1216 
1217  // This is a symbol reference.
1219  if (SymbolName.empty())
1220  return Error(getLexer().getLoc(), "expected a symbol reference");
1221 
1222  MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1223 
1224  // Lookup the symbol variant if used.
1225  if (!Split.second.empty()) {
1226  Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
1227  if (Variant != MCSymbolRefExpr::VK_Invalid) {
1228  SymbolName = Split.first;
1229  } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
1230  Variant = MCSymbolRefExpr::VK_None;
1231  } else {
1232  return Error(SMLoc::getFromPointer(Split.second.begin()),
1233  "invalid variant '" + Split.second + "'");
1234  }
1235  }
1236 
1237  MCSymbol *Sym = getContext().getInlineAsmLabel(SymbolName);
1238  if (!Sym)
1239  Sym = getContext().getOrCreateSymbol(
1241 
1242  // If this is an absolute variable reference, substitute it now to preserve
1243  // semantics in the face of reassignment.
1244  if (Sym->isVariable()) {
1245  auto V = Sym->getVariableValue(/*SetUsed*/ false);
1246  bool DoInline = isa<MCConstantExpr>(V) && !Variant;
1247  if (auto TV = dyn_cast<MCTargetExpr>(V))
1248  DoInline = TV->inlineAssignedExpr();
1249  if (DoInline) {
1250  if (Variant)
1251  return Error(EndLoc, "unexpected modifier on variable reference");
1252  Res = Sym->getVariableValue(/*SetUsed*/ false);
1253  return false;
1254  }
1255  }
1256 
1257  // Otherwise create a symbol ref.
1258  Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
1259  return false;
1260  }
1261  case AsmToken::BigNum:
1262  return TokError("literal value out of range for directive");
1263  case AsmToken::Integer: {
1264  SMLoc Loc = getTok().getLoc();
1265  int64_t IntVal = getTok().getIntVal();
1266  Res = MCConstantExpr::create(IntVal, getContext());
1267  EndLoc = Lexer.getTok().getEndLoc();
1268  Lex(); // Eat token.
1269  // Look for 'b' or 'f' following an Integer as a directional label
1270  if (Lexer.getKind() == AsmToken::Identifier) {
1271  StringRef IDVal = getTok().getString();
1272  // Lookup the symbol variant if used.
1273  std::pair<StringRef, StringRef> Split = IDVal.split('@');
1274  MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1275  if (Split.first.size() != IDVal.size()) {
1276  Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
1277  if (Variant == MCSymbolRefExpr::VK_Invalid)
1278  return TokError("invalid variant '" + Split.second + "'");
1279  IDVal = Split.first;
1280  }
1281  if (IDVal == "f" || IDVal == "b") {
1282  MCSymbol *Sym =
1283  Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
1284  Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
1285  if (IDVal == "b" && Sym->isUndefined())
1286  return Error(Loc, "directional label undefined");
1287  DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
1288  EndLoc = Lexer.getTok().getEndLoc();
1289  Lex(); // Eat identifier.
1290  }
1291  }
1292  return false;
1293  }
1294  case AsmToken::Real: {
1295  APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
1296  uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
1297  Res = MCConstantExpr::create(IntVal, getContext());
1298  EndLoc = Lexer.getTok().getEndLoc();
1299  Lex(); // Eat token.
1300  return false;
1301  }
1302  case AsmToken::Dot: {
1303  if (!MAI.getDotIsPC())
1304  return TokError("cannot use . as current PC");
1305 
1306  // This is a '.' reference, which references the current PC. Emit a
1307  // temporary label to the streamer and refer to it.
1308  MCSymbol *Sym = Ctx.createTempSymbol();
1309  Out.emitLabel(Sym);
1310  Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
1311  EndLoc = Lexer.getTok().getEndLoc();
1312  Lex(); // Eat identifier.
1313  return false;
1314  }
1315  case AsmToken::LParen:
1316  Lex(); // Eat the '('.
1317  return parseParenExpr(Res, EndLoc);
1318  case AsmToken::LBrac:
1319  if (!PlatformParser->HasBracketExpressions())
1320  return TokError("brackets expression not supported on this target");
1321  Lex(); // Eat the '['.
1322  return parseBracketExpr(Res, EndLoc);
1323  case AsmToken::Minus:
1324  Lex(); // Eat the operator.
1325  if (parsePrimaryExpr(Res, EndLoc, TypeInfo))
1326  return true;
1327  Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
1328  return false;
1329  case AsmToken::Plus:
1330  Lex(); // Eat the operator.
1331  if (parsePrimaryExpr(Res, EndLoc, TypeInfo))
1332  return true;
1333  Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
1334  return false;
1335  case AsmToken::Tilde:
1336  Lex(); // Eat the operator.
1337  if (parsePrimaryExpr(Res, EndLoc, TypeInfo))
1338  return true;
1339  Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
1340  return false;
1341  // MIPS unary expression operators. The lexer won't generate these tokens if
1342  // MCAsmInfo::HasMipsExpressions is false for the target.
1343  case AsmToken::PercentCall16:
1344  case AsmToken::PercentCall_Hi:
1345  case AsmToken::PercentCall_Lo:
1346  case AsmToken::PercentDtprel_Hi:
1347  case AsmToken::PercentDtprel_Lo:
1348  case AsmToken::PercentGot:
1349  case AsmToken::PercentGot_Disp:
1350  case AsmToken::PercentGot_Hi:
1351  case AsmToken::PercentGot_Lo:
1352  case AsmToken::PercentGot_Ofst:
1353  case AsmToken::PercentGot_Page:
1354  case AsmToken::PercentGottprel:
1355  case AsmToken::PercentGp_Rel:
1356  case AsmToken::PercentHi:
1357  case AsmToken::PercentHigher:
1358  case AsmToken::PercentHighest:
1359  case AsmToken::PercentLo:
1360  case AsmToken::PercentNeg:
1361  case AsmToken::PercentPcrel_Hi:
1362  case AsmToken::PercentPcrel_Lo:
1363  case AsmToken::PercentTlsgd:
1364  case AsmToken::PercentTlsldm:
1365  case AsmToken::PercentTprel_Hi:
1366  case AsmToken::PercentTprel_Lo:
1367  Lex(); // Eat the operator.
1368  if (Lexer.isNot(AsmToken::LParen))
1369  return TokError("expected '(' after operator");
1370  Lex(); // Eat the operator.
1371  if (parseExpression(Res, EndLoc))
1372  return true;
1373  if (Lexer.isNot(AsmToken::RParen))
1374  return TokError("expected ')'");
1375  Lex(); // Eat the operator.
1376  Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1377  return !Res;
1378  }
1379 }
1380 
1381 bool AsmParser::parseExpression(const MCExpr *&Res) {
1382  SMLoc EndLoc;
1383  return parseExpression(Res, EndLoc);
1384 }
1385 
1386 const MCExpr *
1387 AsmParser::applyModifierToExpr(const MCExpr *E,
1388  MCSymbolRefExpr::VariantKind Variant) {
1389  // Ask the target implementation about this expression first.
1390  const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1391  if (NewE)
1392  return NewE;
1393  // Recurse over the given expression, rebuilding it to apply the given variant
1394  // if there is exactly one symbol.
1395  switch (E->getKind()) {
1396  case MCExpr::Target:
1397  case MCExpr::Constant:
1398  return nullptr;
1399 
1400  case MCExpr::SymbolRef: {
1401  const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1402 
1403  if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
1404  TokError("invalid variant on expression '" + getTok().getIdentifier() +
1405  "' (already modified)");
1406  return E;
1407  }
1408 
1409  return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
1410  }
1411 
1412  case MCExpr::Unary: {
1413  const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
1414  const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
1415  if (!Sub)
1416  return nullptr;
1417  return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
1418  }
1419 
1420  case MCExpr::Binary: {
1421  const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1422  const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1423  const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1424 
1425  if (!LHS && !RHS)
1426  return nullptr;
1427 
1428  if (!LHS)
1429  LHS = BE->getLHS();
1430  if (!RHS)
1431  RHS = BE->getRHS();
1432 
1433  return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
1434  }
1435  }
1436 
1437  llvm_unreachable("Invalid expression kind!");
1438 }
1439 
1440 /// This function checks if the next token is <string> type or arithmetic.
1441 /// string that begin with character '<' must end with character '>'.
1442 /// otherwise it is arithmetics.
1443 /// If the function returns a 'true' value,
1444 /// the End argument will be filled with the last location pointed to the '>'
1445 /// character.
1446 
1447 /// There is a gap between the AltMacro's documentation and the single quote
1448 /// implementation. GCC does not fully support this feature and so we will not
1449 /// support it.
1450 /// TODO: Adding single quote as a string.
1451 static bool isAngleBracketString(SMLoc &StrLoc, SMLoc &EndLoc) {
1452  assert((StrLoc.getPointer() != nullptr) &&
1453  "Argument to the function cannot be a NULL value");
1454  const char *CharPtr = StrLoc.getPointer();
1455  while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') &&
1456  (*CharPtr != '\0')) {
1457  if (*CharPtr == '!')
1458  CharPtr++;
1459  CharPtr++;
1460  }
1461  if (*CharPtr == '>') {
1462  EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1463  return true;
1464  }
1465  return false;
1466 }
1467 
1468 /// creating a string without the escape characters '!'.
1469 static std::string angleBracketString(StringRef AltMacroStr) {
1470  std::string Res;
1471  for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) {
1472  if (AltMacroStr[Pos] == '!')
1473  Pos++;
1474  Res += AltMacroStr[Pos];
1475  }
1476  return Res;
1477 }
1478 
1479 /// Parse an expression and return it.
1480 ///
1481 /// expr ::= expr &&,|| expr -> lowest.
1482 /// expr ::= expr |,^,&,! expr
1483 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1484 /// expr ::= expr <<,>> expr
1485 /// expr ::= expr +,- expr
1486 /// expr ::= expr *,/,% expr -> highest.
1487 /// expr ::= primaryexpr
1488 ///
1489 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1490  // Parse the expression.
1491  Res = nullptr;
1492  if (getTargetParser().parsePrimaryExpr(Res, EndLoc) ||
1493  parseBinOpRHS(1, Res, EndLoc))
1494  return true;
1495 
1496  // As a special case, we support 'a op b @ modifier' by rewriting the
1497  // expression to include the modifier. This is inefficient, but in general we
1498  // expect users to use 'a@modifier op b'.
1499  if (Lexer.getKind() == AsmToken::At) {
1500  Lex();
1501 
1502  if (Lexer.isNot(AsmToken::Identifier))
1503  return TokError("unexpected symbol modifier following '@'");
1504 
1506  MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1507  if (Variant == MCSymbolRefExpr::VK_Invalid)
1508  return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1509 
1510  const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1511  if (!ModifiedRes) {
1512  return TokError("invalid modifier '" + getTok().getIdentifier() +
1513  "' (no symbols present)");
1514  }
1515 
1516  Res = ModifiedRes;
1517  Lex();
1518  }
1519 
1520  // Try to constant fold it up front, if possible. Do not exploit
1521  // assembler here.
1522  int64_t Value;
1523  if (Res->evaluateAsAbsolute(Value))
1524  Res = MCConstantExpr::create(Value, getContext());
1525 
1526  return false;
1527 }
1528 
1529 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1530  Res = nullptr;
1531  return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1532 }
1533 
1534 bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1535  SMLoc &EndLoc) {
1536  if (parseParenExpr(Res, EndLoc))
1537  return true;
1538 
1539  for (; ParenDepth > 0; --ParenDepth) {
1540  if (parseBinOpRHS(1, Res, EndLoc))
1541  return true;
1542 
1543  // We don't Lex() the last RParen.
1544  // This is the same behavior as parseParenExpression().
1545  if (ParenDepth - 1 > 0) {
1546  EndLoc = getTok().getEndLoc();
1547  if (parseToken(AsmToken::RParen,
1548  "expected ')' in parentheses expression"))
1549  return true;
1550  }
1551  }
1552  return false;
1553 }
1554 
1555 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1556  const MCExpr *Expr;
1557 
1558  SMLoc StartLoc = Lexer.getLoc();
1559  if (parseExpression(Expr))
1560  return true;
1561 
1562  if (!Expr->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
1563  return Error(StartLoc, "expected absolute expression");
1564 
1565  return false;
1566 }
1567 
1570  bool ShouldUseLogicalShr) {
1571  switch (K) {
1572  default:
1573  return 0; // not a binop.
1574 
1575  // Lowest Precedence: &&, ||
1576  case AsmToken::AmpAmp:
1577  Kind = MCBinaryExpr::LAnd;
1578  return 1;
1579  case AsmToken::PipePipe:
1580  Kind = MCBinaryExpr::LOr;
1581  return 1;
1582 
1583  // Low Precedence: |, &, ^
1584  case AsmToken::Pipe:
1585  Kind = MCBinaryExpr::Or;
1586  return 2;
1587  case AsmToken::Caret:
1588  Kind = MCBinaryExpr::Xor;
1589  return 2;
1590  case AsmToken::Amp:
1591  Kind = MCBinaryExpr::And;
1592  return 2;
1593 
1594  // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1595  case AsmToken::EqualEqual:
1597  return 3;
1598  case AsmToken::ExclaimEqual:
1599  case AsmToken::LessGreater:
1601  return 3;
1602  case AsmToken::Less:
1604  return 3;
1605  case AsmToken::LessEqual:
1606  Kind = MCBinaryExpr::LTE;
1607  return 3;
1608  case AsmToken::Greater:
1610  return 3;
1611  case AsmToken::GreaterEqual:
1612  Kind = MCBinaryExpr::GTE;
1613  return 3;
1614 
1615  // Intermediate Precedence: <<, >>
1616  case AsmToken::LessLess:
1617  Kind = MCBinaryExpr::Shl;
1618  return 4;
1619  case AsmToken::GreaterGreater:
1620  Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1621  return 4;
1622 
1623  // High Intermediate Precedence: +, -
1624  case AsmToken::Plus:
1626  return 5;
1627  case AsmToken::Minus:
1628  Kind = MCBinaryExpr::Sub;
1629  return 5;
1630 
1631  // Highest Precedence: *, /, %
1632  case AsmToken::Star:
1633  Kind = MCBinaryExpr::Mul;
1634  return 6;
1635  case AsmToken::Slash:
1636  Kind = MCBinaryExpr::Div;
1637  return 6;
1638  case AsmToken::Percent:
1640  return 6;
1641  }
1642 }
1643 
1644 static unsigned getGNUBinOpPrecedence(const MCAsmInfo &MAI,
1647  bool ShouldUseLogicalShr) {
1648  switch (K) {
1649  default:
1650  return 0; // not a binop.
1651 
1652  // Lowest Precedence: &&, ||
1653  case AsmToken::AmpAmp:
1654  Kind = MCBinaryExpr::LAnd;
1655  return 2;
1656  case AsmToken::PipePipe:
1657  Kind = MCBinaryExpr::LOr;
1658  return 1;
1659 
1660  // Low Precedence: ==, !=, <>, <, <=, >, >=
1661  case AsmToken::EqualEqual:
1663  return 3;
1664  case AsmToken::ExclaimEqual:
1665  case AsmToken::LessGreater:
1667  return 3;
1668  case AsmToken::Less:
1670  return 3;
1671  case AsmToken::LessEqual:
1672  Kind = MCBinaryExpr::LTE;
1673  return 3;
1674  case AsmToken::Greater:
1676  return 3;
1677  case AsmToken::GreaterEqual:
1678  Kind = MCBinaryExpr::GTE;
1679  return 3;
1680 
1681  // Low Intermediate Precedence: +, -
1682  case AsmToken::Plus:
1684  return 4;
1685  case AsmToken::Minus:
1686  Kind = MCBinaryExpr::Sub;
1687  return 4;
1688 
1689  // High Intermediate Precedence: |, !, &, ^
1690  //
1691  case AsmToken::Pipe:
1692  Kind = MCBinaryExpr::Or;
1693  return 5;
1694  case AsmToken::Exclaim:
1695  // Hack to support ARM compatible aliases (implied 'sp' operand in 'srs*'
1696  // instructions like 'srsda #31!') and not parse ! as an infix operator.
1697  if (MAI.getCommentString() == "@")
1698  return 0;
1699  Kind = MCBinaryExpr::OrNot;
1700  return 5;
1701  case AsmToken::Caret:
1702  Kind = MCBinaryExpr::Xor;
1703  return 5;
1704  case AsmToken::Amp:
1705  Kind = MCBinaryExpr::And;
1706  return 5;
1707 
1708  // Highest Precedence: *, /, %, <<, >>
1709  case AsmToken::Star:
1710  Kind = MCBinaryExpr::Mul;
1711  return 6;
1712  case AsmToken::Slash:
1713  Kind = MCBinaryExpr::Div;
1714  return 6;
1715  case AsmToken::Percent:
1717  return 6;
1718  case AsmToken::LessLess:
1719  Kind = MCBinaryExpr::Shl;
1720  return 6;
1721  case AsmToken::GreaterGreater:
1722  Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1723  return 6;
1724  }
1725 }
1726 
1727 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1729  bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1730  return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1731  : getGNUBinOpPrecedence(MAI, K, Kind, ShouldUseLogicalShr);
1732 }
1733 
1734 /// Parse all binary operators with precedence >= 'Precedence'.
1735 /// Res contains the LHS of the expression on input.
1736 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1737  SMLoc &EndLoc) {
1738  SMLoc StartLoc = Lexer.getLoc();
1739  while (true) {
1741  unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1742 
1743  // If the next token is lower precedence than we are allowed to eat, return
1744  // successfully with what we ate already.
1745  if (TokPrec < Precedence)
1746  return false;
1747 
1748  Lex();
1749 
1750  // Eat the next primary expression.
1751  const MCExpr *RHS;
1752  if (getTargetParser().parsePrimaryExpr(RHS, EndLoc))
1753  return true;
1754 
1755  // If BinOp binds less tightly with RHS than the operator after RHS, let
1756  // the pending operator take RHS as its LHS.
1758  unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1759  if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1760  return true;
1761 
1762  // Merge LHS and RHS according to operator.
1763  Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
1764  }
1765 }
1766 
1767 /// ParseStatement:
1768 /// ::= EndOfStatement
1769 /// ::= Label* Directive ...Operands... EndOfStatement
1770 /// ::= Label* Identifier OperandList* EndOfStatement
1771 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1773  assert(!hasPendingError() && "parseStatement started with pending error");
1774  // Eat initial spaces and comments
1775  while (Lexer.is(AsmToken::Space))
1776  Lex();
1777  if (Lexer.is(AsmToken::EndOfStatement)) {
1778  // if this is a line comment we can drop it safely
1779  if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
1780  getTok().getString().front() == '\n')
1781  Out.AddBlankLine();
1782  Lex();
1783  return false;
1784  }
1785  // Statements always start with an identifier.
1786  AsmToken ID = getTok();
1787  SMLoc IDLoc = ID.getLoc();
1788  StringRef IDVal;
1789  int64_t LocalLabelVal = -1;
1790  StartTokLoc = ID.getLoc();
1791  if (Lexer.is(AsmToken::HashDirective))
1792  return parseCppHashLineFilenameComment(IDLoc,
1793  !isInsideMacroInstantiation());
1794 
1795  // Allow an integer followed by a ':' as a directional local label.
1796  if (Lexer.is(AsmToken::Integer)) {
1797  LocalLabelVal = getTok().getIntVal();
1798  if (LocalLabelVal < 0) {
1799  if (!TheCondState.Ignore) {
1800  Lex(); // always eat a token
1801  return Error(IDLoc, "unexpected token at start of statement");
1802  }
1803  IDVal = "";
1804  } else {
1805  IDVal = getTok().getString();
1806  Lex(); // Consume the integer token to be used as an identifier token.
1807  if (Lexer.getKind() != AsmToken::Colon) {
1808  if (!TheCondState.Ignore) {
1809  Lex(); // always eat a token
1810  return Error(IDLoc, "unexpected token at start of statement");
1811  }
1812  }
1813  }
1814  } else if (Lexer.is(AsmToken::Dot)) {
1815  // Treat '.' as a valid identifier in this context.
1816  Lex();
1817  IDVal = ".";
1818  } else if (Lexer.is(AsmToken::LCurly)) {
1819  // Treat '{' as a valid identifier in this context.
1820  Lex();
1821  IDVal = "{";
1822 
1823  } else if (Lexer.is(AsmToken::RCurly)) {
1824  // Treat '}' as a valid identifier in this context.
1825  Lex();
1826  IDVal = "}";
1827  } else if (Lexer.is(AsmToken::Star) &&
1828  getTargetParser().starIsStartOfStatement()) {
1829  // Accept '*' as a valid start of statement.
1830  Lex();
1831  IDVal = "*";
1832  } else if (parseIdentifier(IDVal)) {
1833  if (!TheCondState.Ignore) {
1834  Lex(); // always eat a token
1835  return Error(IDLoc, "unexpected token at start of statement");
1836  }
1837  IDVal = "";
1838  }
1839 
1840  // Handle conditional assembly here before checking for skipping. We
1841  // have to do this so that .endif isn't skipped in a ".if 0" block for
1842  // example.
1844  DirectiveKindMap.find(IDVal.lower());
1845  DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1846  ? DK_NO_DIRECTIVE
1847  : DirKindIt->getValue();
1848  switch (DirKind) {
1849  default:
1850  break;
1851  case DK_IF:
1852  case DK_IFEQ:
1853  case DK_IFGE:
1854  case DK_IFGT:
1855  case DK_IFLE:
1856  case DK_IFLT:
1857  case DK_IFNE:
1858  return parseDirectiveIf(IDLoc, DirKind);
1859  case DK_IFB:
1860  return parseDirectiveIfb(IDLoc, true);
1861  case DK_IFNB:
1862  return parseDirectiveIfb(IDLoc, false);
1863  case DK_IFC:
1864  return parseDirectiveIfc(IDLoc, true);
1865  case DK_IFEQS:
1866  return parseDirectiveIfeqs(IDLoc, true);
1867  case DK_IFNC:
1868  return parseDirectiveIfc(IDLoc, false);
1869  case DK_IFNES:
1870  return parseDirectiveIfeqs(IDLoc, false);
1871  case DK_IFDEF:
1872  return parseDirectiveIfdef(IDLoc, true);
1873  case DK_IFNDEF:
1874  case DK_IFNOTDEF:
1875  return parseDirectiveIfdef(IDLoc, false);
1876  case DK_ELSEIF:
1877  return parseDirectiveElseIf(IDLoc);
1878  case DK_ELSE:
1879  return parseDirectiveElse(IDLoc);
1880  case DK_ENDIF:
1881  return parseDirectiveEndIf(IDLoc);
1882  }
1883 
1884  // Ignore the statement if in the middle of inactive conditional
1885  // (e.g. ".if 0").
1886  if (TheCondState.Ignore) {
1887  eatToEndOfStatement();
1888  return false;
1889  }
1890 
1891  // FIXME: Recurse on local labels?
1892 
1893  // See what kind of statement we have.
1894  switch (Lexer.getKind()) {
1895  case AsmToken::Colon: {
1896  if (!getTargetParser().isLabel(ID))
1897  break;
1898  if (checkForValidSection())
1899  return true;
1900 
1901  // identifier ':' -> Label.
1902  Lex();
1903 
1904  // Diagnose attempt to use '.' as a label.
1905  if (IDVal == ".")
1906  return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1907 
1908  // Diagnose attempt to use a variable as a label.
1909  //
1910  // FIXME: Diagnostics. Note the location of the definition as a label.
1911  // FIXME: This doesn't diagnose assignment to a symbol which has been
1912  // implicitly marked as external.
1913  MCSymbol *Sym;
1914  if (LocalLabelVal == -1) {
1915  if (ParsingMSInlineAsm && SI) {
1916  StringRef RewrittenLabel =
1917  SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1918  assert(!RewrittenLabel.empty() &&
1919  "We should have an internal name here.");
1920  Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1921  RewrittenLabel);
1922  IDVal = RewrittenLabel;
1923  }
1924  Sym = getContext().getOrCreateSymbol(IDVal);
1925  } else
1926  Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1927  // End of Labels should be treated as end of line for lexing
1928  // purposes but that information is not available to the Lexer who
1929  // does not understand Labels. This may cause us to see a Hash
1930  // here instead of a preprocessor line comment.
1931  if (getTok().is(AsmToken::Hash)) {
1932  StringRef CommentStr = parseStringToEndOfStatement();
1933  Lexer.Lex();
1934  Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1935  }
1936 
1937  // Consume any end of statement token, if present, to avoid spurious
1938  // AddBlankLine calls().
1939  if (getTok().is(AsmToken::EndOfStatement)) {
1940  Lex();
1941  }
1942 
1943  if (discardLTOSymbol(IDVal))
1944  return false;
1945 
1946  getTargetParser().doBeforeLabelEmit(Sym);
1947 
1948  // Emit the label.
1949  if (!getTargetParser().isParsingMSInlineAsm())
1950  Out.emitLabel(Sym, IDLoc);
1951 
1952  // If we are generating dwarf for assembly source files then gather the
1953  // info to make a dwarf label entry for this label if needed.
1954  if (enabledGenDwarfForAssembly())
1955  MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1956  IDLoc);
1957 
1958  getTargetParser().onLabelParsed(Sym);
1959 
1960  return false;
1961  }
1962 
1963  case AsmToken::Equal:
1964  if (!getTargetParser().equalIsAsmAssignment())
1965  break;
1966  // identifier '=' ... -> assignment statement
1967  Lex();
1968 
1969  return parseAssignment(IDVal, true);
1970 
1971  default: // Normal instruction or directive.
1972  break;
1973  }
1974 
1975  // If macros are enabled, check to see if this is a macro instantiation.
1976  if (areMacrosEnabled())
1977  if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) {
1978  return handleMacroEntry(M, IDLoc);
1979  }
1980 
1981  // Otherwise, we have a normal instruction or directive.
1982 
1983  // Directives start with "."
1984  if (IDVal.startswith(".") && IDVal != ".") {
1985  // There are several entities interested in parsing directives:
1986  //
1987  // 1. The target-specific assembly parser. Some directives are target
1988  // specific or may potentially behave differently on certain targets.
1989  // 2. Asm parser extensions. For example, platform-specific parsers
1990  // (like the ELF parser) register themselves as extensions.
1991  // 3. The generic directive parser implemented by this class. These are
1992  // all the directives that behave in a target and platform independent
1993  // manner, or at least have a default behavior that's shared between
1994  // all targets and platforms.
1995 
1996  getTargetParser().flushPendingInstructions(getStreamer());
1997 
1998  SMLoc StartTokLoc = getTok().getLoc();
1999  bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
2000 
2001  if (hasPendingError())
2002  return true;
2003  // Currently the return value should be true if we are
2004  // uninterested but as this is at odds with the standard parsing
2005  // convention (return true = error) we have instances of a parsed
2006  // directive that fails returning true as an error. Catch these
2007  // cases as best as possible errors here.
2008  if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
2009  return true;
2010  // Return if we did some parsing or believe we succeeded.
2011  if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
2012  return false;
2013 
2014  // Next, check the extension directive map to see if any extension has
2015  // registered itself to parse this directive.
2016  std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
2017  ExtensionDirectiveMap.lookup(IDVal);
2018  if (Handler.first)
2019  return (*Handler.second)(Handler.first, IDVal, IDLoc);
2020 
2021  // Finally, if no one else is interested in this directive, it must be
2022  // generic and familiar to this class.
2023  switch (DirKind) {
2024  default:
2025  break;
2026  case DK_SET:
2027  case DK_EQU:
2028  return parseDirectiveSet(IDVal, true);
2029  case DK_EQUIV:
2030  return parseDirectiveSet(IDVal, false);
2031  case DK_ASCII:
2032  return parseDirectiveAscii(IDVal, false);
2033  case DK_ASCIZ:
2034  case DK_STRING:
2035  return parseDirectiveAscii(IDVal, true);
2036  case DK_BYTE:
2037  case DK_DC_B:
2038  return parseDirectiveValue(IDVal, 1);
2039  case DK_DC:
2040  case DK_DC_W:
2041  case DK_SHORT:
2042  case DK_VALUE:
2043  case DK_2BYTE:
2044  return parseDirectiveValue(IDVal, 2);
2045  case DK_LONG:
2046  case DK_INT:
2047  case DK_4BYTE:
2048  case DK_DC_L:
2049  return parseDirectiveValue(IDVal, 4);
2050  case DK_QUAD:
2051  case DK_8BYTE:
2052  return parseDirectiveValue(IDVal, 8);
2053  case DK_DC_A:
2054  return parseDirectiveValue(
2055  IDVal, getContext().getAsmInfo()->getCodePointerSize());
2056  case DK_OCTA:
2057  return parseDirectiveOctaValue(IDVal);
2058  case DK_SINGLE:
2059  case DK_FLOAT:
2060  case DK_DC_S:
2061  return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
2062  case DK_DOUBLE:
2063  case DK_DC_D:
2064  return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
2065  case DK_ALIGN: {
2066  bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
2067  return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
2068  }
2069  case DK_ALIGN32: {
2070  bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
2071  return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
2072  }
2073  case DK_BALIGN:
2074  return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
2075  case DK_BALIGNW:
2076  return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
2077  case DK_BALIGNL:
2078  return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
2079  case DK_P2ALIGN:
2080  return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
2081  case DK_P2ALIGNW:
2082  return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
2083  case DK_P2ALIGNL:
2084  return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
2085  case DK_ORG:
2086  return parseDirectiveOrg();
2087  case DK_FILL:
2088  return parseDirectiveFill();
2089  case DK_ZERO:
2090  return parseDirectiveZero();
2091  case DK_EXTERN:
2092  eatToEndOfStatement(); // .extern is the default, ignore it.
2093  return false;
2094  case DK_GLOBL:
2095  case DK_GLOBAL:
2096  return parseDirectiveSymbolAttribute(MCSA_Global);
2097  case DK_LAZY_REFERENCE:
2098  return parseDirectiveSymbolAttribute(MCSA_LazyReference);
2099  case DK_NO_DEAD_STRIP:
2100  return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
2101  case DK_SYMBOL_RESOLVER:
2102  return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
2103  case DK_PRIVATE_EXTERN:
2104  return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
2105  case DK_REFERENCE:
2106  return parseDirectiveSymbolAttribute(MCSA_Reference);
2107  case DK_WEAK_DEFINITION:
2108  return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
2109  case DK_WEAK_REFERENCE:
2110  return parseDirectiveSymbolAttribute(MCSA_WeakReference);
2111  case DK_WEAK_DEF_CAN_BE_HIDDEN:
2112  return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
2113  case DK_COLD:
2114  return parseDirectiveSymbolAttribute(MCSA_Cold);
2115  case DK_COMM:
2116  case DK_COMMON:
2117  return parseDirectiveComm(/*IsLocal=*/false);
2118  case DK_LCOMM:
2119  return parseDirectiveComm(/*IsLocal=*/true);
2120  case DK_ABORT:
2121  return parseDirectiveAbort();
2122  case DK_INCLUDE:
2123  return parseDirectiveInclude();
2124  case DK_INCBIN:
2125  return parseDirectiveIncbin();
2126  case DK_CODE16:
2127  case DK_CODE16GCC:
2128  return TokError(Twine(IDVal) +
2129  " not currently supported for this target");
2130  case DK_REPT:
2131  return parseDirectiveRept(IDLoc, IDVal);
2132  case DK_IRP:
2133  return parseDirectiveIrp(IDLoc);
2134  case DK_IRPC:
2135  return parseDirectiveIrpc(IDLoc);
2136  case DK_ENDR:
2137  return parseDirectiveEndr(IDLoc);
2138  case DK_BUNDLE_ALIGN_MODE:
2139  return parseDirectiveBundleAlignMode();
2140  case DK_BUNDLE_LOCK:
2141  return parseDirectiveBundleLock();
2142  case DK_BUNDLE_UNLOCK:
2143  return parseDirectiveBundleUnlock();
2144  case DK_SLEB128:
2145  return parseDirectiveLEB128(true);
2146  case DK_ULEB128:
2147  return parseDirectiveLEB128(false);
2148  case DK_SPACE:
2149  case DK_SKIP:
2150  return parseDirectiveSpace(IDVal);
2151  case DK_FILE:
2152  return parseDirectiveFile(IDLoc);
2153  case DK_LINE:
2154  return parseDirectiveLine();
2155  case DK_LOC:
2156  return parseDirectiveLoc();
2157  case DK_STABS:
2158  return parseDirectiveStabs();
2159  case DK_CV_FILE:
2160  return parseDirectiveCVFile();
2161  case DK_CV_FUNC_ID:
2162  return parseDirectiveCVFuncId();
2163  case DK_CV_INLINE_SITE_ID:
2164  return parseDirectiveCVInlineSiteId();
2165  case DK_CV_LOC:
2166  return parseDirectiveCVLoc();
2167  case DK_CV_LINETABLE:
2168  return parseDirectiveCVLinetable();
2169  case DK_CV_INLINE_LINETABLE:
2170  return parseDirectiveCVInlineLinetable();
2171  case DK_CV_DEF_RANGE:
2172  return parseDirectiveCVDefRange();
2173  case DK_CV_STRING:
2174  return parseDirectiveCVString();
2175  case DK_CV_STRINGTABLE:
2176  return parseDirectiveCVStringTable();
2177  case DK_CV_FILECHECKSUMS:
2178  return parseDirectiveCVFileChecksums();
2179  case DK_CV_FILECHECKSUM_OFFSET:
2180  return parseDirectiveCVFileChecksumOffset();
2181  case DK_CV_FPO_DATA:
2182  return parseDirectiveCVFPOData();
2183  case DK_CFI_SECTIONS:
2184  return parseDirectiveCFISections();
2185  case DK_CFI_STARTPROC:
2186  return parseDirectiveCFIStartProc();
2187  case DK_CFI_ENDPROC:
2188  return parseDirectiveCFIEndProc();
2189  case DK_CFI_DEF_CFA:
2190  return parseDirectiveCFIDefCfa(IDLoc);
2191  case DK_CFI_DEF_CFA_OFFSET:
2192  return parseDirectiveCFIDefCfaOffset();
2193  case DK_CFI_ADJUST_CFA_OFFSET:
2194  return parseDirectiveCFIAdjustCfaOffset();
2195  case DK_CFI_DEF_CFA_REGISTER:
2196  return parseDirectiveCFIDefCfaRegister(IDLoc);
2197  case DK_CFI_LLVM_DEF_ASPACE_CFA:
2198  return parseDirectiveCFILLVMDefAspaceCfa(IDLoc);
2199  case DK_CFI_OFFSET:
2200  return parseDirectiveCFIOffset(IDLoc);
2201  case DK_CFI_REL_OFFSET:
2202  return parseDirectiveCFIRelOffset(IDLoc);
2203  case DK_CFI_PERSONALITY:
2204  return parseDirectiveCFIPersonalityOrLsda(true);
2205  case DK_CFI_LSDA:
2206  return parseDirectiveCFIPersonalityOrLsda(false);
2207  case DK_CFI_REMEMBER_STATE:
2208  return parseDirectiveCFIRememberState();
2209  case DK_CFI_RESTORE_STATE:
2210  return parseDirectiveCFIRestoreState();
2211  case DK_CFI_SAME_VALUE:
2212  return parseDirectiveCFISameValue(IDLoc);
2213  case DK_CFI_RESTORE:
2214  return parseDirectiveCFIRestore(IDLoc);
2215  case DK_CFI_ESCAPE:
2216  return parseDirectiveCFIEscape();
2217  case DK_CFI_RETURN_COLUMN:
2218  return parseDirectiveCFIReturnColumn(IDLoc);
2219  case DK_CFI_SIGNAL_FRAME:
2220  return parseDirectiveCFISignalFrame();
2221  case DK_CFI_UNDEFINED:
2222  return parseDirectiveCFIUndefined(IDLoc);
2223  case DK_CFI_REGISTER:
2224  return parseDirectiveCFIRegister(IDLoc);
2225  case DK_CFI_WINDOW_SAVE:
2226  return parseDirectiveCFIWindowSave();
2227  case DK_MACROS_ON:
2228  case DK_MACROS_OFF:
2229  return parseDirectiveMacrosOnOff(IDVal);
2230  case DK_MACRO:
2231  return parseDirectiveMacro(IDLoc);
2232  case DK_ALTMACRO:
2233  case DK_NOALTMACRO:
2234  return parseDirectiveAltmacro(IDVal);
2235  case DK_EXITM:
2236  return parseDirectiveExitMacro(IDVal);
2237  case DK_ENDM:
2238  case DK_ENDMACRO:
2239  return parseDirectiveEndMacro(IDVal);
2240  case DK_PURGEM:
2241  return parseDirectivePurgeMacro(IDLoc);
2242  case DK_END:
2243  return parseDirectiveEnd(IDLoc);
2244  case DK_ERR:
2245  return parseDirectiveError(IDLoc, false);
2246  case DK_ERROR:
2247  return parseDirectiveError(IDLoc, true);
2248  case DK_WARNING:
2249  return parseDirectiveWarning(IDLoc);
2250  case DK_RELOC:
2251  return parseDirectiveReloc(IDLoc);
2252  case DK_DCB:
2253  case DK_DCB_W:
2254  return parseDirectiveDCB(IDVal, 2);
2255  case DK_DCB_B:
2256  return parseDirectiveDCB(IDVal, 1);
2257  case DK_DCB_D:
2258  return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
2259  case DK_DCB_L:
2260  return parseDirectiveDCB(IDVal, 4);
2261  case DK_DCB_S:
2262  return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
2263  case DK_DC_X:
2264  case DK_DCB_X:
2265  return TokError(Twine(IDVal) +
2266  " not currently supported for this target");
2267  case DK_DS:
2268  case DK_DS_W:
2269  return parseDirectiveDS(IDVal, 2);
2270  case DK_DS_B:
2271  return parseDirectiveDS(IDVal, 1);
2272  case DK_DS_D:
2273  return parseDirectiveDS(IDVal, 8);
2274  case DK_DS_L:
2275  case DK_DS_S:
2276  return parseDirectiveDS(IDVal, 4);
2277  case DK_DS_P:
2278  case DK_DS_X:
2279  return parseDirectiveDS(IDVal, 12);
2280  case DK_PRINT:
2281  return parseDirectivePrint(IDLoc);
2282  case DK_ADDRSIG:
2283  return parseDirectiveAddrsig();
2284  case DK_ADDRSIG_SYM:
2285  return parseDirectiveAddrsigSym();
2286  case DK_PSEUDO_PROBE:
2287  return parseDirectivePseudoProbe();
2288  case DK_LTO_DISCARD:
2289  return parseDirectiveLTODiscard();
2290  }
2291 
2292  return Error(IDLoc, "unknown directive");
2293  }
2294 
2295  // __asm _emit or __asm __emit
2296  if (ParsingMSInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2297  IDVal == "_EMIT" || IDVal == "__EMIT"))
2298  return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
2299 
2300  // __asm align
2301  if (ParsingMSInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
2302  return parseDirectiveMSAlign(IDLoc, Info);
2303 
2304  if (ParsingMSInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
2305  Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
2306  if (checkForValidSection())
2307  return true;
2308 
2309  return parseAndMatchAndEmitTargetInstruction(Info, IDVal, ID, IDLoc);
2310 }
2311 
2312 bool AsmParser::parseAndMatchAndEmitTargetInstruction(ParseStatementInfo &Info,
2313  StringRef IDVal,
2314  AsmToken ID,
2315  SMLoc IDLoc) {
2316  // Canonicalize the opcode to lower case.
2317  std::string OpcodeStr = IDVal.lower();
2318  ParseInstructionInfo IInfo(Info.AsmRewrites);
2319  bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2320  Info.ParsedOperands);
2321  Info.ParseError = ParseHadError;
2322 
2323  // Dump the parsed representation, if requested.
2324  if (getShowParsedOperands()) {
2325  SmallString<256> Str;
2326  raw_svector_ostream OS(Str);
2327  OS << "parsed instruction: [";
2328  for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
2329  if (i != 0)
2330  OS << ", ";
2331  Info.ParsedOperands[i]->print(OS);
2332  }
2333  OS << "]";
2334 
2335  printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
2336  }
2337 
2338  // Fail even if ParseInstruction erroneously returns false.
2339  if (hasPendingError() || ParseHadError)
2340  return true;
2341 
2342  // If we are generating dwarf for the current section then generate a .loc
2343  // directive for the instruction.
2344  if (!ParseHadError && enabledGenDwarfForAssembly() &&
2345  getContext().getGenDwarfSectionSyms().count(
2346  getStreamer().getCurrentSectionOnly())) {
2347  unsigned Line;
2348  if (ActiveMacros.empty())
2349  Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2350  else
2351  Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2352  ActiveMacros.front()->ExitBuffer);
2353 
2354  // If we previously parsed a cpp hash file line comment then make sure the
2355  // current Dwarf File is for the CppHashFilename if not then emit the
2356  // Dwarf File table for it and adjust the line number for the .loc.
2357  if (!CppHashInfo.Filename.empty()) {
2358  unsigned FileNumber = getStreamer().emitDwarfFileDirective(
2359  0, StringRef(), CppHashInfo.Filename);
2360  getContext().setGenDwarfFileNumber(FileNumber);
2361 
2362  unsigned CppHashLocLineNo =
2363  SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
2364  Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
2365  }
2366 
2367  getStreamer().emitDwarfLocDirective(
2368  getContext().getGenDwarfFileNumber(), Line, 0,
2370  StringRef());
2371  }
2372 
2373  // If parsing succeeded, match the instruction.
2374  if (!ParseHadError) {
2376  if (getTargetParser().MatchAndEmitInstruction(
2377  IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2378  getTargetParser().isParsingMSInlineAsm()))
2379  return true;
2380  }
2381  return false;
2382 }
2383 
2384 // Parse and erase curly braces marking block start/end
2385 bool
2386 AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2387  // Identify curly brace marking block start/end
2388  if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2389  return false;
2390 
2391  SMLoc StartLoc = Lexer.getLoc();
2392  Lex(); // Eat the brace
2393  if (Lexer.is(AsmToken::EndOfStatement))
2394  Lex(); // Eat EndOfStatement following the brace
2395 
2396  // Erase the block start/end brace from the output asm string
2397  AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2398  StartLoc.getPointer());
2399  return true;
2400 }
2401 
2402 /// parseCppHashLineFilenameComment as this:
2403 /// ::= # number "filename"
2404 bool AsmParser::parseCppHashLineFilenameComment(SMLoc L, bool SaveLocInfo) {
2405  Lex(); // Eat the hash token.
2406  // Lexer only ever emits HashDirective if it fully formed if it's
2407  // done the checking already so this is an internal error.
2408  assert(getTok().is(AsmToken::Integer) &&
2409  "Lexing Cpp line comment: Expected Integer");
2410  int64_t LineNumber = getTok().getIntVal();
2411  Lex();
2412  assert(getTok().is(AsmToken::String) &&
2413  "Lexing Cpp line comment: Expected String");
2414  StringRef Filename = getTok().getString();
2415  Lex();
2416 
2417  if (!SaveLocInfo)
2418  return false;
2419 
2420  // Get rid of the enclosing quotes.
2421  Filename = Filename.substr(1, Filename.size() - 2);
2422 
2423  // Save the SMLoc, Filename and LineNumber for later use by diagnostics
2424  // and possibly DWARF file info.
2425  CppHashInfo.Loc = L;
2426  CppHashInfo.Filename = Filename;
2427  CppHashInfo.LineNumber = LineNumber;
2428  CppHashInfo.Buf = CurBuffer;
2429  if (FirstCppHashFilename.empty())
2430  FirstCppHashFilename = Filename;
2431  return false;
2432 }
2433 
2434 /// will use the last parsed cpp hash line filename comment
2435 /// for the Filename and LineNo if any in the diagnostic.
2436 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
2437  auto *Parser = static_cast<AsmParser *>(Context);
2438  raw_ostream &OS = errs();
2439 
2440  const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
2441  SMLoc DiagLoc = Diag.getLoc();
2442  unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2443  unsigned CppHashBuf =
2444  Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
2445 
2446  // Like SourceMgr::printMessage() we need to print the include stack if any
2447  // before printing the message.
2448  unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2449  if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2450  DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
2451  SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2452  DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
2453  }
2454 
2455  // If we have not parsed a cpp hash line filename comment or the source
2456  // manager changed or buffer changed (like in a nested include) then just
2457  // print the normal diagnostic using its Filename and LineNo.
2458  if (!Parser->CppHashInfo.LineNumber || DiagBuf != CppHashBuf) {
2459  if (Parser->SavedDiagHandler)
2460  Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2461  else
2462  Parser->getContext().diagnose(Diag);
2463  return;
2464  }
2465 
2466  // Use the CppHashFilename and calculate a line number based on the
2467  // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2468  // for the diagnostic.
2469  const std::string &Filename = std::string(Parser->CppHashInfo.Filename);
2470 
2471  int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2472  int CppHashLocLineNo =
2473  Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
2474  int LineNo =
2475  Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
2476 
2477  SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2478  Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
2479  Diag.getLineContents(), Diag.getRanges());
2480 
2481  if (Parser->SavedDiagHandler)
2482  Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2483  else
2484  Parser->getContext().diagnose(NewDiag);
2485 }
2486 
2487 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2488 // difference being that that function accepts '@' as part of identifiers and
2489 // we can't do that. AsmLexer.cpp should probably be changed to handle
2490 // '@' as a special case when needed.
2491 static bool isIdentifierChar(char c) {
2492  return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2493  c == '.';
2494 }
2495 
2496 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
2497  ArrayRef<MCAsmMacroParameter> Parameters,
2499  bool EnableAtPseudoVariable, SMLoc L) {
2500  unsigned NParameters = Parameters.size();
2501  bool HasVararg = NParameters ? Parameters.back().Vararg : false;
2502  if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
2503  return Error(L, "Wrong number of arguments");
2504 
2505  // A macro without parameters is handled differently on Darwin:
2506  // gas accepts no arguments and does no substitutions
2507  while (!Body.empty()) {
2508  // Scan for the next substitution.
2509  std::size_t End = Body.size(), Pos = 0;
2510  for (; Pos != End; ++Pos) {
2511  // Check for a substitution or escape.
2512  if (IsDarwin && !NParameters) {
2513  // This macro has no parameters, look for $0, $1, etc.
2514  if (Body[Pos] != '$' || Pos + 1 == End)
2515  continue;
2516 
2517  char Next = Body[Pos + 1];
2518  if (Next == '$' || Next == 'n' ||
2519  isdigit(static_cast<unsigned char>(Next)))
2520  break;
2521  } else {
2522  // This macro has parameters, look for \foo, \bar, etc.
2523  if (Body[Pos] == '\\' && Pos + 1 != End)
2524  break;
2525  }
2526  }
2527 
2528  // Add the prefix.
2529  OS << Body.slice(0, Pos);
2530 
2531  // Check if we reached the end.
2532  if (Pos == End)
2533  break;
2534 
2535  if (IsDarwin && !NParameters) {
2536  switch (Body[Pos + 1]) {
2537  // $$ => $
2538  case '$':
2539  OS << '$';
2540  break;
2541 
2542  // $n => number of arguments
2543  case 'n':
2544  OS << A.size();
2545  break;
2546 
2547  // $[0-9] => argument
2548  default: {
2549  // Missing arguments are ignored.
2550  unsigned Index = Body[Pos + 1] - '0';
2551  if (Index >= A.size())
2552  break;
2553 
2554  // Otherwise substitute with the token values, with spaces eliminated.
2555  for (const AsmToken &Token : A[Index])
2556  OS << Token.getString();
2557  break;
2558  }
2559  }
2560  Pos += 2;
2561  } else {
2562  unsigned I = Pos + 1;
2563 
2564  // Check for the \@ pseudo-variable.
2565  if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
2566  ++I;
2567  else
2568  while (isIdentifierChar(Body[I]) && I + 1 != End)
2569  ++I;
2570 
2571  const char *Begin = Body.data() + Pos + 1;
2572  StringRef Argument(Begin, I - (Pos + 1));
2573  unsigned Index = 0;
2574 
2575  if (Argument == "@") {
2576  OS << NumOfMacroInstantiations;
2577  Pos += 2;
2578  } else {
2579  for (; Index < NParameters; ++Index)
2580  if (Parameters[Index].Name == Argument)
2581  break;
2582 
2583  if (Index == NParameters) {
2584  if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2585  Pos += 3;
2586  else {
2587  OS << '\\' << Argument;
2588  Pos = I;
2589  }
2590  } else {
2591  bool VarargParameter = HasVararg && Index == (NParameters - 1);
2592  for (const AsmToken &Token : A[Index])
2593  // For altmacro mode, you can write '%expr'.
2594  // The prefix '%' evaluates the expression 'expr'
2595  // and uses the result as a string (e.g. replace %(1+2) with the
2596  // string "3").
2597  // Here, we identify the integer token which is the result of the
2598  // absolute expression evaluation and replace it with its string
2599  // representation.
2600  if (AltMacroMode && Token.getString().front() == '%' &&
2601  Token.is(AsmToken::Integer))
2602  // Emit an integer value to the buffer.
2603  OS << Token.getIntVal();
2604  // Only Token that was validated as a string and begins with '<'
2605  // is considered altMacroString!!!
2606  else if (AltMacroMode && Token.getString().front() == '<' &&
2607  Token.is(AsmToken::String)) {
2608  OS << angleBracketString(Token.getStringContents());
2609  }
2610  // We expect no quotes around the string's contents when
2611  // parsing for varargs.
2612  else if (Token.isNot(AsmToken::String) || VarargParameter)
2613  OS << Token.getString();
2614  else
2615  OS << Token.getStringContents();
2616 
2617  Pos += 1 + Argument.size();
2618  }
2619  }
2620  }
2621  // Update the scan point.
2622  Body = Body.substr(Pos);
2623  }
2624 
2625  return false;
2626 }
2627 
2628 static bool isOperator(AsmToken::TokenKind kind) {
2629  switch (kind) {
2630  default:
2631  return false;
2632  case AsmToken::Plus:
2633  case AsmToken::Minus:
2634  case AsmToken::Tilde:
2635  case AsmToken::Slash:
2636  case AsmToken::Star:
2637  case AsmToken::Dot:
2638  case AsmToken::Equal:
2639  case AsmToken::EqualEqual:
2640  case AsmToken::Pipe:
2641  case AsmToken::PipePipe:
2642  case AsmToken::Caret:
2643  case AsmToken::Amp:
2644  case AsmToken::AmpAmp:
2645  case AsmToken::Exclaim:
2646  case AsmToken::ExclaimEqual:
2647  case AsmToken::Less:
2648  case AsmToken::LessEqual:
2649  case AsmToken::LessLess:
2650  case AsmToken::LessGreater:
2651  case AsmToken::Greater:
2652  case AsmToken::GreaterEqual:
2653  case AsmToken::GreaterGreater:
2654  return true;
2655  }
2656 }
2657 
2658 namespace {
2659 
2660 class AsmLexerSkipSpaceRAII {
2661 public:
2662  AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2663  Lexer.setSkipSpace(SkipSpace);
2664  }
2665 
2666  ~AsmLexerSkipSpaceRAII() {
2667  Lexer.setSkipSpace(true);
2668  }
2669 
2670 private:
2671  AsmLexer &Lexer;
2672 };
2673 
2674 } // end anonymous namespace
2675 
2676 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2677 
2678  if (Vararg) {
2679  if (Lexer.isNot(AsmToken::EndOfStatement)) {
2680  StringRef Str = parseStringToEndOfStatement();
2681  MA.emplace_back(AsmToken::String, Str);
2682  }
2683  return false;
2684  }
2685 
2686  unsigned ParenLevel = 0;
2687 
2688  // Darwin doesn't use spaces to delmit arguments.
2689  AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
2690 
2691  bool SpaceEaten;
2692 
2693  while (true) {
2694  SpaceEaten = false;
2695  if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
2696  return TokError("unexpected token in macro instantiation");
2697 
2698  if (ParenLevel == 0) {
2699 
2700  if (Lexer.is(AsmToken::Comma))
2701  break;
2702 
2703  if (Lexer.is(AsmToken::Space)) {
2704  SpaceEaten = true;
2705  Lexer.Lex(); // Eat spaces
2706  }
2707 
2708  // Spaces can delimit parameters, but could also be part an expression.
2709  // If the token after a space is an operator, add the token and the next
2710  // one into this argument
2711  if (!IsDarwin) {
2712  if (isOperator(Lexer.getKind())) {
2713  MA.push_back(getTok());
2714  Lexer.Lex();
2715 
2716  // Whitespace after an operator can be ignored.
2717  if (Lexer.is(AsmToken::Space))
2718  Lexer.Lex();
2719 
2720  continue;
2721  }
2722  }
2723  if (SpaceEaten)
2724  break;
2725  }
2726 
2727  // handleMacroEntry relies on not advancing the lexer here
2728  // to be able to fill in the remaining default parameter values
2729  if (Lexer.is(AsmToken::EndOfStatement))
2730  break;
2731 
2732  // Adjust the current parentheses level.
2733  if (Lexer.is(AsmToken::LParen))
2734  ++ParenLevel;
2735  else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2736  --ParenLevel;
2737 
2738  // Append the token to the current argument list.
2739  MA.push_back(getTok());
2740  Lexer.Lex();
2741  }
2742 
2743  if (ParenLevel != 0)
2744  return TokError("unbalanced parentheses in macro argument");
2745  return false;
2746 }
2747 
2748 // Parse the macro instantiation arguments.
2749 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2750  MCAsmMacroArguments &A) {
2751  const unsigned NParameters = M ? M->Parameters.size() : 0;
2752  bool NamedParametersFound = false;
2753  SmallVector<SMLoc, 4> FALocs;
2754 
2755  A.resize(NParameters);
2756  FALocs.resize(NParameters);
2757 
2758  // Parse two kinds of macro invocations:
2759  // - macros defined without any parameters accept an arbitrary number of them
2760  // - macros defined with parameters accept at most that many of them
2761  bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2762  for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2763  ++Parameter) {
2764  SMLoc IDLoc = Lexer.getLoc();
2766 
2767  if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2768  if (parseIdentifier(FA.Name))
2769  return Error(IDLoc, "invalid argument identifier for formal argument");
2770 
2771  if (Lexer.isNot(AsmToken::Equal))
2772  return TokError("expected '=' after formal parameter identifier");
2773 
2774  Lex();
2775 
2776  NamedParametersFound = true;
2777  }
2778  bool Vararg = HasVararg && Parameter == (NParameters - 1);
2779 
2780  if (NamedParametersFound && FA.Name.empty())
2781  return Error(IDLoc, "cannot mix positional and keyword arguments");
2782 
2783  SMLoc StrLoc = Lexer.getLoc();
2784  SMLoc EndLoc;
2785  if (AltMacroMode && Lexer.is(AsmToken::Percent)) {
2786  const MCExpr *AbsoluteExp;
2787  int64_t Value;
2788  /// Eat '%'
2789  Lex();
2790  if (parseExpression(AbsoluteExp, EndLoc))
2791  return false;
2792  if (!AbsoluteExp->evaluateAsAbsolute(Value,
2793  getStreamer().getAssemblerPtr()))
2794  return Error(StrLoc, "expected absolute expression");
2795  const char *StrChar = StrLoc.getPointer();
2796  const char *EndChar = EndLoc.getPointer();
2797  AsmToken newToken(AsmToken::Integer,
2798  StringRef(StrChar, EndChar - StrChar), Value);
2799  FA.Value.push_back(newToken);
2800  } else if (AltMacroMode && Lexer.is(AsmToken::Less) &&
2801  isAngleBracketString(StrLoc, EndLoc)) {
2802  const char *StrChar = StrLoc.getPointer();
2803  const char *EndChar = EndLoc.getPointer();
2804  jumpToLoc(EndLoc, CurBuffer);
2805  /// Eat from '<' to '>'
2806  Lex();
2807  AsmToken newToken(AsmToken::String,
2808  StringRef(StrChar, EndChar - StrChar));
2809  FA.Value.push_back(newToken);
2810  } else if(parseMacroArgument(FA.Value, Vararg))
2811  return true;
2812 
2813  unsigned PI = Parameter;
2814  if (!FA.Name.empty()) {
2815  unsigned FAI = 0;
2816  for (FAI = 0; FAI < NParameters; ++FAI)
2817  if (M->Parameters[FAI].Name == FA.Name)
2818  break;
2819 
2820  if (FAI >= NParameters) {
2821  assert(M && "expected macro to be defined");
2822  return Error(IDLoc, "parameter named '" + FA.Name +
2823  "' does not exist for macro '" + M->Name + "'");
2824  }
2825  PI = FAI;
2826  }
2827 
2828  if (!FA.Value.empty()) {
2829  if (A.size() <= PI)
2830  A.resize(PI + 1);
2831  A[PI] = FA.Value;
2832 
2833  if (FALocs.size() <= PI)
2834  FALocs.resize(PI + 1);
2835 
2836  FALocs[PI] = Lexer.getLoc();
2837  }
2838 
2839  // At the end of the statement, fill in remaining arguments that have
2840  // default values. If there aren't any, then the next argument is
2841  // required but missing
2842  if (Lexer.is(AsmToken::EndOfStatement)) {
2843  bool Failure = false;
2844  for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2845  if (A[FAI].empty()) {
2846  if (M->Parameters[FAI].Required) {
2847  Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2848  "missing value for required parameter "
2849  "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2850  Failure = true;
2851  }
2852 
2853  if (!M->Parameters[FAI].Value.empty())
2854  A[FAI] = M->Parameters[FAI].Value;
2855  }
2856  }
2857  return Failure;
2858  }
2859 
2860  if (Lexer.is(AsmToken::Comma))
2861  Lex();
2862  }
2863 
2864  return TokError("too many positional arguments");
2865 }
2866 
2867 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2868  // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2869  // eliminate this, although we should protect against infinite loops.
2870  unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2871  if (ActiveMacros.size() == MaxNestingDepth) {
2872  std::ostringstream MaxNestingDepthError;
2873  MaxNestingDepthError << "macros cannot be nested more than "
2874  << MaxNestingDepth << " levels deep."
2875  << " Use -asm-macro-max-nesting-depth to increase "
2876  "this limit.";
2877  return TokError(MaxNestingDepthError.str());
2878  }
2879 
2880  MCAsmMacroArguments A;
2881  if (parseMacroArguments(M, A))
2882  return true;
2883 
2884  // Macro instantiation is lexical, unfortunately. We construct a new buffer
2885  // to hold the macro body with substitutions.
2886  SmallString<256> Buf;
2887  StringRef Body = M->Body;
2888  raw_svector_ostream OS(Buf);
2889 
2890  if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2891  return true;
2892 
2893  // We include the .endmacro in the buffer as our cue to exit the macro
2894  // instantiation.
2895  OS << ".endmacro\n";
2896 
2897  std::unique_ptr<MemoryBuffer> Instantiation =
2898  MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2899 
2900  // Create the macro instantiation object and add to the current macro
2901  // instantiation stack.
2902  MacroInstantiation *MI = new MacroInstantiation{
2903  NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size()};
2904  ActiveMacros.push_back(MI);
2905 
2906  ++NumOfMacroInstantiations;
2907 
2908  // Jump to the macro instantiation and prime the lexer.
2909  CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2910  Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2911  Lex();
2912 
2913  return false;
2914 }
2915 
2916 void AsmParser::handleMacroExit() {
2917  // Jump to the EndOfStatement we should return to, and consume it.
2918  jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2919  Lex();
2920 
2921  // Pop the instantiation entry.
2922  delete ActiveMacros.back();
2923  ActiveMacros.pop_back();
2924 }
2925 
2926 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2927  bool NoDeadStrip) {
2928  MCSymbol *Sym;
2929  const MCExpr *Value;
2930  if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2931  Value))
2932  return true;
2933 
2934  if (!Sym) {
2935  // In the case where we parse an expression starting with a '.', we will
2936  // not generate an error, nor will we create a symbol. In this case we
2937  // should just return out.
2938  return false;
2939  }
2940 
2941  if (discardLTOSymbol(Name))
2942  return false;
2943 
2944  // Do the assignment.
2945  Out.emitAssignment(Sym, Value);
2946  if (NoDeadStrip)
2948 
2949  return false;
2950 }
2951 
2952 /// parseIdentifier:
2953 /// ::= identifier
2954 /// ::= string
2955 bool AsmParser::parseIdentifier(StringRef &Res) {
2956  // The assembler has relaxed rules for accepting identifiers, in particular we
2957  // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2958  // separate tokens. At this level, we have already lexed so we cannot (currently)
2959  // handle this as a context dependent token, instead we detect adjacent tokens
2960  // and return the combined identifier.
2961  if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2962  SMLoc PrefixLoc = getLexer().getLoc();
2963 
2964  // Consume the prefix character, and check for a following identifier.
2965 
2966  AsmToken Buf[1];
2967  Lexer.peekTokens(Buf, false);
2968 
2969  if (Buf[0].isNot(AsmToken::Identifier) && Buf[0].isNot(AsmToken::Integer))
2970  return true;
2971 
2972  // We have a '$' or '@' followed by an identifier or integer token, make
2973  // sure they are adjacent.
2974  if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
2975  return true;
2976 
2977  // eat $ or @
2978  Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
2979  // Construct the joined identifier and consume the token.
2980  Res = StringRef(PrefixLoc.getPointer(), getTok().getString().size() + 1);
2981  Lex(); // Parser Lex to maintain invariants.
2982  return false;
2983  }
2984 
2985  if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2986  return true;
2987 
2988  Res = getTok().getIdentifier();
2989 
2990  Lex(); // Consume the identifier token.
2991 
2992  return false;
2993 }
2994 
2995 /// parseDirectiveSet:
2996 /// ::= .equ identifier ',' expression
2997 /// ::= .equiv identifier ',' expression
2998 /// ::= .set identifier ',' expression
2999 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
3000  StringRef Name;
3001  if (check(parseIdentifier(Name), "expected identifier") || parseComma() ||
3002  parseAssignment(Name, allow_redef, true))
3003  return true;
3004  return false;
3005 }
3006 
3007 bool AsmParser::parseEscapedString(std::string &Data) {
3008  if (check(getTok().isNot(AsmToken::String), "expected string"))
3009  return true;
3010 
3011  Data = "";
3012  StringRef Str = getTok().getStringContents();
3013  for (unsigned i = 0, e = Str.size(); i != e; ++i) {
3014  if (Str[i] != '\\') {
3015  Data += Str[i];
3016  continue;
3017  }
3018 
3019  // Recognize escaped characters. Note that this escape semantics currently
3020  // loosely follows Darwin 'as'.
3021  ++i;
3022  if (i == e)
3023  return TokError("unexpected backslash at end of string");
3024 
3025  // Recognize hex sequences similarly to GNU 'as'.
3026  if (Str[i] == 'x' || Str[i] == 'X') {
3027  size_t length = Str.size();
3028  if (i + 1 >= length || !isHexDigit(Str[i + 1]))
3029  return TokError("invalid hexadecimal escape sequence");
3030 
3031  // Consume hex characters. GNU 'as' reads all hexadecimal characters and
3032  // then truncates to the lower 16 bits. Seems reasonable.
3033  unsigned Value = 0;
3034  while (i + 1 < length && isHexDigit(Str[i + 1]))
3035  Value = Value * 16 + hexDigitValue(Str[++i]);
3036 
3037  Data += (unsigned char)(Value & 0xFF);
3038  continue;
3039  }
3040 
3041  // Recognize octal sequences.
3042  if ((unsigned)(Str[i] - '0') <= 7) {
3043  // Consume up to three octal characters.
3044  unsigned Value = Str[i] - '0';
3045 
3046  if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
3047  ++i;
3048  Value = Value * 8 + (Str[i] - '0');
3049 
3050  if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
3051  ++i;
3052  Value = Value * 8 + (Str[i] - '0');
3053  }
3054  }
3055 
3056  if (Value > 255)
3057  return TokError("invalid octal escape sequence (out of range)");
3058 
3059  Data += (unsigned char)Value;
3060  continue;
3061  }
3062 
3063  // Otherwise recognize individual escapes.
3064  switch (Str[i]) {
3065  default:
3066  // Just reject invalid escape sequences for now.
3067  return TokError("invalid escape sequence (unrecognized character)");
3068 
3069  case 'b': Data += '\b'; break;
3070  case 'f': Data += '\f'; break;
3071  case 'n': Data += '\n'; break;
3072  case 'r': Data += '\r'; break;
3073  case 't': Data += '\t'; break;
3074  case '"': Data += '"'; break;
3075  case '\\': Data += '\\'; break;
3076  }
3077  }
3078 
3079  Lex();
3080  return false;
3081 }
3082 
3083 bool AsmParser::parseAngleBracketString(std::string &Data) {
3084  SMLoc EndLoc, StartLoc = getTok().getLoc();
3085  if (isAngleBracketString(StartLoc, EndLoc)) {
3086  const char *StartChar = StartLoc.getPointer() + 1;
3087  const char *EndChar = EndLoc.getPointer() - 1;
3088  jumpToLoc(EndLoc, CurBuffer);
3089  /// Eat from '<' to '>'
3090  Lex();
3091 
3092  Data = angleBracketString(StringRef(StartChar, EndChar - StartChar));
3093  return false;
3094  }
3095  return true;
3096 }
3097 
3098 /// parseDirectiveAscii:
3099 // ::= .ascii [ "string"+ ( , "string"+ )* ]
3100 /// ::= ( .asciz | .string ) [ "string" ( , "string" )* ]
3101 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
3102  auto parseOp = [&]() -> bool {
3103  std::string Data;
3104  if (checkForValidSection())
3105  return true;
3106  // Only support spaces as separators for .ascii directive for now. See the
3107  // discusssion at https://reviews.llvm.org/D91460 for more details.
3108  do {
3109  if (parseEscapedString(Data))
3110  return true;
3111  getStreamer().emitBytes(Data);
3112  } while (!ZeroTerminated && getTok().is(AsmToken::String));
3113  if (ZeroTerminated)
3114  getStreamer().emitBytes(StringRef("\0", 1));
3115  return false;
3116  };
3117 
3118  return parseMany(parseOp);
3119 }
3120 
3121 /// parseDirectiveReloc
3122 /// ::= .reloc expression , identifier [ , expression ]
3123 bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
3124  const MCExpr *Offset;
3125  const MCExpr *Expr = nullptr;
3126  SMLoc OffsetLoc = Lexer.getTok().getLoc();
3127 
3128  if (parseExpression(Offset))
3129  return true;
3130  if (parseComma() ||
3131  check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
3132  return true;
3133 
3134  SMLoc NameLoc = Lexer.getTok().getLoc();
3135  StringRef Name = Lexer.getTok().getIdentifier();
3136  Lex();
3137 
3138  if (Lexer.is(AsmToken::Comma)) {
3139  Lex();
3140  SMLoc ExprLoc = Lexer.getLoc();
3141  if (parseExpression(Expr))
3142  return true;
3143 
3144  MCValue Value;
3145  if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
3146  return Error(ExprLoc, "expression must be relocatable");
3147  }
3148 
3149  if (parseEOL())
3150  return true;
3151 
3152  const MCTargetAsmParser &MCT = getTargetParser();
3153  const MCSubtargetInfo &STI = MCT.getSTI();
3154  if (Optional<std::pair<bool, std::string>> Err =
3155  getStreamer().emitRelocDirective(*Offset, Name, Expr, DirectiveLoc,
3156  STI))
3157  return Error(Err->first ? NameLoc : OffsetLoc, Err->second);
3158 
3159  return false;
3160 }
3161 
3162 /// parseDirectiveValue
3163 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
3164 bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
3165  auto parseOp = [&]() -> bool {
3166  const MCExpr *Value;
3167  SMLoc ExprLoc = getLexer().getLoc();
3168  if (checkForValidSection() || parseExpression(Value))
3169  return true;
3170  // Special case constant expressions to match code generator.
3171  if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3172  assert(Size <= 8 && "Invalid size");
3173  uint64_t IntValue = MCE->getValue();
3174  if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
3175  return Error(ExprLoc, "out of range literal value");
3176  getStreamer().emitIntValue(IntValue, Size);
3177  } else
3178  getStreamer().emitValue(Value, Size, ExprLoc);
3179  return false;
3180  };
3181 
3182  return parseMany(parseOp);
3183 }
3184 
3185 static bool parseHexOcta(AsmParser &Asm, uint64_t &hi, uint64_t &lo) {
3186  if (Asm.getTok().isNot(AsmToken::Integer) &&
3187  Asm.getTok().isNot(AsmToken::BigNum))
3188  return Asm.TokError("unknown token in expression");
3189  SMLoc ExprLoc = Asm.getTok().getLoc();
3190  APInt IntValue = Asm.getTok().getAPIntVal();
3191  Asm.Lex();
3192  if (!IntValue.isIntN(128))
3193  return Asm.Error(ExprLoc, "out of range literal value");
3194  if (!IntValue.isIntN(64)) {
3195  hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
3196  lo = IntValue.getLoBits(64).getZExtValue();
3197  } else {
3198  hi = 0;
3199  lo = IntValue.getZExtValue();
3200  }
3201  return false;
3202 }
3203 
3204 /// ParseDirectiveOctaValue
3205 /// ::= .octa [ hexconstant (, hexconstant)* ]
3206 
3207 bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
3208  auto parseOp = [&]() -> bool {
3209  if (checkForValidSection())
3210  return true;
3211  uint64_t hi, lo;
3212  if (parseHexOcta(*this, hi, lo))
3213  return true;
3214  if (MAI.isLittleEndian()) {
3215  getStreamer().emitInt64(lo);
3216  getStreamer().emitInt64(hi);
3217  } else {
3218  getStreamer().emitInt64(hi);
3219  getStreamer().emitInt64(lo);
3220  }
3221  return false;
3222  };
3223 
3224  return parseMany(parseOp);
3225 }
3226 
3227 bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
3228  // We don't truly support arithmetic on floating point expressions, so we
3229  // have to manually parse unary prefixes.
3230  bool IsNeg = false;
3231  if (getLexer().is(AsmToken::Minus)) {
3232  Lexer.Lex();
3233  IsNeg = true;
3234  } else if (getLexer().is(AsmToken::Plus))
3235  Lexer.Lex();
3236 
3237  if (Lexer.is(AsmToken::Error))
3238  return TokError(Lexer.getErr());
3239  if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
3240  Lexer.isNot(AsmToken::Identifier))
3241  return TokError("unexpected token in directive");
3242 
3243  // Convert to an APFloat.
3244  APFloat Value(Semantics);
3245  StringRef IDVal = getTok().getString();
3246  if (getLexer().is(AsmToken::Identifier)) {
3247  if (!IDVal.compare_insensitive("infinity") ||
3248  !IDVal.compare_insensitive("inf"))
3249  Value = APFloat::getInf(Semantics);
3250  else if (!IDVal.compare_insensitive("nan"))
3251  Value = APFloat::getNaN(Semantics, false, ~0);
3252  else
3253  return TokError("invalid floating point literal");
3254  } else if (errorToBool(
3255  Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven)
3256  .takeError()))
3257  return TokError("invalid floating point literal");
3258  if (IsNeg)
3259  Value.changeSign();
3260 
3261  // Consume the numeric token.
3262  Lex();
3263 
3264  Res = Value.bitcastToAPInt();
3265 
3266  return false;
3267 }
3268 
3269 /// parseDirectiveRealValue
3270 /// ::= (.single | .double) [ expression (, expression)* ]
3271 bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
3272  const fltSemantics &Semantics) {
3273  auto parseOp = [&]() -> bool {
3274  APInt AsInt;
3275  if (checkForValidSection() || parseRealValue(Semantics, AsInt))
3276  return true;
3277  getStreamer().emitIntValue(AsInt.getLimitedValue(),
3278  AsInt.getBitWidth() / 8);
3279  return false;
3280  };
3281 
3282  return parseMany(parseOp);
3283 }
3284 
3285 /// parseDirectiveZero
3286 /// ::= .zero expression
3287 bool AsmParser::parseDirectiveZero() {
3288  SMLoc NumBytesLoc = Lexer.getLoc();
3289  const MCExpr *NumBytes;
3290  if (checkForValidSection() || parseExpression(NumBytes))
3291  return true;
3292 
3293  int64_t Val = 0;
3294  if (getLexer().is(AsmToken::Comma)) {
3295  Lex();
3296  if (parseAbsoluteExpression(Val))
3297  return true;
3298  }
3299 
3300  if (parseEOL())
3301  return true;
3302  getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
3303 
3304  return false;
3305 }
3306 
3307 /// parseDirectiveFill
3308 /// ::= .fill expression [ , expression [ , expression ] ]
3309 bool AsmParser::parseDirectiveFill() {
3310  SMLoc NumValuesLoc = Lexer.getLoc();
3311  const MCExpr *NumValues;
3312  if (checkForValidSection() || parseExpression(NumValues))
3313  return true;
3314 
3315  int64_t FillSize = 1;
3316  int64_t FillExpr = 0;
3317 
3318  SMLoc SizeLoc, ExprLoc;
3319 
3320  if (parseOptionalToken(AsmToken::Comma)) {
3321  SizeLoc = getTok().getLoc();
3322  if (parseAbsoluteExpression(FillSize))
3323  return true;
3324  if (parseOptionalToken(AsmToken::Comma)) {
3325  ExprLoc = getTok().getLoc();
3326  if (parseAbsoluteExpression(FillExpr))
3327  return true;
3328  }
3329  }
3330  if (parseEOL())
3331  return true;
3332 
3333  if (FillSize < 0) {
3334  Warning(SizeLoc, "'.fill' directive with negative size has no effect");
3335  return false;
3336  }
3337  if (FillSize > 8) {
3338  Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3339  FillSize = 8;
3340  }
3341 
3342  if (!isUInt<32>(FillExpr) && FillSize > 4)
3343  Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3344 
3345  getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
3346 
3347  return false;
3348 }
3349 
3350 /// parseDirectiveOrg
3351 /// ::= .org expression [ , expression ]
3352 bool AsmParser::parseDirectiveOrg() {
3353  const MCExpr *Offset;
3354  SMLoc OffsetLoc = Lexer.getLoc();
3355  if (checkForValidSection() || parseExpression(Offset))
3356  return true;
3357 
3358  // Parse optional fill expression.
3359  int64_t FillExpr = 0;
3360  if (parseOptionalToken(AsmToken::Comma))
3361  if (parseAbsoluteExpression(FillExpr))
3362  return true;
3363  if (parseEOL())
3364  return true;
3365 
3366  getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
3367  return false;
3368 }
3369 
3370 /// parseDirectiveAlign
3371 /// ::= {.align, ...} expression [ , expression [ , expression ]]
3372 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
3373  SMLoc AlignmentLoc = getLexer().getLoc();
3374  int64_t Alignment;
3375  SMLoc MaxBytesLoc;
3376  bool HasFillExpr = false;
3377  int64_t FillExpr = 0;
3378  int64_t MaxBytesToFill = 0;
3379 
3380  auto parseAlign = [&]() -> bool {
3381  if (parseAbsoluteExpression(Alignment))
3382  return true;
3383  if (parseOptionalToken(AsmToken::Comma)) {
3384  // The fill expression can be omitted while specifying a maximum number of
3385  // alignment bytes, e.g:
3386  // .align 3,,4
3387  if (getTok().isNot(AsmToken::Comma)) {
3388  HasFillExpr = true;
3389  if (parseAbsoluteExpression(FillExpr))
3390  return true;
3391  }
3392  if (parseOptionalToken(AsmToken::Comma))
3393  if (parseTokenLoc(MaxBytesLoc) ||
3394  parseAbsoluteExpression(MaxBytesToFill))
3395  return true;
3396  }
3397  return parseEOL();
3398  };
3399 
3400  if (checkForValidSection())
3401  return true;
3402  // Ignore empty '.p2align' directives for GNU-as compatibility
3403  if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) {
3404  Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored");
3405  return parseEOL();
3406  }
3407  if (parseAlign())
3408  return true;
3409 
3410  // Always emit an alignment here even if we thrown an error.
3411  bool ReturnVal = false;
3412 
3413  // Compute alignment in bytes.
3414  if (IsPow2) {
3415  // FIXME: Diagnose overflow.
3416  if (Alignment >= 32) {
3417  ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
3418  Alignment = 31;
3419  }
3420 
3421  Alignment = 1ULL << Alignment;
3422  } else {
3423  // Reject alignments that aren't either a power of two or zero,
3424  // for gas compatibility. Alignment of zero is silently rounded
3425  // up to one.
3426  if (Alignment == 0)
3427  Alignment = 1;
3428  if (!isPowerOf2_64(Alignment))
3429  ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
3430  if (!isUInt<32>(Alignment))
3431  ReturnVal |= Error(AlignmentLoc, "alignment must be smaller than 2**32");
3432  }
3433 
3434  // Diagnose non-sensical max bytes to align.
3435  if (MaxBytesLoc.isValid()) {
3436  if (MaxBytesToFill < 1) {
3437  ReturnVal |= Error(MaxBytesLoc,
3438  "alignment directive can never be satisfied in this "
3439  "many bytes, ignoring maximum bytes expression");
3440  MaxBytesToFill = 0;
3441  }
3442 
3443  if (MaxBytesToFill >= Alignment) {
3444  Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
3445  "has no effect");
3446  MaxBytesToFill = 0;
3447  }
3448  }
3449 
3450  // Check whether we should use optimal code alignment for this .align
3451  // directive.
3452  const MCSection *Section = getStreamer().getCurrentSectionOnly();
3453  assert(Section && "must have section to emit alignment");
3454  bool UseCodeAlign = Section->UseCodeAlign();
3455  if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3456  ValueSize == 1 && UseCodeAlign) {
3457  getStreamer().emitCodeAlignment(Alignment, MaxBytesToFill);
3458  } else {
3459  // FIXME: Target specific behavior about how the "extra" bytes are filled.
3460  getStreamer().emitValueToAlignment(Alignment, FillExpr, ValueSize,
3461  MaxBytesToFill);
3462  }
3463 
3464  return ReturnVal;
3465 }
3466 
3467 /// parseDirectiveFile
3468 /// ::= .file filename
3469 /// ::= .file number [directory] filename [md5 checksum] [source source-text]
3470 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
3471  // FIXME: I'm not sure what this is.
3472  int64_t FileNumber = -1;
3473  if (getLexer().is(AsmToken::Integer)) {
3474  FileNumber = getTok().getIntVal();
3475  Lex();
3476 
3477  if (FileNumber < 0)
3478  return TokError("negative file number");
3479  }
3480 
3481  std::string Path;
3482 
3483  // Usually the directory and filename together, otherwise just the directory.
3484  // Allow the strings to have escaped octal character sequence.
3485  if (parseEscapedString(Path))
3486  return true;
3487 
3488  StringRef Directory;
3489  StringRef Filename;
3490  std::string FilenameData;
3491  if (getLexer().is(AsmToken::String)) {
3492  if (check(FileNumber == -1,
3493  "explicit path specified, but no file number") ||
3494  parseEscapedString(FilenameData))
3495  return true;
3496  Filename = FilenameData;
3497  Directory = Path;
3498  } else {
3499  Filename = Path;
3500  }
3501 
3502  uint64_t MD5Hi, MD5Lo;
3503  bool HasMD5 = false;
3504 
3506  bool HasSource = false;
3507  std::string SourceString;
3508 
3509  while (!parseOptionalToken(AsmToken::EndOfStatement)) {
3510  StringRef Keyword;
3511  if (check(getTok().isNot(AsmToken::Identifier),
3512  "unexpected token in '.file' directive") ||
3513  parseIdentifier(Keyword))
3514  return true;
3515  if (Keyword == "md5") {
3516  HasMD5 = true;
3517  if (check(FileNumber == -1,
3518  "MD5 checksum specified, but no file number") ||
3519  parseHexOcta(*this, MD5Hi, MD5Lo))
3520  return true;
3521  } else if (Keyword == "source") {
3522  HasSource = true;
3523  if (check(FileNumber == -1,
3524  "source specified, but no file number") ||
3525  check(getTok().isNot(AsmToken::String),
3526  "unexpected token in '.file' directive") ||
3527  parseEscapedString(SourceString))
3528  return true;
3529  } else {
3530  return TokError("unexpected token in '.file' directive");
3531  }
3532  }
3533 
3534  if (FileNumber == -1) {
3535  // Ignore the directive if there is no number and the target doesn't support
3536  // numberless .file directives. This allows some portability of assembler
3537  // between different object file formats.
3538  if (getContext().getAsmInfo()->hasSingleParameterDotFile())
3539  getStreamer().emitFileDirective(Filename);
3540  } else {
3541  // In case there is a -g option as well as debug info from directive .file,
3542  // we turn off the -g option, directly use the existing debug info instead.
3543  // Throw away any implicit file table for the assembler source.
3544  if (Ctx.getGenDwarfForAssembly()) {
3546  Ctx.setGenDwarfForAssembly(false);
3547  }
3548 
3550  if (HasMD5) {
3551  MD5::MD5Result Sum;
3552  for (unsigned i = 0; i != 8; ++i) {
3553  Sum.Bytes[i] = uint8_t(MD5Hi >> ((7 - i) * 8));
3554  Sum.Bytes[i + 8] = uint8_t(MD5Lo >> ((7 - i) * 8));
3555  }
3556  CKMem = Sum;
3557  }
3558  if (HasSource) {
3559  char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size()));
3560  memcpy(SourceBuf, SourceString.data(), SourceString.size());
3561  Source = StringRef(SourceBuf, SourceString.size());
3562  }
3563  if (FileNumber == 0) {
3564  // Upgrade to Version 5 for assembly actions like clang -c a.s.
3565  if (Ctx.getDwarfVersion() < 5)
3566  Ctx.setDwarfVersion(5);
3567  getStreamer().emitDwarfFile0Directive(Directory, Filename, CKMem, Source);
3568  } else {
3569  Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective(
3570  FileNumber, Directory, Filename, CKMem, Source);
3571  if (!FileNumOrErr)
3572  return Error(DirectiveLoc, toString(FileNumOrErr.takeError()));
3573  }
3574  // Alert the user if there are some .file directives with MD5 and some not.
3575  // But only do that once.
3576  if (!ReportedInconsistentMD5 && !Ctx.isDwarfMD5UsageConsistent(0)) {
3577  ReportedInconsistentMD5 = true;
3578  return Warning(DirectiveLoc, "inconsistent use of MD5 checksums");
3579  }
3580  }
3581 
3582  return false;
3583 }
3584 
3585 /// parseDirectiveLine
3586 /// ::= .line [number]
3587 bool AsmParser::parseDirectiveLine() {
3588  int64_t LineNumber;
3589  if (getLexer().is(AsmToken::Integer)) {
3590  if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3591  return true;
3592  (void)LineNumber;
3593  // FIXME: Do something with the .line.
3594  }
3595  return parseEOL();
3596 }
3597 
3598 /// parseDirectiveLoc
3599 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3600 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3601 /// The first number is a file number, must have been previously assigned with
3602 /// a .file directive, the second number is the line number and optionally the
3603 /// third number is a column position (zero if not specified). The remaining
3604 /// optional items are .loc sub-directives.
3605 bool AsmParser::parseDirectiveLoc() {
3606  int64_t FileNumber = 0, LineNumber = 0;
3607  SMLoc Loc = getTok().getLoc();
3608  if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3609  check(FileNumber < 1 && Ctx.getDwarfVersion() < 5, Loc,
3610  "file number less than one in '.loc' directive") ||
3611  check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3612  "unassigned file number in '.loc' directive"))
3613  return true;
3614 
3615  // optional
3616  if (getLexer().is(AsmToken::Integer)) {
3617  LineNumber = getTok().getIntVal();
3618  if (LineNumber < 0)
3619  return TokError("line number less than zero in '.loc' directive");
3620  Lex();
3621  }
3622 
3623  int64_t ColumnPos = 0;
3624  if (getLexer().is(AsmToken::Integer)) {
3625  ColumnPos = getTok().getIntVal();
3626  if (ColumnPos < 0)
3627  return TokError("column position less than zero in '.loc' directive");
3628  Lex();
3629  }
3630 
3631  auto PrevFlags = getContext().getCurrentDwarfLoc().getFlags();
3632  unsigned Flags = PrevFlags & DWARF2_FLAG_IS_STMT;
3633  unsigned Isa = 0;
3634  int64_t Discriminator = 0;
3635 
3636  auto parseLocOp = [&]() -> bool {
3637  StringRef Name;
3638  SMLoc Loc = getTok().getLoc();
3639  if (parseIdentifier(Name))
3640  return TokError("unexpected token in '.loc' directive");
3641 
3642  if (Name == "basic_block")
3643  Flags |= DWARF2_FLAG_BASIC_BLOCK;
3644  else if (Name == "prologue_end")
3645  Flags |= DWARF2_FLAG_PROLOGUE_END;
3646  else if (Name == "epilogue_begin")
3647  Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3648  else if (Name == "is_stmt") {
3649  Loc = getTok().getLoc();
3650  const MCExpr *Value;
3651  if (parseExpression(Value))
3652  return true;
3653  // The expression must be the constant 0 or 1.
3654  if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3655  int Value = MCE->getValue();
3656  if (Value == 0)
3657  Flags &= ~DWARF2_FLAG_IS_STMT;
3658  else if (Value == 1)
3659  Flags |= DWARF2_FLAG_IS_STMT;
3660  else
3661  return Error(Loc, "is_stmt value not 0 or 1");
3662  } else {
3663  return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3664  }
3665  } else if (Name == "isa") {
3666  Loc = getTok().getLoc();
3667  const MCExpr *Value;
3668  if (parseExpression(Value))
3669  return true;
3670  // The expression must be a constant greater or equal to 0.
3671  if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3672  int Value = MCE->getValue();
3673  if (Value < 0)
3674  return Error(Loc, "isa number less than zero");
3675  Isa = Value;
3676  } else {
3677  return Error(Loc, "isa number not a constant value");
3678  }
3679  } else if (Name == "discriminator") {
3680  if (parseAbsoluteExpression(Discriminator))
3681  return true;
3682  } else {
3683  return Error(Loc, "unknown sub-directive in '.loc' directive");
3684  }
3685  return false;
3686  };
3687 
3688  if (parseMany(parseLocOp, false /*hasComma*/))
3689  return true;
3690 
3691  getStreamer().emitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3692  Isa, Discriminator, StringRef());
3693 
3694  return false;
3695 }
3696 
3697 /// parseDirectiveStabs
3698 /// ::= .stabs string, number, number, number
3699 bool AsmParser::parseDirectiveStabs() {
3700  return TokError("unsupported directive '.stabs'");
3701 }
3702 
3703 /// parseDirectiveCVFile
3704 /// ::= .cv_file number filename [checksum] [checksumkind]
3705 bool AsmParser::parseDirectiveCVFile() {
3706  SMLoc FileNumberLoc = getTok().getLoc();
3707  int64_t FileNumber;
3708  std::string Filename;
3709  std::string Checksum;
3710  int64_t ChecksumKind = 0;
3711 
3712  if (parseIntToken(FileNumber,
3713  "expected file number in '.cv_file' directive") ||
3714  check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3715  check(getTok().isNot(AsmToken::String),
3716  "unexpected token in '.cv_file' directive") ||
3717  parseEscapedString(Filename))
3718  return true;
3719  if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3720  if (check(getTok().isNot(AsmToken::String),
3721  "unexpected token in '.cv_file' directive") ||
3722  parseEscapedString(Checksum) ||
3723  parseIntToken(ChecksumKind,
3724  "expected checksum kind in '.cv_file' directive") ||
3725  parseToken(AsmToken::EndOfStatement,
3726  "unexpected token in '.cv_file' directive"))
3727  return true;
3728  }
3729 
3730  Checksum = fromHex(Checksum);
3731  void *CKMem = Ctx.allocate(Checksum.size(), 1);
3732  memcpy(CKMem, Checksum.data(), Checksum.size());
3733  ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
3734  Checksum.size());
3735 
3736  if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes,
3737  static_cast<uint8_t>(ChecksumKind)))
3738  return Error(FileNumberLoc, "file number already allocated");
3739 
3740  return false;
3741 }
3742 
3743 bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3744  StringRef DirectiveName) {
3745  SMLoc Loc;
3746  return parseTokenLoc(Loc) ||
3747  parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3748  "' directive") ||
3749  check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3750  "expected function id within range [0, UINT_MAX)");
3751 }
3752 
3753 bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3754  SMLoc Loc;
3755  return parseTokenLoc(Loc) ||
3756  parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3757  "' directive") ||
3758  check(FileNumber < 1, Loc, "file number less than one in '" +
3759  DirectiveName + "' directive") ||
3760  check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3761  "unassigned file number in '" + DirectiveName + "' directive");
3762 }
3763 
3764 /// parseDirectiveCVFuncId
3765 /// ::= .cv_func_id FunctionId
3766 ///
3767 /// Introduces a function ID that can be used with .cv_loc.
3768 bool AsmParser::parseDirectiveCVFuncId() {
3769  SMLoc FunctionIdLoc = getTok().getLoc();
3770  int64_t FunctionId;
3771 
3772  if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3773  parseToken(AsmToken::EndOfStatement,
3774  "unexpected token in '.cv_func_id' directive"))
3775  return true;
3776 
3777  if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
3778  return Error(FunctionIdLoc, "function id already allocated");
3779 
3780  return false;
3781 }
3782 
3783 /// parseDirectiveCVInlineSiteId
3784 /// ::= .cv_inline_site_id FunctionId
3785 /// "within" IAFunc
3786 /// "inlined_at" IAFile IALine [IACol]
3787 ///
3788 /// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3789 /// at" source location information for use in the line table of the caller,
3790 /// whether the caller is a real function or another inlined call site.
3791 bool AsmParser::parseDirectiveCVInlineSiteId() {
3792  SMLoc FunctionIdLoc = getTok().getLoc();
3793  int64_t FunctionId;
3794  int64_t IAFunc;
3795  int64_t IAFile;
3796  int64_t IALine;
3797  int64_t IACol = 0;
3798 
3799  // FunctionId
3800  if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3801  return true;
3802 
3803  // "within"
3804  if (check((getLexer().isNot(AsmToken::Identifier) ||
3805  getTok().getIdentifier() != "within"),
3806  "expected 'within' identifier in '.cv_inline_site_id' directive"))
3807  return true;
3808  Lex();
3809 
3810  // IAFunc
3811  if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3812  return true;
3813 
3814  // "inlined_at"
3815  if (check((getLexer().isNot(AsmToken::Identifier) ||
3816  getTok().getIdentifier() != "inlined_at"),
3817  "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3818  "directive") )
3819  return true;
3820  Lex();
3821 
3822  // IAFile IALine
3823  if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3824  parseIntToken(IALine, "expected line number after 'inlined_at'"))
3825  return true;
3826 
3827  // [IACol]
3828  if (getLexer().is(AsmToken::Integer)) {
3829  IACol = getTok().getIntVal();
3830  Lex();
3831  }
3832 
3833  if (parseToken(AsmToken::EndOfStatement,
3834  "unexpected token in '.cv_inline_site_id' directive"))
3835  return true;
3836 
3837  if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3838  IALine, IACol, FunctionIdLoc))
3839  return Error(FunctionIdLoc, "function id already allocated");
3840 
3841  return false;
3842 }
3843 
3844 /// parseDirectiveCVLoc
3845 /// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3846 /// [is_stmt VALUE]
3847 /// The first number is a file number, must have been previously assigned with
3848 /// a .file directive, the second number is the line number and optionally the
3849 /// third number is a column position (zero if not specified). The remaining
3850 /// optional items are .loc sub-directives.
3851 bool AsmParser::parseDirectiveCVLoc() {
3852  SMLoc DirectiveLoc = getTok().getLoc();
3853  int64_t FunctionId, FileNumber;
3854  if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3855  parseCVFileId(FileNumber, ".cv_loc"))
3856  return true;
3857 
3858  int64_t LineNumber = 0;
3859  if (getLexer().is(AsmToken::Integer)) {
3860  LineNumber = getTok().getIntVal();
3861  if (LineNumber < 0)
3862  return TokError("line number less than zero in '.cv_loc' directive");
3863  Lex();
3864  }
3865 
3866  int64_t ColumnPos = 0;
3867  if (getLexer().is(AsmToken::Integer)) {
3868  ColumnPos = getTok().getIntVal();
3869  if (ColumnPos < 0)
3870  return TokError("column position less than zero in '.cv_loc' directive");
3871  Lex();
3872  }
3873 
3874  bool PrologueEnd = false;
3875  uint64_t IsStmt = 0;
3876 
3877  auto parseOp = [&]() -> bool {
3878  StringRef Name;
3879  SMLoc Loc = getTok().getLoc();
3880  if (parseIdentifier(Name))
3881  return TokError("unexpected token in '.cv_loc' directive");
3882  if (Name == "prologue_end")
3883  PrologueEnd = true;
3884  else if (Name == "is_stmt") {
3885  Loc = getTok().getLoc();
3886  const MCExpr *Value;
3887  if (parseExpression(Value))
3888  return true;
3889  // The expression must be the constant 0 or 1.
3890  IsStmt = ~0ULL;
3891  if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3892  IsStmt = MCE->getValue();
3893 
3894  if (IsStmt > 1)
3895  return Error(Loc, "is_stmt value not 0 or 1");
3896  } else {
3897  return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3898  }
3899  return false;
3900  };
3901 
3902  if (parseMany(parseOp, false /*hasComma*/))
3903  return true;
3904 
3905  getStreamer().emitCVLocDirective(FunctionId, FileNumber, LineNumber,
3906  ColumnPos, PrologueEnd, IsStmt, StringRef(),
3907  DirectiveLoc);
3908  return false;
3909 }
3910 
3911 /// parseDirectiveCVLinetable
3912 /// ::= .cv_linetable FunctionId, FnStart, FnEnd
3913 bool AsmParser::parseDirectiveCVLinetable() {
3914  int64_t FunctionId;
3915  StringRef FnStartName, FnEndName;
3916  SMLoc Loc = getTok().getLoc();
3917  if (parseCVFunctionId(FunctionId, ".cv_linetable") || parseComma() ||
3918  parseTokenLoc(Loc) ||
3919  check(parseIdentifier(FnStartName), Loc,
3920  "expected identifier in directive") ||
3921  parseComma() || parseTokenLoc(Loc) ||
3922  check(parseIdentifier(FnEndName), Loc,
3923  "expected identifier in directive"))
3924  return true;
3925 
3926  MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3927  MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3928 
3929  getStreamer().emitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3930  return false;
3931 }
3932 
3933 /// parseDirectiveCVInlineLinetable
3934 /// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
3935 bool AsmParser::parseDirectiveCVInlineLinetable() {
3936  int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3937  StringRef FnStartName, FnEndName;
3938  SMLoc Loc = getTok().getLoc();
3939  if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
3940  parseTokenLoc(Loc) ||
3941  parseIntToken(
3942  SourceFileId,
3943  "expected SourceField in '.cv_inline_linetable' directive") ||
3944  check(SourceFileId <= 0, Loc,
3945  "File id less than zero in '.cv_inline_linetable' directive") ||
3946  parseTokenLoc(Loc) ||
3947  parseIntToken(
3948  SourceLineNum,
3949  "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3950  check(SourceLineNum < 0, Loc,
3951  "Line number less than zero in '.cv_inline_linetable' directive") ||
3952  parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3953  "expected identifier in directive") ||
3954  parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3955  "expected identifier in directive"))
3956  return true;
3957 
3958  if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3959  return true;
3960 
3961  MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3962  MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3963  getStreamer().emitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3964  SourceLineNum, FnStartSym,
3965  FnEndSym);
3966  return false;
3967 }
3968 
3969 void AsmParser::initializeCVDefRangeTypeMap() {
3970  CVDefRangeTypeMap["reg"] = CVDR_DEFRANGE_REGISTER;
3971  CVDefRangeTypeMap["frame_ptr_rel"] = CVDR_DEFRANGE_FRAMEPOINTER_REL;
3972  CVDefRangeTypeMap["subfield_reg"] = CVDR_DEFRANGE_SUBFIELD_REGISTER;
3973  CVDefRangeTypeMap["reg_rel"] = CVDR_DEFRANGE_REGISTER_REL;
3974 }
3975 
3976 /// parseDirectiveCVDefRange
3977 /// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3978 bool AsmParser::parseDirectiveCVDefRange() {
3979  SMLoc Loc;
3980  std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3981  while (getLexer().is(AsmToken::Identifier)) {
3982  Loc = getLexer().getLoc();
3983  StringRef GapStartName;
3984  if (parseIdentifier(GapStartName))
3985  return Error(Loc, "expected identifier in directive");
3986  MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3987 
3988  Loc = getLexer().getLoc();
3989  StringRef GapEndName;
3990  if (parseIdentifier(GapEndName))
3991  return Error(Loc, "expected identifier in directive");
3992  MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3993 
3994  Ranges.push_back({GapStartSym, GapEndSym});
3995  }
3996 
3997  StringRef CVDefRangeTypeStr;
3998  if (parseToken(
4000  "expected comma before def_range type in .cv_def_range directive") ||
4001  parseIdentifier(CVDefRangeTypeStr))
4002  return Error(Loc, "expected def_range type in directive");
4003 
4005  CVDefRangeTypeMap.find(CVDefRangeTypeStr);
4006  CVDefRangeType CVDRType = (CVTypeIt == CVDefRangeTypeMap.end())
4007  ? CVDR_DEFRANGE
4008  : CVTypeIt->getValue();
4009  switch (CVDRType) {
4010  case CVDR_DEFRANGE_REGISTER: {
4011  int64_t DRRegister;
4012  if (parseToken(AsmToken::Comma, "expected comma before register number in "
4013  ".cv_def_range directive") ||
4014  parseAbsoluteExpression(DRRegister))
4015  return Error(Loc, "expected register number");
4016 
4018  DRHdr.Register = DRRegister;
4019  DRHdr.MayHaveNoName = 0;
4020  getStreamer().emitCVDefRangeDirective(Ranges, DRHdr);
4021  break;
4022  }
4023  case CVDR_DEFRANGE_FRAMEPOINTER_REL: {
4024  int64_t DROffset;
4025  if (parseToken(AsmToken::Comma,
4026  "expected comma before offset in .cv_def_range directive") ||
4027  parseAbsoluteExpression(DROffset))
4028  return Error(Loc, "expected offset value");
4029 
4031  DRHdr.Offset = DROffset;
4032  getStreamer().emitCVDefRangeDirective(Ranges, DRHdr);
4033  break;
4034  }
4035  case CVDR_DEFRANGE_SUBFIELD_REGISTER: {
4036  int64_t DRRegister;
4037  int64_t DROffsetInParent;
4038  if (parseToken(AsmToken::Comma, "expected comma before register number in "
4039  ".cv_def_range directive") ||
4040  parseAbsoluteExpression(DRRegister))
4041  return Error(Loc, "expected register number");
4042  if (parseToken(AsmToken::Comma,
4043  "expected comma before offset in .cv_def_range directive") ||
4044  parseAbsoluteExpression(DROffsetInParent))
4045  return Error(Loc, "expected offset value");
4046 
4048  DRHdr.Register = DRRegister;
4049  DRHdr.MayHaveNoName = 0;
4050  DRHdr.OffsetInParent = DROffsetInParent;
4051  getStreamer().emitCVDefRangeDirective(Ranges, DRHdr);
4052  break;
4053  }
4054  case CVDR_DEFRANGE_REGISTER_REL: {
4055  int64_t DRRegister;
4056  int64_t DRFlags;
4057  int64_t DRBasePointerOffset;
4058  if (parseToken(AsmToken::Comma, "expected comma before register number in "
4059  ".cv_def_range directive") ||
4060  parseAbsoluteExpression(DRRegister))
4061  return Error(Loc, "expected register value");
4062  if (parseToken(
4064  "expected comma before flag value in .cv_def_range directive") ||
4065  parseAbsoluteExpression(DRFlags))
4066  return Error(Loc, "expected flag value");
4067  if (parseToken(AsmToken::Comma, "expected comma before base pointer offset "
4068  "in .cv_def_range directive") ||
4069  parseAbsoluteExpression(DRBasePointerOffset))
4070  return Error(Loc, "expected base pointer offset value");
4071 
4073  DRHdr.Register = DRRegister;
4074  DRHdr.Flags = DRFlags;
4075  DRHdr.BasePointerOffset = DRBasePointerOffset;
4076  getStreamer().emitCVDefRangeDirective(Ranges, DRHdr);
4077  break;
4078  }
4079  default:
4080  return Error(Loc, "unexpected def_range type in .cv_def_range directive");
4081  }
4082  return true;
4083 }
4084 
4085 /// parseDirectiveCVString
4086 /// ::= .cv_stringtable "string"
4087 bool AsmParser::parseDirectiveCVString() {
4088  std::string Data;
4089  if (checkForValidSection() || parseEscapedString(Data))
4090  return true;
4091 
4092  // Put the string in the table and emit the offset.
4093  std::pair<StringRef, unsigned> Insertion =
4094  getCVContext().addToStringTable(Data);
4095  getStreamer().emitInt32(Insertion.second);
4096  return false;
4097 }
4098 
4099 /// parseDirectiveCVStringTable
4100 /// ::= .cv_stringtable
4101 bool AsmParser::parseDirectiveCVStringTable() {
4102  getStreamer().emitCVStringTableDirective();
4103  return false;
4104 }
4105 
4106 /// parseDirectiveCVFileChecksums
4107 /// ::= .cv_filechecksums
4108 bool AsmParser::parseDirectiveCVFileChecksums() {
4109  getStreamer().emitCVFileChecksumsDirective();
4110  return false;
4111 }
4112 
4113 /// parseDirectiveCVFileChecksumOffset
4114 /// ::= .cv_filechecksumoffset fileno
4115 bool AsmParser::parseDirectiveCVFileChecksumOffset() {
4116  int64_t FileNo;
4117  if (parseIntToken(FileNo, "expected identifier in directive"))
4118  return true;
4119  if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
4120  return true;
4121  getStreamer().emitCVFileChecksumOffsetDirective(FileNo);
4122  return false;
4123 }
4124 
4125 /// parseDirectiveCVFPOData
4126 /// ::= .cv_fpo_data procsym
4127 bool AsmParser::parseDirectiveCVFPOData() {
4128  SMLoc DirLoc = getLexer().getLoc();
4129  StringRef ProcName;
4130  if (parseIdentifier(ProcName))
4131  return TokError("expected symbol name");
4132  if (parseEOL())
4133  return true;
4134  MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
4135  getStreamer().EmitCVFPOData(ProcSym, DirLoc);
4136  return false;
4137 }
4138 
4139 /// parseDirectiveCFISections
4140 /// ::= .cfi_sections section [, section]
4141 bool AsmParser::parseDirectiveCFISections() {
4142  StringRef Name;
4143  bool EH = false;
4144  bool Debug = false;
4145 
4146  if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4147  for (;;) {
4148  if (parseIdentifier(Name))
4149  return TokError("expected .eh_frame or .debug_frame");
4150  if (Name == ".eh_frame")
4151  EH = true;
4152  else if (Name == ".debug_frame")
4153  Debug = true;
4154  if (parseOptionalToken(AsmToken::EndOfStatement))
4155  break;
4156  if (parseComma())
4157  return true;
4158  }
4159  }
4160  getStreamer().emitCFISections(EH, Debug);
4161  return false;
4162 }
4163 
4164 /// parseDirectiveCFIStartProc
4165 /// ::= .cfi_startproc [simple]
4166 bool AsmParser::parseDirectiveCFIStartProc() {
4167  StringRef Simple;
4168  if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4169  if (check(parseIdentifier(Simple) || Simple != "simple",
4170  "unexpected token") ||
4171  parseEOL())
4172  return true;
4173  }
4174 
4175  // TODO(kristina): Deal with a corner case of incorrect diagnostic context
4176  // being produced if this directive is emitted as part of preprocessor macro
4177  // expansion which can *ONLY* happen if Clang's cc1as is the API consumer.
4178  // Tools like llvm-mc on the other hand are not affected by it, and report
4179  // correct context information.
4180  getStreamer().emitCFIStartProc(!Simple.empty(), Lexer.getLoc());
4181  return false;
4182 }
4183 
4184 /// parseDirectiveCFIEndProc
4185 /// ::= .cfi_endproc
4186 bool AsmParser::parseDirectiveCFIEndProc() {
4187  if (parseEOL())
4188  return true;
4189  getStreamer().emitCFIEndProc();
4190  return false;
4191 }
4192 
4193 /// parse register name or number.
4194 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
4195  SMLoc DirectiveLoc) {
4196  unsigned RegNo;
4197 
4198  if (getLexer().isNot(AsmToken::Integer)) {
4199  if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
4200  return true;
4201  Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
4202  } else
4203  return parseAbsoluteExpression(Register);
4204 
4205  return false;
4206 }
4207 
4208 /// parseDirectiveCFIDefCfa
4209 /// ::= .cfi_def_cfa register, offset
4210 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
4211  int64_t Register = 0, Offset = 0;
4212  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseComma() ||
4213  parseAbsoluteExpression(Offset) || parseEOL())
4214  return true;
4215 
4216  getStreamer().emitCFIDefCfa(Register, Offset);
4217  return false;
4218 }
4219 
4220 /// parseDirectiveCFIDefCfaOffset
4221 /// ::= .cfi_def_cfa_offset offset
4222 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
4223  int64_t Offset = 0;
4224  if (parseAbsoluteExpression(Offset) || parseEOL())
4225  return true;
4226 
4227  getStreamer().emitCFIDefCfaOffset(Offset);
4228  return false;
4229 }
4230 
4231 /// parseDirectiveCFIRegister
4232 /// ::= .cfi_register register, register
4233 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
4234  int64_t Register1 = 0, Register2 = 0;
4235  if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) || parseComma() ||
4236  parseRegisterOrRegisterNumber(Register2, DirectiveLoc) || parseEOL())
4237  return true;
4238 
4239  getStreamer().emitCFIRegister(Register1, Register2);
4240  return false;
4241 }
4242 
4243 /// parseDirectiveCFIWindowSave
4244 /// ::= .cfi_window_save
4245 bool AsmParser::parseDirectiveCFIWindowSave() {
4246  if (parseEOL())
4247  return true;
4248  getStreamer().emitCFIWindowSave();
4249  return false;
4250 }
4251 
4252 /// parseDirectiveCFIAdjustCfaOffset
4253 /// ::= .cfi_adjust_cfa_offset adjustment
4254 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
4255  int64_t Adjustment = 0;
4256  if (parseAbsoluteExpression(Adjustment) || parseEOL())
4257  return true;
4258 
4259  getStreamer().emitCFIAdjustCfaOffset(Adjustment);
4260  return false;
4261 }
4262 
4263 /// parseDirectiveCFIDefCfaRegister
4264 /// ::= .cfi_def_cfa_register register
4265 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
4266  int64_t Register = 0;
4267  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseEOL())
4268  return true;
4269 
4270  getStreamer().emitCFIDefCfaRegister(Register);
4271  return false;
4272 }
4273 
4274 /// parseDirectiveCFILLVMDefAspaceCfa
4275 /// ::= .cfi_llvm_def_aspace_cfa register, offset, address_space
4276 bool AsmParser::parseDirectiveCFILLVMDefAspaceCfa(SMLoc DirectiveLoc) {
4277  int64_t Register = 0, Offset = 0, AddressSpace = 0;
4278  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseComma() ||
4279  parseAbsoluteExpression(Offset) || parseComma() ||
4280  parseAbsoluteExpression(AddressSpace) || parseEOL())
4281  return true;
4282 
4283  getStreamer().emitCFILLVMDefAspaceCfa(Register, Offset, AddressSpace);
4284  return false;
4285 }
4286 
4287 /// parseDirectiveCFIOffset
4288 /// ::= .cfi_offset register, offset
4289 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
4290  int64_t Register = 0;
4291  int64_t Offset = 0;
4292 
4293  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseComma() ||
4294  parseAbsoluteExpression(Offset) || parseEOL())
4295  return true;
4296 
4297  getStreamer().emitCFIOffset(Register, Offset);
4298  return false;
4299 }
4300 
4301 /// parseDirectiveCFIRelOffset
4302 /// ::= .cfi_rel_offset register, offset
4303 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
4304  int64_t Register = 0, Offset = 0;
4305 
4306  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseComma() ||
4307  parseAbsoluteExpression(Offset) || parseEOL())
4308  return true;
4309 
4310  getStreamer().emitCFIRelOffset(Register, Offset);
4311  return false;
4312 }
4313 
4314 static bool isValidEncoding(int64_t Encoding) {
4315  if (Encoding & ~0xff)
4316  return false;
4317 
4318  if (Encoding == dwarf::DW_EH_PE_omit)
4319  return true;
4320 
4321  const unsigned Format = Encoding & 0xf;
4326  return false;
4327 
4328  const unsigned Application = Encoding & 0x70;
4329  if (Application != dwarf::DW_EH_PE_absptr &&
4330  Application != dwarf::DW_EH_PE_pcrel)
4331  return false;
4332 
4333  return true;
4334 }
4335 
4336 /// parseDirectiveCFIPersonalityOrLsda
4337 /// IsPersonality true for cfi_personality, false for cfi_lsda
4338 /// ::= .cfi_personality encoding, [symbol_name]
4339 /// ::= .cfi_lsda encoding, [symbol_name]
4340 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
4341  int64_t Encoding = 0;
4342  if (parseAbsoluteExpression(Encoding))
4343  return true;
4344  if (Encoding == dwarf::DW_EH_PE_omit)
4345  return false;
4346 
4347  StringRef Name;
4348  if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
4349  parseComma() ||
4350  check(parseIdentifier(Name), "expected identifier in directive") ||
4351  parseEOL())
4352  return true;
4353 
4354  MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4355 
4356  if (IsPersonality)
4357  getStreamer().emitCFIPersonality(Sym, Encoding);
4358  else
4359  getStreamer().emitCFILsda(Sym, Encoding);
4360  return false;
4361 }
4362 
4363 /// parseDirectiveCFIRememberState
4364 /// ::= .cfi_remember_state
4365 bool AsmParser::parseDirectiveCFIRememberState() {
4366  if (parseEOL())
4367  return true;
4368  getStreamer().emitCFIRememberState();
4369  return false;
4370 }
4371 
4372 /// parseDirectiveCFIRestoreState
4373 /// ::= .cfi_remember_state
4374 bool AsmParser::parseDirectiveCFIRestoreState() {
4375  if (parseEOL())
4376  return true;
4377  getStreamer().emitCFIRestoreState();
4378  return false;
4379 }
4380 
4381 /// parseDirectiveCFISameValue
4382 /// ::= .cfi_same_value register
4383 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
4384  int64_t Register = 0;
4385 
4386  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseEOL())
4387  return true;
4388 
4389  getStreamer().emitCFISameValue(Register);
4390  return false;
4391 }
4392 
4393 /// parseDirectiveCFIRestore
4394 /// ::= .cfi_restore register
4395 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
4396  int64_t Register = 0;
4397  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseEOL())
4398  return true;
4399 
4400  getStreamer().emitCFIRestore(Register);
4401  return false;
4402 }
4403 
4404 /// parseDirectiveCFIEscape
4405 /// ::= .cfi_escape expression[,...]
4406 bool AsmParser::parseDirectiveCFIEscape() {
4407  std::string Values;
4408  int64_t CurrValue;
4409  if (parseAbsoluteExpression(CurrValue))
4410  return true;
4411 
4412  Values.push_back((uint8_t)CurrValue);
4413 
4414  while (getLexer().is(AsmToken::Comma)) {
4415  Lex();
4416 
4417  if (parseAbsoluteExpression(CurrValue))
4418  return true;
4419 
4420  Values.push_back((uint8_t)CurrValue);
4421  }
4422 
4423  getStreamer().emitCFIEscape(Values);
4424  return false;
4425 }
4426 
4427 /// parseDirectiveCFIReturnColumn
4428 /// ::= .cfi_return_column register
4429 bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
4430  int64_t Register = 0;
4431  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseEOL())
4432  return true;
4433  getStreamer().emitCFIReturnColumn(Register);
4434  return false;
4435 }
4436 
4437 /// parseDirectiveCFISignalFrame
4438 /// ::= .cfi_signal_frame
4439 bool AsmParser::parseDirectiveCFISignalFrame() {
4440  if (parseEOL())
4441  return true;
4442 
4443  getStreamer().emitCFISignalFrame();
4444  return false;
4445 }
4446 
4447 /// parseDirectiveCFIUndefined
4448 /// ::= .cfi_undefined register
4449 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
4450  int64_t Register = 0;
4451 
4452  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseEOL())
4453  return true;
4454 
4455  getStreamer().emitCFIUndefined(Register);
4456  return false;
4457 }
4458 
4459 /// parseDirectiveAltmacro
4460 /// ::= .altmacro
4461 /// ::= .noaltmacro
4462 bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
4463  if (parseEOL())
4464  return true;
4465  AltMacroMode = (Directive == ".altmacro");
4466  return false;
4467 }
4468 
4469 /// parseDirectiveMacrosOnOff
4470 /// ::= .macros_on
4471 /// ::= .macros_off
4472 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
4473  if (parseEOL())
4474  return true;
4475  setMacrosEnabled(Directive == ".macros_on");
4476  return false;
4477 }
4478 
4479 /// parseDirectiveMacro
4480 /// ::= .macro name[,] [parameters]
4481 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
4482  StringRef Name;
4483  if (parseIdentifier(Name))
4484  return TokError("expected identifier in '.macro' directive");
4485 
4486  if (getLexer().is(AsmToken::Comma))
4487  Lex();
4488 
4489  MCAsmMacroParameters Parameters;
4490  while (getLexer().isNot(AsmToken::EndOfStatement)) {
4491 
4492  if (!Parameters.empty() && Parameters.back().Vararg)
4493  return Error(Lexer.getLoc(), "vararg parameter '" +
4494  Parameters.back().Name +
4495  "' should be the last parameter");
4496 
4497  MCAsmMacroParameter Parameter;
4498  if (parseIdentifier(Parameter.Name))
4499  return TokError("expected identifier in '.macro' directive");
4500 
4501  // Emit an error if two (or more) named parameters share the same name
4502  for (const MCAsmMacroParameter& CurrParam : Parameters)
4503  if (CurrParam.Name.equals(Parameter.Name))
4504  return TokError("macro '" + Name + "' has multiple parameters"
4505  " named '" + Parameter.Name + "'");
4506 
4507  if (Lexer.is(AsmToken::Colon)) {
4508  Lex(); // consume ':'
4509 
4510  SMLoc QualLoc;
4511  StringRef Qualifier;
4512 
4513  QualLoc = Lexer.getLoc();
4514  if (parseIdentifier(Qualifier))
4515  return Error(QualLoc, "missing parameter qualifier for "
4516  "'" + Parameter.Name + "' in macro '" + Name + "'");
4517 
4518  if (Qualifier == "req")
4519  Parameter.Required = true;
4520  else if (Qualifier == "vararg")
4521  Parameter.Vararg = true;
4522  else
4523  return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4524  "for '" + Parameter.Name + "' in macro '" + Name + "'");
4525  }
4526 
4527  if (getLexer().is(AsmToken::Equal)) {
4528  Lex();
4529 
4530  SMLoc ParamLoc;
4531 
4532  ParamLoc = Lexer.getLoc();
4533  if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
4534  return true;
4535 
4536  if (Parameter.Required)
4537  Warning(ParamLoc, "pointless default value for required parameter "
4538  "'" + Parameter.Name + "' in macro '" + Name + "'");
4539  }
4540 
4541  Parameters.push_back(std::move(Parameter));
4542 
4543  if (getLexer().is(AsmToken::Comma))
4544  Lex();
4545  }
4546 
4547  // Eat just the end of statement.
4548  Lexer.Lex();
4549 
4550  // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
4551  AsmToken EndToken, StartToken = getTok();
4552  unsigned MacroDepth = 0;
4553  // Lex the macro definition.
4554  while (true) {
4555  // Ignore Lexing errors in macros.
4556  while (Lexer.is(AsmToken::Error)) {
4557  Lexer.Lex();
4558  }
4559 
4560  // Check whether we have reached the end of the file.
4561  if (getLexer().is(AsmToken::Eof))
4562  return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4563 
4564  // Otherwise, check whether we have reach the .endmacro or the start of a
4565  // preprocessor line marker.
4566  if (getLexer().is(AsmToken::Identifier)) {
4567  if (getTok().getIdentifier() == ".endm" ||
4568  getTok().getIdentifier() == ".endmacro") {
4569  if (MacroDepth == 0) { // Outermost macro.
4570  EndToken = getTok();
4571  Lexer.Lex();
4572  if (getLexer().isNot(AsmToken::EndOfStatement))
4573  return TokError("unexpected token in '" + EndToken.getIdentifier() +
4574  "' directive");
4575  break;
4576  } else {
4577  // Otherwise we just found the end of an inner macro.
4578  --MacroDepth;
4579  }
4580  } else if (getTok().getIdentifier() == ".macro") {
4581  // We allow nested macros. Those aren't instantiated until the outermost
4582  // macro is expanded so just ignore them for now.
4583  ++MacroDepth;
4584  }
4585  } else if (Lexer.is(AsmToken::HashDirective)) {
4586  (void)parseCppHashLineFilenameComment(getLexer().getLoc());
4587  }
4588 
4589  // Otherwise, scan til the end of the statement.
4590  eatToEndOfStatement();
4591  }
4592 
4593  if (getContext().lookupMacro(Name)) {
4594  return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4595  }
4596 
4597  const char *BodyStart = StartToken.getLoc().getPointer();
4598  const char *BodyEnd = EndToken.getLoc().getPointer();
4599  StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4600  checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
4601  MCAsmMacro Macro(Name, Body, std::move(Parameters));
4602  DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n";
4603  Macro.dump());
4604  getContext().defineMacro(Name, std::move(Macro));
4605  return false;
4606 }
4607 
4608 /// checkForBadMacro
4609 ///
4610 /// With the support added for named parameters there may be code out there that
4611 /// is transitioning from positional parameters. In versions of gas that did
4612 /// not support named parameters they would be ignored on the macro definition.
4613 /// But to support both styles of parameters this is not possible so if a macro
4614 /// definition has named parameters but does not use them and has what appears
4615 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4616 /// warning that the positional parameter found in body which have no effect.
4617 /// Hoping the developer will either remove the named parameters from the macro
4618 /// definition so the positional parameters get used if that was what was
4619 /// intended or change the macro to use the named parameters. It is possible
4620 /// this warning will trigger when the none of the named parameters are used
4621 /// and the strings like $1 are infact to simply to be passed trough unchanged.
4622 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
4623  StringRef Body,
4624  ArrayRef<MCAsmMacroParameter> Parameters) {
4625  // If this macro is not defined with named parameters the warning we are
4626  // checking for here doesn't apply.
4627  unsigned NParameters = Parameters.size();
4628  if (NParameters == 0)
4629  return;
4630 
4631  bool NamedParametersFound = false;
4632  bool PositionalParametersFound = false;
4633 
4634  // Look at the body of the macro for use of both the named parameters and what
4635  // are likely to be positional parameters. This is what expandMacro() is
4636  // doing when it finds the parameters in the body.
4637  while (!Body.empty()) {
4638  // Scan for the next possible parameter.
4639  std::size_t End = Body.size(), Pos = 0;
4640  for (; Pos != End; ++Pos) {
4641  // Check for a substitution or escape.
4642  // This macro is defined with parameters, look for \foo, \bar, etc.
4643  if (Body[Pos] == '\\' && Pos + 1 != End)
4644  break;
4645 
4646  // This macro should have parameters, but look for $0, $1, ..., $n too.
4647  if (Body[Pos] != '$' || Pos + 1 == End)
4648  continue;
4649  char Next = Body[Pos + 1];
4650  if (Next == '$' || Next == 'n' ||
4651  isdigit(static_cast<unsigned char>(Next)))
4652  break;
4653  }
4654 
4655  // Check if we reached the end.
4656  if (Pos == End)
4657  break;
4658 
4659  if (Body[Pos] == '$') {
4660  switch (Body[Pos + 1]) {
4661  // $$ => $
4662  case '$':
4663  break;
4664 
4665  // $n => number of arguments
4666  case 'n':
4667  PositionalParametersFound = true;
4668  break;
4669 
4670  // $[0-9] => argument
4671  default: {
4672  PositionalParametersFound = true;
4673  break;
4674  }
4675  }
4676  Pos += 2;
4677  } else {
4678  unsigned I = Pos + 1;
4679  while (isIdentifierChar(Body[I]) && I + 1 != End)
4680  ++I;
4681 
4682  const char *Begin = Body.data() + Pos + 1;
4683  StringRef Argument(Begin, I - (Pos + 1));
4684  unsigned Index = 0;
4685  for (; Index < NParameters; ++Index)
4686  if (Parameters[Index].Name == Argument)
4687  break;
4688 
4689  if (Index == NParameters) {
4690  if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4691  Pos += 3;
4692  else {
4693  Pos = I;
4694  }
4695  } else {
4696  NamedParametersFound = true;
4697  Pos += 1 + Argument.size();
4698  }
4699  }
4700  // Update the scan point.
4701  Body = Body.substr(Pos);
4702  }
4703 
4704  if (!NamedParametersFound && PositionalParametersFound)
4705  Warning(DirectiveLoc, "macro defined with named parameters which are not "
4706  "used in macro body, possible positional parameter "
4707  "found in body which will have no effect");
4708 }
4709 
4710 /// parseDirectiveExitMacro
4711 /// ::= .exitm
4712 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
4713  if (parseEOL())
4714  return true;
4715 
4716  if (!isInsideMacroInstantiation())
4717  return TokError("unexpected '" + Directive + "' in file, "
4718  "no current macro definition");
4719 
4720  // Exit all conditionals that are active in the current macro.
4721  while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4722  TheCondState = TheCondStack.back();
4723  TheCondStack.pop_back();
4724  }
4725 
4726  handleMacroExit();
4727  return false;
4728 }
4729 
4730 /// parseDirectiveEndMacro
4731 /// ::= .endm
4732 /// ::= .endmacro
4733 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
4734  if (getLexer().isNot(AsmToken::EndOfStatement))
4735  return TokError("unexpected token in '" + Directive + "' directive");
4736 
4737  // If we are inside a macro instantiation, terminate the current
4738  // instantiation.
4739  if (isInsideMacroInstantiation()) {
4740  handleMacroExit();
4741  return false;
4742  }
4743 
4744  // Otherwise, this .endmacro is a stray entry in the file; well formed
4745  // .endmacro directives are handled during the macro definition parsing.
4746  return TokError("unexpected '" + Directive + "' in file, "
4747  "no current macro definition");
4748 }
4749 
4750 /// parseDirectivePurgeMacro
4751 /// ::= .purgem name
4752 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
4753  StringRef Name;
4754  SMLoc Loc;
4755  if (parseTokenLoc(Loc) ||
4756  check(parseIdentifier(Name), Loc,
4757  "expected identifier in '.purgem' directive") ||
4758  parseEOL())
4759  return true;
4760 
4761  if (!getContext().lookupMacro(Name))
4762  return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4763 
4764  getContext().undefineMacro(Name);
4765  DEBUG_WITH_TYPE("asm-macros", dbgs()
4766  << "Un-defining macro: " << Name << "\n");
4767  return false;
4768 }
4769 
4770 /// parseDirectiveBundleAlignMode
4771 /// ::= {.bundle_align_mode} expression
4772 bool AsmParser::parseDirectiveBundleAlignMode() {
4773  // Expect a single argument: an expression that evaluates to a constant
4774  // in the inclusive range 0-30.
4775  SMLoc ExprLoc = getLexer().getLoc();
4776  int64_t AlignSizePow2;
4777  if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
4778  parseEOL() ||
4779  check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4780  "invalid bundle alignment size (expected between 0 and 30)"))
4781  return true;
4782 
4783  // Because of AlignSizePow2's verified range we can safely truncate it to
4784  // unsigned.
4785  getStreamer().emitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4786  return false;
4787 }
4788 
4789 /// parseDirectiveBundleLock
4790 /// ::= {.bundle_lock} [align_to_end]
4791 bool AsmParser::parseDirectiveBundleLock() {
4792  if (checkForValidSection())
4793  return true;
4794  bool AlignToEnd = false;
4795 
4796  StringRef Option;
4797  SMLoc Loc = getTok().getLoc();
4798  const char *kInvalidOptionError =
4799  "invalid option for '.bundle_lock' directive";
4800 
4801  if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4802  if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4803  check(Option != "align_to_end", Loc, kInvalidOptionError) || parseEOL())
4804  return true;
4805  AlignToEnd = true;
4806  }
4807 
4808  getStreamer().emitBundleLock(AlignToEnd);
4809  return false;
4810 }
4811 
4812 /// parseDirectiveBundleLock
4813 /// ::= {.bundle_lock}
4814 bool AsmParser::parseDirectiveBundleUnlock() {
4815  if (checkForValidSection() || parseEOL())
4816  return true;
4817 
4818  getStreamer().emitBundleUnlock();
4819  return false;
4820 }
4821 
4822 /// parseDirectiveSpace
4823 /// ::= (.skip | .space) expression [ , expression ]
4824 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
4825  SMLoc NumBytesLoc = Lexer.getLoc();
4826  const MCExpr *NumBytes;
4827  if (checkForValidSection() || parseExpression(NumBytes))
4828  return true;
4829 
4830  int64_t FillExpr = 0;
4831  if (parseOptionalToken(AsmToken::Comma))
4832  if (parseAbsoluteExpression(FillExpr))
4833  return true;
4834  if (parseEOL())
4835  return true;
4836 
4837  // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
4838  getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
4839 
4840  return false;
4841 }
4842 
4843 /// parseDirectiveDCB
4844 /// ::= .dcb.{b, l, w} expression, expression
4845 bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
4846  SMLoc NumValuesLoc = Lexer.getLoc();
4847  int64_t NumValues;
4848  if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4849  return true;
4850 
4851  if (NumValues < 0) {
4852  Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4853  return false;
4854  }
4855 
4856  if (parseComma())
4857  return true;
4858 
4859  const MCExpr *Value;
4860  SMLoc ExprLoc = getLexer().getLoc();
4861  if (parseExpression(Value))
4862  return true;
4863 
4864  // Special case constant expressions to match code generator.
4865  if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4866  assert(Size <= 8 && "Invalid size");
4867  uint64_t IntValue = MCE->getValue();
4868  if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4869  return Error(ExprLoc, "literal value out of range for directive");
4870  for (uint64_t i = 0, e = NumValues; i != e; ++i)
4871  getStreamer().emitIntValue(IntValue, Size);
4872  } else {
4873  for (uint64_t i = 0, e = NumValues; i != e; ++i)
4874  getStreamer().emitValue(Value, Size, ExprLoc);
4875  }
4876 
4877  return parseEOL();
4878 }
4879 
4880 /// parseDirectiveRealDCB
4881 /// ::= .dcb.{d, s} expression, expression
4882 bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
4883  SMLoc NumValuesLoc = Lexer.getLoc();
4884  int64_t NumValues;
4885  if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4886  return true;
4887 
4888  if (NumValues < 0) {
4889  Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4890  return false;
4891  }
4892 
4893  if (parseComma())
4894  return true;
4895 
4896  APInt AsInt;
4897  if (parseRealValue(Semantics, AsInt) || parseEOL())
4898  return true;
4899 
4900  for (uint64_t i = 0, e = NumValues; i != e; ++i)
4901  getStreamer().emitIntValue(AsInt.getLimitedValue(),
4902  AsInt.getBitWidth() / 8);
4903 
4904  return false;
4905 }
4906 
4907 /// parseDirectiveDS
4908 /// ::= .ds.{b, d, l, p, s, w, x} expression
4909 bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
4910  SMLoc NumValuesLoc = Lexer.getLoc();
4911  int64_t NumValues;
4912  if (checkForValidSection() || parseAbsoluteExpression(NumValues) ||
4913  parseEOL())
4914  return true;
4915 
4916  if (NumValues < 0) {
4917  Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4918  return false;
4919  }
4920 
4921  for (uint64_t i = 0, e = NumValues; i != e; ++i)
4922  getStreamer().emitFill(Size, 0);
4923 
4924  return false;
4925 }
4926 
4927 /// parseDirectiveLEB128
4928 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
4929 bool AsmParser::parseDirectiveLEB128(bool Signed) {
4930  if (checkForValidSection())
4931  return true;
4932 
4933  auto parseOp = [&]() -> bool {
4934  const MCExpr *Value;
4935  if (parseExpression(Value))
4936  return true;
4937  if (Signed)
4938  getStreamer().emitSLEB128Value(Value);
4939  else
4940  getStreamer().emitULEB128Value(Value);
4941  return false;
4942  };
4943 
4944  return parseMany(parseOp);
4945 }
4946 
4947 /// parseDirectiveSymbolAttribute
4948 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
4949 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
4950  auto parseOp = [&]() -> bool {
4951  StringRef Name;
4952  SMLoc Loc = getTok().getLoc();
4953  if (parseIdentifier(Name))
4954  return Error(Loc, "expected identifier");
4955 
4956  if (discardLTOSymbol(Name))
4957  return false;
4958 
4959  MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4960 
4961  // Assembler local symbols don't make any sense here. Complain loudly.
4962  if (Sym->isTemporary())
4963  return Error(Loc, "non-local symbol required");
4964 
4965  if (!getStreamer().emitSymbolAttribute(Sym, Attr))
4966  return Error(Loc, "unable to emit symbol attribute");
4967  return false;
4968  };
4969 
4970  return parseMany(parseOp);
4971 }
4972 
4973 /// parseDirectiveComm
4974 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
4975 bool AsmParser::parseDirectiveComm(bool IsLocal) {
4976  if (checkForValidSection())
4977  return true;
4978 
4979  SMLoc IDLoc = getLexer().getLoc();
4980  StringRef Name;
4981  if (parseIdentifier(Name))
4982  return TokError("expected identifier in directive");
4983 
4984  // Handle the identifier as the key symbol.
4985  MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4986 
4987  if (parseComma())
4988  return true;
4989 
4990  int64_t Size;
4991  SMLoc SizeLoc = getLexer().getLoc();
4992  if (parseAbsoluteExpression(Size))
4993  return true;
4994 
4995  int64_t Pow2Alignment = 0;
4996  SMLoc Pow2AlignmentLoc;
4997  if (getLexer().is(AsmToken::Comma)) {
4998  Lex();
4999  Pow2AlignmentLoc = getLexer().getLoc();
5000  if (parseAbsoluteExpression(Pow2Alignment))
5001  return true;
5002 
5003  LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
5004  if (IsLocal && LCOMM == LCOMM::NoAlignment)
5005  return Error(Pow2AlignmentLoc, "alignment not supported on this target");
5006 
5007  // If this target takes alignments in bytes (not log) validate and convert.
5008  if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
5009  (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
5010  if (!isPowerOf2_64(Pow2Alignment))
5011  return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
5012  Pow2Alignment = Log2_64(Pow2Alignment);
5013  }
5014  }
5015 
5016  if (parseEOL())
5017  return true;
5018 
5019  // NOTE: a size of zero for a .comm should create a undefined symbol
5020  // but a size of .lcomm creates a bss symbol of size zero.
5021  if (Size < 0)
5022  return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
5023  "be less than zero");
5024 
5025  // NOTE: The alignment in the directive is a power of 2 value, the assembler
5026  // may internally end up wanting an alignment in bytes.
5027  // FIXME: Diagnose overflow.
5028  if (Pow2Alignment < 0)
5029  return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
5030  "alignment, can't be less than zero");
5031 
5032  Sym->redefineIfPossible();
5033  if (!Sym->isUndefined())
5034  return Error(IDLoc, "invalid symbol redefinition");
5035 
5036  // Create the Symbol as a common or local common with Size and Pow2Alignment
5037  if (IsLocal) {
5038  getStreamer().emitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
5039  return false;
5040  }
5041 
5042  getStreamer().emitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
5043  return false;
5044 }
5045 
5046 /// parseDirectiveAbort
5047 /// ::= .abort [... message ...]
5048 bool AsmParser::parseDirectiveAbort() {
5049  // FIXME: Use loc from directive.
5050  SMLoc Loc = getLexer().getLoc();
5051 
5052  StringRef Str = parseStringToEndOfStatement();
5053  if (parseEOL())
5054  return true;
5055 
5056  if (Str.empty())
5057  return Error(Loc, ".abort detected. Assembly stopping.");
5058  else
5059  return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
5060  // FIXME: Actually abort assembly here.
5061 
5062  return false;
5063 }
5064 
5065 /// parseDirectiveInclude
5066 /// ::= .include "filename"
5067 bool AsmParser::parseDirectiveInclude() {
5068  // Allow the strings to have escaped octal character sequence.
5069  std::string Filename;
5070  SMLoc IncludeLoc = getTok().getLoc();
5071 
5072  if (check(getTok().isNot(AsmToken::String),
5073  "expected string in '.include' directive") ||
5074  parseEscapedString(Filename) ||
5075  check(getTok().isNot(AsmToken::EndOfStatement),
5076  "unexpected token in '.include' directive") ||
5077  // Attempt to switch the lexer to the included file before consuming the
5078  // end of statement to avoid losing it when we switch.
5079  check(enterIncludeFile(Filename), IncludeLoc,
5080  "Could not find include file '" + Filename + "'"))
5081  return true;
5082 
5083  return false;
5084 }
5085 
5086 /// parseDirectiveIncbin
5087 /// ::= .incbin "filename" [ , skip [ , count ] ]
5088 bool AsmParser::parseDirectiveIncbin() {
5089  // Allow the strings to have escaped octal character sequence.
5090  std::string Filename;
5091  SMLoc IncbinLoc = getTok().getLoc();
5092  if (check(getTok().isNot(AsmToken::String),
5093  "expected string in '.incbin' directive") ||
5094  parseEscapedString(Filename))
5095  return true;
5096 
5097  int64_t Skip = 0;
5098  const MCExpr *Count = nullptr;
5099  SMLoc SkipLoc, CountLoc;
5100  if (parseOptionalToken(AsmToken::Comma)) {
5101  // The skip expression can be omitted while specifying the count, e.g:
5102  // .incbin "filename",,4
5103  if (getTok().isNot(AsmToken::Comma)) {
5104  if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
5105  return true;
5106  }
5107  if (parseOptionalToken(AsmToken::Comma)) {
5108  CountLoc = getTok().getLoc();
5109  if (parseExpression(Count))
5110  return true;
5111  }
5112  }
5113 
5114  if (parseEOL())
5115  return true;
5116 
5117  if (check(Skip < 0, SkipLoc, "skip is negative"))
5118  return true;
5119 
5120  // Attempt to process the included file.
5121  if (processIncbinFile(Filename, Skip, Count, CountLoc))
5122  return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
5123  return false;
5124 }
5125 
5126 /// parseDirectiveIf
5127 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
5128 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
5129  TheCondStack.push_back(TheCondState);
5130  TheCondState.TheCond = AsmCond::IfCond;
5131  if (TheCondState.Ignore) {
5132  eatToEndOfStatement();
5133  } else {
5134  int64_t ExprValue;
5135  if (parseAbsoluteExpression(ExprValue) || parseEOL())
5136  return true;
5137 
5138  switch (DirKind) {
5139  default:
5140  llvm_unreachable("unsupported directive");
5141  case DK_IF:
5142  case DK_IFNE:
5143  break;
5144  case DK_IFEQ:
5145  ExprValue = ExprValue == 0;
5146  break;
5147  case DK_IFGE:
5148  ExprValue = ExprValue >= 0;
5149  break;
5150  case DK_IFGT:
5151  ExprValue = ExprValue > 0;
5152  break;
5153  case DK_IFLE:
5154  ExprValue = ExprValue <= 0;
5155  break;
5156  case DK_IFLT:
5157  ExprValue = ExprValue < 0;
5158  break;
5159  }
5160 
5161  TheCondState.CondMet = ExprValue;
5162  TheCondState.Ignore = !TheCondState.CondMet;
5163  }
5164 
5165  return false;
5166 }
5167 
5168 /// parseDirectiveIfb
5169 /// ::= .ifb string
5170 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
5171  TheCondStack.push_back(TheCondState);
5172  TheCondState.TheCond = AsmCond::IfCond;
5173 
5174  if (TheCondState.Ignore) {
5175  eatToEndOfStatement();
5176  } else {
5177  StringRef Str = parseStringToEndOfStatement();
5178 
5179  if (parseEOL())
5180  return true;
5181 
5182  TheCondState.CondMet = ExpectBlank == Str.empty();
5183  TheCondState.Ignore = !TheCondState.CondMet;
5184  }
5185 
5186  return false;
5187 }
5188 
5189 /// parseDirectiveIfc
5190 /// ::= .ifc string1, string2
5191 /// ::= .ifnc string1, string2
5192 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
5193  TheCondStack.push_back(TheCondState);
5194  TheCondState.TheCond = AsmCond::IfCond;
5195 
5196  if (TheCondState.Ignore) {
5197  eatToEndOfStatement();
5198  } else {
5199  StringRef Str1 = parseStringToComma();
5200 
5201  if (parseComma())
5202  return true;
5203 
5204  StringRef Str2 = parseStringToEndOfStatement();
5205 
5206  if (parseEOL())
5207  return true;
5208 
5209  TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
5210  TheCondState.Ignore = !TheCondState.CondMet;
5211  }
5212 
5213  return false;
5214 }
5215 
5216 /// parseDirectiveIfeqs
5217 /// ::= .ifeqs string1, string2
5218 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
5219  if (Lexer.isNot(AsmToken::String)) {
5220  if (ExpectEqual)
5221  return TokError("expected string parameter for '.ifeqs' directive");
5222  return TokError("expected string parameter for '.ifnes' directive");
5223  }
5224 
5225  StringRef String1 = getTok().getStringContents();
5226  Lex();
5227 
5228  if (Lexer.isNot(AsmToken::Comma)) {
5229  if (ExpectEqual)
5230  return TokError(
5231  "expected comma after first string for '.ifeqs' directive");
5232  return TokError("expected comma after first string for '.ifnes' directive");
5233  }
5234 
5235  Lex();
5236 
5237  if (Lexer.isNot(AsmToken::String)) {
5238  if (ExpectEqual)
5239  return TokError("expected string parameter for '.ifeqs' directive");
5240  return TokError("expected string parameter for '.ifnes' directive");
5241  }
5242 
5243  StringRef String2 = getTok().getStringContents();
5244  Lex();
5245 
5246  TheCondStack.push_back(TheCondState);
5247  TheCondState.TheCond = AsmCond::IfCond;
5248  TheCondState.CondMet = ExpectEqual == (String1 == String2);
5249  TheCondState.Ignore = !TheCondState.CondMet;
5250 
5251  return false;
5252 }
5253 
5254 /// parseDirectiveIfdef
5255 /// ::= .ifdef symbol
5256 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
5257  StringRef Name;
5258  TheCondStack.push_back(TheCondState);
5259  TheCondState.TheCond = AsmCond::IfCond;
5260 
5261  if (TheCondState.Ignore) {
5262  eatToEndOfStatement();
5263  } else {
5264  if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
5265  parseEOL())
5266  return true;
5267 
5268  MCSymbol *Sym = getContext().lookupSymbol(Name);
5269 
5270  if (expect_defined)
5271  TheCondState.CondMet = (Sym && !Sym->isUndefined(false));
5272  else
5273  TheCondState.CondMet = (!Sym || Sym->isUndefined(false));
5274  TheCondState.Ignore = !TheCondState.CondMet;
5275  }
5276 
5277  return false;
5278 }
5279 
5280 /// parseDirectiveElseIf
5281 /// ::= .elseif expression
5282 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
5283  if (TheCondState.TheCond != AsmCond::IfCond &&
5284  TheCondState.TheCond != AsmCond::ElseIfCond)
5285  return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
5286  " .if or an .elseif");
5287  TheCondState.TheCond = AsmCond::ElseIfCond;
5288 
5289  bool LastIgnoreState = false;
5290  if (!TheCondStack.empty())
5291  LastIgnoreState = TheCondStack.back().Ignore;
5292  if (LastIgnoreState || TheCondState.CondMet) {
5293  TheCondState.Ignore = true;
5294  eatToEndOfStatement();
5295  } else {
5296  int64_t ExprValue;
5297  if (parseAbsoluteExpression(ExprValue))
5298  return true;
5299 
5300  if (parseEOL())
5301  return true;
5302 
5303  TheCondState.CondMet = ExprValue;
5304  TheCondState.Ignore = !TheCondState.CondMet;
5305  }
5306 
5307  return false;
5308 }
5309 
5310 /// parseDirectiveElse
5311 /// ::= .else
5312 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
5313  if (parseEOL())
5314  return true;
5315 
5316  if (TheCondState.TheCond != AsmCond::IfCond &&
5317  TheCondState.TheCond != AsmCond::ElseIfCond)
5318  return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
5319  " an .if or an .elseif");
5320  TheCondState.TheCond = AsmCond::ElseCond;
5321  bool LastIgnoreState = false;
5322  if (!TheCondStack.empty())
5323  LastIgnoreState = TheCondStack.back().Ignore;
5324  if (LastIgnoreState || TheCondState.CondMet)
5325  TheCondState.Ignore = true;
5326  else
5327  TheCondState.Ignore = false;
5328 
5329  return false;
5330 }
5331 
5332 /// parseDirectiveEnd
5333 /// ::= .end
5334 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
5335  if (parseEOL())
5336  return true;
5337 
5338  while (Lexer.isNot(AsmToken::Eof))
5339  Lexer.Lex();
5340 
5341  return false;
5342 }
5343 
5344 /// parseDirectiveError
5345 /// ::= .err
5346 /// ::= .error [string]
5347 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
5348  if (!TheCondStack.empty()) {
5349  if (TheCondStack.back().Ignore) {
5350  eatToEndOfStatement();
5351  return false;
5352  }
5353  }
5354 
5355  if (!WithMessage)
5356  return Error(L, ".err encountered");
5357 
5358  StringRef Message = ".error directive invoked in source file";
5359  if (Lexer.isNot(AsmToken::EndOfStatement)) {
5360  if (Lexer.isNot(AsmToken::String))
5361  return TokError(".error argument must be a string");
5362 
5363  Message = getTok().getStringContents();
5364  Lex();
5365  }
5366 
5367  return Error(L, Message);
5368 }
5369 
5370 /// parseDirectiveWarning
5371 /// ::= .warning [string]
5372 bool AsmParser::parseDirectiveWarning(SMLoc L) {
5373  if (!TheCondStack.empty()) {
5374  if (TheCondStack.back().Ignore) {
5375  eatToEndOfStatement();
5376  return false;
5377  }
5378  }
5379 
5380  StringRef Message = ".warning directive invoked in source file";
5381 
5382  if (!parseOptionalToken(AsmToken::EndOfStatement)) {
5383  if (Lexer.isNot(AsmToken::String))
5384  return TokError(".warning argument must be a string");
5385 
5386  Message = getTok().getStringContents();
5387  Lex();
5388  if (parseEOL())
5389  return true;
5390  }
5391 
5392  return Warning(L, Message);
5393 }
5394 
5395 /// parseDirectiveEndIf
5396 /// ::= .endif
5397 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
5398  if (parseEOL())
5399  return true;
5400 
5401  if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
5402  return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
5403  "an .if or .else");
5404  if (!TheCondStack.empty()) {
5405  TheCondState = TheCondStack.back();
5406  TheCondStack.pop_back();
5407  }
5408 
5409  return false;
5410 }
5411 
5412 void AsmParser::initializeDirectiveKindMap() {
5413  /* Lookup will be done with the directive
5414  * converted to lower case, so all these
5415  * keys should be lower case.
5416  * (target specific directives are handled
5417  * elsewhere)
5418  */
5419  DirectiveKindMap[".set"] = DK_SET;
5420  DirectiveKindMap[".equ"] = DK_EQU;
5421  DirectiveKindMap[".equiv"] = DK_EQUIV;
5422  DirectiveKindMap[".ascii"] = DK_ASCII;
5423  DirectiveKindMap[".asciz"] = DK_ASCIZ;
5424  DirectiveKindMap[".string"] = DK_STRING;
5425  DirectiveKindMap[".byte"] = DK_BYTE;
5426  DirectiveKindMap[".short"] = DK_SHORT;
5427  DirectiveKindMap[".value"] = DK_VALUE;
5428  DirectiveKindMap[".2byte"] = DK_2BYTE;
5429  DirectiveKindMap[".long"] = DK_LONG;
5430  DirectiveKindMap[".int"] = DK_INT;
5431  DirectiveKindMap[".4byte"] = DK_4BYTE;
5432  DirectiveKindMap[".quad"] = DK_QUAD;
5433  DirectiveKindMap[".8byte"] = DK_8BYTE;
5434  DirectiveKindMap[".octa"] = DK_OCTA;
5435  DirectiveKindMap[".single"] = DK_SINGLE;
5436  DirectiveKindMap[".float"] = DK_FLOAT;
5437  DirectiveKindMap[".double"] = DK_DOUBLE;
5438  DirectiveKindMap[".align"] = DK_ALIGN;
5439  DirectiveKindMap[".align32"] = DK_ALIGN32;
5440  DirectiveKindMap[".balign"] = DK_BALIGN;
5441  DirectiveKindMap[".balignw"] = DK_BALIGNW;
5442  DirectiveKindMap[".balignl"] = DK_BALIGNL;
5443  DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5444  DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5445  DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5446  DirectiveKindMap[".org"] = DK_ORG;
5447  DirectiveKindMap[".fill"] = DK_FILL;
5448  DirectiveKindMap[".zero"] = DK_ZERO;
5449  DirectiveKindMap[".extern"] = DK_EXTERN;
5450  DirectiveKindMap[".globl"] = DK_GLOBL;
5451  DirectiveKindMap[".global"] = DK_GLOBAL;
5452  DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5453  DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5454  DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5455  DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5456  DirectiveKindMap[".reference"] = DK_REFERENCE;
5457  DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5458  DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5459  DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
5460  DirectiveKindMap[".cold"] = DK_COLD;
5461  DirectiveKindMap[".comm"] = DK_COMM;
5462  DirectiveKindMap[".common"] = DK_COMMON;
5463  DirectiveKindMap[".lcomm"] = DK_LCOMM;
5464  DirectiveKindMap[".abort"] = DK_ABORT;
5465  DirectiveKindMap[".include"] = DK_INCLUDE;
5466  DirectiveKindMap[".incbin"] = DK_INCBIN;
5467  DirectiveKindMap[".code16"] = DK_CODE16;
5468  DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5469  DirectiveKindMap[".rept"] = DK_REPT;
5470  DirectiveKindMap[".rep"] = DK_REPT;
5471  DirectiveKindMap[".irp"] = DK_IRP;
5472  DirectiveKindMap[".irpc"] = DK_IRPC;
5473  DirectiveKindMap[".endr"] = DK_ENDR;
5474  DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5475  DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5476  DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5477  DirectiveKindMap[".if"] = DK_IF;
5478  DirectiveKindMap[".ifeq"] = DK_IFEQ;
5479  DirectiveKindMap[".ifge"] = DK_IFGE;
5480  DirectiveKindMap[".ifgt"] = DK_IFGT;
5481  DirectiveKindMap[".ifle"] = DK_IFLE;
5482  DirectiveKindMap[".iflt"] = DK_IFLT;
5483  DirectiveKindMap[".ifne"] = DK_IFNE;
5484  DirectiveKindMap[".ifb"] = DK_IFB;
5485  DirectiveKindMap[".ifnb"] = DK_IFNB;
5486  DirectiveKindMap[".ifc"] = DK_IFC;
5487  DirectiveKindMap[".ifeqs"] = DK_IFEQS;
5488  DirectiveKindMap[".ifnc"] = DK_IFNC;
5489  DirectiveKindMap[".ifnes"] = DK_IFNES;
5490  DirectiveKindMap[".ifdef"] = DK_IFDEF;
5491  DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5492  DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5493  DirectiveKindMap[".elseif"] = DK_ELSEIF;
5494  DirectiveKindMap[".else"] = DK_ELSE;
5495  DirectiveKindMap[".end"] = DK_END;
5496  DirectiveKindMap[".endif"] = DK_ENDIF;
5497  DirectiveKindMap[".skip"] = DK_SKIP;
5498  DirectiveKindMap[".space"] = DK_SPACE;
5499  DirectiveKindMap[".file"] = DK_FILE;
5500  DirectiveKindMap[".line"] = DK_LINE;
5501  DirectiveKindMap[".loc"] = DK_LOC;
5502  DirectiveKindMap[".stabs"] = DK_STABS;
5503  DirectiveKindMap[".cv_file"] = DK_CV_FILE;
5504  DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
5505  DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5506  DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
5507  DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
5508  DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
5509  DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
5510  DirectiveKindMap[".cv_string"] = DK_CV_STRING;
5511  DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5512  DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
5513  DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET;
5514  DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA;
5515  DirectiveKindMap[".sleb128"] = DK_SLEB128;
5516  DirectiveKindMap[".uleb128"] = DK_ULEB128;
5517  DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5518  DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5519  DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5520  DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5521  DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5522  DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5523  DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5524  DirectiveKindMap[".cfi_llvm_def_aspace_cfa"] = DK_CFI_LLVM_DEF_ASPACE_CFA;
5525  DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5526  DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5527  DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5528  DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5529  DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5530  DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5531  DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5532  DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5533  DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
5534  DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
5535  DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5536  DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5537  DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
5538  DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
5539  DirectiveKindMap[".cfi_b_key_frame"] = DK_CFI_B_KEY_FRAME;
5540  DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5541  DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5542  DirectiveKindMap[".macro"] = DK_MACRO;
5543  DirectiveKindMap[".exitm"] = DK_EXITM;
5544  DirectiveKindMap[".endm"] = DK_ENDM;
5545  DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5546  DirectiveKindMap[".purgem"] = DK_PURGEM;
5547  DirectiveKindMap[".err"] = DK_ERR;
5548  DirectiveKindMap[".error"] = DK_ERROR;
5549  DirectiveKindMap[".warning"] = DK_WARNING;
5550  DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5551  DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
5552  DirectiveKindMap[".reloc"] = DK_RELOC;
5553  DirectiveKindMap[".dc"] = DK_DC;
5554  DirectiveKindMap[".dc.a"] = DK_DC_A;
5555  DirectiveKindMap[".dc.b"] = DK_DC_B;
5556  DirectiveKindMap[".dc.d"] = DK_DC_D;
5557  DirectiveKindMap[".dc.l"] = DK_DC_L;
5558  DirectiveKindMap[".dc.s"] = DK_DC_S;
5559  DirectiveKindMap[".dc.w"] = DK_DC_W;
5560  DirectiveKindMap[".dc.x"] = DK_DC_X;
5561  DirectiveKindMap[".dcb"] = DK_DCB;
5562  DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5563  DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5564  DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5565  DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5566  DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5567  DirectiveKindMap[".dcb.x"] = DK_DCB_X;
5568  DirectiveKindMap[".ds"] = DK_DS;
5569  DirectiveKindMap[".ds.b"] = DK_DS_B;
5570  DirectiveKindMap[".ds.d"] = DK_DS_D;
5571  DirectiveKindMap[".ds.l"] = DK_DS_L;
5572  DirectiveKindMap[".ds.p"] = DK_DS_P;
5573  DirectiveKindMap[".ds.s"] = DK_DS_S;
5574  DirectiveKindMap[".ds.w"] = DK_DS_W;
5575  DirectiveKindMap[".ds.x"] = DK_DS_X;
5576  DirectiveKindMap[".print"] = DK_PRINT;
5577  DirectiveKindMap[".addrsig"] = DK_ADDRSIG;
5578  DirectiveKindMap[".addrsig_sym"] = DK_ADDRSIG_SYM;
5579  DirectiveKindMap[".pseudoprobe"] = DK_PSEUDO_PROBE;
5580  DirectiveKindMap[".lto_discard"] = DK_LTO_DISCARD;
5581 }
5582 
5583 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
5584  AsmToken EndToken, StartToken = getTok();
5585 
5586  unsigned NestLevel = 0;
5587  while (true) {
5588  // Check whether we have reached the end of the file.
5589  if (getLexer().is(AsmToken::Eof)) {
5590  printError(DirectiveLoc, "no matching '.endr' in definition");
5591  return nullptr;
5592  }
5593 
5594  if (Lexer.is(AsmToken::Identifier) &&
5595  (getTok().getIdentifier() == ".rep" ||
5596  getTok().getIdentifier() == ".rept" ||
5597  getTok().getIdentifier() == ".irp" ||
5598  getTok().getIdentifier() == ".irpc")) {
5599  ++NestLevel;
5600  }
5601 
5602  // Otherwise, check whether we have reached the .endr.
5603  if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
5604  if (NestLevel == 0) {
5605  EndToken = getTok();
5606  Lex();
5607  if (Lexer.isNot(AsmToken::EndOfStatement)) {
5608  printError(getTok().getLoc(),
5609  "unexpected token in '.endr' directive");
5610  return nullptr;
5611  }
5612  break;
5613  }
5614  --NestLevel;
5615  }
5616 
5617  // Otherwise, scan till the end of the statement.
5618  eatToEndOfStatement();
5619  }
5620 
5621  const char *BodyStart = StartToken.getLoc().getPointer();
5622  const char *BodyEnd = EndToken.getLoc().getPointer();
5623  StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5624 
5625  // We Are Anonymous.
5626  MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
5627  return &MacroLikeBodies.back();
5628 }
5629 
5630 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
5631  raw_svector_ostream &OS) {
5632  OS << ".endr\n";
5633 
5634  std::unique_ptr<MemoryBuffer> Instantiation =
5635  MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
5636 
5637  // Create the macro instantiation object and add to the current macro
5638  // instantiation stack.
5639  MacroInstantiation *MI = new MacroInstantiation{
5640  DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size()};
5641  ActiveMacros.push_back(MI);
5642 
5643  // Jump to the macro instantiation and prime the lexer.
5644  CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
5645  Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
5646  Lex();
5647 }
5648 
5649 /// parseDirectiveRept
5650 /// ::= .rep | .rept count
5651 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
5652  const MCExpr *CountExpr;
5653  SMLoc CountLoc = getTok().getLoc();
5654  if (parseExpression(CountExpr))
5655  return true;
5656 
5657  int64_t Count;
5658  if (!CountExpr->evaluateAsAbsolute(Count, getStreamer().getAssemblerPtr())) {
5659  return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5660  }
5661 
5662  if (check(Count < 0, CountLoc, "Count is negative") || parseEOL())
5663  return true;
5664 
5665  // Lex the rept definition.
5666  MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5667  if (!M)
5668  return true;
5669 
5670  // Macro instantiation is lexical, unfortunately. We construct a new buffer
5671  // to hold the macro body with substitutions.
5672  SmallString<256> Buf;
5673  raw_svector_ostream OS(Buf);
5674  while (Count--) {
5675  // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5676  if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
5677  return true;
5678  }
5679  instantiateMacroLikeBody(M, DirectiveLoc, OS);
5680 
5681  return false;
5682 }
5683 
5684 /// parseDirectiveIrp
5685 /// ::= .irp symbol,values
5686 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
5687  MCAsmMacroParameter Parameter;
5688  MCAsmMacroArguments A;
5689  if (check(parseIdentifier(Parameter.Name),
5690  "expected identifier in '.irp' directive") ||
5691  parseComma() || parseMacroArguments(nullptr, A) || parseEOL())
5692  return true;
5693 
5694  // Lex the irp definition.
5695  MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5696  if (!M)
5697  return true;
5698 
5699  // Macro instantiation is lexical, unfortunately. We construct a new buffer
5700  // to hold the macro body with substitutions.
5701  SmallString<256> Buf;
5702  raw_svector_ostream OS(Buf);
5703 
5704  for (const MCAsmMacroArgument &Arg : A) {
5705  // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5706  // This is undocumented, but GAS seems to support it.
5707  if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
5708  return true;
5709  }
5710 
5711  instantiateMacroLikeBody(M, DirectiveLoc, OS);
5712 
5713  return false;
5714 }
5715 
5716 /// parseDirectiveIrpc
5717 /// ::= .irpc symbol,values
5718 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
5719  MCAsmMacroParameter Parameter;
5720  MCAsmMacroArguments A;
5721 
5722  if (check(parseIdentifier(Parameter.Name),
5723  "expected identifier in '.irpc' directive") ||
5724  parseComma() || parseMacroArguments(nullptr, A))
5725  return true;
5726 
5727  if (A.size() != 1 || A.front().size() != 1)
5728  return TokError("unexpected token in '.irpc' directive");
5729  if (parseEOL())
5730  return true;
5731 
5732  // Lex the irpc definition.
5733  MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5734  if (!M)
5735  return true;
5736 
5737  // Macro instantiation is lexical, unfortunately. We construct a new buffer
5738  // to hold the macro body with substitutions.
5739  SmallString<256> Buf;
5740  raw_svector_ostream OS(Buf);
5741 
5742  StringRef Values = A.front().front().getString();
5743  for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
5744  MCAsmMacroArgument Arg;
5745  Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
5746 
5747  // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5748  // This is undocumented, but GAS seems to support it.
5749  if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
5750  return true;
5751  }
5752 
5753  instantiateMacroLikeBody(M, DirectiveLoc, OS);
5754 
5755  return false;
5756 }
5757 
5758 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
5759  if (ActiveMacros.empty())
5760  return TokError("unmatched '.endr' directive");
5761 
5762  // The only .repl that should get here are the ones created by
5763  // instantiateMacroLikeBody.
5764  assert(getLexer().is(AsmToken::EndOfStatement));
5765 
5766  handleMacroExit();
5767  return false;
5768 }
5769 
5770 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
5771  size_t Len) {
5772  const MCExpr *Value;
5773  SMLoc ExprLoc = getLexer().getLoc();
5774  if (parseExpression(Value))
5775  return true;
5776  const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5777  if (!MCE)
5778  return Error(ExprLoc, "unexpected expression in _emit");
5779  uint64_t IntValue = MCE->getValue();
5780  if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
5781  return Error(ExprLoc, "literal value out of range for directive");
5782 
5783  Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
5784  return false;
5785 }
5786 
5787 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
5788  const MCExpr *Value;
5789  SMLoc ExprLoc = getLexer().getLoc();
5790  if (parseExpression(Value))
5791  return true;
5792  const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5793  if (!MCE)
5794  return Error(ExprLoc, "unexpected expression in align");
5795  uint64_t IntValue = MCE->getValue();
5796  if (!isPowerOf2_64(IntValue))
5797  return Error(ExprLoc, "literal value not a power of two greater then zero");
5798 
5799  Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
5800  return false;
5801 }
5802 
5803 bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) {
5804  const AsmToken StrTok = getTok();
5805  Lex();
5806  if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"')
5807  return Error(DirectiveLoc, "expected double quoted string after .print");
5808  if (parseEOL())
5809  return true;
5810  llvm::outs() << StrTok.getStringContents() << '\n';
5811  return false;
5812 }
5813 
5814 bool AsmParser::parseDirectiveAddrsig() {
5815  if (parseEOL())
5816  return true;
5817  getStreamer().emitAddrsig();
5818  return false;
5819 }
5820 
5821 bool AsmParser::parseDirectiveAddrsigSym() {
5822  StringRef Name;
5823  if (check(parseIdentifier(Name), "expected identifier") || parseEOL())
5824  return true;
5825  MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
5826  getStreamer().emitAddrsigSym(Sym);
5827  return false;
5828 }
5829 
5830 bool AsmParser::parseDirectivePseudoProbe() {
5831  int64_t Guid;
5832  int64_t Index;
5833  int64_t Type;
5834  int64_t Attr;
5835 
5836  if (getLexer().is(AsmToken::Integer)) {
5837  if (parseIntToken(Guid, "unexpected token in '.pseudoprobe' directive"))
5838  return true;
5839  }
5840 
5841  if (getLexer().is(AsmToken::Integer)) {
5842  if (parseIntToken(Index, "unexpected token in '.pseudoprobe' directive"))
5843  return true;
5844  }
5845 
5846  if (getLexer().is(AsmToken::Integer)) {
5847  if (parseIntToken(Type, "unexpected token in '.pseudoprobe' directive"))
5848  return true;
5849  }
5850 
5851  if (getLexer().is(AsmToken::Integer)) {
5852  if (parseIntToken(Attr, "unexpected token in '.pseudoprobe' directive"))
5853  return true;
5854  }
5855 
5856  // Parse inline stack like @ GUID:11:12 @ GUID:1:11 @ GUID:3:21
5857  MCPseudoProbeInlineStack InlineStack;
5858 
5859  while (getLexer().is(AsmToken::At)) {
5860  // eat @
5861  Lex();
5862 
5863  int64_t CallerGuid = 0;
5864  if (getLexer().is(AsmToken::Integer)) {
5865  if (parseIntToken(CallerGuid,
5866  "unexpected token in '.pseudoprobe' directive"))
5867  return true;
5868  }
5869 
5870  // eat colon
5871  if (getLexer().is(AsmToken::Colon))
5872  Lex();
5873 
5874  int64_t CallerProbeId = 0;
5875  if (getLexer().is(AsmToken::Integer)) {
5876  if (parseIntToken(CallerProbeId,
5877  "unexpected token in '.pseudoprobe' directive"))
5878  return true;
5879  }
5880 
5881  InlineSite Site(CallerGuid, CallerProbeId);
5882  InlineStack.push_back(Site);
5883  }
5884 
5885  if (parseEOL())
5886  return true;
5887 
5888  getStreamer().emitPseudoProbe(Guid, Index, Type, Attr, InlineStack);
5889  return false;
5890 }
5891 
5892 /// parseDirectiveLTODiscard
5893 /// ::= ".lto_discard" [ identifier ( , identifier )* ]
5894 /// The LTO library emits this directive to discard non-prevailing symbols.
5895 /// We ignore symbol assignments and attribute changes for the specified
5896 /// symbols.
5897 bool AsmParser::parseDirectiveLTODiscard() {
5898  auto ParseOp = [&]() -> bool {
5899  StringRef Name;
5900  SMLoc Loc = getTok().getLoc();
5901  if (parseIdentifier(Name))
5902  return Error(Loc, "expected identifier");
5903  LTODiscardSymbols.insert(Name);
5904  return false;
5905  };
5906 
5907  LTODiscardSymbols.clear();
5908  return parseMany(ParseOp);
5909 }
5910 
5911 // We are comparing pointers, but the pointers are relative to a single string.
5912 // Thus, this should always be deterministic.
5913 static int rewritesSort(const AsmRewrite *AsmRewriteA,
5914  const AsmRewrite *AsmRewriteB) {
5915  if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5916  return -1;
5917  if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5918  return 1;
5919 
5920  // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5921  // rewrite to the same location. Make sure the SizeDirective rewrite is
5922  // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5923  // ensures the sort algorithm is stable.
5924  if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5925  AsmRewritePrecedence[AsmRewriteB->Kind])
5926  return -1;
5927 
5928  if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5929  AsmRewritePrecedence[AsmRewriteB->Kind])
5930  return 1;
5931  llvm_unreachable("Unstable rewrite sort.");
5932 }
5933 
5934 bool AsmParser::parseMSInlineAsm(
5935  std::string &AsmString, unsigned &NumOutputs, unsigned &NumInputs,
5936  SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
5937  SmallVectorImpl<std::string> &Constraints,
5938  SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5940  SmallVector<void *, 4> InputDecls;
5941  SmallVector<void *, 4> OutputDecls;
5942  SmallVector<bool, 4> InputDeclsAddressOf;
5943  SmallVector<bool, 4> OutputDeclsAddressOf;
5944  SmallVector<std::string, 4> InputConstraints;
5945  SmallVector<std::string, 4> OutputConstraints;
5946  SmallVector<unsigned, 4> ClobberRegs;
5947 
5948  SmallVector<AsmRewrite, 4> AsmStrRewrites;
5949 
5950  // Prime the lexer.
5951  Lex();
5952 
5953  // While we have input, parse each statement.
5954  unsigned InputIdx = 0;
5955  unsigned OutputIdx = 0;
5956  while (getLexer().isNot(AsmToken::Eof)) {
5957  // Parse curly braces marking block start/end
5958  if (parseCurlyBlockScope(AsmStrRewrites))
5959  continue;
5960 
5961  ParseStatementInfo Info(&AsmStrRewrites);
5962  bool StatementErr = parseStatement(Info, &SI);
5963 
5964  if (StatementErr || Info.ParseError) {
5965  // Emit pending errors if any exist.
5966  printPendingErrors();
5967  return true;
5968  }
5969 
5970  // No pending error should exist here.
5971  assert(!hasPendingError() && "unexpected error from parseStatement");
5972 
5973  if (Info.Opcode == ~0U)
5974  continue;
5975 
5976  const MCInstrDesc &Desc = MII->get(Info.Opcode);
5977 
5978  // Build the list of clobbers, outputs and inputs.
5979  for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
5980  MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
5981 
5982  // Register operand.
5983  if (Operand.isReg() && !Operand.needAddressOf() &&
5984  !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
5985  unsigned NumDefs = Desc.getNumDefs();
5986  // Clobber.
5987  if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5988  ClobberRegs.push_back(Operand.getReg());
5989  continue;
5990  }
5991 
5992