Coverage Report

Created: 2025-09-22 06:59

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