LLVM 24.0.0git
MIParser.cpp
Go to the documentation of this file.
1//===- MIParser.cpp - Machine instructions parser implementation ----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the parsing of machine instructions.
10//
11//===----------------------------------------------------------------------===//
12
14#include "MILexer.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/APSInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/StringMap.h"
21#include "llvm/ADT/StringRef.h"
23#include "llvm/ADT/Twine.h"
43#include "llvm/IR/BasicBlock.h"
44#include "llvm/IR/Constants.h"
45#include "llvm/IR/DataLayout.h"
47#include "llvm/IR/DebugLoc.h"
48#include "llvm/IR/Function.h"
49#include "llvm/IR/InlineAsm.h"
50#include "llvm/IR/InstrTypes.h"
52#include "llvm/IR/Intrinsics.h"
53#include "llvm/IR/Metadata.h"
54#include "llvm/IR/Module.h"
56#include "llvm/IR/Type.h"
57#include "llvm/IR/Value.h"
59#include "llvm/MC/LaneBitmask.h"
60#include "llvm/MC/MCContext.h"
61#include "llvm/MC/MCDwarf.h"
62#include "llvm/MC/MCInstrDesc.h"
68#include "llvm/Support/SMLoc.h"
71#include <cassert>
72#include <cctype>
73#include <cstddef>
74#include <cstdint>
75#include <limits>
76#include <string>
77#include <utility>
78
79using namespace llvm;
80
82 const TargetSubtargetInfo &NewSubtarget) {
83
84 // If the subtarget changed, over conservatively assume everything is invalid.
85 if (&Subtarget == &NewSubtarget)
86 return;
87
88 Names2InstrOpCodes.clear();
89 Names2Regs.clear();
90 Names2RegMasks.clear();
91 Names2SubRegIndices.clear();
92 Names2TargetIndices.clear();
93 Names2DirectTargetFlags.clear();
94 Names2BitmaskTargetFlags.clear();
95 Names2MMOTargetFlags.clear();
96
97 initNames2RegClasses();
98 initNames2RegBanks();
99}
100
101void PerTargetMIParsingState::initNames2Regs() {
102 if (!Names2Regs.empty())
103 return;
104
105 // The '%noreg' register is the register 0.
106 Names2Regs.insert(std::make_pair("noreg", 0));
107 const auto *TRI = Subtarget.getRegisterInfo();
108 assert(TRI && "Expected target register info");
109
110 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
111 bool WasInserted =
112 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
113 .second;
114 (void)WasInserted;
115 assert(WasInserted && "Expected registers to be unique case-insensitively");
116 }
117}
118
120 Register &Reg) {
121 initNames2Regs();
122 auto RegInfo = Names2Regs.find(RegName);
123 if (RegInfo == Names2Regs.end())
124 return true;
125 Reg = RegInfo->getValue();
126 return false;
127}
128
130 uint8_t &FlagValue) const {
131 const auto *TRI = Subtarget.getRegisterInfo();
132 std::optional<uint8_t> FV = TRI->getVRegFlagValue(FlagName);
133 if (!FV)
134 return true;
135 FlagValue = *FV;
136 return false;
137}
138
139void PerTargetMIParsingState::initNames2InstrOpCodes() {
140 if (!Names2InstrOpCodes.empty())
141 return;
142 const auto *TII = Subtarget.getInstrInfo();
143 assert(TII && "Expected target instruction info");
144 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
145 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
146}
147
149 unsigned &OpCode) {
150 initNames2InstrOpCodes();
151 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
152 if (InstrInfo == Names2InstrOpCodes.end())
153 return true;
154 OpCode = InstrInfo->getValue();
155 return false;
156}
157
158void PerTargetMIParsingState::initNames2RegMasks() {
159 if (!Names2RegMasks.empty())
160 return;
161 const auto *TRI = Subtarget.getRegisterInfo();
162 assert(TRI && "Expected target register info");
163 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
164 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
165 assert(RegMasks.size() == RegMaskNames.size());
166 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
167 Names2RegMasks.insert(
168 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
169}
170
172 initNames2RegMasks();
173 auto RegMaskInfo = Names2RegMasks.find(Identifier);
174 if (RegMaskInfo == Names2RegMasks.end())
175 return nullptr;
176 return RegMaskInfo->getValue();
177}
178
179void PerTargetMIParsingState::initNames2SubRegIndices() {
180 if (!Names2SubRegIndices.empty())
181 return;
182 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
183 for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
184 Names2SubRegIndices.insert(
185 std::make_pair(TRI->getSubRegIndexName(I), I));
186}
187
189 initNames2SubRegIndices();
190 auto SubRegInfo = Names2SubRegIndices.find(Name);
191 if (SubRegInfo == Names2SubRegIndices.end())
192 return 0;
193 return SubRegInfo->getValue();
194}
195
196void PerTargetMIParsingState::initNames2TargetIndices() {
197 if (!Names2TargetIndices.empty())
198 return;
199 const auto *TII = Subtarget.getInstrInfo();
200 assert(TII && "Expected target instruction info");
201 auto Indices = TII->getSerializableTargetIndices();
202 for (const auto &I : Indices)
203 Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
204}
205
207 initNames2TargetIndices();
208 auto IndexInfo = Names2TargetIndices.find(Name);
209 if (IndexInfo == Names2TargetIndices.end())
210 return true;
211 Index = IndexInfo->second;
212 return false;
213}
214
215void PerTargetMIParsingState::initNames2DirectTargetFlags() {
216 if (!Names2DirectTargetFlags.empty())
217 return;
218
219 const auto *TII = Subtarget.getInstrInfo();
220 assert(TII && "Expected target instruction info");
221 auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
222 for (const auto &I : Flags)
223 Names2DirectTargetFlags.insert(
224 std::make_pair(StringRef(I.second), I.first));
225}
226
228 unsigned &Flag) {
229 initNames2DirectTargetFlags();
230 auto FlagInfo = Names2DirectTargetFlags.find(Name);
231 if (FlagInfo == Names2DirectTargetFlags.end())
232 return true;
233 Flag = FlagInfo->second;
234 return false;
235}
236
237void PerTargetMIParsingState::initNames2BitmaskTargetFlags() {
238 if (!Names2BitmaskTargetFlags.empty())
239 return;
240
241 const auto *TII = Subtarget.getInstrInfo();
242 assert(TII && "Expected target instruction info");
243 auto Flags = TII->getSerializableBitmaskMachineOperandTargetFlags();
244 for (const auto &I : Flags)
245 Names2BitmaskTargetFlags.insert(
246 std::make_pair(StringRef(I.second), I.first));
247}
248
250 unsigned &Flag) {
251 initNames2BitmaskTargetFlags();
252 auto FlagInfo = Names2BitmaskTargetFlags.find(Name);
253 if (FlagInfo == Names2BitmaskTargetFlags.end())
254 return true;
255 Flag = FlagInfo->second;
256 return false;
257}
258
259void PerTargetMIParsingState::initNames2MMOTargetFlags() {
260 if (!Names2MMOTargetFlags.empty())
261 return;
262
263 const auto *TII = Subtarget.getInstrInfo();
264 assert(TII && "Expected target instruction info");
265 auto Flags = TII->getSerializableMachineMemOperandTargetFlags();
266 for (const auto &I : Flags)
267 Names2MMOTargetFlags.insert(std::make_pair(StringRef(I.second), I.first));
268}
269
272 initNames2MMOTargetFlags();
273 auto FlagInfo = Names2MMOTargetFlags.find(Name);
274 if (FlagInfo == Names2MMOTargetFlags.end())
275 return true;
276 Flag = FlagInfo->second;
277 return false;
278}
279
280void PerTargetMIParsingState::initNames2RegClasses() {
281 if (!Names2RegClasses.empty())
282 return;
283
284 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
285 for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) {
286 const auto *RC = TRI->getRegClass(I);
287 Names2RegClasses.insert(
288 std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC));
289 }
290}
291
292void PerTargetMIParsingState::initNames2RegBanks() {
293 if (!Names2RegBanks.empty())
294 return;
295
296 const RegisterBankInfo *RBI = Subtarget.getRegBankInfo();
297 // If the target does not support GlobalISel, we may not have a
298 // register bank info.
299 if (!RBI)
300 return;
301
302 for (unsigned I = 0, E = RBI->getNumRegBanks(); I < E; ++I) {
303 const auto &RegBank = RBI->getRegBank(I);
304 Names2RegBanks.insert(
305 std::make_pair(StringRef(RegBank.getName()).lower(), &RegBank));
306 }
307}
308
311 auto RegClassInfo = Names2RegClasses.find(Name);
312 if (RegClassInfo == Names2RegClasses.end())
313 return nullptr;
314 return RegClassInfo->getValue();
315}
316
318 auto RegBankInfo = Names2RegBanks.find(Name);
319 if (RegBankInfo == Names2RegBanks.end())
320 return nullptr;
321 return RegBankInfo->getValue();
322}
323
328
330 auto I = VRegInfos.try_emplace(Num);
331 if (I.second) {
332 MachineRegisterInfo &MRI = MF.getRegInfo();
333 VRegInfo *Info = new (Allocator) VRegInfo;
335 I.first->second = Info;
336 }
337 return *I.first->second;
338}
339
341 assert(RegName != "" && "Expected named reg.");
342
343 auto I = VRegInfosNamed.try_emplace(RegName.str());
344 if (I.second) {
345 VRegInfo *Info = new (Allocator) VRegInfo;
346 Info->VReg = MF.getRegInfo().createIncompleteVirtualRegister(RegName);
347 I.first->second = Info;
348 }
349 return *I.first->second;
350}
351
352static void mapValueToSlot(const Value *V, ModuleSlotTracker &MST,
353 DenseMap<unsigned, const Value *> &Slots2Values) {
354 int Slot = MST.getLocalSlot(V);
355 if (Slot == -1)
356 return;
357 Slots2Values.insert(std::make_pair(unsigned(Slot), V));
358}
359
360/// Creates the mapping from slot numbers to function's unnamed IR values.
361static void initSlots2Values(const Function &F,
362 DenseMap<unsigned, const Value *> &Slots2Values) {
363 ModuleSlotTracker MST(F.getParent());
365 for (const auto &Arg : F.args())
366 mapValueToSlot(&Arg, MST, Slots2Values);
367 for (const auto &BB : F) {
368 mapValueToSlot(&BB, MST, Slots2Values);
369 for (const auto &I : BB)
370 mapValueToSlot(&I, MST, Slots2Values);
371 }
372}
373
375 if (Slots2Values.empty())
376 initSlots2Values(MF.getFunction(), Slots2Values);
377 return Slots2Values.lookup(Slot);
378}
379
380namespace {
381
382/// A wrapper struct around the 'MachineOperand' struct that includes a source
383/// range and other attributes.
384struct ParsedMachineOperand {
385 MachineOperand Operand;
388 std::optional<unsigned> TiedDefIdx;
389
390 ParsedMachineOperand(const MachineOperand &Operand, StringRef::iterator Begin,
392 std::optional<unsigned> &TiedDefIdx)
393 : Operand(Operand), Begin(Begin), End(End), TiedDefIdx(TiedDefIdx) {
394 if (TiedDefIdx)
395 assert(Operand.isReg() && Operand.isUse() &&
396 "Only used register operands can be tied");
397 }
398};
399
400class MIParser {
401 MachineFunction &MF;
402 SMDiagnostic &Error;
403 StringRef Source, CurrentSource;
404 MIToken Token;
405 PerFunctionMIParsingState &PFS;
406 /// Maps from slot numbers to function's unnamed basic blocks.
407 DenseMap<unsigned, const BasicBlock *> Slots2BasicBlocks;
408
409public:
410 MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
411 StringRef Source);
412
413 /// \p SkipChar gives the number of characters to skip before looking
414 /// for the next token.
415 void lex(unsigned SkipChar = 0);
416
417 /// Report an error at the current location with the given message.
418 ///
419 /// This function always return true.
420 bool error(const Twine &Msg);
421
422 /// Report an error at the given location with the given message.
423 ///
424 /// This function always return true.
425 bool error(StringRef::iterator Loc, const Twine &Msg);
426
427 bool
428 parseBasicBlockDefinitions(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
429 bool parseBasicBlocks();
430 bool parse(MachineInstr *&MI);
431 bool parseStandaloneMBB(MachineBasicBlock *&MBB);
432 bool parseStandaloneNamedRegister(Register &Reg);
433 bool parseStandaloneVirtualRegister(VRegInfo *&Info);
434 bool parseStandaloneRegister(Register &Reg);
435 bool parseStandaloneStackObject(int &FI);
436 bool parseStandaloneMDNode(MDNode *&Node);
437
438 bool
439 parseBasicBlockDefinition(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
440 bool parseBasicBlock(MachineBasicBlock &MBB,
441 MachineBasicBlock *&AddFalthroughFrom);
442 bool parseBasicBlockLiveins(MachineBasicBlock &MBB);
443 bool parseBasicBlockSuccessors(MachineBasicBlock &MBB);
444
445 bool parseNamedRegister(Register &Reg);
446 bool parseVirtualRegister(VRegInfo *&Info);
447 bool parseNamedVirtualRegister(VRegInfo *&Info);
448 bool parseRegister(Register &Reg, VRegInfo *&VRegInfo);
449 bool parseRegisterFlag(RegState &Flags);
450 bool parseRegisterClassOrBank(VRegInfo &RegInfo);
451 bool parseSubRegisterIndex(unsigned &SubReg);
452 bool parseRegisterTiedDefIndex(unsigned &TiedDefIdx);
453 bool parseRegisterOperand(MachineOperand &Dest,
454 std::optional<unsigned> &TiedDefIdx,
455 bool IsDef = false);
456 bool parseImmediateOperand(MachineOperand &Dest);
457 bool parseSymbolicInlineAsmOperand(unsigned OpIdx, MachineOperand &Dest);
458 bool parseIRConstant(StringRef::iterator Loc, StringRef StringValue,
459 const Constant *&C);
460 bool parseIRConstant(StringRef::iterator Loc, const Constant *&C);
461 bool parseLowLevelType(StringRef::iterator Loc, LLT &Ty);
462 bool parseTypedImmediateOperand(MachineOperand &Dest);
463 bool parseFPImmediateOperand(MachineOperand &Dest);
464 bool parseMBBReference(MachineBasicBlock *&MBB);
465 bool parseMBBOperand(MachineOperand &Dest);
466 bool parseStackFrameIndex(int &FI);
467 bool parseStackObjectOperand(MachineOperand &Dest);
468 bool parseFixedStackFrameIndex(int &FI);
469 bool parseFixedStackObjectOperand(MachineOperand &Dest);
470 bool parseGlobalValue(GlobalValue *&GV);
471 bool parseGlobalAddressOperand(MachineOperand &Dest);
472 bool parseConstantPoolIndexOperand(MachineOperand &Dest);
473 bool parseSubRegisterIndexOperand(MachineOperand &Dest);
474 bool parseJumpTableIndexOperand(MachineOperand &Dest);
475 bool parseExternalSymbolOperand(MachineOperand &Dest);
476 bool parseMCSymbolOperand(MachineOperand &Dest);
477 [[nodiscard]] bool parseMDNode(MDNode *&Node);
478 bool parseDIExpression(MDNode *&Expr);
479 bool parseDILocation(MDNode *&Expr);
480 bool parseMetadataOperand(MachineOperand &Dest);
481 bool parseCFIOffset(int &Offset);
482 bool parseCFIUnsigned(unsigned &Value);
483 bool parseCFIRegister(unsigned &Reg);
484 bool parseCFIAddressSpace(unsigned &AddressSpace);
485 bool parseCFIEscapeValues(std::string& Values);
486 bool parseCFIOperand(MachineOperand &Dest);
487 bool parseIRBlock(BasicBlock *&BB, const Function &F);
488 bool parseBlockAddressOperand(MachineOperand &Dest);
489 bool parseIntrinsicOperand(MachineOperand &Dest);
490 bool parsePredicateOperand(MachineOperand &Dest);
491 bool parseShuffleMaskOperand(MachineOperand &Dest);
492 bool parseTargetIndexOperand(MachineOperand &Dest);
493 bool parseDbgInstrRefOperand(MachineOperand &Dest);
494 bool parseCustomRegisterMaskOperand(MachineOperand &Dest);
495 bool parseLaneMaskOperand(MachineOperand &Dest);
496 bool parseLiveoutRegisterMaskOperand(MachineOperand &Dest);
497 bool parseMachineOperand(const unsigned OpCode, const unsigned OpIdx,
498 MachineOperand &Dest,
499 std::optional<unsigned> &TiedDefIdx);
500 bool parseMachineOperandAndTargetFlags(const unsigned OpCode,
501 const unsigned OpIdx,
502 MachineOperand &Dest,
503 std::optional<unsigned> &TiedDefIdx);
504 bool parseOffset(int64_t &Offset);
505 bool parseIRBlockAddressTaken(BasicBlock *&BB);
506 bool parseAlignment(uint64_t &Alignment);
507 bool parseAddrspace(unsigned &Addrspace);
508 bool parseSectionID(std::optional<MBBSectionID> &SID);
509 bool parseBBID(std::optional<UniqueBBID> &BBID);
510 bool parseCallFrameSize(unsigned &CallFrameSize);
511 bool parsePrefetchTarget(CallsiteID &Target);
512 bool parseOperandsOffset(MachineOperand &Op);
513 bool parseIRValue(const Value *&V);
514 bool parseMemoryOperandFlag(MachineMemOperand::Flags &Flags);
515 bool parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV);
516 bool parseMachinePointerInfo(MachinePointerInfo &Dest);
517 bool parseOptionalScope(LLVMContext &Context, SyncScope::ID &SSID);
518 bool parseOptionalAtomicOrdering(AtomicOrdering &Order);
519 bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
520 bool parsePreOrPostInstrSymbol(MCSymbol *&Symbol);
521 bool parseHeapAllocMarker(MDNode *&Node);
522 bool parsePCSections(MDNode *&Node);
523 bool parseMMRA(MDNode *&Node);
524
525 bool parseTargetImmMnemonic(const unsigned OpCode, const unsigned OpIdx,
526 MachineOperand &Dest, const MIRFormatter &MF);
527
528private:
529 /// Convert the integer literal in the current token into an unsigned integer.
530 ///
531 /// Return true if an error occurred.
532 bool getUnsigned(unsigned &Result);
533
534 /// Convert the integer literal in the current token into an uint64.
535 ///
536 /// Return true if an error occurred.
537 bool getUint64(uint64_t &Result);
538
539 /// Convert the hexadecimal literal in the current token into an unsigned
540 /// APInt with a minimum bitwidth required to represent the value.
541 ///
542 /// Return true if the literal does not represent an integer value.
543 bool getHexUint(APInt &Result);
544
545 /// If the current token is of the given kind, consume it and return false.
546 /// Otherwise report an error and return true.
547 bool expectAndConsume(MIToken::TokenKind TokenKind);
548
549 /// If the current token is of the given kind, consume it and return true.
550 /// Otherwise return false.
551 bool consumeIfPresent(MIToken::TokenKind TokenKind);
552
553 bool parseInstruction(unsigned &OpCode, unsigned &Flags);
554
555 bool assignRegisterTies(MachineInstr &MI,
557
558 bool verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands,
559 const MCInstrDesc &MCID);
560
561 const BasicBlock *getIRBlock(unsigned Slot);
562 const BasicBlock *getIRBlock(unsigned Slot, const Function &F);
563
564 /// Get or create an MCSymbol for a given name.
565 MCSymbol *getOrCreateMCSymbol(StringRef Name);
566
567 /// parseStringConstant
568 /// ::= StringConstant
569 bool parseStringConstant(std::string &Result);
570};
571
572} // end anonymous namespace
573
574MIParser::MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
575 StringRef Source)
576 : MF(PFS.MF), Error(Error), Source(Source), CurrentSource(Source), PFS(PFS)
577{}
578
579void MIParser::lex(unsigned SkipChar) {
580 CurrentSource = lexMIToken(
581 CurrentSource.substr(SkipChar), Token,
582 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
583}
584
585bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
586
587bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
588 const SourceMgr &SM = *PFS.SM;
589 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
590 const MemoryBuffer &Buffer = *SM.getMemoryBuffer(SM.getMainFileID());
591 if (Loc >= Buffer.getBufferStart() && Loc <= Buffer.getBufferEnd()) {
592 // Create an ordinary diagnostic when the source manager's buffer is the
593 // source string.
595 return true;
596 }
597 // Create a diagnostic for a YAML string literal.
598 Error = SMDiagnostic(SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
599 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(),
600 Source, {}, {});
601 return true;
602}
603
604typedef function_ref<bool(StringRef::iterator Loc, const Twine &)>
606
607static const char *toString(MIToken::TokenKind TokenKind) {
608 switch (TokenKind) {
609 case MIToken::comma:
610 return "','";
611 case MIToken::equal:
612 return "'='";
613 case MIToken::colon:
614 return "':'";
615 case MIToken::lparen:
616 return "'('";
617 case MIToken::rparen:
618 return "')'";
619 default:
620 return "<unknown token>";
621 }
622}
623
624bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
625 if (Token.isNot(TokenKind))
626 return error(Twine("expected ") + toString(TokenKind));
627 lex();
628 return false;
629}
630
631bool MIParser::consumeIfPresent(MIToken::TokenKind TokenKind) {
632 if (Token.isNot(TokenKind))
633 return false;
634 lex();
635 return true;
636}
637
638// Parse Machine Basic Block Section ID.
639bool MIParser::parseSectionID(std::optional<MBBSectionID> &SID) {
641 lex();
642 if (Token.is(MIToken::IntegerLiteral)) {
643 unsigned Value = 0;
644 if (getUnsigned(Value))
645 return error("Unknown Section ID");
646 SID = MBBSectionID{Value};
647 } else {
648 const StringRef &S = Token.stringValue();
649 if (S == "Exception")
651 else if (S == "Cold")
653 else
654 return error("Unknown Section ID");
655 }
656 lex();
657 return false;
658}
659
660// Parse Machine Basic Block ID.
661bool MIParser::parseBBID(std::optional<UniqueBBID> &BBID) {
662 if (Token.isNot(MIToken::kw_bb_id))
663 return error("expected 'bb_id'");
664 lex();
665 unsigned BaseID = 0;
666 unsigned CloneID = 0;
667 if (Token.is(MIToken::FloatingPointLiteral)) {
668 StringRef S = Token.range();
669 auto Parts = S.split('.');
670 if (Parts.first.getAsInteger(10, BaseID) ||
671 Parts.second.getAsInteger(10, CloneID))
672 return error("Unknown BB ID");
673 lex();
674 } else {
675 if (getUnsigned(BaseID))
676 return error("Unknown BB ID");
677 lex();
678 if (Token.is(MIToken::comma) || Token.is(MIToken::dot)) {
679 lex();
680 if (getUnsigned(CloneID))
681 return error("Unknown Clone ID");
682 lex();
683 } else if (Token.is(MIToken::IntegerLiteral)) {
684 if (getUnsigned(CloneID))
685 return error("Unknown Clone ID");
686 lex();
687 }
688 }
689 BBID = {BaseID, CloneID};
690 return false;
691}
692
693// Parse basic block call frame size.
694bool MIParser::parseCallFrameSize(unsigned &CallFrameSize) {
696 lex();
697 unsigned Value = 0;
698 if (getUnsigned(Value))
699 return error("Unknown call frame size");
700 CallFrameSize = Value;
701 lex();
702 return false;
703}
704
705bool MIParser::parsePrefetchTarget(CallsiteID &Target) {
706 lex();
707 std::optional<UniqueBBID> BBID;
708 if (parseBBID(BBID))
709 return true;
710 Target.BBID = *BBID;
711 if (expectAndConsume(MIToken::comma))
712 return true;
713 return getUnsigned(Target.CallsiteIndex);
714}
715
716bool MIParser::parseBasicBlockDefinition(
719 unsigned ID = 0;
720 if (getUnsigned(ID))
721 return true;
722 auto Loc = Token.location();
723 auto Name = Token.stringValue();
724 lex();
725 bool MachineBlockAddressTaken = false;
726 BasicBlock *AddressTakenIRBlock = nullptr;
727 bool IsLandingPad = false;
728 bool IsInlineAsmBrIndirectTarget = false;
729 bool IsEHFuncletEntry = false;
730 bool IsEHScopeEntry = false;
731 std::optional<MBBSectionID> SectionID;
733 std::optional<UniqueBBID> BBID;
734 unsigned CallFrameSize = 0;
735 BasicBlock *BB = nullptr;
736 if (consumeIfPresent(MIToken::lparen)) {
737 do {
738 // TODO: Report an error when multiple same attributes are specified.
739 switch (Token.kind()) {
741 MachineBlockAddressTaken = true;
742 lex();
743 break;
745 if (parseIRBlockAddressTaken(AddressTakenIRBlock))
746 return true;
747 break;
749 IsLandingPad = true;
750 lex();
751 break;
753 IsInlineAsmBrIndirectTarget = true;
754 lex();
755 break;
757 IsEHFuncletEntry = true;
758 lex();
759 break;
761 IsEHScopeEntry = true;
762 lex();
763 break;
765 if (parseAlignment(Alignment))
766 return true;
767 break;
768 case MIToken::IRBlock:
770 // TODO: Report an error when both name and ir block are specified.
771 if (parseIRBlock(BB, MF.getFunction()))
772 return true;
773 lex();
774 break;
776 if (parseSectionID(SectionID))
777 return true;
778 break;
780 if (parseBBID(BBID))
781 return true;
782 break;
784 if (parseCallFrameSize(CallFrameSize))
785 return true;
786 break;
787 default:
788 break;
789 }
790 } while (consumeIfPresent(MIToken::comma));
791 if (expectAndConsume(MIToken::rparen))
792 return true;
793 }
794 if (expectAndConsume(MIToken::colon))
795 return true;
796
797 if (!Name.empty()) {
799 MF.getFunction().getValueSymbolTable()->lookup(Name));
800 if (!BB)
801 return error(Loc, Twine("basic block '") + Name +
802 "' is not defined in the function '" +
803 MF.getName() + "'");
804 }
805 auto *MBB = MF.CreateMachineBasicBlock(BB, BBID);
806 MF.insert(MF.end(), MBB);
807 bool WasInserted = MBBSlots.insert(std::make_pair(ID, MBB)).second;
808 if (!WasInserted)
809 return error(Loc, Twine("redefinition of machine basic block with id #") +
810 Twine(ID));
811 if (Alignment)
812 MBB->setAlignment(Align(Alignment));
813 if (MachineBlockAddressTaken)
815 if (AddressTakenIRBlock)
816 MBB->setAddressTakenIRBlock(AddressTakenIRBlock);
817 MBB->setIsEHPad(IsLandingPad);
818 MBB->setIsInlineAsmBrIndirectTarget(IsInlineAsmBrIndirectTarget);
819 MBB->setIsEHFuncletEntry(IsEHFuncletEntry);
820 MBB->setIsEHScopeEntry(IsEHScopeEntry);
821 if (SectionID) {
822 MBB->setSectionID(*SectionID);
823 MF.setBBSectionsType(BasicBlockSection::List);
824 }
825 MBB->setCallFrameSize(CallFrameSize);
826 return false;
827}
828
829bool MIParser::parseBasicBlockDefinitions(
831 lex();
832 // Skip until the first machine basic block.
833 while (Token.is(MIToken::Newline))
834 lex();
835 if (Token.isErrorOrEOF())
836 return Token.isError();
837 if (Token.isNot(MIToken::MachineBasicBlockLabel))
838 return error("expected a basic block definition before instructions");
839 unsigned BraceDepth = 0;
840 do {
841 if (parseBasicBlockDefinition(MBBSlots))
842 return true;
843 bool IsAfterNewline = false;
844 // Skip until the next machine basic block.
845 while (true) {
846 if ((Token.is(MIToken::MachineBasicBlockLabel) && IsAfterNewline) ||
847 Token.isErrorOrEOF())
848 break;
849 else if (Token.is(MIToken::MachineBasicBlockLabel))
850 return error("basic block definition should be located at the start of "
851 "the line");
852 else if (consumeIfPresent(MIToken::Newline)) {
853 IsAfterNewline = true;
854 continue;
855 }
856 IsAfterNewline = false;
857 if (Token.is(MIToken::lbrace))
858 ++BraceDepth;
859 if (Token.is(MIToken::rbrace)) {
860 if (!BraceDepth)
861 return error("extraneous closing brace ('}')");
862 --BraceDepth;
863 }
864 lex();
865 }
866 // Verify that we closed all of the '{' at the end of a file or a block.
867 if (!Token.isError() && BraceDepth)
868 return error("expected '}'"); // FIXME: Report a note that shows '{'.
869 } while (!Token.isErrorOrEOF());
870 return Token.isError();
871}
872
873bool MIParser::parseBasicBlockLiveins(MachineBasicBlock &MBB) {
874 assert(Token.is(MIToken::kw_liveins));
875 lex();
876 if (expectAndConsume(MIToken::colon))
877 return true;
878 if (Token.isNewlineOrEOF()) // Allow an empty list of liveins.
879 return false;
880 do {
881 if (Token.isNot(MIToken::NamedRegister))
882 return error("expected a named register");
884 if (parseNamedRegister(Reg))
885 return true;
886 lex();
888 if (consumeIfPresent(MIToken::colon)) {
889 // Parse lane mask.
890 if (Token.isNot(MIToken::IntegerLiteral) &&
891 Token.isNot(MIToken::HexLiteral))
892 return error("expected a lane mask");
893 static_assert(sizeof(LaneBitmask::Type) == sizeof(uint64_t),
894 "Use correct get-function for lane mask");
896 if (getUint64(V))
897 return error("invalid lane mask value");
898 Mask = LaneBitmask(V);
899 lex();
900 }
901 MBB.addLiveIn(Reg, Mask);
902 } while (consumeIfPresent(MIToken::comma));
903 return false;
904}
905
906bool MIParser::parseBasicBlockSuccessors(MachineBasicBlock &MBB) {
908 lex();
909 if (expectAndConsume(MIToken::colon))
910 return true;
911 if (Token.isNewlineOrEOF()) // Allow an empty list of successors.
912 return false;
913 do {
914 if (Token.isNot(MIToken::MachineBasicBlock))
915 return error("expected a machine basic block reference");
916 MachineBasicBlock *SuccMBB = nullptr;
917 if (parseMBBReference(SuccMBB))
918 return true;
919 lex();
920 unsigned Weight = 0;
921 if (consumeIfPresent(MIToken::lparen)) {
922 if (Token.isNot(MIToken::IntegerLiteral) &&
923 Token.isNot(MIToken::HexLiteral))
924 return error("expected an integer literal after '('");
925 if (getUnsigned(Weight))
926 return true;
927 lex();
928 if (expectAndConsume(MIToken::rparen))
929 return true;
930 }
932 } while (consumeIfPresent(MIToken::comma));
934 return false;
935}
936
937bool MIParser::parseBasicBlock(MachineBasicBlock &MBB,
938 MachineBasicBlock *&AddFalthroughFrom) {
939 // Skip the definition.
941 lex();
942 if (consumeIfPresent(MIToken::lparen)) {
943 while (Token.isNot(MIToken::rparen) && !Token.isErrorOrEOF())
944 lex();
945 consumeIfPresent(MIToken::rparen);
946 }
947 consumeIfPresent(MIToken::colon);
948
949 // Parse the liveins and successors.
950 // N.B: Multiple lists of successors and liveins are allowed and they're
951 // merged into one.
952 // Example:
953 // liveins: $edi
954 // liveins: $esi
955 //
956 // is equivalent to
957 // liveins: $edi, $esi
958 bool ExplicitSuccessors = false;
959 while (true) {
960 if (Token.is(MIToken::kw_successors)) {
961 if (parseBasicBlockSuccessors(MBB))
962 return true;
963 ExplicitSuccessors = true;
964 } else if (Token.is(MIToken::kw_liveins)) {
965 if (parseBasicBlockLiveins(MBB))
966 return true;
967 } else if (consumeIfPresent(MIToken::Newline)) {
968 continue;
969 } else {
970 break;
971 }
972 if (!Token.isNewlineOrEOF())
973 return error("expected line break at the end of a list");
974 lex();
975 }
976
977 // Parse the instructions.
978 bool IsInBundle = false;
979 MachineInstr *PrevMI = nullptr;
980 while (!Token.is(MIToken::MachineBasicBlockLabel) &&
981 !Token.is(MIToken::Eof)) {
982 if (consumeIfPresent(MIToken::Newline))
983 continue;
984 if (consumeIfPresent(MIToken::rbrace)) {
985 // The first parsing pass should verify that all closing '}' have an
986 // opening '{'.
987 assert(IsInBundle);
988 IsInBundle = false;
989 continue;
990 }
991 MachineInstr *MI = nullptr;
992 if (parse(MI))
993 return true;
994 MBB.insert(MBB.end(), MI);
995 if (IsInBundle) {
998 }
999 PrevMI = MI;
1000 if (Token.is(MIToken::lbrace)) {
1001 if (IsInBundle)
1002 return error("nested instruction bundles are not allowed");
1003 lex();
1004 // This instruction is the start of the bundle.
1005 MI->setFlag(MachineInstr::BundledSucc);
1006 IsInBundle = true;
1007 if (!Token.is(MIToken::Newline))
1008 // The next instruction can be on the same line.
1009 continue;
1010 }
1011 assert(Token.isNewlineOrEOF() && "MI is not fully parsed");
1012 lex();
1013 }
1014
1015 // Construct successor list by searching for basic block machine operands.
1016 if (!ExplicitSuccessors) {
1018 bool IsFallthrough;
1019 guessSuccessors(MBB, Successors, IsFallthrough);
1020 for (MachineBasicBlock *Succ : Successors)
1021 MBB.addSuccessor(Succ);
1022
1023 if (IsFallthrough) {
1024 AddFalthroughFrom = &MBB;
1025 } else {
1027 }
1028 }
1029
1030 return false;
1031}
1032
1033bool MIParser::parseBasicBlocks() {
1034 lex();
1035 // Skip until the first machine basic block.
1036 while (Token.is(MIToken::Newline))
1037 lex();
1038 if (Token.isErrorOrEOF())
1039 return Token.isError();
1040 // The first parsing pass should have verified that this token is a MBB label
1041 // in the 'parseBasicBlockDefinitions' method.
1043 MachineBasicBlock *AddFalthroughFrom = nullptr;
1044 do {
1045 MachineBasicBlock *MBB = nullptr;
1047 return true;
1048 if (AddFalthroughFrom) {
1049 if (!AddFalthroughFrom->isSuccessor(MBB))
1050 AddFalthroughFrom->addSuccessor(MBB);
1051 AddFalthroughFrom->normalizeSuccProbs();
1052 AddFalthroughFrom = nullptr;
1053 }
1054 if (parseBasicBlock(*MBB, AddFalthroughFrom))
1055 return true;
1056 // The method 'parseBasicBlock' should parse the whole block until the next
1057 // block or the end of file.
1058 assert(Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof));
1059 } while (Token.isNot(MIToken::Eof));
1060 return false;
1061}
1062
1063bool MIParser::parse(MachineInstr *&MI) {
1064 // Parse any register operands before '='
1067 while (Token.isRegister() || Token.isRegisterFlag()) {
1068 auto Loc = Token.location();
1069 std::optional<unsigned> TiedDefIdx;
1070 if (parseRegisterOperand(MO, TiedDefIdx, /*IsDef=*/true))
1071 return true;
1072 Operands.push_back(
1073 ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx));
1074 if (Token.isNot(MIToken::comma))
1075 break;
1076 lex();
1077 }
1078 if (!Operands.empty() && expectAndConsume(MIToken::equal))
1079 return true;
1080
1081 unsigned OpCode, Flags = 0;
1082 if (Token.isError() || parseInstruction(OpCode, Flags))
1083 return true;
1084
1085 // Parse the remaining machine operands.
1086 while (!Token.isNewlineOrEOF() && Token.isNot(MIToken::kw_pre_instr_symbol) &&
1087 Token.isNot(MIToken::kw_post_instr_symbol) &&
1088 Token.isNot(MIToken::kw_heap_alloc_marker) &&
1089 Token.isNot(MIToken::kw_pcsections) && Token.isNot(MIToken::kw_mmra) &&
1090 Token.isNot(MIToken::kw_cfi_type) &&
1091 Token.isNot(MIToken::kw_deactivation_symbol) &&
1092 Token.isNot(MIToken::kw_debug_location) &&
1093 Token.isNot(MIToken::kw_debug_instr_number) &&
1094 Token.isNot(MIToken::coloncolon) && Token.isNot(MIToken::lbrace)) {
1095 auto Loc = Token.location();
1096 std::optional<unsigned> TiedDefIdx;
1097 if (parseMachineOperandAndTargetFlags(OpCode, Operands.size(), MO, TiedDefIdx))
1098 return true;
1099 Operands.push_back(
1100 ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx));
1101 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
1102 Token.is(MIToken::lbrace))
1103 break;
1104 if (Token.isNot(MIToken::comma))
1105 return error("expected ',' before the next machine operand");
1106 lex();
1107 }
1108
1109 MCSymbol *PreInstrSymbol = nullptr;
1110 if (Token.is(MIToken::kw_pre_instr_symbol))
1111 if (parsePreOrPostInstrSymbol(PreInstrSymbol))
1112 return true;
1113 MCSymbol *PostInstrSymbol = nullptr;
1114 if (Token.is(MIToken::kw_post_instr_symbol))
1115 if (parsePreOrPostInstrSymbol(PostInstrSymbol))
1116 return true;
1117 MDNode *HeapAllocMarker = nullptr;
1118 if (Token.is(MIToken::kw_heap_alloc_marker))
1119 if (parseHeapAllocMarker(HeapAllocMarker))
1120 return true;
1121 MDNode *PCSections = nullptr;
1122 if (Token.is(MIToken::kw_pcsections))
1123 if (parsePCSections(PCSections))
1124 return true;
1125 MDNode *MMRA = nullptr;
1126 if (Token.is(MIToken::kw_mmra) && parseMMRA(MMRA))
1127 return true;
1128 unsigned CFIType = 0;
1129 if (Token.is(MIToken::kw_cfi_type)) {
1130 lex();
1131 if (Token.isNot(MIToken::IntegerLiteral))
1132 return error("expected an integer literal after 'cfi-type'");
1133 // getUnsigned is sufficient for 32-bit integers.
1134 if (getUnsigned(CFIType))
1135 return true;
1136 lex();
1137 // Lex past trailing comma if present.
1138 if (Token.is(MIToken::comma))
1139 lex();
1140 }
1141
1142 GlobalValue *DS = nullptr;
1143 if (Token.is(MIToken::kw_deactivation_symbol)) {
1144 lex();
1145 if (parseGlobalValue(DS))
1146 return true;
1147 lex();
1148 }
1149
1150 unsigned InstrNum = 0;
1151 if (Token.is(MIToken::kw_debug_instr_number)) {
1152 lex();
1153 if (Token.isNot(MIToken::IntegerLiteral))
1154 return error("expected an integer literal after 'debug-instr-number'");
1155 if (getUnsigned(InstrNum))
1156 return true;
1157 lex();
1158 // Lex past trailing comma if present.
1159 if (Token.is(MIToken::comma))
1160 lex();
1161 }
1162
1163 DebugLoc DebugLocation;
1164 if (Token.is(MIToken::kw_debug_location)) {
1165 lex();
1166 MDNode *Node = nullptr;
1167 if (Token.is(MIToken::exclaim)) {
1168 if (parseMDNode(Node))
1169 return true;
1170 } else if (Token.is(MIToken::md_dilocation)) {
1171 if (parseDILocation(Node))
1172 return true;
1173 } else {
1174 return error("expected a metadata node after 'debug-location'");
1175 }
1176 DebugLocation = DebugLoc(dyn_cast<DILocation>(Node));
1177 if (!DebugLocation)
1178 return error("referenced metadata is not a DILocation");
1179 }
1180
1181 // Parse the machine memory operands.
1183 if (Token.is(MIToken::coloncolon)) {
1184 lex();
1185 while (!Token.isNewlineOrEOF()) {
1186 MachineMemOperand *MemOp = nullptr;
1187 if (parseMachineMemoryOperand(MemOp))
1188 return true;
1189 MemOperands.push_back(MemOp);
1190 if (Token.isNewlineOrEOF())
1191 break;
1192 if (OpCode == TargetOpcode::BUNDLE && Token.is(MIToken::lbrace))
1193 break;
1194 if (Token.isNot(MIToken::comma))
1195 return error("expected ',' before the next machine memory operand");
1196 lex();
1197 }
1198 }
1199
1200 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
1201 if (!MCID.isVariadic()) {
1202 // FIXME: Move the implicit operand verification to the machine verifier.
1203 if (verifyImplicitOperands(Operands, MCID))
1204 return true;
1205 }
1206
1207 MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
1208 MI->setFlags(Flags);
1209
1210 // Don't check the operands make sense, let the verifier catch any
1211 // improprieties.
1212 for (const auto &Operand : Operands)
1213 MI->addOperand(MF, Operand.Operand);
1214
1215 if (assignRegisterTies(*MI, Operands))
1216 return true;
1217 if (PreInstrSymbol)
1218 MI->setPreInstrSymbol(MF, PreInstrSymbol);
1219 if (PostInstrSymbol)
1220 MI->setPostInstrSymbol(MF, PostInstrSymbol);
1221 if (HeapAllocMarker)
1222 MI->setHeapAllocMarker(MF, HeapAllocMarker);
1223 if (PCSections)
1224 MI->setPCSections(MF, PCSections);
1225 if (MMRA)
1226 MI->setMMRAMetadata(MF, MMRA);
1227 if (CFIType)
1228 MI->setCFIType(MF, CFIType);
1229 if (DS)
1230 MI->setDeactivationSymbol(MF, DS);
1231 if (!MemOperands.empty())
1232 MI->setMemRefs(MF, MemOperands);
1233 if (InstrNum)
1234 MI->setDebugInstrNum(InstrNum);
1235 return false;
1236}
1237
1238bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
1239 lex();
1240 if (Token.isNot(MIToken::MachineBasicBlock))
1241 return error("expected a machine basic block reference");
1243 return true;
1244 lex();
1245 if (Token.isNot(MIToken::Eof))
1246 return error(
1247 "expected end of string after the machine basic block reference");
1248 return false;
1249}
1250
1251bool MIParser::parseStandaloneNamedRegister(Register &Reg) {
1252 lex();
1253 if (Token.isNot(MIToken::NamedRegister))
1254 return error("expected a named register");
1255 if (parseNamedRegister(Reg))
1256 return true;
1257 lex();
1258 if (Token.isNot(MIToken::Eof))
1259 return error("expected end of string after the register reference");
1260 return false;
1261}
1262
1263bool MIParser::parseStandaloneVirtualRegister(VRegInfo *&Info) {
1264 lex();
1265 if (Token.isNot(MIToken::VirtualRegister))
1266 return error("expected a virtual register");
1267 if (parseVirtualRegister(Info))
1268 return true;
1269 lex();
1270 if (Token.isNot(MIToken::Eof))
1271 return error("expected end of string after the register reference");
1272 return false;
1273}
1274
1275bool MIParser::parseStandaloneRegister(Register &Reg) {
1276 lex();
1277 if (Token.isNot(MIToken::NamedRegister) &&
1278 Token.isNot(MIToken::VirtualRegister))
1279 return error("expected either a named or virtual register");
1280
1281 VRegInfo *Info;
1282 if (parseRegister(Reg, Info))
1283 return true;
1284
1285 lex();
1286 if (Token.isNot(MIToken::Eof))
1287 return error("expected end of string after the register reference");
1288 return false;
1289}
1290
1291bool MIParser::parseStandaloneStackObject(int &FI) {
1292 lex();
1293 if (Token.isNot(MIToken::StackObject))
1294 return error("expected a stack object");
1295 if (parseStackFrameIndex(FI))
1296 return true;
1297 if (Token.isNot(MIToken::Eof))
1298 return error("expected end of string after the stack object reference");
1299 return false;
1300}
1301
1302bool MIParser::parseStandaloneMDNode(MDNode *&Node) {
1303 lex();
1304 if (Token.is(MIToken::exclaim)) {
1305 if (parseMDNode(Node))
1306 return true;
1307 } else if (Token.is(MIToken::md_diexpr)) {
1308 if (parseDIExpression(Node))
1309 return true;
1310 } else if (Token.is(MIToken::md_dilocation)) {
1311 if (parseDILocation(Node))
1312 return true;
1313 } else {
1314 return error("expected a metadata node");
1315 }
1316 if (Token.isNot(MIToken::Eof))
1317 return error("expected end of string after the metadata node");
1318 return false;
1319}
1320
1321static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
1322 assert(MO.isImplicit());
1323 return MO.isDef() ? "implicit-def" : "implicit";
1324}
1325
1326static std::string getRegisterName(const TargetRegisterInfo *TRI,
1327 Register Reg) {
1328 assert(Reg.isPhysical() && "expected phys reg");
1329 return StringRef(TRI->getName(Reg)).lower();
1330}
1331
1332/// Return true if the parsed machine operands contain a given machine operand.
1333static bool isImplicitOperandIn(const MachineOperand &ImplicitOperand,
1335 for (const auto &I : Operands) {
1336 if (ImplicitOperand.isIdenticalTo(I.Operand))
1337 return true;
1338 }
1339 return false;
1340}
1341
1342bool MIParser::verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands,
1343 const MCInstrDesc &MCID) {
1344 if (MCID.isCall())
1345 // We can't verify call instructions as they can contain arbitrary implicit
1346 // register and register mask operands.
1347 return false;
1348
1349 // Gather all the expected implicit operands.
1350 SmallVector<MachineOperand, 4> ImplicitOperands;
1351 for (MCPhysReg ImpDef : MCID.implicit_defs())
1352 ImplicitOperands.push_back(MachineOperand::CreateReg(ImpDef, true, true));
1353 for (MCPhysReg ImpUse : MCID.implicit_uses())
1354 ImplicitOperands.push_back(MachineOperand::CreateReg(ImpUse, false, true));
1355
1356 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1357 assert(TRI && "Expected target register info");
1358 for (const auto &I : ImplicitOperands) {
1360 continue;
1361 return error(Operands.empty() ? Token.location() : Operands.back().End,
1362 Twine("missing implicit register operand '") +
1364 getRegisterName(TRI, I.getReg()) + "'");
1365 }
1366 return false;
1367}
1368
1369bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
1370 // Allow frame and fast math flags for OPCODE
1371 // clang-format off
1372 while (Token.is(MIToken::kw_frame_setup) ||
1373 Token.is(MIToken::kw_frame_destroy) ||
1374 Token.is(MIToken::kw_nnan) ||
1375 Token.is(MIToken::kw_ninf) ||
1376 Token.is(MIToken::kw_nsz) ||
1377 Token.is(MIToken::kw_arcp) ||
1378 Token.is(MIToken::kw_contract) ||
1379 Token.is(MIToken::kw_afn) ||
1380 Token.is(MIToken::kw_reassoc) ||
1381 Token.is(MIToken::kw_nuw) ||
1382 Token.is(MIToken::kw_nsw) ||
1383 Token.is(MIToken::kw_exact) ||
1384 Token.is(MIToken::kw_nofpexcept) ||
1385 Token.is(MIToken::kw_noconvergent) ||
1386 Token.is(MIToken::kw_unpredictable) ||
1387 Token.is(MIToken::kw_nneg) ||
1388 Token.is(MIToken::kw_disjoint) ||
1389 Token.is(MIToken::kw_nusw) ||
1390 Token.is(MIToken::kw_samesign) ||
1391 Token.is(MIToken::kw_inbounds) ||
1392 Token.is(MIToken::kw_nonnull) ||
1393 Token.is(MIToken::kw_lr_split)) {
1394 // clang-format on
1395 // Mine frame and fast math flags
1396 if (Token.is(MIToken::kw_frame_setup))
1398 if (Token.is(MIToken::kw_frame_destroy))
1400 if (Token.is(MIToken::kw_nnan))
1402 if (Token.is(MIToken::kw_ninf))
1404 if (Token.is(MIToken::kw_nsz))
1406 if (Token.is(MIToken::kw_arcp))
1408 if (Token.is(MIToken::kw_contract))
1410 if (Token.is(MIToken::kw_afn))
1412 if (Token.is(MIToken::kw_reassoc))
1414 if (Token.is(MIToken::kw_nuw))
1416 if (Token.is(MIToken::kw_nsw))
1418 if (Token.is(MIToken::kw_exact))
1420 if (Token.is(MIToken::kw_nofpexcept))
1422 if (Token.is(MIToken::kw_unpredictable))
1424 if (Token.is(MIToken::kw_noconvergent))
1426 if (Token.is(MIToken::kw_nneg))
1428 if (Token.is(MIToken::kw_disjoint))
1430 if (Token.is(MIToken::kw_nusw))
1432 if (Token.is(MIToken::kw_samesign))
1434 if (Token.is(MIToken::kw_inbounds))
1436 if (Token.is(MIToken::kw_nonnull))
1438 if (Token.is(MIToken::kw_lr_split))
1440
1441 lex();
1442 }
1443 if (Token.isNot(MIToken::Identifier))
1444 return error("expected a machine instruction");
1445 StringRef InstrName = Token.stringValue();
1446 if (PFS.Target.parseInstrName(InstrName, OpCode))
1447 return error(Twine("unknown machine instruction name '") + InstrName + "'");
1448 lex();
1449 return false;
1450}
1451
1452bool MIParser::parseNamedRegister(Register &Reg) {
1453 assert(Token.is(MIToken::NamedRegister) && "Needs NamedRegister token");
1454 StringRef Name = Token.stringValue();
1455 if (PFS.Target.getRegisterByName(Name, Reg))
1456 return error(Twine("unknown register name '") + Name + "'");
1457 return false;
1458}
1459
1460bool MIParser::parseNamedVirtualRegister(VRegInfo *&Info) {
1461 assert(Token.is(MIToken::NamedVirtualRegister) && "Expected NamedVReg token");
1462 StringRef Name = Token.stringValue();
1463 // TODO: Check that the VReg name is not the same as a physical register name.
1464 // If it is, then print a warning (when warnings are implemented).
1465 Info = &PFS.getVRegInfoNamed(Name);
1466 return false;
1467}
1468
1469bool MIParser::parseVirtualRegister(VRegInfo *&Info) {
1470 if (Token.is(MIToken::NamedVirtualRegister))
1471 return parseNamedVirtualRegister(Info);
1472 assert(Token.is(MIToken::VirtualRegister) && "Needs VirtualRegister token");
1473 unsigned ID;
1474 if (getUnsigned(ID))
1475 return true;
1476 Info = &PFS.getVRegInfo(ID);
1477 return false;
1478}
1479
1480bool MIParser::parseRegister(Register &Reg, VRegInfo *&Info) {
1481 switch (Token.kind()) {
1483 Reg = 0;
1484 return false;
1486 return parseNamedRegister(Reg);
1489 if (parseVirtualRegister(Info))
1490 return true;
1491 Reg = Info->VReg;
1492 return false;
1493 // TODO: Parse other register kinds.
1494 default:
1495 llvm_unreachable("The current token should be a register");
1496 }
1497}
1498
1499bool MIParser::parseRegisterClassOrBank(VRegInfo &RegInfo) {
1500 if (Token.isNot(MIToken::Identifier) && Token.isNot(MIToken::underscore))
1501 return error("expected '_', register class, or register bank name");
1502 StringRef::iterator Loc = Token.location();
1503 StringRef Name = Token.stringValue();
1504
1505 // Was it a register class?
1506 const TargetRegisterClass *RC = PFS.Target.getRegClass(Name);
1507 if (RC) {
1508 lex();
1509
1510 switch (RegInfo.Kind) {
1511 case VRegInfo::UNKNOWN:
1512 case VRegInfo::NORMAL:
1513 RegInfo.Kind = VRegInfo::NORMAL;
1514 if (RegInfo.Explicit && RegInfo.D.RC != RC) {
1515 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1516 return error(Loc, Twine("conflicting register classes, previously: ") +
1517 Twine(TRI.getRegClassName(RegInfo.D.RC)));
1518 }
1519 RegInfo.D.RC = RC;
1520 RegInfo.Explicit = true;
1521 return false;
1522
1523 case VRegInfo::GENERIC:
1524 case VRegInfo::REGBANK:
1525 return error(Loc, "register class specification on generic register");
1526 }
1527 llvm_unreachable("Unexpected register kind");
1528 }
1529
1530 // Should be a register bank or a generic register.
1531 const RegisterBank *RegBank = nullptr;
1532 if (Name != "_") {
1533 RegBank = PFS.Target.getRegBank(Name);
1534 if (!RegBank)
1535 return error(Loc, "expected '_', register class, or register bank name");
1536 }
1537
1538 lex();
1539
1540 switch (RegInfo.Kind) {
1541 case VRegInfo::UNKNOWN:
1542 case VRegInfo::GENERIC:
1543 case VRegInfo::REGBANK:
1544 RegInfo.Kind = RegBank ? VRegInfo::REGBANK : VRegInfo::GENERIC;
1545 if (RegInfo.Explicit && RegInfo.D.RegBank != RegBank)
1546 return error(Loc, "conflicting generic register banks");
1547 RegInfo.D.RegBank = RegBank;
1548 RegInfo.Explicit = true;
1549 return false;
1550
1551 case VRegInfo::NORMAL:
1552 return error(Loc, "register bank specification on normal register");
1553 }
1554 llvm_unreachable("Unexpected register kind");
1555}
1556
1557bool MIParser::parseRegisterFlag(RegState &Flags) {
1558 const RegState OldFlags = Flags;
1559 switch (Token.kind()) {
1562 break;
1565 break;
1566 case MIToken::kw_def:
1568 break;
1569 case MIToken::kw_dead:
1571 break;
1572 case MIToken::kw_killed:
1574 break;
1575 case MIToken::kw_undef:
1577 break;
1580 break;
1583 break;
1586 break;
1589 break;
1590 default:
1591 llvm_unreachable("The current token should be a register flag");
1592 }
1593 if (OldFlags == Flags)
1594 // We know that the same flag is specified more than once when the flags
1595 // weren't modified.
1596 return error("duplicate '" + Token.stringValue() + "' register flag");
1597 lex();
1598 return false;
1599}
1600
1601bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
1602 assert(Token.is(MIToken::dot));
1603 lex();
1604 if (Token.isNot(MIToken::Identifier))
1605 return error("expected a subregister index after '.'");
1606 auto Name = Token.stringValue();
1607 SubReg = PFS.Target.getSubRegIndex(Name);
1608 if (!SubReg)
1609 return error(Twine("use of unknown subregister index '") + Name + "'");
1610 lex();
1611 return false;
1612}
1613
1614bool MIParser::parseRegisterTiedDefIndex(unsigned &TiedDefIdx) {
1615 assert(Token.is(MIToken::kw_tied_def));
1616 lex();
1617 if (Token.isNot(MIToken::IntegerLiteral))
1618 return error("expected an integer literal after 'tied-def'");
1619 if (getUnsigned(TiedDefIdx))
1620 return true;
1621 lex();
1622 return expectAndConsume(MIToken::rparen);
1623}
1624
1625bool MIParser::assignRegisterTies(MachineInstr &MI,
1627 SmallVector<std::pair<unsigned, unsigned>, 4> TiedRegisterPairs;
1628 for (unsigned I = 0, E = Operands.size(); I != E; ++I) {
1629 if (!Operands[I].TiedDefIdx)
1630 continue;
1631 // The parser ensures that this operand is a register use, so we just have
1632 // to check the tied-def operand.
1633 unsigned DefIdx = *Operands[I].TiedDefIdx;
1634 if (DefIdx >= E)
1635 return error(Operands[I].Begin,
1636 Twine("use of invalid tied-def operand index '" +
1637 Twine(DefIdx) + "'; instruction has only ") +
1638 Twine(E) + " operands");
1639 const auto &DefOperand = Operands[DefIdx].Operand;
1640 if (!DefOperand.isReg() || !DefOperand.isDef())
1641 // FIXME: add note with the def operand.
1642 return error(Operands[I].Begin,
1643 Twine("use of invalid tied-def operand index '") +
1644 Twine(DefIdx) + "'; the operand #" + Twine(DefIdx) +
1645 " isn't a defined register");
1646 // Check that the tied-def operand wasn't tied elsewhere.
1647 for (const auto &TiedPair : TiedRegisterPairs) {
1648 if (TiedPair.first == DefIdx)
1649 return error(Operands[I].Begin,
1650 Twine("the tied-def operand #") + Twine(DefIdx) +
1651 " is already tied with another register operand");
1652 }
1653 TiedRegisterPairs.push_back(std::make_pair(DefIdx, I));
1654 }
1655 // FIXME: Verify that for non INLINEASM instructions, the def and use tied
1656 // indices must be less than tied max.
1657 for (const auto &TiedPair : TiedRegisterPairs)
1658 MI.tieOperands(TiedPair.first, TiedPair.second);
1659 return false;
1660}
1661
1662bool MIParser::parseRegisterOperand(MachineOperand &Dest,
1663 std::optional<unsigned> &TiedDefIdx,
1664 bool IsDef) {
1665 RegState Flags = getDefRegState(IsDef);
1666 while (Token.isRegisterFlag()) {
1667 if (parseRegisterFlag(Flags))
1668 return true;
1669 }
1670 // Update IsDef as we may have read a def flag.
1671 IsDef = hasRegState(Flags, RegState::Define);
1672 if (!Token.isRegister())
1673 return error("expected a register after register flags");
1674 Register Reg;
1675 VRegInfo *RegInfo;
1676 if (parseRegister(Reg, RegInfo))
1677 return true;
1678 lex();
1679 unsigned SubReg = 0;
1680 if (Token.is(MIToken::dot)) {
1681 if (parseSubRegisterIndex(SubReg))
1682 return true;
1683 if (!Reg.isVirtual())
1684 return error("subregister index expects a virtual register");
1685 }
1686 if (Token.is(MIToken::colon)) {
1687 if (!Reg.isVirtual())
1688 return error("register class specification expects a virtual register");
1689 lex();
1690 if (parseRegisterClassOrBank(*RegInfo))
1691 return true;
1692 }
1693
1694 if (consumeIfPresent(MIToken::lparen)) {
1695 // For a def, we only expect a type. For use we expect either a type or a
1696 // tied-def. Additionally, for physical registers, we don't expect a type.
1697 if (Token.is(MIToken::kw_tied_def)) {
1698 if (IsDef)
1699 return error("tied-def not supported for defs");
1700 unsigned Idx;
1701 if (parseRegisterTiedDefIndex(Idx))
1702 return true;
1703 TiedDefIdx = Idx;
1704 } else {
1705 if (!Reg.isVirtual())
1706 return error("unexpected type on physical register");
1707
1708 LLT Ty;
1709 // If type parsing fails, forwad the parse error for defs.
1710 if (parseLowLevelType(Token.location(), Ty))
1711 return IsDef ? true
1712 : error("expected tied-def or low-level type after '('");
1713
1714 if (expectAndConsume(MIToken::rparen))
1715 return true;
1716
1717 MachineRegisterInfo &MRI = MF.getRegInfo();
1718 if (MRI.getType(Reg).isValid() && MRI.getType(Reg) != Ty)
1719 return error("inconsistent type for generic virtual register");
1720
1721 MRI.setRegClassOrRegBank(Reg, static_cast<RegisterBank *>(nullptr));
1722 MRI.setType(Reg, Ty);
1724 }
1725 } else if (IsDef && Reg.isVirtual()) {
1726 // Generic virtual registers defs must have a type.
1727 if (RegInfo->Kind == VRegInfo::GENERIC ||
1728 RegInfo->Kind == VRegInfo::REGBANK)
1729 return error("generic virtual registers must have a type");
1730 }
1731
1732 if (IsDef) {
1733 if (hasRegState(Flags, RegState::Kill))
1734 return error("cannot have a killed def operand");
1735 } else {
1736 if (hasRegState(Flags, RegState::Dead))
1737 return error("cannot have a dead use operand");
1738 }
1739
1741 Reg, IsDef, hasRegState(Flags, RegState::Implicit),
1744 hasRegState(Flags, RegState::EarlyClobber), SubReg,
1748
1749 return false;
1750}
1751
1752bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
1754 const APSInt &Int = Token.integerValue();
1755 if (auto SImm = Int.trySExtValue(); Int.isSigned() && SImm.has_value())
1756 Dest = MachineOperand::CreateImm(*SImm);
1757 else if (auto UImm = Int.tryZExtValue(); !Int.isSigned() && UImm.has_value())
1758 Dest = MachineOperand::CreateImm(*UImm);
1759 else
1760 return error("integer literal is too large to be an immediate operand");
1761 lex();
1762 return false;
1763}
1764
1765bool MIParser::parseSymbolicInlineAsmOperand(unsigned OpIdx,
1766 MachineOperand &Dest) {
1768 assert(Token.is(MIToken::Identifier) &&
1769 "expected symbolic inline asm operand");
1770
1771 // Parse ExtraInfo flags.
1772 if (OpIdx == InlineAsm::MIOp_ExtraInfo) {
1773 unsigned ExtraInfo = 0;
1774 for (;;) {
1775 if (Token.isNot(MIToken::Identifier))
1776 break;
1777
1778 StringRef FlagName = Token.stringValue();
1779 unsigned Flag = StringSwitch<unsigned>(FlagName)
1781 .Case("mayload", InlineAsm::Extra_MayLoad)
1782 .Case("maystore", InlineAsm::Extra_MayStore)
1783 .Case("isconvergent", InlineAsm::Extra_IsConvergent)
1784 .Case("alignstack", InlineAsm::Extra_IsAlignStack)
1786 .Case("attdialect", 0)
1787 .Case("inteldialect", InlineAsm::Extra_AsmDialect)
1788 .Default(~0u);
1789 if (Flag == ~0u)
1790 return error("unknown inline asm extra info flag '" + FlagName + "'");
1791
1792 ExtraInfo |= Flag;
1793 lex();
1794 }
1795
1796 Dest = MachineOperand::CreateImm(ExtraInfo);
1797 return false;
1798 }
1799
1800 // Parse symbolic form: kind[:constraint].
1801 StringRef KindStr = Token.stringValue();
1802 constexpr auto InvalidKind = static_cast<InlineAsm::Kind>(0);
1805 .Case("regdef", InlineAsm::Kind::RegDef)
1806 .Case("reguse", InlineAsm::Kind::RegUse)
1808 .Case("clobber", InlineAsm::Kind::Clobber)
1809 .Case("imm", InlineAsm::Kind::Imm)
1810 .Case("mem", InlineAsm::Kind::Mem)
1811 .Default(InvalidKind);
1812 if (K == InvalidKind)
1813 return error("unknown inline asm operand kind '" + KindStr + "'");
1814
1815 lex();
1816
1817 // Create the flag with default of 1 operand.
1818 InlineAsm::Flag F(K, 1);
1819
1820 // Parse optional tiedto constraint: tiedto:$N.
1821 if (Token.is(MIToken::Identifier) && Token.stringValue() == "tiedto") {
1822 lex();
1823 if (Token.isNot(MIToken::colon))
1824 return error("expected ':' after 'tiedto'");
1825 lex();
1826 if (Token.isNot(MIToken::NamedRegister))
1827 return error("expected '$N' operand number after 'tiedto:'");
1828 unsigned OperandNo;
1829 if (Token.stringValue().getAsInteger(10, OperandNo))
1830 return error("invalid operand number in tiedto constraint");
1831 lex();
1832
1833 F.setMatchingOp(OperandNo);
1834
1836 return false;
1837 }
1838
1839 // Parse optional constraint after ':'.
1840 if (Token.isNot(MIToken::colon)) {
1842 return false;
1843 }
1844
1845 lex();
1846
1847 if (Token.isNot(MIToken::Identifier))
1848 return error("expected register class or memory constraint name after ':'");
1849
1850 StringRef ConstraintStr = Token.stringValue();
1851 if (K == InlineAsm::Kind::Mem) {
1884 return error("unknown memory constraint '" + ConstraintStr + "'");
1885 F.setMemConstraint(CC);
1886 } else if (K == InlineAsm::Kind::RegDef || K == InlineAsm::Kind::RegUse ||
1888 const TargetRegisterClass *RC =
1889 PFS.Target.getRegClass(ConstraintStr.lower());
1890 if (!RC)
1891 return error("unknown register class '" + ConstraintStr + "'");
1892 F.setRegClass(RC->getID());
1893 }
1894
1895 lex();
1896
1898 return false;
1899}
1900
1901bool MIParser::parseTargetImmMnemonic(const unsigned OpCode,
1902 const unsigned OpIdx,
1903 MachineOperand &Dest,
1904 const MIRFormatter &MF) {
1905 assert(Token.is(MIToken::dot));
1906 auto Loc = Token.location(); // record start position
1907 size_t Len = 1; // for "."
1908 lex();
1909
1910 // Handle the case that mnemonic starts with number.
1911 if (Token.is(MIToken::IntegerLiteral)) {
1912 Len += Token.range().size();
1913 lex();
1914 }
1915
1916 StringRef Src;
1917 if (Token.is(MIToken::comma))
1918 Src = StringRef(Loc, Len);
1919 else {
1920 assert(Token.is(MIToken::Identifier));
1921 Src = StringRef(Loc, Len + Token.stringValue().size());
1922 }
1923 int64_t Val;
1924 if (MF.parseImmMnemonic(OpCode, OpIdx, Src, Val,
1925 [this](StringRef::iterator Loc, const Twine &Msg)
1926 -> bool { return error(Loc, Msg); }))
1927 return true;
1928
1929 Dest = MachineOperand::CreateImm(Val);
1930 if (!Token.is(MIToken::comma))
1931 lex();
1932 return false;
1933}
1934
1936 PerFunctionMIParsingState &PFS, const Constant *&C,
1937 ErrorCallbackType ErrCB) {
1938 auto Source = StringValue.str(); // The source has to be null terminated.
1939 SMDiagnostic Err;
1940 C = parseConstantValue(Source, Err, *PFS.MF.getFunction().getParent(),
1941 &PFS.IRSlots);
1942 if (!C)
1943 return ErrCB(Loc + Err.getColumnNo(), Err.getMessage());
1944 return false;
1945}
1946
1947bool MIParser::parseIRConstant(StringRef::iterator Loc, StringRef StringValue,
1948 const Constant *&C) {
1949 return ::parseIRConstant(
1950 Loc, StringValue, PFS, C,
1951 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
1952 return error(Loc, Msg);
1953 });
1954}
1955
1956bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
1957 if (parseIRConstant(Loc, StringRef(Loc, Token.range().end() - Loc), C))
1958 return true;
1959 lex();
1960 return false;
1961}
1962
1963// See LLT implementation for bit size limits.
1965 return Size != 0 && isUInt<16>(Size);
1966}
1967
1969 return NumElts != 0 && isUInt<16>(NumElts);
1970}
1971
1972static bool verifyAddrSpace(uint64_t AddrSpace) {
1973 return isUInt<24>(AddrSpace);
1974}
1975
1976bool MIParser::parseLowLevelType(StringRef::iterator Loc, LLT &Ty) {
1977 StringRef TypeDigits = Token.range();
1978 if (TypeDigits.consume_front("s") || TypeDigits.consume_front("i") ||
1979 TypeDigits.consume_front("f") || TypeDigits.consume_front("p") ||
1980 TypeDigits.consume_front("bf")) {
1981 if (TypeDigits.empty() || !llvm::all_of(TypeDigits, isdigit))
1982 return error(
1983 "expected integers after 's'/'i'/'f'/'bf'/'p' type identifier");
1984 }
1985
1986 bool Scalar = Token.range().starts_with("s");
1987 if (Scalar || Token.range().starts_with("i")) {
1988 auto ScalarSize = APSInt(TypeDigits).getZExtValue();
1989 if (!ScalarSize) {
1990 Ty = LLT::token();
1991 lex();
1992 return false;
1993 }
1994
1995 if (!verifyScalarSize(ScalarSize))
1996 return error("invalid size for scalar type");
1997
1998 Ty = Scalar ? LLT::scalar(ScalarSize) : LLT::integer(ScalarSize);
1999 lex();
2000 return false;
2001 }
2002
2003 if (Token.range().starts_with("p")) {
2004 const DataLayout &DL = MF.getDataLayout();
2005 uint64_t AS = APSInt(TypeDigits).getZExtValue();
2006 if (!verifyAddrSpace(AS))
2007 return error("invalid address space number");
2008
2009 Ty = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
2010 lex();
2011 return false;
2012 }
2013
2014 if (Token.range().starts_with("f") || Token.range().starts_with("bf")) {
2015 auto ScalarSize = APSInt(TypeDigits).getZExtValue();
2016 if (!ScalarSize || !verifyScalarSize(ScalarSize))
2017 return error("invalid size for scalar type");
2018
2019 if (Token.range().starts_with("bf") && ScalarSize != 16)
2020 return error("invalid size for bfloat");
2021
2022 Ty = Token.range().starts_with("bf") ? LLT::bfloat16()
2023 : LLT::floatIEEE(ScalarSize);
2024 lex();
2025 return false;
2026 }
2027
2028 // Now we're looking for a vector.
2029 if (Token.isNot(MIToken::less))
2030 return error(Loc, "expected tN, pA, <M x tN>, <M x pA>, <vscale x M x tN>, "
2031 "or <vscale x M x pA> for GlobalISel type, "
2032 "where t = {'s', 'i', 'f', 'bf'}");
2033 lex();
2034
2035 bool HasVScale =
2036 Token.is(MIToken::Identifier) && Token.stringValue() == "vscale";
2037 if (HasVScale) {
2038 lex();
2039 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != "x")
2040 return error(
2041 "expected <vscale x M x tN>, where t = {'s', 'i', 'f', 'bf', 'p'}");
2042 lex();
2043 }
2044
2045 auto GetError = [this, &HasVScale, Loc]() {
2046 if (HasVScale)
2047 return error(Loc, "expected <vscale x M x tN> for vector type, where t = "
2048 "{'s', 'i', 'f', 'bf', 'p'}");
2049 return error(Loc, "expected <M x tN> for vector type, where t = {'s', 'i', "
2050 "'f', 'bf', 'p'}");
2051 };
2052
2053 if (Token.isNot(MIToken::IntegerLiteral))
2054 return GetError();
2055 uint64_t NumElements = Token.integerValue().getZExtValue();
2056 if (!verifyVectorElementCount(NumElements))
2057 return error("invalid number of vector elements");
2058
2059 lex();
2060
2061 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != "x")
2062 return GetError();
2063 lex();
2064
2065 StringRef VectorTyDigits = Token.range();
2066 if (!VectorTyDigits.consume_front("s") &&
2067 !VectorTyDigits.consume_front("i") &&
2068 !VectorTyDigits.consume_front("f") &&
2069 !VectorTyDigits.consume_front("p") && !VectorTyDigits.consume_front("bf"))
2070 return GetError();
2071
2072 if (VectorTyDigits.empty() || !llvm::all_of(VectorTyDigits, isdigit))
2073 return error(
2074 "expected integers after 's'/'i'/'f'/'bf'/'p' type identifier");
2075
2076 Scalar = Token.range().starts_with("s");
2077 if (Scalar || Token.range().starts_with("i")) {
2078 auto ScalarSize = APSInt(VectorTyDigits).getZExtValue();
2079 if (!verifyScalarSize(ScalarSize))
2080 return error("invalid size for scalar element in vector");
2081 Ty = Scalar ? LLT::scalar(ScalarSize) : LLT::integer(ScalarSize);
2082 } else if (Token.range().starts_with("p")) {
2083 const DataLayout &DL = MF.getDataLayout();
2084 uint64_t AS = APSInt(VectorTyDigits).getZExtValue();
2085 if (!verifyAddrSpace(AS))
2086 return error("invalid address space number");
2087
2088 Ty = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
2089 } else if (Token.range().starts_with("f")) {
2090 auto ScalarSize = APSInt(VectorTyDigits).getZExtValue();
2091 if (!verifyScalarSize(ScalarSize))
2092 return error("invalid size for float element in vector");
2093 Ty = LLT::floatIEEE(ScalarSize);
2094 } else if (Token.range().starts_with("bf")) {
2095 auto ScalarSize = APSInt(VectorTyDigits).getZExtValue();
2096 if (!verifyScalarSize(ScalarSize))
2097 return error("invalid size for bfloat element in vector");
2098 Ty = LLT::bfloat16();
2099 } else {
2100 return GetError();
2101 }
2102 lex();
2103
2104 if (Token.isNot(MIToken::greater))
2105 return GetError();
2106
2107 lex();
2108
2109 Ty = LLT::vector(ElementCount::get(NumElements, HasVScale), Ty);
2110 return false;
2111}
2112
2113bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) {
2114 assert(Token.is(MIToken::Identifier));
2115 StringRef TypeDigits = Token.range();
2116 if (!TypeDigits.consume_front("i") && !TypeDigits.consume_front("s") &&
2117 !TypeDigits.consume_front("p") && !TypeDigits.consume_front("f") &&
2118 !TypeDigits.consume_front("bf"))
2119 return error("a typed immediate operand should start with one of 'i', "
2120 "'s', 'f', 'bf', or 'p'");
2121 if (TypeDigits.empty() || !llvm::all_of(TypeDigits, isdigit))
2122 return error(
2123 "expected integers after 'i'/'s'/'f'/'bf'/'p' type identifier");
2124
2125 auto Loc = Token.location();
2126 lex();
2127 if (Token.isNot(MIToken::IntegerLiteral)) {
2128 if (Token.isNot(MIToken::Identifier) ||
2129 !(Token.range() == "true" || Token.range() == "false"))
2130 return error("expected an integer literal");
2131 }
2132 const Constant *C = nullptr;
2133 if (parseIRConstant(Loc, C))
2134 return true;
2136 return false;
2137}
2138
2139bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
2140 auto Loc = Token.location();
2141 lex();
2142 if (Token.isNot(MIToken::FloatingPointLiteral) &&
2143 Token.isNot(MIToken::HexLiteral))
2144 return error("expected a floating point literal");
2145 const Constant *C = nullptr;
2146 if (parseIRConstant(Loc, C))
2147 return true;
2149 return false;
2150}
2151
2152static bool getHexUint(const MIToken &Token, APInt &Result) {
2154 StringRef S = Token.range();
2155 assert(S[0] == '0' && tolower(S[1]) == 'x');
2156 // This could be a floating point literal with a special prefix.
2157 if (!isxdigit(S[2]))
2158 return true;
2159 StringRef V = S.substr(2);
2160 APInt A(V.size()*4, V, 16);
2161
2162 // If A is 0, then A.getActiveBits() is 0. This isn't a valid bitwidth. Make
2163 // sure it isn't the case before constructing result.
2164 unsigned NumBits = (A == 0) ? 32 : A.getActiveBits();
2165 Result = APInt(NumBits, ArrayRef<uint64_t>(A.getRawData(), A.getNumWords()));
2166 return false;
2167}
2168
2169static bool getUnsigned(const MIToken &Token, unsigned &Result,
2170 ErrorCallbackType ErrCB) {
2171 if (Token.hasIntegerValue()) {
2172 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
2173 const APSInt &SInt = Token.integerValue();
2174 if (SInt.isNegative())
2175 return ErrCB(Token.location(), "expected unsigned integer");
2176 uint64_t Val64 = SInt.getLimitedValue(Limit);
2177 if (Val64 == Limit)
2178 return ErrCB(Token.location(), "expected 32-bit integer (too large)");
2179 Result = Val64;
2180 return false;
2181 }
2182 if (Token.is(MIToken::HexLiteral)) {
2183 APInt A;
2184 if (getHexUint(Token, A))
2185 return true;
2186 if (A.getBitWidth() > 32)
2187 return ErrCB(Token.location(), "expected 32-bit integer (too large)");
2188 Result = A.getZExtValue();
2189 return false;
2190 }
2191 return true;
2192}
2193
2194bool MIParser::getUnsigned(unsigned &Result) {
2195 return ::getUnsigned(
2196 Token, Result, [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
2197 return error(Loc, Msg);
2198 });
2199}
2200
2201bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
2204 unsigned Number;
2205 if (getUnsigned(Number))
2206 return true;
2207 auto MBBInfo = PFS.MBBSlots.find(Number);
2208 if (MBBInfo == PFS.MBBSlots.end())
2209 return error(Twine("use of undefined machine basic block #") +
2210 Twine(Number));
2211 MBB = MBBInfo->second;
2212 // TODO: Only parse the name if it's a MachineBasicBlockLabel. Deprecate once
2213 // we drop the <irname> from the bb.<id>.<irname> format.
2214 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
2215 return error(Twine("the name of machine basic block #") + Twine(Number) +
2216 " isn't '" + Token.stringValue() + "'");
2217 return false;
2218}
2219
2220bool MIParser::parseMBBOperand(MachineOperand &Dest) {
2223 return true;
2225 lex();
2226 return false;
2227}
2228
2229bool MIParser::parseStackFrameIndex(int &FI) {
2230 assert(Token.is(MIToken::StackObject));
2231 unsigned ID;
2232 if (getUnsigned(ID))
2233 return true;
2234 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
2235 if (ObjectInfo == PFS.StackObjectSlots.end())
2236 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
2237 "'");
2239 if (const auto *Alloca =
2240 MF.getFrameInfo().getObjectAllocation(ObjectInfo->second))
2241 Name = Alloca->getName();
2242 if (!Token.stringValue().empty() && Token.stringValue() != Name)
2243 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
2244 "' isn't '" + Token.stringValue() + "'");
2245 lex();
2246 FI = ObjectInfo->second;
2247 return false;
2248}
2249
2250bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
2251 int FI;
2252 if (parseStackFrameIndex(FI))
2253 return true;
2254 Dest = MachineOperand::CreateFI(FI);
2255 return false;
2256}
2257
2258bool MIParser::parseFixedStackFrameIndex(int &FI) {
2260 unsigned ID;
2261 if (getUnsigned(ID))
2262 return true;
2263 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
2264 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
2265 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
2266 Twine(ID) + "'");
2267 lex();
2268 FI = ObjectInfo->second;
2269 return false;
2270}
2271
2272bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
2273 int FI;
2274 if (parseFixedStackFrameIndex(FI))
2275 return true;
2276 Dest = MachineOperand::CreateFI(FI);
2277 return false;
2278}
2279
2280static bool parseGlobalValue(const MIToken &Token,
2282 ErrorCallbackType ErrCB) {
2283 switch (Token.kind()) {
2285 const Module *M = PFS.MF.getFunction().getParent();
2286 GV = M->getNamedValue(Token.stringValue());
2287 if (!GV)
2288 return ErrCB(Token.location(), Twine("use of undefined global value '") +
2289 Token.range() + "'");
2290 break;
2291 }
2292 case MIToken::GlobalValue: {
2293 unsigned GVIdx;
2294 if (getUnsigned(Token, GVIdx, ErrCB))
2295 return true;
2296 GV = PFS.IRSlots.GlobalValues.get(GVIdx);
2297 if (!GV)
2298 return ErrCB(Token.location(), Twine("use of undefined global value '@") +
2299 Twine(GVIdx) + "'");
2300 break;
2301 }
2302 default:
2303 llvm_unreachable("The current token should be a global value");
2304 }
2305 return false;
2306}
2307
2308bool MIParser::parseGlobalValue(GlobalValue *&GV) {
2309 return ::parseGlobalValue(
2310 Token, PFS, GV,
2311 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
2312 return error(Loc, Msg);
2313 });
2314}
2315
2316bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
2317 GlobalValue *GV = nullptr;
2318 if (parseGlobalValue(GV))
2319 return true;
2320 lex();
2321 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
2322 if (parseOperandsOffset(Dest))
2323 return true;
2324 return false;
2325}
2326
2327bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
2329 unsigned ID;
2330 if (getUnsigned(ID))
2331 return true;
2332 auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
2333 if (ConstantInfo == PFS.ConstantPoolSlots.end())
2334 return error("use of undefined constant '%const." + Twine(ID) + "'");
2335 lex();
2336 Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
2337 if (parseOperandsOffset(Dest))
2338 return true;
2339 return false;
2340}
2341
2342bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
2344 unsigned ID;
2345 if (getUnsigned(ID))
2346 return true;
2347 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
2348 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
2349 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
2350 lex();
2351 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
2352 return false;
2353}
2354
2355bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
2357 const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
2358 lex();
2359 Dest = MachineOperand::CreateES(Symbol);
2360 if (parseOperandsOffset(Dest))
2361 return true;
2362 return false;
2363}
2364
2365bool MIParser::parseMCSymbolOperand(MachineOperand &Dest) {
2366 assert(Token.is(MIToken::MCSymbol));
2367 MCSymbol *Symbol = getOrCreateMCSymbol(Token.stringValue());
2368 lex();
2369 Dest = MachineOperand::CreateMCSymbol(Symbol);
2370 if (parseOperandsOffset(Dest))
2371 return true;
2372 return false;
2373}
2374
2375bool MIParser::parseSubRegisterIndexOperand(MachineOperand &Dest) {
2377 StringRef Name = Token.stringValue();
2378 unsigned SubRegIndex = PFS.Target.getSubRegIndex(Token.stringValue());
2379 if (SubRegIndex == 0)
2380 return error(Twine("unknown subregister index '") + Name + "'");
2381 lex();
2382 Dest = MachineOperand::CreateImm(SubRegIndex);
2383 return false;
2384}
2385
2386bool MIParser::parseMDNode(MDNode *&Node) {
2387 assert(Token.is(MIToken::exclaim));
2388
2389 auto Loc = Token.location();
2390 lex();
2391 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
2392 return error("expected metadata id after '!'");
2393 unsigned ID;
2394 if (getUnsigned(ID))
2395 return true;
2396 auto NodeInfo = PFS.IRSlots.MetadataNodes.find(ID);
2397 if (NodeInfo == PFS.IRSlots.MetadataNodes.end()) {
2398 NodeInfo = PFS.MachineMetadataNodes.find(ID);
2399 if (NodeInfo == PFS.MachineMetadataNodes.end())
2400 return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
2401 }
2402 lex();
2403 Node = NodeInfo->second.get();
2404 return false;
2405}
2406
2407bool MIParser::parseDIExpression(MDNode *&Expr) {
2408 unsigned Read;
2410 CurrentSource, Read, Error, *PFS.MF.getFunction().getParent(),
2411 &PFS.IRSlots);
2412 CurrentSource = CurrentSource.substr(Read);
2413 lex();
2414 if (!Expr)
2415 return error(Error.getMessage());
2416 return false;
2417}
2418
2419bool MIParser::parseDILocation(MDNode *&Loc) {
2420 assert(Token.is(MIToken::md_dilocation));
2421 lex();
2422
2423 bool HaveLine = false;
2424 unsigned Line = 0;
2425 unsigned Column = 0;
2426 MDNode *Scope = nullptr;
2427 MDNode *InlinedAt = nullptr;
2428 bool ImplicitCode = false;
2429 uint64_t AtomGroup = 0;
2430 uint64_t AtomRank = 0;
2431
2432 if (expectAndConsume(MIToken::lparen))
2433 return true;
2434
2435 if (Token.isNot(MIToken::rparen)) {
2436 do {
2437 if (Token.is(MIToken::Identifier)) {
2438 if (Token.stringValue() == "line") {
2439 lex();
2440 if (expectAndConsume(MIToken::colon))
2441 return true;
2442 if (Token.isNot(MIToken::IntegerLiteral) ||
2443 Token.integerValue().isSigned())
2444 return error("expected unsigned integer");
2445 Line = Token.integerValue().getZExtValue();
2446 HaveLine = true;
2447 lex();
2448 continue;
2449 }
2450 if (Token.stringValue() == "column") {
2451 lex();
2452 if (expectAndConsume(MIToken::colon))
2453 return true;
2454 if (Token.isNot(MIToken::IntegerLiteral) ||
2455 Token.integerValue().isSigned())
2456 return error("expected unsigned integer");
2457 Column = Token.integerValue().getZExtValue();
2458 lex();
2459 continue;
2460 }
2461 if (Token.stringValue() == "scope") {
2462 lex();
2463 if (expectAndConsume(MIToken::colon))
2464 return true;
2465 if (parseMDNode(Scope))
2466 return error("expected metadata node");
2467 if (!isa<DIScope>(Scope))
2468 return error("expected DIScope node");
2469 continue;
2470 }
2471 if (Token.stringValue() == "inlinedAt") {
2472 lex();
2473 if (expectAndConsume(MIToken::colon))
2474 return true;
2475 if (Token.is(MIToken::exclaim)) {
2476 if (parseMDNode(InlinedAt))
2477 return true;
2478 } else if (Token.is(MIToken::md_dilocation)) {
2479 if (parseDILocation(InlinedAt))
2480 return true;
2481 } else {
2482 return error("expected metadata node");
2483 }
2484 if (!isa<DILocation>(InlinedAt))
2485 return error("expected DILocation node");
2486 continue;
2487 }
2488 if (Token.stringValue() == "isImplicitCode") {
2489 lex();
2490 if (expectAndConsume(MIToken::colon))
2491 return true;
2492 if (!Token.is(MIToken::Identifier))
2493 return error("expected true/false");
2494 // As far as I can see, we don't have any existing need for parsing
2495 // true/false in MIR yet. Do it ad-hoc until there's something else
2496 // that needs it.
2497 if (Token.stringValue() == "true")
2498 ImplicitCode = true;
2499 else if (Token.stringValue() == "false")
2500 ImplicitCode = false;
2501 else
2502 return error("expected true/false");
2503 lex();
2504 continue;
2505 }
2506 if (Token.stringValue() == "atomGroup") {
2507 lex();
2508 if (expectAndConsume(MIToken::colon))
2509 return true;
2510 if (Token.isNot(MIToken::IntegerLiteral) ||
2511 Token.integerValue().isSigned())
2512 return error("expected unsigned integer");
2513 AtomGroup = Token.integerValue().getZExtValue();
2514 lex();
2515 continue;
2516 }
2517 if (Token.stringValue() == "atomRank") {
2518 lex();
2519 if (expectAndConsume(MIToken::colon))
2520 return true;
2521 if (Token.isNot(MIToken::IntegerLiteral) ||
2522 Token.integerValue().isSigned())
2523 return error("expected unsigned integer");
2524 AtomRank = Token.integerValue().getZExtValue();
2525 lex();
2526 continue;
2527 }
2528 }
2529 return error(Twine("invalid DILocation argument '") +
2530 Token.stringValue() + "'");
2531 } while (consumeIfPresent(MIToken::comma));
2532 }
2533
2534 if (expectAndConsume(MIToken::rparen))
2535 return true;
2536
2537 if (!HaveLine)
2538 return error("DILocation requires line number");
2539 if (!Scope)
2540 return error("DILocation requires a scope");
2541
2542 Loc = DILocation::get(MF.getFunction().getContext(), Line, Column, Scope,
2543 InlinedAt, ImplicitCode, AtomGroup, AtomRank);
2544 return false;
2545}
2546
2547bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
2548 MDNode *Node = nullptr;
2549 if (Token.is(MIToken::exclaim)) {
2550 if (parseMDNode(Node))
2551 return true;
2552 } else if (Token.is(MIToken::md_diexpr)) {
2553 if (parseDIExpression(Node))
2554 return true;
2555 }
2556 Dest = MachineOperand::CreateMetadata(Node);
2557 return false;
2558}
2559
2560bool MIParser::parseCFIOffset(int &Offset) {
2561 if (Token.isNot(MIToken::IntegerLiteral))
2562 return error("expected a cfi offset");
2563 if (Token.integerValue().getSignificantBits() > 32)
2564 return error("expected a 32 bit integer (the cfi offset is too large)");
2565 Offset = (int)Token.integerValue().getExtValue();
2566 lex();
2567 return false;
2568}
2569
2570bool MIParser::parseCFIUnsigned(unsigned &Value) {
2571 if (getUnsigned(Value))
2572 return true;
2573 lex();
2574 return false;
2575}
2576
2577bool MIParser::parseCFIRegister(unsigned &Reg) {
2578 if (Token.isNot(MIToken::NamedRegister))
2579 return error("expected a cfi register");
2580 Register LLVMReg;
2581 if (parseNamedRegister(LLVMReg))
2582 return true;
2583 const auto *TRI = MF.getSubtarget().getRegisterInfo();
2584 assert(TRI && "Expected target register info");
2585 int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
2586 if (DwarfReg < 0)
2587 return error("invalid DWARF register");
2588 Reg = (unsigned)DwarfReg;
2589 lex();
2590 return false;
2591}
2592
2593bool MIParser::parseCFIAddressSpace(unsigned &AddressSpace) {
2594 if (Token.isNot(MIToken::IntegerLiteral))
2595 return error("expected a cfi address space literal");
2596 if (Token.integerValue().isSigned())
2597 return error("expected an unsigned integer (cfi address space)");
2598 AddressSpace = Token.integerValue().getZExtValue();
2599 lex();
2600 return false;
2601}
2602
2603bool MIParser::parseCFIEscapeValues(std::string &Values) {
2604 do {
2605 if (Token.isNot(MIToken::HexLiteral))
2606 return error("expected a hexadecimal literal");
2607 unsigned Value;
2608 if (getUnsigned(Value))
2609 return true;
2610 if (Value > UINT8_MAX)
2611 return error("expected a 8-bit integer (too large)");
2612 Values.push_back(static_cast<uint8_t>(Value));
2613 lex();
2614 } while (consumeIfPresent(MIToken::comma));
2615 return false;
2616}
2617
2618bool MIParser::parseCFIOperand(MachineOperand &Dest) {
2619 auto Kind = Token.kind();
2620 lex();
2621 int Offset;
2622 unsigned Reg;
2623 unsigned AddressSpace;
2624 unsigned CFIIndex;
2625 switch (Kind) {
2627 if (parseCFIRegister(Reg))
2628 return true;
2629 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(nullptr, Reg));
2630 break;
2632 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2633 parseCFIOffset(Offset))
2634 return true;
2635 CFIIndex =
2636 MF.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
2637 break;
2639 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2640 parseCFIOffset(Offset))
2641 return true;
2642 CFIIndex = MF.addFrameInst(
2644 break;
2646 if (parseCFIRegister(Reg))
2647 return true;
2648 CFIIndex =
2649 MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
2650 break;
2652 if (parseCFIOffset(Offset))
2653 return true;
2654 CFIIndex =
2655 MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, Offset));
2656 break;
2658 if (parseCFIOffset(Offset))
2659 return true;
2660 CFIIndex = MF.addFrameInst(
2662 break;
2664 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2665 parseCFIOffset(Offset))
2666 return true;
2667 CFIIndex =
2668 MF.addFrameInst(MCCFIInstruction::cfiDefCfa(nullptr, Reg, Offset));
2669 break;
2671 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2672 parseCFIOffset(Offset) || expectAndConsume(MIToken::comma) ||
2673 parseCFIAddressSpace(AddressSpace))
2674 return true;
2675 CFIIndex = MF.addFrameInst(MCCFIInstruction::createLLVMDefAspaceCfa(
2676 nullptr, Reg, Offset, AddressSpace, SMLoc()));
2677 break;
2679 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRememberState(nullptr));
2680 break;
2682 if (parseCFIRegister(Reg))
2683 return true;
2684 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, Reg));
2685 break;
2687 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestoreState(nullptr));
2688 break;
2690 if (parseCFIRegister(Reg))
2691 return true;
2692 CFIIndex = MF.addFrameInst(MCCFIInstruction::createUndefined(nullptr, Reg));
2693 break;
2695 unsigned Reg2;
2696 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2697 parseCFIRegister(Reg2))
2698 return true;
2699
2700 CFIIndex =
2701 MF.addFrameInst(MCCFIInstruction::createRegister(nullptr, Reg, Reg2));
2702 break;
2703 }
2705 CFIIndex = MF.addFrameInst(MCCFIInstruction::createWindowSave(nullptr));
2706 break;
2708 CFIIndex = MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
2709 break;
2711 CFIIndex =
2712 MF.addFrameInst(MCCFIInstruction::createNegateRAStateWithPC(nullptr));
2713 break;
2715 unsigned State;
2716 MCSymbol *PACSym = nullptr;
2717 if (parseCFIUnsigned(State) || expectAndConsume(MIToken::comma))
2718 return true;
2719 if (Token.is(MIToken::MCSymbol)) {
2720 PACSym = getOrCreateMCSymbol(Token.stringValue());
2721 lex();
2722 CFIIndex = MF.addFrameInst(
2723 MCCFIInstruction::createSetRAState(nullptr, State, PACSym));
2724 } else if (Token.is(MIToken::IntegerLiteral)) {
2725 int Offset;
2726 if (parseCFIOffset(Offset))
2727 return true;
2728 CFIIndex = MF.addFrameInst(
2730 } else {
2731 return error("expected '<mcsymbol ...>' or integer offset for "
2732 "cfi_set_ra_state");
2733 }
2734 break;
2735 }
2737 unsigned Reg, R1, R2;
2738 unsigned R1Size, R2Size;
2739 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2740 parseCFIRegister(R1) || expectAndConsume(MIToken::comma) ||
2741 parseCFIUnsigned(R1Size) || expectAndConsume(MIToken::comma) ||
2742 parseCFIRegister(R2) || expectAndConsume(MIToken::comma) ||
2743 parseCFIUnsigned(R2Size))
2744 return true;
2745
2746 CFIIndex = MF.addFrameInst(MCCFIInstruction::createLLVMRegisterPair(
2747 nullptr, Reg, R1, R1Size, R2, R2Size));
2748 break;
2749 }
2751 std::vector<MCCFIInstruction::VectorRegisterWithLane> VectorRegisters;
2752 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma))
2753 return true;
2754 do {
2755 unsigned VR;
2756 unsigned Lane, Size;
2757 if (parseCFIRegister(VR) || expectAndConsume(MIToken::comma) ||
2758 parseCFIUnsigned(Lane) || expectAndConsume(MIToken::comma) ||
2759 parseCFIUnsigned(Size))
2760 return true;
2761 VectorRegisters.push_back({VR, Lane, Size});
2762 } while (consumeIfPresent(MIToken::comma));
2763
2764 CFIIndex = MF.addFrameInst(MCCFIInstruction::createLLVMVectorRegisters(
2765 nullptr, Reg, std::move(VectorRegisters)));
2766 break;
2767 }
2769 unsigned Reg, MaskReg;
2770 unsigned RegSize, MaskRegSize;
2771 int Offset = 0;
2772
2773 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2774 parseCFIUnsigned(RegSize) || expectAndConsume(MIToken::comma) ||
2775 parseCFIRegister(MaskReg) || expectAndConsume(MIToken::comma) ||
2776 parseCFIUnsigned(MaskRegSize) || expectAndConsume(MIToken::comma) ||
2777 parseCFIOffset(Offset))
2778 return true;
2779
2780 CFIIndex = MF.addFrameInst(MCCFIInstruction::createLLVMVectorOffset(
2781 nullptr, Reg, RegSize, MaskReg, MaskRegSize, Offset));
2782 break;
2783 }
2785 unsigned Reg, SpillReg, MaskReg;
2786 unsigned SpillRegLaneSize, MaskRegSize;
2787
2788 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2789 parseCFIRegister(SpillReg) || expectAndConsume(MIToken::comma) ||
2790 parseCFIUnsigned(SpillRegLaneSize) ||
2791 expectAndConsume(MIToken::comma) || parseCFIRegister(MaskReg) ||
2792 expectAndConsume(MIToken::comma) || parseCFIUnsigned(MaskRegSize))
2793 return true;
2794
2795 CFIIndex = MF.addFrameInst(MCCFIInstruction::createLLVMVectorRegisterMask(
2796 nullptr, Reg, SpillReg, SpillRegLaneSize, MaskReg, MaskRegSize));
2797 break;
2798 }
2800 std::string Values;
2801 if (parseCFIEscapeValues(Values))
2802 return true;
2803 CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape(nullptr, Values));
2804 break;
2805 }
2806 default:
2807 // TODO: Parse the other CFI operands.
2808 llvm_unreachable("The current token should be a cfi operand");
2809 }
2810 Dest = MachineOperand::CreateCFIIndex(CFIIndex);
2811 return false;
2812}
2813
2814bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
2815 switch (Token.kind()) {
2816 case MIToken::NamedIRBlock: {
2818 F.getValueSymbolTable()->lookup(Token.stringValue()));
2819 if (!BB)
2820 return error(Twine("use of undefined IR block '") + Token.range() + "'");
2821 break;
2822 }
2823 case MIToken::IRBlock: {
2824 unsigned SlotNumber = 0;
2825 if (getUnsigned(SlotNumber))
2826 return true;
2827 BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F));
2828 if (!BB)
2829 return error(Twine("use of undefined IR block '%ir-block.") +
2830 Twine(SlotNumber) + "'");
2831 break;
2832 }
2833 default:
2834 llvm_unreachable("The current token should be an IR block reference");
2835 }
2836 return false;
2837}
2838
2839bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
2841 lex();
2842 if (expectAndConsume(MIToken::lparen))
2843 return true;
2844 if (Token.isNot(MIToken::GlobalValue) &&
2845 Token.isNot(MIToken::NamedGlobalValue))
2846 return error("expected a global value");
2847 GlobalValue *GV = nullptr;
2848 if (parseGlobalValue(GV))
2849 return true;
2850 auto *F = dyn_cast<Function>(GV);
2851 if (!F)
2852 return error("expected an IR function reference");
2853 lex();
2854 if (expectAndConsume(MIToken::comma))
2855 return true;
2856 BasicBlock *BB = nullptr;
2857 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
2858 return error("expected an IR block reference");
2859 if (parseIRBlock(BB, *F))
2860 return true;
2861 lex();
2862 if (expectAndConsume(MIToken::rparen))
2863 return true;
2864 Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
2865 if (parseOperandsOffset(Dest))
2866 return true;
2867 return false;
2868}
2869
2870bool MIParser::parseIntrinsicOperand(MachineOperand &Dest) {
2871 assert(Token.is(MIToken::kw_intrinsic));
2872 lex();
2873 if (expectAndConsume(MIToken::lparen))
2874 return error("expected syntax intrinsic(@llvm.whatever)");
2875
2876 if (Token.isNot(MIToken::NamedGlobalValue))
2877 return error("expected syntax intrinsic(@llvm.whatever)");
2878
2879 std::string Name = std::string(Token.stringValue());
2880 lex();
2881
2882 if (expectAndConsume(MIToken::rparen))
2883 return error("expected ')' to terminate intrinsic name");
2884
2885 // Find out what intrinsic we're dealing with.
2887 if (ID == Intrinsic::not_intrinsic)
2888 return error("unknown intrinsic name");
2890
2891 return false;
2892}
2893
2894bool MIParser::parsePredicateOperand(MachineOperand &Dest) {
2895 assert(Token.is(MIToken::kw_intpred) || Token.is(MIToken::kw_floatpred));
2896 bool IsFloat = Token.is(MIToken::kw_floatpred);
2897 lex();
2898
2899 if (expectAndConsume(MIToken::lparen))
2900 return error("expected syntax intpred(whatever) or floatpred(whatever");
2901
2902 if (Token.isNot(MIToken::Identifier))
2903 return error("whatever");
2904
2905 CmpInst::Predicate Pred;
2906 if (IsFloat) {
2907 Pred = StringSwitch<CmpInst::Predicate>(Token.stringValue())
2908 .Case("false", CmpInst::FCMP_FALSE)
2909 .Case("oeq", CmpInst::FCMP_OEQ)
2910 .Case("ogt", CmpInst::FCMP_OGT)
2911 .Case("oge", CmpInst::FCMP_OGE)
2912 .Case("olt", CmpInst::FCMP_OLT)
2913 .Case("ole", CmpInst::FCMP_OLE)
2914 .Case("one", CmpInst::FCMP_ONE)
2915 .Case("ord", CmpInst::FCMP_ORD)
2916 .Case("uno", CmpInst::FCMP_UNO)
2917 .Case("ueq", CmpInst::FCMP_UEQ)
2918 .Case("ugt", CmpInst::FCMP_UGT)
2919 .Case("uge", CmpInst::FCMP_UGE)
2920 .Case("ult", CmpInst::FCMP_ULT)
2921 .Case("ule", CmpInst::FCMP_ULE)
2922 .Case("une", CmpInst::FCMP_UNE)
2923 .Case("true", CmpInst::FCMP_TRUE)
2925 if (!CmpInst::isFPPredicate(Pred))
2926 return error("invalid floating-point predicate");
2927 } else {
2928 Pred = StringSwitch<CmpInst::Predicate>(Token.stringValue())
2929 .Case("eq", CmpInst::ICMP_EQ)
2930 .Case("ne", CmpInst::ICMP_NE)
2931 .Case("sgt", CmpInst::ICMP_SGT)
2932 .Case("sge", CmpInst::ICMP_SGE)
2933 .Case("slt", CmpInst::ICMP_SLT)
2934 .Case("sle", CmpInst::ICMP_SLE)
2935 .Case("ugt", CmpInst::ICMP_UGT)
2936 .Case("uge", CmpInst::ICMP_UGE)
2937 .Case("ult", CmpInst::ICMP_ULT)
2938 .Case("ule", CmpInst::ICMP_ULE)
2940 if (!CmpInst::isIntPredicate(Pred))
2941 return error("invalid integer predicate");
2942 }
2943
2944 lex();
2946 if (expectAndConsume(MIToken::rparen))
2947 return error("predicate should be terminated by ')'.");
2948
2949 return false;
2950}
2951
2952bool MIParser::parseShuffleMaskOperand(MachineOperand &Dest) {
2954
2955 lex();
2956 if (expectAndConsume(MIToken::lparen))
2957 return error("expected syntax shufflemask(<integer or undef>, ...)");
2958
2959 SmallVector<int, 32> ShufMask;
2960 do {
2961 if (Token.is(MIToken::kw_undef)) {
2962 ShufMask.push_back(-1);
2963 } else if (Token.is(MIToken::IntegerLiteral)) {
2964 const APSInt &Int = Token.integerValue();
2965 ShufMask.push_back(Int.getExtValue());
2966 } else {
2967 return error("expected integer constant");
2968 }
2969
2970 lex();
2971 } while (consumeIfPresent(MIToken::comma));
2972
2973 if (expectAndConsume(MIToken::rparen))
2974 return error("shufflemask should be terminated by ')'.");
2975
2976 if (ShufMask.size() < 2)
2977 return error("shufflemask should have > 1 element");
2978
2979 ArrayRef<int> MaskAlloc = MF.allocateShuffleMask(ShufMask);
2980 Dest = MachineOperand::CreateShuffleMask(MaskAlloc);
2981 return false;
2982}
2983
2984bool MIParser::parseDbgInstrRefOperand(MachineOperand &Dest) {
2986
2987 lex();
2988 if (expectAndConsume(MIToken::lparen))
2989 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
2990
2991 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isNegative())
2992 return error("expected unsigned integer for instruction index");
2993 uint64_t InstrIdx = Token.integerValue().getZExtValue();
2994 assert(InstrIdx <= std::numeric_limits<unsigned>::max() &&
2995 "Instruction reference's instruction index is too large");
2996 lex();
2997
2998 if (expectAndConsume(MIToken::comma))
2999 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
3000
3001 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isNegative())
3002 return error("expected unsigned integer for operand index");
3003 uint64_t OpIdx = Token.integerValue().getZExtValue();
3004 assert(OpIdx <= std::numeric_limits<unsigned>::max() &&
3005 "Instruction reference's operand index is too large");
3006 lex();
3007
3008 if (expectAndConsume(MIToken::rparen))
3009 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
3010
3011 Dest = MachineOperand::CreateDbgInstrRef(InstrIdx, OpIdx);
3012 return false;
3013}
3014
3015bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
3017 lex();
3018 if (expectAndConsume(MIToken::lparen))
3019 return true;
3020 if (Token.isNot(MIToken::Identifier))
3021 return error("expected the name of the target index");
3022 int Index = 0;
3023 if (PFS.Target.getTargetIndex(Token.stringValue(), Index))
3024 return error("use of undefined target index '" + Token.stringValue() + "'");
3025 lex();
3026 if (expectAndConsume(MIToken::rparen))
3027 return true;
3028 Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
3029 if (parseOperandsOffset(Dest))
3030 return true;
3031 return false;
3032}
3033
3034bool MIParser::parseCustomRegisterMaskOperand(MachineOperand &Dest) {
3035 assert(Token.stringValue() == "CustomRegMask" && "Expected a custom RegMask");
3036 lex();
3037 if (expectAndConsume(MIToken::lparen))
3038 return true;
3039
3040 uint32_t *Mask = MF.allocateRegMask();
3041 do {
3042 if (Token.isNot(MIToken::rparen)) {
3043 if (Token.isNot(MIToken::NamedRegister))
3044 return error("expected a named register");
3045 Register Reg;
3046 if (parseNamedRegister(Reg))
3047 return true;
3048 lex();
3049 Mask[Reg.id() / 32] |= 1U << (Reg.id() % 32);
3050 }
3051
3052 // TODO: Report an error if the same register is used more than once.
3053 } while (consumeIfPresent(MIToken::comma));
3054
3055 if (expectAndConsume(MIToken::rparen))
3056 return true;
3057 Dest = MachineOperand::CreateRegMask(Mask);
3058 return false;
3059}
3060
3061bool MIParser::parseLaneMaskOperand(MachineOperand &Dest) {
3062 assert(Token.is(MIToken::kw_lanemask));
3063
3064 lex();
3065 if (expectAndConsume(MIToken::lparen))
3066 return true;
3067
3068 // Parse lanemask.
3069 if (Token.isNot(MIToken::IntegerLiteral) && Token.isNot(MIToken::HexLiteral))
3070 return error("expected a valid lane mask value");
3071 static_assert(sizeof(LaneBitmask::Type) == sizeof(uint64_t),
3072 "Use correct get-function for lane mask.");
3074 if (getUint64(V))
3075 return true;
3076 LaneBitmask LaneMask(V);
3077 lex();
3078
3079 if (expectAndConsume(MIToken::rparen))
3080 return true;
3081
3082 Dest = MachineOperand::CreateLaneMask(LaneMask);
3083 return false;
3084}
3085
3086bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) {
3087 assert(Token.is(MIToken::kw_liveout));
3088 uint32_t *Mask = MF.allocateRegMask();
3089 lex();
3090 if (expectAndConsume(MIToken::lparen))
3091 return true;
3092 while (true) {
3093 if (Token.isNot(MIToken::NamedRegister))
3094 return error("expected a named register");
3095 Register Reg;
3096 if (parseNamedRegister(Reg))
3097 return true;
3098 lex();
3099 Mask[Reg.id() / 32] |= 1U << (Reg.id() % 32);
3100 // TODO: Report an error if the same register is used more than once.
3101 if (Token.isNot(MIToken::comma))
3102 break;
3103 lex();
3104 }
3105 if (expectAndConsume(MIToken::rparen))
3106 return true;
3108 return false;
3109}
3110
3111bool MIParser::parseMachineOperand(const unsigned OpCode, const unsigned OpIdx,
3112 MachineOperand &Dest,
3113 std::optional<unsigned> &TiedDefIdx) {
3114 switch (Token.kind()) {
3117 case MIToken::kw_def:
3118 case MIToken::kw_dead:
3119 case MIToken::kw_killed:
3120 case MIToken::kw_undef:
3129 return parseRegisterOperand(Dest, TiedDefIdx);
3131 // TODO: Forbid numeric operands for INLINEASM once the transition to the
3132 // symbolic form is over.
3133 return parseImmediateOperand(Dest);
3134 case MIToken::kw_half:
3135 case MIToken::kw_bfloat:
3136 case MIToken::kw_float:
3137 case MIToken::kw_double:
3139 case MIToken::kw_fp128:
3141 return parseFPImmediateOperand(Dest);
3143 return parseMBBOperand(Dest);
3145 return parseStackObjectOperand(Dest);
3147 return parseFixedStackObjectOperand(Dest);
3150 return parseGlobalAddressOperand(Dest);
3152 return parseConstantPoolIndexOperand(Dest);
3154 return parseJumpTableIndexOperand(Dest);
3156 return parseExternalSymbolOperand(Dest);
3157 case MIToken::MCSymbol:
3158 return parseMCSymbolOperand(Dest);
3160 return parseSubRegisterIndexOperand(Dest);
3161 case MIToken::md_diexpr:
3162 case MIToken::exclaim:
3163 return parseMetadataOperand(Dest);
3186 return parseCFIOperand(Dest);
3188 return parseBlockAddressOperand(Dest);
3190 return parseIntrinsicOperand(Dest);
3192 return parseTargetIndexOperand(Dest);
3194 return parseLaneMaskOperand(Dest);
3196 return parseLiveoutRegisterMaskOperand(Dest);
3199 return parsePredicateOperand(Dest);
3201 return parseShuffleMaskOperand(Dest);
3203 return parseDbgInstrRefOperand(Dest);
3204 case MIToken::Error:
3205 return true;
3206 case MIToken::Identifier: {
3207 bool IsInlineAsm = OpCode == TargetOpcode::INLINEASM ||
3208 OpCode == TargetOpcode::INLINEASM_BR;
3209 if (IsInlineAsm)
3210 return parseSymbolicInlineAsmOperand(OpIdx, Dest);
3211
3212 StringRef Id = Token.stringValue();
3213 if (const auto *RegMask = PFS.Target.getRegMask(Id)) {
3214 Dest = MachineOperand::CreateRegMask(RegMask);
3215 lex();
3216 break;
3217 } else if (Id == "CustomRegMask") {
3218 return parseCustomRegisterMaskOperand(Dest);
3219 } else {
3220 return parseTypedImmediateOperand(Dest);
3221 }
3222 }
3223 case MIToken::dot: {
3224 const auto *TII = MF.getSubtarget().getInstrInfo();
3225 if (const auto *Formatter = TII->getMIRFormatter()) {
3226 return parseTargetImmMnemonic(OpCode, OpIdx, Dest, *Formatter);
3227 }
3228 [[fallthrough]];
3229 }
3230 default:
3231 // FIXME: Parse the MCSymbol machine operand.
3232 return error("expected a machine operand");
3233 }
3234 return false;
3235}
3236
3237bool MIParser::parseMachineOperandAndTargetFlags(
3238 const unsigned OpCode, const unsigned OpIdx, MachineOperand &Dest,
3239 std::optional<unsigned> &TiedDefIdx) {
3240 unsigned TF = 0;
3241 bool HasTargetFlags = false;
3242 if (Token.is(MIToken::kw_target_flags)) {
3243 HasTargetFlags = true;
3244 lex();
3245 if (expectAndConsume(MIToken::lparen))
3246 return true;
3247 if (Token.isNot(MIToken::Identifier))
3248 return error("expected the name of the target flag");
3249 if (PFS.Target.getDirectTargetFlag(Token.stringValue(), TF)) {
3250 if (PFS.Target.getBitmaskTargetFlag(Token.stringValue(), TF))
3251 return error("use of undefined target flag '" + Token.stringValue() +
3252 "'");
3253 }
3254 lex();
3255 while (Token.is(MIToken::comma)) {
3256 lex();
3257 if (Token.isNot(MIToken::Identifier))
3258 return error("expected the name of the target flag");
3259 unsigned BitFlag = 0;
3260 if (PFS.Target.getBitmaskTargetFlag(Token.stringValue(), BitFlag))
3261 return error("use of undefined target flag '" + Token.stringValue() +
3262 "'");
3263 // TODO: Report an error when using a duplicate bit target flag.
3264 TF |= BitFlag;
3265 lex();
3266 }
3267 if (expectAndConsume(MIToken::rparen))
3268 return true;
3269 }
3270 auto Loc = Token.location();
3271 if (parseMachineOperand(OpCode, OpIdx, Dest, TiedDefIdx))
3272 return true;
3273 if (!HasTargetFlags)
3274 return false;
3275 if (Dest.isReg())
3276 return error(Loc, "register operands can't have target flags");
3277 Dest.setTargetFlags(TF);
3278 return false;
3279}
3280
3281bool MIParser::parseOffset(int64_t &Offset) {
3282 if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
3283 return false;
3284 StringRef Sign = Token.range();
3285 bool IsNegative = Token.is(MIToken::minus);
3286 lex();
3287 if (Token.isNot(MIToken::IntegerLiteral))
3288 return error("expected an integer literal after '" + Sign + "'");
3289 if (Token.integerValue().getSignificantBits() > 64)
3290 return error("expected 64-bit integer (too large)");
3291 Offset = Token.integerValue().getExtValue();
3292 if (IsNegative)
3293 Offset = -Offset;
3294 lex();
3295 return false;
3296}
3297
3298bool MIParser::parseIRBlockAddressTaken(BasicBlock *&BB) {
3300 lex();
3301 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
3302 return error("expected basic block after 'ir_block_address_taken'");
3303
3304 if (parseIRBlock(BB, MF.getFunction()))
3305 return true;
3306
3307 lex();
3308 return false;
3309}
3310
3311bool MIParser::parseAlignment(uint64_t &Alignment) {
3312 assert(Token.is(MIToken::kw_align) || Token.is(MIToken::kw_basealign));
3313 lex();
3314 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
3315 return error("expected an integer literal after 'align'");
3316 if (getUint64(Alignment))
3317 return true;
3318 lex();
3319
3320 if (!isPowerOf2_64(Alignment))
3321 return error("expected a power-of-2 literal after 'align'");
3322
3323 return false;
3324}
3325
3326bool MIParser::parseAddrspace(unsigned &Addrspace) {
3327 assert(Token.is(MIToken::kw_addrspace));
3328 lex();
3329 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
3330 return error("expected an integer literal after 'addrspace'");
3331 if (getUnsigned(Addrspace))
3332 return true;
3333 lex();
3334 return false;
3335}
3336
3337bool MIParser::parseOperandsOffset(MachineOperand &Op) {
3338 int64_t Offset = 0;
3339 if (parseOffset(Offset))
3340 return true;
3341 Op.setOffset(Offset);
3342 return false;
3343}
3344
3345static bool parseIRValue(const MIToken &Token, PerFunctionMIParsingState &PFS,
3346 const Value *&V, ErrorCallbackType ErrCB) {
3347 switch (Token.kind()) {
3348 case MIToken::NamedIRValue: {
3349 V = PFS.MF.getFunction().getValueSymbolTable()->lookup(Token.stringValue());
3350 break;
3351 }
3352 case MIToken::IRValue: {
3353 unsigned SlotNumber = 0;
3354 if (getUnsigned(Token, SlotNumber, ErrCB))
3355 return true;
3356 V = PFS.getIRValue(SlotNumber);
3357 break;
3358 }
3360 case MIToken::GlobalValue: {
3361 GlobalValue *GV = nullptr;
3362 if (parseGlobalValue(Token, PFS, GV, ErrCB))
3363 return true;
3364 V = GV;
3365 break;
3366 }
3368 const Constant *C = nullptr;
3369 if (parseIRConstant(Token.location(), Token.stringValue(), PFS, C, ErrCB))
3370 return true;
3371 V = C;
3372 break;
3373 }
3375 V = nullptr;
3376 return false;
3377 default:
3378 llvm_unreachable("The current token should be an IR block reference");
3379 }
3380 if (!V)
3381 return ErrCB(Token.location(), Twine("use of undefined IR value '") + Token.range() + "'");
3382 return false;
3383}
3384
3385bool MIParser::parseIRValue(const Value *&V) {
3386 return ::parseIRValue(
3387 Token, PFS, V, [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
3388 return error(Loc, Msg);
3389 });
3390}
3391
3392bool MIParser::getUint64(uint64_t &Result) {
3393 if (Token.hasIntegerValue()) {
3394 if (Token.integerValue().getActiveBits() > 64)
3395 return error("expected 64-bit integer (too large)");
3396 Result = Token.integerValue().getZExtValue();
3397 return false;
3398 }
3399 if (Token.is(MIToken::HexLiteral)) {
3400 APInt A;
3401 if (getHexUint(A))
3402 return true;
3403 if (A.getBitWidth() > 64)
3404 return error("expected 64-bit integer (too large)");
3405 Result = A.getZExtValue();
3406 return false;
3407 }
3408 return true;
3409}
3410
3411bool MIParser::getHexUint(APInt &Result) {
3412 return ::getHexUint(Token, Result);
3413}
3414
3415bool MIParser::parseMemoryOperandFlag(MachineMemOperand::Flags &Flags) {
3416 const auto OldFlags = Flags;
3417 switch (Token.kind()) {
3420 break;
3423 break;
3426 break;
3429 break;
3432 if (PFS.Target.getMMOTargetFlag(Token.stringValue(), TF))
3433 return error("use of undefined target MMO flag '" + Token.stringValue() +
3434 "'");
3435 Flags |= TF;
3436 break;
3437 }
3438 default:
3439 llvm_unreachable("The current token should be a memory operand flag");
3440 }
3441 if (OldFlags == Flags)
3442 // We know that the same flag is specified more than once when the flags
3443 // weren't modified.
3444 return error("duplicate '" + Token.stringValue() + "' memory operand flag");
3445 lex();
3446 return false;
3447}
3448
3449bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV) {
3450 switch (Token.kind()) {
3451 case MIToken::kw_stack:
3452 PSV = MF.getPSVManager().getStack();
3453 break;
3454 case MIToken::kw_got:
3455 PSV = MF.getPSVManager().getGOT();
3456 break;
3458 PSV = MF.getPSVManager().getJumpTable();
3459 break;
3461 PSV = MF.getPSVManager().getConstantPool();
3462 break;
3464 int FI;
3465 if (parseFixedStackFrameIndex(FI))
3466 return true;
3467 PSV = MF.getPSVManager().getFixedStack(FI);
3468 // The token was already consumed, so use return here instead of break.
3469 return false;
3470 }
3471 case MIToken::StackObject: {
3472 int FI;
3473 if (parseStackFrameIndex(FI))
3474 return true;
3475 PSV = MF.getPSVManager().getFixedStack(FI);
3476 // The token was already consumed, so use return here instead of break.
3477 return false;
3478 }
3480 lex();
3481 switch (Token.kind()) {
3484 GlobalValue *GV = nullptr;
3485 if (parseGlobalValue(GV))
3486 return true;
3487 PSV = MF.getPSVManager().getGlobalValueCallEntry(GV);
3488 break;
3489 }
3491 PSV = MF.getPSVManager().getExternalSymbolCallEntry(
3492 MF.createExternalSymbolName(Token.stringValue()));
3493 break;
3494 default:
3495 return error(
3496 "expected a global value or an external symbol after 'call-entry'");
3497 }
3498 break;
3499 case MIToken::kw_custom: {
3500 lex();
3501 const auto *TII = MF.getSubtarget().getInstrInfo();
3502 if (const auto *Formatter = TII->getMIRFormatter()) {
3503 if (Formatter->parseCustomPseudoSourceValue(
3504 Token.stringValue(), MF, PFS, PSV,
3505 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
3506 return error(Loc, Msg);
3507 }))
3508 return true;
3509 } else {
3510 return error("unable to parse target custom pseudo source value");
3511 }
3512 break;
3513 }
3514 default:
3515 llvm_unreachable("The current token should be pseudo source value");
3516 }
3517 lex();
3518 return false;
3519}
3520
3521bool MIParser::parseMachinePointerInfo(MachinePointerInfo &Dest) {
3522 if (Token.is(MIToken::kw_constant_pool) || Token.is(MIToken::kw_stack) ||
3523 Token.is(MIToken::kw_got) || Token.is(MIToken::kw_jump_table) ||
3524 Token.is(MIToken::FixedStackObject) || Token.is(MIToken::StackObject) ||
3525 Token.is(MIToken::kw_call_entry) || Token.is(MIToken::kw_custom)) {
3526 const PseudoSourceValue *PSV = nullptr;
3527 if (parseMemoryPseudoSourceValue(PSV))
3528 return true;
3529 int64_t Offset = 0;
3530 if (parseOffset(Offset))
3531 return true;
3532 Dest = MachinePointerInfo(PSV, Offset);
3533 return false;
3534 }
3535 if (Token.isNot(MIToken::NamedIRValue) && Token.isNot(MIToken::IRValue) &&
3536 Token.isNot(MIToken::GlobalValue) &&
3537 Token.isNot(MIToken::NamedGlobalValue) &&
3538 Token.isNot(MIToken::QuotedIRValue) &&
3539 Token.isNot(MIToken::kw_unknown_address))
3540 return error("expected an IR value reference");
3541 const Value *V = nullptr;
3542 if (parseIRValue(V))
3543 return true;
3544 if (V && !V->getType()->isPointerTy())
3545 return error("expected a pointer IR value");
3546 lex();
3547 int64_t Offset = 0;
3548 if (parseOffset(Offset))
3549 return true;
3550 Dest = MachinePointerInfo(V, Offset);
3551 return false;
3552}
3553
3554bool MIParser::parseOptionalScope(LLVMContext &Context,
3555 SyncScope::ID &SSID) {
3556 SSID = SyncScope::System;
3557 if (Token.is(MIToken::Identifier) && Token.stringValue() == "syncscope") {
3558 lex();
3559 if (expectAndConsume(MIToken::lparen))
3560 return error("expected '(' in syncscope");
3561
3562 std::string SSN;
3563 if (parseStringConstant(SSN))
3564 return true;
3565
3566 SSID = Context.getOrInsertSyncScopeID(SSN);
3567 if (expectAndConsume(MIToken::rparen))
3568 return error("expected ')' in syncscope");
3569 }
3570
3571 return false;
3572}
3573
3574bool MIParser::parseOptionalAtomicOrdering(AtomicOrdering &Order) {
3576 if (Token.isNot(MIToken::Identifier))
3577 return false;
3578
3579 Order = StringSwitch<AtomicOrdering>(Token.stringValue())
3580 .Case("unordered", AtomicOrdering::Unordered)
3581 .Case("monotonic", AtomicOrdering::Monotonic)
3582 .Case("acquire", AtomicOrdering::Acquire)
3583 .Case("release", AtomicOrdering::Release)
3587
3588 if (Order != AtomicOrdering::NotAtomic) {
3589 lex();
3590 return false;
3591 }
3592
3593 return error("expected an atomic scope, ordering or a size specification");
3594}
3595
3596bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
3597 if (expectAndConsume(MIToken::lparen))
3598 return true;
3600 while (Token.isMemoryOperandFlag()) {
3601 if (parseMemoryOperandFlag(Flags))
3602 return true;
3603 }
3604 if (Token.isNot(MIToken::Identifier) ||
3605 (Token.stringValue() != "load" && Token.stringValue() != "store"))
3606 return error("expected 'load' or 'store' memory operation");
3607 if (Token.stringValue() == "load")
3609 else
3611 lex();
3612
3613 // Optional 'store' for operands that both load and store.
3614 if (Token.is(MIToken::Identifier) && Token.stringValue() == "store") {
3616 lex();
3617 }
3618
3619 // Optional synchronization scope.
3620 SyncScope::ID SSID;
3621 if (parseOptionalScope(MF.getFunction().getContext(), SSID))
3622 return true;
3623
3624 // Up to two atomic orderings (cmpxchg provides guarantees on failure).
3625 AtomicOrdering Order, FailureOrder;
3626 if (parseOptionalAtomicOrdering(Order))
3627 return true;
3628
3629 if (parseOptionalAtomicOrdering(FailureOrder))
3630 return true;
3631
3632 if (Token.isNot(MIToken::IntegerLiteral) &&
3633 Token.isNot(MIToken::kw_unknown_size) &&
3634 Token.isNot(MIToken::lparen))
3635 return error("expected memory LLT, the size integer literal or 'unknown-size' after "
3636 "memory operation");
3637
3639 if (Token.is(MIToken::IntegerLiteral)) {
3640 uint64_t Size;
3641 if (getUint64(Size))
3642 return true;
3643
3644 // Convert from bytes to bits for storage.
3646 lex();
3647 } else if (Token.is(MIToken::kw_unknown_size)) {
3648 lex();
3649 } else {
3650 if (expectAndConsume(MIToken::lparen))
3651 return true;
3652 if (parseLowLevelType(Token.location(), MemoryType))
3653 return true;
3654 if (expectAndConsume(MIToken::rparen))
3655 return true;
3656 }
3657
3659 if (Token.is(MIToken::Identifier)) {
3660 const char *Word =
3663 ? "on"
3664 : Flags & MachineMemOperand::MOLoad ? "from" : "into";
3665 if (Token.stringValue() != Word)
3666 return error(Twine("expected '") + Word + "'");
3667 lex();
3668
3669 if (parseMachinePointerInfo(Ptr))
3670 return true;
3671 }
3672 uint64_t BaseAlignment =
3673 MemoryType.isValid()
3674 ? PowerOf2Ceil(MemoryType.getSizeInBytes().getKnownMinValue())
3675 : 1;
3676 AAMDNodes AAInfo;
3677 MDNode *Range = nullptr;
3678 MDNode *MemCacheHint = nullptr;
3679 while (consumeIfPresent(MIToken::comma)) {
3680 switch (Token.kind()) {
3681 case MIToken::kw_align: {
3682 // align is printed if it is different than size.
3684 if (parseAlignment(Alignment))
3685 return true;
3686 if (Ptr.Offset & (Alignment - 1)) {
3687 // MachineMemOperand::getAlign never returns a value greater than the
3688 // alignment of offset, so this just guards against hand-written MIR
3689 // that specifies a large "align" value when it should probably use
3690 // "basealign" instead.
3691 return error("specified alignment is more aligned than offset");
3692 }
3693 BaseAlignment = Alignment;
3694 break;
3695 }
3697 // basealign is printed if it is different than align.
3698 if (parseAlignment(BaseAlignment))
3699 return true;
3700 break;
3702 if (parseAddrspace(Ptr.AddrSpace))
3703 return true;
3704 break;
3705 case MIToken::md_tbaa:
3706 lex();
3707 if (parseMDNode(AAInfo.TBAA))
3708 return true;
3709 break;
3711 lex();
3712 if (parseMDNode(AAInfo.Scope))
3713 return true;
3714 break;
3716 lex();
3717 if (parseMDNode(AAInfo.NoAlias))
3718 return true;
3719 break;
3721 lex();
3722 if (parseMDNode(AAInfo.NoAliasAddrSpace))
3723 return true;
3724 break;
3725 case MIToken::md_range:
3726 lex();
3727 if (parseMDNode(Range))
3728 return true;
3729 break;
3731 lex();
3732 if (parseMDNode(MemCacheHint))
3733 return true;
3734 break;
3735 // TODO: Report an error on duplicate metadata nodes.
3736 default:
3737 return error("expected 'align' or '!tbaa' or '!alias.scope' or "
3738 "'!noalias' or '!range' or '!mem.cache_hint' or "
3739 "'!noalias.addrspace'");
3740 }
3741 }
3742 if (expectAndConsume(MIToken::rparen))
3743 return true;
3744 Dest = MF.getMachineMemOperand(Ptr, Flags, MemoryType, Align(BaseAlignment),
3745 MMOMetadata(AAInfo, Range, MemCacheHint), SSID,
3746 Order, FailureOrder);
3747 return false;
3748}
3749
3750bool MIParser::parsePreOrPostInstrSymbol(MCSymbol *&Symbol) {
3752 Token.is(MIToken::kw_post_instr_symbol)) &&
3753 "Invalid token for a pre- post-instruction symbol!");
3754 lex();
3755 if (Token.isNot(MIToken::MCSymbol))
3756 return error("expected a symbol after 'pre-instr-symbol'");
3757 Symbol = getOrCreateMCSymbol(Token.stringValue());
3758 lex();
3759 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3760 Token.is(MIToken::lbrace))
3761 return false;
3762 if (Token.isNot(MIToken::comma))
3763 return error("expected ',' before the next machine operand");
3764 lex();
3765 return false;
3766}
3767
3768bool MIParser::parseHeapAllocMarker(MDNode *&Node) {
3770 "Invalid token for a heap alloc marker!");
3771 lex();
3772 if (parseMDNode(Node))
3773 return true;
3774 if (!Node)
3775 return error("expected a MDNode after 'heap-alloc-marker'");
3776 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3777 Token.is(MIToken::lbrace))
3778 return false;
3779 if (Token.isNot(MIToken::comma))
3780 return error("expected ',' before the next machine operand");
3781 lex();
3782 return false;
3783}
3784
3785bool MIParser::parsePCSections(MDNode *&Node) {
3786 assert(Token.is(MIToken::kw_pcsections) &&
3787 "Invalid token for a PC sections!");
3788 lex();
3789 if (parseMDNode(Node))
3790 return true;
3791 if (!Node)
3792 return error("expected a MDNode after 'pcsections'");
3793 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3794 Token.is(MIToken::lbrace))
3795 return false;
3796 if (Token.isNot(MIToken::comma))
3797 return error("expected ',' before the next machine operand");
3798 lex();
3799 return false;
3800}
3801
3802bool MIParser::parseMMRA(MDNode *&Node) {
3803 assert(Token.is(MIToken::kw_mmra) && "Invalid token for MMRA!");
3804 lex();
3805 if (parseMDNode(Node))
3806 return true;
3807 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3808 Token.is(MIToken::lbrace))
3809 return false;
3810 if (Token.isNot(MIToken::comma))
3811 return error("expected ',' before the next machine operand");
3812 lex();
3813 return false;
3814}
3815
3817 const Function &F,
3818 DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
3819 ModuleSlotTracker MST(F.getParent());
3821 for (const auto &BB : F) {
3822 if (BB.hasName())
3823 continue;
3824 int Slot = MST.getLocalSlot(&BB);
3825 if (Slot == -1)
3826 continue;
3827 Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
3828 }
3829}
3830
3832 unsigned Slot,
3833 const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
3834 return Slots2BasicBlocks.lookup(Slot);
3835}
3836
3837const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
3838 if (Slots2BasicBlocks.empty())
3839 initSlots2BasicBlocks(MF.getFunction(), Slots2BasicBlocks);
3840 return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
3841}
3842
3843const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
3844 if (&F == &MF.getFunction())
3845 return getIRBlock(Slot);
3846 DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
3847 initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
3848 return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
3849}
3850
3851MCSymbol *MIParser::getOrCreateMCSymbol(StringRef Name) {
3852 // FIXME: Currently we can't recognize temporary or local symbols and call all
3853 // of the appropriate forms to create them. However, this handles basic cases
3854 // well as most of the special aspects are recognized by a prefix on their
3855 // name, and the input names should already be unique. For test cases, keeping
3856 // the symbol name out of the symbol table isn't terribly important.
3857 return MF.getContext().getOrCreateSymbol(Name);
3858}
3859
3860bool MIParser::parseStringConstant(std::string &Result) {
3861 if (Token.isNot(MIToken::StringConstant))
3862 return error("expected string constant");
3863 Result = std::string(Token.stringValue());
3864 lex();
3865 return false;
3866}
3867
3869 StringRef Src,
3871 return MIParser(PFS, Error, Src).parseBasicBlockDefinitions(PFS.MBBSlots);
3872}
3873
3876 return MIParser(PFS, Error, Src).parseBasicBlocks();
3877}
3878
3882 return MIParser(PFS, Error, Src).parseStandaloneMBB(MBB);
3883}
3884
3886 Register &Reg, StringRef Src,
3888 return MIParser(PFS, Error, Src).parseStandaloneRegister(Reg);
3889}
3890
3892 Register &Reg, StringRef Src,
3894 return MIParser(PFS, Error, Src).parseStandaloneNamedRegister(Reg);
3895}
3896
3898 VRegInfo *&Info, StringRef Src,
3900 return MIParser(PFS, Error, Src).parseStandaloneVirtualRegister(Info);
3901}
3902
3905 return MIParser(PFS, Error, Src).parseStandaloneStackObject(FI);
3906}
3907
3911 return MIParser(PFS, Error, Src).parsePrefetchTarget(Target);
3912}
3915 return MIParser(PFS, Error, Src).parseStandaloneMDNode(Node);
3916}
3917
3919 PerFunctionMIParsingState &PFS, const Value *&V,
3920 ErrorCallbackType ErrorCallback) {
3921 MIToken Token;
3922 Src = lexMIToken(Src, Token, [&](StringRef::iterator Loc, const Twine &Msg) {
3923 ErrorCallback(Loc, Msg);
3924 });
3925 V = nullptr;
3926
3927 return ::parseIRValue(Token, PFS, V, ErrorCallback);
3928}
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
unsigned uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
basic Basic Alias true
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static Error parseAlignment(StringRef Str, Align &Alignment, StringRef Name, bool AllowZero=false)
Attempts to parse an alignment component of a specification.
This file defines the DenseMap class.
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
#define RegName(no)
A common definition of LaneBitmask for use in TableGen and CodeGen.
static llvm::Error parse(GsymDataExtractor &Data, uint64_t BaseAddr, LineEntryCallback const &Callback)
Definition LineTable.cpp:54
Implement a low-level type suitable for MachineInstr level instruction selection.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static const char * printImplicitRegisterFlag(const MachineOperand &MO)
static const BasicBlock * getIRBlockFromSlot(unsigned Slot, const DenseMap< unsigned, const BasicBlock * > &Slots2BasicBlocks)
static std::string getRegisterName(const TargetRegisterInfo *TRI, Register Reg)
static bool parseIRConstant(StringRef::iterator Loc, StringRef StringValue, PerFunctionMIParsingState &PFS, const Constant *&C, ErrorCallbackType ErrCB)
static void initSlots2Values(const Function &F, DenseMap< unsigned, const Value * > &Slots2Values)
Creates the mapping from slot numbers to function's unnamed IR values.
Definition MIParser.cpp:361
static bool parseIRValue(const MIToken &Token, PerFunctionMIParsingState &PFS, const Value *&V, ErrorCallbackType ErrCB)
static bool verifyScalarSize(uint64_t Size)
static bool getUnsigned(const MIToken &Token, unsigned &Result, ErrorCallbackType ErrCB)
static bool getHexUint(const MIToken &Token, APInt &Result)
static bool verifyVectorElementCount(uint64_t NumElts)
static void mapValueToSlot(const Value *V, ModuleSlotTracker &MST, DenseMap< unsigned, const Value * > &Slots2Values)
Definition MIParser.cpp:352
static void initSlots2BasicBlocks(const Function &F, DenseMap< unsigned, const BasicBlock * > &Slots2BasicBlocks)
function_ref< bool(StringRef::iterator Loc, const Twine &)> ErrorCallbackType
Definition MIParser.cpp:605
static bool isImplicitOperandIn(const MachineOperand &ImplicitOperand, ArrayRef< ParsedMachineOperand > Operands)
Return true if the parsed machine operands contain a given machine operand.
static bool parseGlobalValue(const MIToken &Token, PerFunctionMIParsingState &PFS, GlobalValue *&GV, ErrorCallbackType ErrCB)
static bool verifyAddrSpace(uint64_t AddrSpace)
Register Reg
Register const TargetRegisterInfo * TRI
#define R2(n)
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file contains the declarations for metadata subclasses.
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
SI Fold Operands
const char * Msg
This file defines the SmallVector class.
This file implements the StringSwitch template, which mimics a switch() statement whose cases are str...
#define error(X)
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:472
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
bool isNegative() const
Determine sign of this APSInt.
Definition APSInt.h:50
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
LLVM Basic Block Representation.
Definition BasicBlock.h:62
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static constexpr BranchProbability getRaw(uint32_t N)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:756
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:833
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:126
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:250
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:311
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
ValueSymbolTable * getValueSymbolTable()
getSymbolTable() - Return the symbol table if any, otherwise nullptr.
Definition Function.h:802
Module * getParent()
Get the module that this global value is contained inside of...
static constexpr LLT vector(ElementCount EC, unsigned ScalarSizeInBits)
Get a low-level vector of some number of elements and element width.
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
constexpr bool isValid() const
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
static constexpr LLT token()
Get a low-level token; just a scalar with zero bits (or no size).
static constexpr LLT bfloat16()
static LLT floatIEEE(unsigned SizeInBits)
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
static MCCFIInstruction createDefCfaRegister(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_def_cfa_register modifies a rule for computing CFA.
Definition MCDwarf.h:635
static MCCFIInstruction createLLVMVectorOffset(MCSymbol *L, unsigned Register, unsigned RegisterSizeInBits, unsigned MaskRegister, unsigned MaskRegisterSizeInBits, int64_t Offset, SMLoc Loc={})
.cfi_llvm_vector_offset Previous value of Register is saved at Offset from CFA.
Definition MCDwarf.h:797
static MCCFIInstruction createUndefined(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_undefined From now on the previous value of Register can't be restored anymore.
Definition MCDwarf.h:732
static MCCFIInstruction createLLVMVectorRegisters(MCSymbol *L, unsigned Register, ArrayRef< VectorRegisterWithLane > VectorRegisters, SMLoc Loc={})
.cfi_llvm_vector_registers Previous value of Register is saved in lanes of vector registers.
Definition MCDwarf.h:787
static MCCFIInstruction createRestore(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_restore says that the rule for Register is now the same as it was at the beginning of the functi...
Definition MCDwarf.h:725
static MCCFIInstruction createSetRAState(MCSymbol *L, unsigned State, MCSymbol *PACSym=nullptr, SMLoc Loc={})
.cfi_set_ra_state AArch64 set RA sign state,
Definition MCDwarf.h:708
static MCCFIInstruction createLLVMDefAspaceCfa(MCSymbol *L, unsigned Register, int64_t Offset, unsigned AddressSpace, SMLoc Loc)
.cfi_llvm_def_aspace_cfa defines the rule for computing the CFA to be the result of evaluating the DW...
Definition MCDwarf.h:660
static MCCFIInstruction createLLVMVectorRegisterMask(MCSymbol *L, unsigned Register, unsigned SpillRegister, unsigned SpillRegisterLaneSizeInBits, unsigned MaskRegister, unsigned MaskRegisterSizeInBits, SMLoc Loc={})
.cfi_llvm_vector_register_mask Previous value of Register is saved in SpillRegister,...
Definition MCDwarf.h:808
static MCCFIInstruction createRegister(MCSymbol *L, unsigned Register1, unsigned Register2, SMLoc Loc={})
.cfi_register Previous value of Register1 is saved in register Register2.
Definition MCDwarf.h:685
static MCCFIInstruction cfiDefCfa(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa defines a rule for computing CFA as: take address from Register and add Offset to it.
Definition MCDwarf.h:628
static MCCFIInstruction createOffset(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_offset Previous value of Register is saved at offset Offset from CFA.
Definition MCDwarf.h:670
static MCCFIInstruction createNegateRAStateWithPC(MCSymbol *L, SMLoc Loc={})
.cfi_negate_ra_state_with_pc AArch64 negate RA state with PC.
Definition MCDwarf.h:701
static MCCFIInstruction createNegateRAState(MCSymbol *L, SMLoc Loc={})
.cfi_negate_ra_state AArch64 negate RA state.
Definition MCDwarf.h:696
static MCCFIInstruction createRememberState(MCSymbol *L, SMLoc Loc={})
.cfi_remember_state Save all current rules for all registers.
Definition MCDwarf.h:745
static MCCFIInstruction createLLVMRegisterPair(MCSymbol *L, unsigned Register, unsigned R1, unsigned R1SizeInBits, unsigned R2, unsigned R2SizeInBits, SMLoc Loc={})
.cfi_llvm_register_pair Previous value of Register is saved in R1:R2.
Definition MCDwarf.h:777
static MCCFIInstruction cfiDefCfaOffset(MCSymbol *L, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa_offset modifies a rule for computing CFA.
Definition MCDwarf.h:643
static MCCFIInstruction createEscape(MCSymbol *L, StringRef Vals, SMLoc Loc={}, StringRef Comment="")
.cfi_escape Allows the user to add arbitrary bytes to the unwind info.
Definition MCDwarf.h:756
static MCCFIInstruction createWindowSave(MCSymbol *L, SMLoc Loc={})
.cfi_window_save SPARC register window is saved.
Definition MCDwarf.h:691
static MCCFIInstruction createAdjustCfaOffset(MCSymbol *L, int64_t Adjustment, SMLoc Loc={})
.cfi_adjust_cfa_offset Same as .cfi_def_cfa_offset, but Offset is a relative value that is added/subt...
Definition MCDwarf.h:651
static MCCFIInstruction createRestoreState(MCSymbol *L, SMLoc Loc={})
.cfi_restore_state Restore the previously saved state.
Definition MCDwarf.h:750
static MCCFIInstruction createSameValue(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_same_value Current value of Register is the same as in the previous frame.
Definition MCDwarf.h:739
static MCCFIInstruction createRelOffset(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_rel_offset Previous value of Register is saved at offset Offset from the current CFA register.
Definition MCDwarf.h:678
Describe properties that are true of each instruction in the target description file.
unsigned getID() const
getID() - Return the register class ID number.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
Metadata node.
Definition Metadata.h:1069
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
MIRFormater - Interface to format MIR operand based on target.
virtual bool parseImmMnemonic(const unsigned OpCode, const unsigned OpIdx, StringRef Src, int64_t &Imm, ErrorCallbackType ErrorCallback) const
Implement target specific parsing of immediate mnemonics.
function_ref< bool(StringRef::iterator Loc, const Twine &)> ErrorCallbackType
static LLVM_ABI bool parseIRValue(StringRef Src, MachineFunction &MF, PerFunctionMIParsingState &PFS, const Value *&V, ErrorCallbackType ErrorCallback)
Helper functions to parse IR value from MIR serialization format which will be useful for target spec...
void normalizeSuccProbs()
Normalize probabilities of all successors so that the sum of them becomes one.
void setAddressTakenIRBlock(BasicBlock *BB)
Set this block to reflect that it corresponds to an IR-level basic block with a BlockAddress.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
void setCallFrameSize(unsigned N)
Set the call frame size on entry to this basic block.
void setAlignment(Align A)
Set alignment of the basic block.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
void setSectionID(MBBSectionID V)
Sets the section ID for this basic block.
void setIsInlineAsmBrIndirectTarget(bool V=true)
Indicates if this is the indirect dest of an INLINEASM_BR.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
void setIsEHFuncletEntry(bool V=true)
Indicates if this is the entry block of an EH funclet.
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
void setIsEHScopeEntry(bool V=true)
Indicates if this is the entry block of an EH scope, i.e., the block that that used to have a catchpa...
void setMachineBlockAddressTaken()
Set this block to indicate that its address is used as something other than the target of a terminato...
void setIsEHPad(bool V=true)
Indicates the block is a landing pad.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
void setFlag(MIFlag Flag)
Set a MI flag.
A description of a memory reference used in the backend.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MONonTemporal
The memory access is non-temporal.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
MachineOperand class - Representation of each machine instruction operand.
static MachineOperand CreateMCSymbol(MCSymbol *Sym, unsigned TargetFlags=0)
static MachineOperand CreateES(const char *SymName, unsigned TargetFlags=0)
static MachineOperand CreateFPImm(const ConstantFP *CFP)
static MachineOperand CreateCFIIndex(unsigned CFIIndex)
static MachineOperand CreateRegMask(const uint32_t *Mask)
CreateRegMask - Creates a register mask operand referencing Mask.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
static MachineOperand CreateCImm(const ConstantInt *CI)
static MachineOperand CreateMetadata(const MDNode *Meta)
static MachineOperand CreatePredicate(unsigned Pred)
static MachineOperand CreateImm(int64_t Val)
static MachineOperand CreateShuffleMask(ArrayRef< int > Mask)
static MachineOperand CreateJTI(unsigned Idx, unsigned TargetFlags=0)
static MachineOperand CreateDbgInstrRef(unsigned InstrIdx, unsigned OpIdx)
static MachineOperand CreateRegLiveOut(const uint32_t *Mask)
static MachineOperand CreateGA(const GlobalValue *GV, int64_t Offset, unsigned TargetFlags=0)
static MachineOperand CreateBA(const BlockAddress *BA, int64_t Offset, unsigned TargetFlags=0)
void setTargetFlags(unsigned F)
static MachineOperand CreateLaneMask(LaneBitmask LaneMask)
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
static MachineOperand CreateCPI(unsigned Idx, int Offset, unsigned TargetFlags=0)
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
static MachineOperand CreateTargetIndex(unsigned Idx, int64_t Offset, unsigned TargetFlags=0)
static MachineOperand CreateMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0)
static MachineOperand CreateIntrinsicID(Intrinsic::ID ID)
static MachineOperand CreateFI(int Idx)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
void setRegClassOrRegBank(Register Reg, const RegClassOrRegBank &RCOrRB)
LLT getType(Register Reg) const
Get the low-level type of Reg or LLT{} if Reg is not a generic (target independent) virtual register.
LLVM_ABI Register createIncompleteVirtualRegister(StringRef Name="")
Creates a new virtual register that has no register class, register bank or size assigned yet.
LLVM_ABI void setType(Register VReg, LLT Ty)
Set the low-level type of VReg to Ty.
void noteNewVirtualRegister(Register Reg)
This interface provides simple read-only access to a block of memory, and provides simple methods for...
virtual StringRef getBufferIdentifier() const
Return an identifier for this buffer, typically the filename it was read from.
const char * getBufferEnd() const
const char * getBufferStart() const
Manage lifetime of a slot tracker for printing IR.
int getLocalSlot(const Value *V)
Return the slot number of the specified local value.
void incorporateFunction(const Function &F)
Incorporate the given function.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Special value supplied for machine level alias analysis.
const RegisterBank & getRegBank(unsigned ID)
Get the register bank identified by ID.
unsigned getNumRegBanks() const
Get the total number of register banks.
This class implements the register bank concept.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr unsigned id() const
Definition Register.h:100
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition SourceMgr.h:308
Represents a location in source code.
Definition SMLoc.h:22
static SMLoc getFromPointer(const char *Ptr)
Definition SMLoc.h:35
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling.
Definition SourceMgr.h:37
unsigned getMainFileID() const
Definition SourceMgr.h:151
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition SourceMgr.h:144
LLVM_ABI SMDiagnostic GetMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg, ArrayRef< SMRange > Ranges={}, ArrayRef< SMFixIt > FixIts={}) const
Return an SMDiagnostic at the specified location with the specified string.
bool empty() const
Definition StringMap.h:103
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition StringMap.h:311
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:736
const char * iterator
Definition StringRef.h:60
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
LLVM_ABI std::string lower() const
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:661
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
Value * lookup(StringRef Name) const
This method finds the value with the given Name in the the symbol table.
LLVM Value Representation.
Definition Value.h:75
bool hasName() const
Definition Value.h:261
An efficient, type-erasing, non-owning reference to a callable.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
support::ulittle32_t Word
Definition IRSymtab.h:53
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
LLVM_ABI bool parseStackObjectReference(PerFunctionMIParsingState &PFS, int &FI, StringRef Src, SMDiagnostic &Error)
LLVM_ABI bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node, StringRef Src, SMDiagnostic &Error)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
RegState
Flags to represent properties of register accesses.
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Dead
Unused definition.
@ Kill
The last use of a register.
@ InternalRead
Register reads a value that is defined inside the same instruction or bundle.
@ Undef
Value of the register doesn't matter.
@ EarlyClobber
Register definition happens before uses.
@ Define
Register definition.
@ Renamable
Register that may be renamed.
@ Debug
Register 'use' is for debugging purpose.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
StringRef lexMIToken(StringRef Source, MIToken &Token, function_ref< void(StringRef::iterator, const Twine &)> ErrorCallback)
Consume a single machine instruction token in the given source and return the remaining source string...
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
LLVM_ABI bool parseMachineBasicBlockDefinitions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine basic block definitions, and skip the machine instructions.
LLVM_ABI bool parsePrefetchTarget(PerFunctionMIParsingState &PFS, CallsiteID &Target, StringRef Src, SMDiagnostic &Error)
LLVM_ABI void guessSuccessors(const MachineBasicBlock &MBB, SmallVectorImpl< MachineBasicBlock * > &Result, bool &IsFallthrough)
Determine a possible list of successors of a basic block based on the basic block machine operand bei...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool parseMBBReference(PerFunctionMIParsingState &PFS, MachineBasicBlock *&MBB, StringRef Src, SMDiagnostic &Error)
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:380
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI DIExpression * parseDIExpressionBodyAtBeginning(StringRef Asm, unsigned &Read, SMDiagnostic &Err, const Module &M, const SlotMapping *Slots)
Definition Parser.cpp:238
constexpr RegState getDefRegState(bool B)
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
constexpr bool hasRegState(RegState Value, RegState Test)
AtomicOrdering
Atomic ordering for LLVM's memory model.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
LLVM_ABI bool parseMachineInstructions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine instructions.
LLVM_ABI bool parseRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
LLVM_ABI Constant * parseConstantValue(StringRef Asm, SMDiagnostic &Err, const Module &M, const SlotMapping *Slots=nullptr)
Parse a type and a constant value in the given string.
Definition Parser.cpp:197
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool parseVirtualRegisterReference(PerFunctionMIParsingState &PFS, VRegInfo *&Info, StringRef Src, SMDiagnostic &Error)
LLVM_ABI bool parseNamedRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:763
MDNode * NoAliasAddrSpace
The tag specifying the noalias address spaces.
Definition Metadata.h:792
MDNode * Scope
The tag for alias scope specification (used with noalias).
Definition Metadata.h:786
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:780
MDNode * NoAlias
The tag specifying the noalias scope.
Definition Metadata.h:789
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
static constexpr LaneBitmask getAll()
Definition LaneBitmask.h:82
LLVM_ABI static const MBBSectionID ExceptionSectionID
LLVM_ABI static const MBBSectionID ColdSectionID
A token produced by the machine instruction lexer.
Definition MILexer.h:26
TokenKind kind() const
Definition MILexer.h:218
bool hasIntegerValue() const
Definition MILexer.h:258
bool is(TokenKind K) const
Definition MILexer.h:245
StringRef stringValue() const
Return the token's string value.
Definition MILexer.h:254
@ kw_pre_instr_symbol
Definition MILexer.h:142
@ kw_deactivation_symbol
Definition MILexer.h:147
@ kw_call_frame_size
Definition MILexer.h:154
@ kw_cfi_aarch64_negate_ra_sign_state
Definition MILexer.h:101
@ kw_cfi_llvm_def_aspace_cfa
Definition MILexer.h:94
@ MachineBasicBlock
Definition MILexer.h:177
@ kw_dbg_instr_ref
Definition MILexer.h:85
@ NamedVirtualRegister
Definition MILexer.h:175
@ kw_early_clobber
Definition MILexer.h:59
@ kw_unpredictable
Definition MILexer.h:77
@ FloatingPointLiteral
Definition MILexer.h:187
@ kw_cfi_window_save
Definition MILexer.h:100
@ kw_cfi_llvm_register_pair
Definition MILexer.h:104
@ kw_frame_destroy
Definition MILexer.h:64
@ kw_cfi_undefined
Definition MILexer.h:99
@ MachineBasicBlockLabel
Definition MILexer.h:176
@ kw_cfi_llvm_vector_offset
Definition MILexer.h:106
@ kw_cfi_register
Definition MILexer.h:95
@ kw_inlineasm_br_indirect_target
Definition MILexer.h:134
@ kw_cfi_rel_offset
Definition MILexer.h:88
@ kw_cfi_llvm_vector_registers
Definition MILexer.h:105
@ kw_ehfunclet_entry
Definition MILexer.h:136
@ kw_cfi_llvm_vector_register_mask
Definition MILexer.h:107
@ kw_cfi_aarch64_negate_ra_sign_state_with_pc
Definition MILexer.h:102
@ kw_cfi_def_cfa_register
Definition MILexer.h:89
@ kw_cfi_same_value
Definition MILexer.h:86
@ kw_cfi_set_ra_state
Definition MILexer.h:103
@ kw_cfi_adjust_cfa_offset
Definition MILexer.h:91
@ kw_dereferenceable
Definition MILexer.h:55
@ kw_implicit_define
Definition MILexer.h:52
@ kw_cfi_def_cfa_offset
Definition MILexer.h:90
@ md_mem_cache_hint
Definition MILexer.h:168
@ kw_machine_block_address_taken
Definition MILexer.h:153
@ kw_cfi_remember_state
Definition MILexer.h:96
@ kw_debug_instr_number
Definition MILexer.h:84
@ kw_post_instr_symbol
Definition MILexer.h:143
@ kw_cfi_restore_state
Definition MILexer.h:98
@ kw_ir_block_address_taken
Definition MILexer.h:152
@ kw_unknown_address
Definition MILexer.h:151
@ md_noalias_addrspace
Definition MILexer.h:166
@ kw_debug_location
Definition MILexer.h:83
@ kw_heap_alloc_marker
Definition MILexer.h:144
StringRef range() const
Definition MILexer.h:251
StringRef::iterator location() const
Definition MILexer.h:249
const APSInt & integerValue() const
Definition MILexer.h:256
LLVM IR metadata carried by a MachineMemOperand.
This class contains a discriminated union of information about pointers in memory operands,...
int64_t Offset
Offset - This is an offset from the base Value*.
LLVM_ABI VRegInfo & getVRegInfo(Register Num)
Definition MIParser.cpp:329
const SlotMapping & IRSlots
Definition MIParser.h:172
LLVM_ABI const Value * getIRValue(unsigned Slot)
Definition MIParser.cpp:374
DenseMap< unsigned, MachineBasicBlock * > MBBSlots
Definition MIParser.h:177
StringMap< VRegInfo * > VRegInfosNamed
Definition MIParser.h:179
DenseMap< unsigned, const Value * > Slots2Values
Maps from slot numbers to function's unnamed values.
Definition MIParser.h:186
LLVM_ABI PerFunctionMIParsingState(MachineFunction &MF, SourceMgr &SM, const SlotMapping &IRSlots, PerTargetMIParsingState &Target)
Definition MIParser.cpp:324
PerTargetMIParsingState & Target
Definition MIParser.h:173
DenseMap< Register, VRegInfo * > VRegInfos
Definition MIParser.h:178
LLVM_ABI VRegInfo & getVRegInfoNamed(StringRef RegName)
Definition MIParser.cpp:340
LLVM_ABI bool getVRegFlagValue(StringRef FlagName, uint8_t &FlagValue) const
Definition MIParser.cpp:129
LLVM_ABI bool getDirectTargetFlag(StringRef Name, unsigned &Flag)
Try to convert a name of a direct target flag to the corresponding target flag.
Definition MIParser.cpp:227
LLVM_ABI const RegisterBank * getRegBank(StringRef Name)
Check if the given identifier is a name of a register bank.
Definition MIParser.cpp:317
LLVM_ABI bool parseInstrName(StringRef InstrName, unsigned &OpCode)
Try to convert an instruction name to an opcode.
Definition MIParser.cpp:148
LLVM_ABI unsigned getSubRegIndex(StringRef Name)
Check if the given identifier is a name of a subregister index.
Definition MIParser.cpp:188
LLVM_ABI bool getTargetIndex(StringRef Name, int &Index)
Try to convert a name of target index to the corresponding target index.
Definition MIParser.cpp:206
LLVM_ABI void setTarget(const TargetSubtargetInfo &NewSubtarget)
Definition MIParser.cpp:81
LLVM_ABI bool getRegisterByName(StringRef RegName, Register &Reg)
Try to convert a register name to a register number.
Definition MIParser.cpp:119
LLVM_ABI bool getMMOTargetFlag(StringRef Name, MachineMemOperand::Flags &Flag)
Try to convert a name of a MachineMemOperand target flag to the corresponding target flag.
Definition MIParser.cpp:270
LLVM_ABI bool getBitmaskTargetFlag(StringRef Name, unsigned &Flag)
Try to convert a name of a bitmask target flag to the corresponding target flag.
Definition MIParser.cpp:249
LLVM_ABI const TargetRegisterClass * getRegClass(StringRef Name)
Check if the given identifier is a name of a register class.
Definition MIParser.cpp:310
LLVM_ABI const uint32_t * getRegMask(StringRef Identifier)
Check if the given identifier is a name of a register mask.
Definition MIParser.cpp:171
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition SlotMapping.h:32
NumberedValues< GlobalValue * > GlobalValues
Definition SlotMapping.h:33
const RegisterBank * RegBank
Definition MIParser.h:46
union llvm::VRegInfo::@127225073067155374133234315364317264041071000132 D
const TargetRegisterClass * RC
Definition MIParser.h:45
enum llvm::VRegInfo::@374354327266250320012227113300214031244227062232 Kind
Register VReg
Definition MIParser.h:48
bool Explicit
VReg was explicitly specified in the .mir file.
Definition MIParser.h:43