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;
334 Info->VReg = MRI.createIncompleteVirtualRegister();
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 parseMaxBytesForAlignment(unsigned &MaxBytesForAlignment);
512 bool parsePrefetchTarget(CallsiteID &Target);
513 bool parseOperandsOffset(MachineOperand &Op);
514 bool parseIRValue(const Value *&V);
515 bool parseMemoryOperandFlag(MachineMemOperand::Flags &Flags);
516 bool parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV);
517 bool parseMachinePointerInfo(MachinePointerInfo &Dest);
518 bool parseOptionalScope(LLVMContext &Context, SyncScope::ID &SSID);
519 bool parseOptionalAtomicOrdering(AtomicOrdering &Order);
520 bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
521 bool parsePreOrPostInstrSymbol(MCSymbol *&Symbol);
522 bool parseHeapAllocMarker(MDNode *&Node);
523 bool parsePCSections(MDNode *&Node);
524 bool parseMMRA(MDNode *&Node);
525
526 bool parseTargetImmMnemonic(const unsigned OpCode, const unsigned OpIdx,
527 MachineOperand &Dest, const MIRFormatter &MF);
528
529private:
530 /// Convert the integer literal in the current token into an unsigned integer.
531 ///
532 /// Return true if an error occurred.
533 bool getUnsigned(unsigned &Result);
534
535 /// Convert the integer literal in the current token into an uint64.
536 ///
537 /// Return true if an error occurred.
538 bool getUint64(uint64_t &Result);
539
540 /// Convert the hexadecimal literal in the current token into an unsigned
541 /// APInt with a minimum bitwidth required to represent the value.
542 ///
543 /// Return true if the literal does not represent an integer value.
544 bool getHexUint(APInt &Result);
545
546 /// If the current token is of the given kind, consume it and return false.
547 /// Otherwise report an error and return true.
548 bool expectAndConsume(MIToken::TokenKind TokenKind);
549
550 /// If the current token is of the given kind, consume it and return true.
551 /// Otherwise return false.
552 bool consumeIfPresent(MIToken::TokenKind TokenKind);
553
554 bool parseInstruction(unsigned &OpCode, unsigned &Flags);
555
556 bool assignRegisterTies(MachineInstr &MI,
558
559 bool verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands,
560 const MCInstrDesc &MCID);
561
562 const BasicBlock *getIRBlock(unsigned Slot);
563 const BasicBlock *getIRBlock(unsigned Slot, const Function &F);
564
565 /// Get or create an MCSymbol for a given name.
566 MCSymbol *getOrCreateMCSymbol(StringRef Name);
567
568 /// parseStringConstant
569 /// ::= StringConstant
570 bool parseStringConstant(std::string &Result);
571};
572
573} // end anonymous namespace
574
575MIParser::MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
576 StringRef Source)
577 : MF(PFS.MF), Error(Error), Source(Source), CurrentSource(Source), PFS(PFS)
578{}
579
580void MIParser::lex(unsigned SkipChar) {
581 CurrentSource = lexMIToken(
582 CurrentSource.substr(SkipChar), Token,
583 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
584}
585
586bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
587
588bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
589 const SourceMgr &SM = *PFS.SM;
590 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
591 const MemoryBuffer &Buffer = *SM.getMemoryBuffer(SM.getMainFileID());
592 if (Loc >= Buffer.getBufferStart() && Loc <= Buffer.getBufferEnd()) {
593 // Create an ordinary diagnostic when the source manager's buffer is the
594 // source string.
596 return true;
597 }
598 // Create a diagnostic for a YAML string literal.
599 Error = SMDiagnostic(SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
600 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(),
601 Source, {}, {});
602 return true;
603}
604
605typedef function_ref<bool(StringRef::iterator Loc, const Twine &)>
607
608static const char *toString(MIToken::TokenKind TokenKind) {
609 switch (TokenKind) {
610 case MIToken::comma:
611 return "','";
612 case MIToken::equal:
613 return "'='";
614 case MIToken::colon:
615 return "':'";
616 case MIToken::lparen:
617 return "'('";
618 case MIToken::rparen:
619 return "')'";
620 default:
621 return "<unknown token>";
622 }
623}
624
625bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
626 if (Token.isNot(TokenKind))
627 return error(Twine("expected ") + toString(TokenKind));
628 lex();
629 return false;
630}
631
632bool MIParser::consumeIfPresent(MIToken::TokenKind TokenKind) {
633 if (Token.isNot(TokenKind))
634 return false;
635 lex();
636 return true;
637}
638
639// Parse Machine Basic Block Section ID.
640bool MIParser::parseSectionID(std::optional<MBBSectionID> &SID) {
642 lex();
643 if (Token.is(MIToken::IntegerLiteral)) {
644 unsigned Value = 0;
645 if (getUnsigned(Value))
646 return error("Unknown Section ID");
647 SID = MBBSectionID{Value};
648 } else {
649 const StringRef &S = Token.stringValue();
650 if (S == "Exception")
652 else if (S == "Cold")
654 else
655 return error("Unknown Section ID");
656 }
657 lex();
658 return false;
659}
660
661// Parse Machine Basic Block ID.
662bool MIParser::parseBBID(std::optional<UniqueBBID> &BBID) {
663 if (Token.isNot(MIToken::kw_bb_id))
664 return error("expected 'bb_id'");
665 lex();
666 unsigned BaseID = 0;
667 unsigned CloneID = 0;
668 if (Token.is(MIToken::FloatingPointLiteral)) {
669 StringRef S = Token.range();
670 auto Parts = S.split('.');
671 if (Parts.first.getAsInteger(10, BaseID) ||
672 Parts.second.getAsInteger(10, CloneID))
673 return error("Unknown BB ID");
674 lex();
675 } else {
676 if (getUnsigned(BaseID))
677 return error("Unknown BB ID");
678 lex();
679 if (Token.is(MIToken::comma) || Token.is(MIToken::dot)) {
680 lex();
681 if (getUnsigned(CloneID))
682 return error("Unknown Clone ID");
683 lex();
684 } else if (Token.is(MIToken::IntegerLiteral)) {
685 if (getUnsigned(CloneID))
686 return error("Unknown Clone ID");
687 lex();
688 }
689 }
690 BBID = {BaseID, CloneID};
691 return false;
692}
693
694// Parse basic block call frame size.
695bool MIParser::parseCallFrameSize(unsigned &CallFrameSize) {
697 lex();
698 unsigned Value = 0;
699 if (getUnsigned(Value))
700 return error("Unknown call frame size");
701 CallFrameSize = Value;
702 lex();
703 return false;
704}
705
706// Parse the maximum number of bytes permitted for basic block alignment
707// padding.
708bool MIParser::parseMaxBytesForAlignment(unsigned &MaxBytesForAlignment) {
710 lex();
711 if (Token.isNot(MIToken::IntegerLiteral) && Token.isNot(MIToken::HexLiteral))
712 return error("expected an integer literal after 'max-bytes-for-alignment'");
713 unsigned Value = 0;
714 if (getUnsigned(Value))
715 return true;
716 MaxBytesForAlignment = Value;
717 lex();
718 return false;
719}
720
721bool MIParser::parsePrefetchTarget(CallsiteID &Target) {
722 lex();
723 std::optional<UniqueBBID> BBID;
724 if (parseBBID(BBID))
725 return true;
726 Target.BBID = *BBID;
727 if (expectAndConsume(MIToken::comma))
728 return true;
729 return getUnsigned(Target.CallsiteIndex);
730}
731
732bool MIParser::parseBasicBlockDefinition(
735 unsigned ID = 0;
736 if (getUnsigned(ID))
737 return true;
738 auto Loc = Token.location();
739 auto Name = Token.stringValue();
740 lex();
741 bool MachineBlockAddressTaken = false;
742 bool LabelMustBeEmitted = false;
743 BasicBlock *AddressTakenIRBlock = nullptr;
744 bool IsLandingPad = false;
745 bool IsInlineAsmBrIndirectTarget = false;
746 bool IsEHFuncletEntry = false;
747 bool IsEHScopeEntry = false;
748 bool IsCleanupFuncletEntry = false;
749 bool IsEHContTarget = false;
750 std::optional<MBBSectionID> SectionID;
752 unsigned MaxBytesForAlignment = 0;
753 std::optional<UniqueBBID> BBID;
754 unsigned CallFrameSize = 0;
755 BasicBlock *BB = nullptr;
756 if (consumeIfPresent(MIToken::lparen)) {
757 do {
758 // TODO: Report an error when multiple same attributes are specified.
759 switch (Token.kind()) {
761 MachineBlockAddressTaken = true;
762 lex();
763 break;
765 LabelMustBeEmitted = true;
766 lex();
767 break;
769 if (parseIRBlockAddressTaken(AddressTakenIRBlock))
770 return true;
771 break;
773 IsLandingPad = true;
774 lex();
775 break;
777 IsInlineAsmBrIndirectTarget = true;
778 lex();
779 break;
781 IsEHFuncletEntry = true;
782 lex();
783 break;
785 IsEHScopeEntry = true;
786 lex();
787 break;
789 IsCleanupFuncletEntry = true;
790 lex();
791 break;
793 IsEHContTarget = true;
794 lex();
795 break;
797 if (parseAlignment(Alignment))
798 return true;
799 break;
801 if (parseMaxBytesForAlignment(MaxBytesForAlignment))
802 return true;
803 break;
804 case MIToken::IRBlock:
806 // TODO: Report an error when both name and ir block are specified.
807 if (parseIRBlock(BB, MF.getFunction()))
808 return true;
809 lex();
810 break;
812 if (parseSectionID(SectionID))
813 return true;
814 break;
816 if (parseBBID(BBID))
817 return true;
818 break;
820 if (parseCallFrameSize(CallFrameSize))
821 return true;
822 break;
823 default:
824 break;
825 }
826 } while (consumeIfPresent(MIToken::comma));
827 if (expectAndConsume(MIToken::rparen))
828 return true;
829 }
830 if (expectAndConsume(MIToken::colon))
831 return true;
832
833 if (!Name.empty()) {
835 MF.getFunction().getValueSymbolTable()->lookup(Name));
836 if (!BB)
837 return error(Loc, Twine("basic block '") + Name +
838 "' is not defined in the function '" +
839 MF.getName() + "'");
840 }
841 auto *MBB = MF.CreateMachineBasicBlock(BB, BBID);
842 MF.insert(MF.end(), MBB);
843 bool WasInserted = MBBSlots.insert(std::make_pair(ID, MBB)).second;
844 if (!WasInserted)
845 return error(Loc, Twine("redefinition of machine basic block with id #") +
846 Twine(ID));
847 if (Alignment)
848 MBB->setAlignment(Align(Alignment));
849 else if (MaxBytesForAlignment)
850 return error(Loc, "'max-bytes-for-alignment' requires 'align'");
851 MBB->setMaxBytesForAlignment(MaxBytesForAlignment);
852 if (MachineBlockAddressTaken)
854 if (LabelMustBeEmitted)
856 if (AddressTakenIRBlock)
857 MBB->setAddressTakenIRBlock(AddressTakenIRBlock);
858 MBB->setIsEHPad(IsLandingPad);
859 MBB->setIsInlineAsmBrIndirectTarget(IsInlineAsmBrIndirectTarget);
860 MBB->setIsEHFuncletEntry(IsEHFuncletEntry);
861 MBB->setIsEHScopeEntry(IsEHScopeEntry);
862 MBB->setIsCleanupFuncletEntry(IsCleanupFuncletEntry);
863 MBB->setIsEHContTarget(IsEHContTarget);
864 if (SectionID) {
865 MBB->setSectionID(*SectionID);
866 MF.setBBSectionsType(BasicBlockSection::List);
867 }
868 MBB->setCallFrameSize(CallFrameSize);
869 return false;
870}
871
872bool MIParser::parseBasicBlockDefinitions(
874 lex();
875 // Skip until the first machine basic block.
876 while (Token.is(MIToken::Newline))
877 lex();
878 if (Token.isErrorOrEOF())
879 return Token.isError();
880 if (Token.isNot(MIToken::MachineBasicBlockLabel))
881 return error("expected a basic block definition before instructions");
882 unsigned BraceDepth = 0;
883 do {
884 if (parseBasicBlockDefinition(MBBSlots))
885 return true;
886 bool IsAfterNewline = false;
887 // Skip until the next machine basic block.
888 while (true) {
889 if ((Token.is(MIToken::MachineBasicBlockLabel) && IsAfterNewline) ||
890 Token.isErrorOrEOF())
891 break;
892 else if (Token.is(MIToken::MachineBasicBlockLabel))
893 return error("basic block definition should be located at the start of "
894 "the line");
895 else if (consumeIfPresent(MIToken::Newline)) {
896 IsAfterNewline = true;
897 continue;
898 }
899 IsAfterNewline = false;
900 if (Token.is(MIToken::lbrace))
901 ++BraceDepth;
902 if (Token.is(MIToken::rbrace)) {
903 if (!BraceDepth)
904 return error("extraneous closing brace ('}')");
905 --BraceDepth;
906 }
907 lex();
908 }
909 // Verify that we closed all of the '{' at the end of a file or a block.
910 if (!Token.isError() && BraceDepth)
911 return error("expected '}'"); // FIXME: Report a note that shows '{'.
912 } while (!Token.isErrorOrEOF());
913 return Token.isError();
914}
915
916bool MIParser::parseBasicBlockLiveins(MachineBasicBlock &MBB) {
917 assert(Token.is(MIToken::kw_liveins));
918 lex();
919 if (expectAndConsume(MIToken::colon))
920 return true;
921 if (Token.isNewlineOrEOF()) // Allow an empty list of liveins.
922 return false;
923 do {
924 if (Token.isNot(MIToken::NamedRegister))
925 return error("expected a named register");
927 if (parseNamedRegister(Reg))
928 return true;
929 lex();
931 if (consumeIfPresent(MIToken::colon)) {
932 // Parse lane mask.
933 if (Token.isNot(MIToken::IntegerLiteral) &&
934 Token.isNot(MIToken::HexLiteral))
935 return error("expected a lane mask");
936 static_assert(sizeof(LaneBitmask::Type) == sizeof(uint64_t),
937 "Use correct get-function for lane mask");
939 if (getUint64(V))
940 return error("invalid lane mask value");
941 Mask = LaneBitmask(V);
942 lex();
943 }
944 MBB.addLiveIn(Reg, Mask);
945 } while (consumeIfPresent(MIToken::comma));
946 return false;
947}
948
949bool MIParser::parseBasicBlockSuccessors(MachineBasicBlock &MBB) {
951 lex();
952 if (expectAndConsume(MIToken::colon))
953 return true;
954 if (Token.isNewlineOrEOF()) // Allow an empty list of successors.
955 return false;
956 do {
957 if (Token.isNot(MIToken::MachineBasicBlock))
958 return error("expected a machine basic block reference");
959 MachineBasicBlock *SuccMBB = nullptr;
960 if (parseMBBReference(SuccMBB))
961 return true;
962 lex();
963 unsigned Weight = 0;
964 if (consumeIfPresent(MIToken::lparen)) {
965 if (Token.isNot(MIToken::IntegerLiteral) &&
966 Token.isNot(MIToken::HexLiteral))
967 return error("expected an integer literal after '('");
968 if (getUnsigned(Weight))
969 return true;
970 lex();
971 if (expectAndConsume(MIToken::rparen))
972 return true;
973 }
975 } while (consumeIfPresent(MIToken::comma));
977 return false;
978}
979
980bool MIParser::parseBasicBlock(MachineBasicBlock &MBB,
981 MachineBasicBlock *&AddFalthroughFrom) {
982 // Skip the definition.
984 lex();
985 if (consumeIfPresent(MIToken::lparen)) {
986 while (Token.isNot(MIToken::rparen) && !Token.isErrorOrEOF())
987 lex();
988 consumeIfPresent(MIToken::rparen);
989 }
990 consumeIfPresent(MIToken::colon);
991
992 // Parse the liveins and successors.
993 // N.B: Multiple lists of successors and liveins are allowed and they're
994 // merged into one.
995 // Example:
996 // liveins: $edi
997 // liveins: $esi
998 //
999 // is equivalent to
1000 // liveins: $edi, $esi
1001 bool ExplicitSuccessors = false;
1002 while (true) {
1003 if (Token.is(MIToken::kw_successors)) {
1004 if (parseBasicBlockSuccessors(MBB))
1005 return true;
1006 ExplicitSuccessors = true;
1007 } else if (Token.is(MIToken::kw_liveins)) {
1008 if (parseBasicBlockLiveins(MBB))
1009 return true;
1010 } else if (consumeIfPresent(MIToken::Newline)) {
1011 continue;
1012 } else {
1013 break;
1014 }
1015 if (!Token.isNewlineOrEOF())
1016 return error("expected line break at the end of a list");
1017 lex();
1018 }
1019
1020 // Parse the instructions.
1021 bool IsInBundle = false;
1022 MachineInstr *PrevMI = nullptr;
1023 while (!Token.is(MIToken::MachineBasicBlockLabel) &&
1024 !Token.is(MIToken::Eof)) {
1025 if (consumeIfPresent(MIToken::Newline))
1026 continue;
1027 if (consumeIfPresent(MIToken::rbrace)) {
1028 // The first parsing pass should verify that all closing '}' have an
1029 // opening '{'.
1030 assert(IsInBundle);
1031 IsInBundle = false;
1032 continue;
1033 }
1034 MachineInstr *MI = nullptr;
1035 if (parse(MI))
1036 return true;
1037 MBB.insert(MBB.end(), MI);
1038 if (IsInBundle) {
1040 MI->setFlag(MachineInstr::BundledPred);
1041 }
1042 PrevMI = MI;
1043 if (Token.is(MIToken::lbrace)) {
1044 if (IsInBundle)
1045 return error("nested instruction bundles are not allowed");
1046 lex();
1047 // This instruction is the start of the bundle.
1048 MI->setFlag(MachineInstr::BundledSucc);
1049 IsInBundle = true;
1050 if (!Token.is(MIToken::Newline))
1051 // The next instruction can be on the same line.
1052 continue;
1053 }
1054 assert(Token.isNewlineOrEOF() && "MI is not fully parsed");
1055 lex();
1056 }
1057
1058 // Construct successor list by searching for basic block machine operands.
1059 if (!ExplicitSuccessors) {
1061 bool IsFallthrough;
1062 guessSuccessors(MBB, Successors, IsFallthrough);
1063 for (MachineBasicBlock *Succ : Successors)
1064 MBB.addSuccessor(Succ);
1065
1066 if (IsFallthrough) {
1067 AddFalthroughFrom = &MBB;
1068 } else {
1070 }
1071 }
1072
1073 return false;
1074}
1075
1076bool MIParser::parseBasicBlocks() {
1077 lex();
1078 // Skip until the first machine basic block.
1079 while (Token.is(MIToken::Newline))
1080 lex();
1081 if (Token.isErrorOrEOF())
1082 return Token.isError();
1083 // The first parsing pass should have verified that this token is a MBB label
1084 // in the 'parseBasicBlockDefinitions' method.
1086 MachineBasicBlock *AddFalthroughFrom = nullptr;
1087 do {
1088 MachineBasicBlock *MBB = nullptr;
1090 return true;
1091 if (AddFalthroughFrom) {
1092 if (!AddFalthroughFrom->isSuccessor(MBB))
1093 AddFalthroughFrom->addSuccessor(MBB);
1094 AddFalthroughFrom->normalizeSuccProbs();
1095 AddFalthroughFrom = nullptr;
1096 }
1097 if (parseBasicBlock(*MBB, AddFalthroughFrom))
1098 return true;
1099 // The method 'parseBasicBlock' should parse the whole block until the next
1100 // block or the end of file.
1101 assert(Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof));
1102 } while (Token.isNot(MIToken::Eof));
1103 return false;
1104}
1105
1106bool MIParser::parse(MachineInstr *&MI) {
1107 // Parse any register operands before '='
1110 while (Token.isRegister() || Token.isRegisterFlag()) {
1111 auto Loc = Token.location();
1112 std::optional<unsigned> TiedDefIdx;
1113 if (parseRegisterOperand(MO, TiedDefIdx, /*IsDef=*/true))
1114 return true;
1115 Operands.push_back(
1116 ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx));
1117 if (Token.isNot(MIToken::comma))
1118 break;
1119 lex();
1120 }
1121 if (!Operands.empty() && expectAndConsume(MIToken::equal))
1122 return true;
1123
1124 unsigned OpCode, Flags = 0;
1125 if (Token.isError() || parseInstruction(OpCode, Flags))
1126 return true;
1127
1128 // Parse the remaining machine operands.
1129 while (!Token.isNewlineOrEOF() && Token.isNot(MIToken::kw_pre_instr_symbol) &&
1130 Token.isNot(MIToken::kw_post_instr_symbol) &&
1131 Token.isNot(MIToken::kw_heap_alloc_marker) &&
1132 Token.isNot(MIToken::kw_pcsections) && Token.isNot(MIToken::kw_mmra) &&
1133 Token.isNot(MIToken::kw_cfi_type) &&
1134 Token.isNot(MIToken::kw_deactivation_symbol) &&
1135 Token.isNot(MIToken::kw_debug_location) &&
1136 Token.isNot(MIToken::kw_debug_instr_number) &&
1137 Token.isNot(MIToken::coloncolon) && Token.isNot(MIToken::lbrace)) {
1138 auto Loc = Token.location();
1139 std::optional<unsigned> TiedDefIdx;
1140 if (parseMachineOperandAndTargetFlags(OpCode, Operands.size(), MO, TiedDefIdx))
1141 return true;
1142 Operands.push_back(
1143 ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx));
1144 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
1145 Token.is(MIToken::lbrace))
1146 break;
1147 if (Token.isNot(MIToken::comma))
1148 return error("expected ',' before the next machine operand");
1149 lex();
1150 }
1151
1152 MCSymbol *PreInstrSymbol = nullptr;
1153 if (Token.is(MIToken::kw_pre_instr_symbol))
1154 if (parsePreOrPostInstrSymbol(PreInstrSymbol))
1155 return true;
1156 MCSymbol *PostInstrSymbol = nullptr;
1157 if (Token.is(MIToken::kw_post_instr_symbol))
1158 if (parsePreOrPostInstrSymbol(PostInstrSymbol))
1159 return true;
1160 MDNode *HeapAllocMarker = nullptr;
1161 if (Token.is(MIToken::kw_heap_alloc_marker))
1162 if (parseHeapAllocMarker(HeapAllocMarker))
1163 return true;
1164 MDNode *PCSections = nullptr;
1165 if (Token.is(MIToken::kw_pcsections))
1166 if (parsePCSections(PCSections))
1167 return true;
1168 MDNode *MMRA = nullptr;
1169 if (Token.is(MIToken::kw_mmra) && parseMMRA(MMRA))
1170 return true;
1171 unsigned CFIType = 0;
1172 if (Token.is(MIToken::kw_cfi_type)) {
1173 lex();
1174 if (Token.isNot(MIToken::IntegerLiteral))
1175 return error("expected an integer literal after 'cfi-type'");
1176 // getUnsigned is sufficient for 32-bit integers.
1177 if (getUnsigned(CFIType))
1178 return true;
1179 lex();
1180 // Lex past trailing comma if present.
1181 if (Token.is(MIToken::comma))
1182 lex();
1183 }
1184
1185 GlobalValue *DS = nullptr;
1186 if (Token.is(MIToken::kw_deactivation_symbol)) {
1187 lex();
1188 if (parseGlobalValue(DS))
1189 return true;
1190 lex();
1191 }
1192
1193 unsigned InstrNum = 0;
1194 if (Token.is(MIToken::kw_debug_instr_number)) {
1195 lex();
1196 if (Token.isNot(MIToken::IntegerLiteral))
1197 return error("expected an integer literal after 'debug-instr-number'");
1198 if (getUnsigned(InstrNum))
1199 return true;
1200 lex();
1201 // Lex past trailing comma if present.
1202 if (Token.is(MIToken::comma))
1203 lex();
1204 }
1205
1206 DebugLoc DebugLocation;
1207 if (Token.is(MIToken::kw_debug_location)) {
1208 lex();
1209 MDNode *Node = nullptr;
1210 if (Token.is(MIToken::exclaim)) {
1211 if (parseMDNode(Node))
1212 return true;
1213 } else if (Token.is(MIToken::md_dilocation)) {
1214 if (parseDILocation(Node))
1215 return true;
1216 } else {
1217 return error("expected a metadata node after 'debug-location'");
1218 }
1219 DebugLocation = DebugLoc(dyn_cast<DILocation>(Node));
1220 if (!DebugLocation)
1221 return error("referenced metadata is not a DILocation");
1222 }
1223
1224 // Parse the machine memory operands.
1226 if (Token.is(MIToken::coloncolon)) {
1227 lex();
1228 while (!Token.isNewlineOrEOF()) {
1229 MachineMemOperand *MemOp = nullptr;
1230 if (parseMachineMemoryOperand(MemOp))
1231 return true;
1232 MemOperands.push_back(MemOp);
1233 if (Token.isNewlineOrEOF())
1234 break;
1235 if (OpCode == TargetOpcode::BUNDLE && Token.is(MIToken::lbrace))
1236 break;
1237 if (Token.isNot(MIToken::comma))
1238 return error("expected ',' before the next machine memory operand");
1239 lex();
1240 }
1241 }
1242
1243 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
1244 if (!MCID.isVariadic()) {
1245 // FIXME: Move the implicit operand verification to the machine verifier.
1246 if (verifyImplicitOperands(Operands, MCID))
1247 return true;
1248 }
1249
1250 MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
1251 MI->setFlags(Flags);
1252
1253 // Don't check the operands make sense, let the verifier catch any
1254 // improprieties.
1255 for (const auto &Operand : Operands)
1256 MI->addOperand(MF, Operand.Operand);
1257
1258 if (assignRegisterTies(*MI, Operands))
1259 return true;
1260 if (PreInstrSymbol)
1261 MI->setPreInstrSymbol(MF, PreInstrSymbol);
1262 if (PostInstrSymbol)
1263 MI->setPostInstrSymbol(MF, PostInstrSymbol);
1264 if (HeapAllocMarker)
1265 MI->setHeapAllocMarker(MF, HeapAllocMarker);
1266 if (PCSections)
1267 MI->setPCSections(MF, PCSections);
1268 if (MMRA)
1269 MI->setMMRAMetadata(MF, MMRA);
1270 if (CFIType)
1271 MI->setCFIType(MF, CFIType);
1272 if (DS)
1273 MI->setDeactivationSymbol(MF, DS);
1274 if (!MemOperands.empty())
1275 MI->setMemRefs(MF, MemOperands);
1276 if (InstrNum)
1277 MI->setDebugInstrNum(InstrNum);
1278 return false;
1279}
1280
1281bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
1282 lex();
1283 if (Token.isNot(MIToken::MachineBasicBlock))
1284 return error("expected a machine basic block reference");
1286 return true;
1287 lex();
1288 if (Token.isNot(MIToken::Eof))
1289 return error(
1290 "expected end of string after the machine basic block reference");
1291 return false;
1292}
1293
1294bool MIParser::parseStandaloneNamedRegister(Register &Reg) {
1295 lex();
1296 if (Token.isNot(MIToken::NamedRegister))
1297 return error("expected a named register");
1298 if (parseNamedRegister(Reg))
1299 return true;
1300 lex();
1301 if (Token.isNot(MIToken::Eof))
1302 return error("expected end of string after the register reference");
1303 return false;
1304}
1305
1306bool MIParser::parseStandaloneVirtualRegister(VRegInfo *&Info) {
1307 lex();
1308 if (Token.isNot(MIToken::VirtualRegister))
1309 return error("expected a virtual register");
1310 if (parseVirtualRegister(Info))
1311 return true;
1312 lex();
1313 if (Token.isNot(MIToken::Eof))
1314 return error("expected end of string after the register reference");
1315 return false;
1316}
1317
1318bool MIParser::parseStandaloneRegister(Register &Reg) {
1319 lex();
1320 if (Token.isNot(MIToken::NamedRegister) &&
1321 Token.isNot(MIToken::VirtualRegister))
1322 return error("expected either a named or virtual register");
1323
1324 VRegInfo *Info;
1325 if (parseRegister(Reg, Info))
1326 return true;
1327
1328 lex();
1329 if (Token.isNot(MIToken::Eof))
1330 return error("expected end of string after the register reference");
1331 return false;
1332}
1333
1334bool MIParser::parseStandaloneStackObject(int &FI) {
1335 lex();
1336 if (Token.isNot(MIToken::StackObject))
1337 return error("expected a stack object");
1338 if (parseStackFrameIndex(FI))
1339 return true;
1340 if (Token.isNot(MIToken::Eof))
1341 return error("expected end of string after the stack object reference");
1342 return false;
1343}
1344
1345bool MIParser::parseStandaloneMDNode(MDNode *&Node) {
1346 lex();
1347 if (Token.is(MIToken::exclaim)) {
1348 if (parseMDNode(Node))
1349 return true;
1350 } else if (Token.is(MIToken::md_diexpr)) {
1351 if (parseDIExpression(Node))
1352 return true;
1353 } else if (Token.is(MIToken::md_dilocation)) {
1354 if (parseDILocation(Node))
1355 return true;
1356 } else {
1357 return error("expected a metadata node");
1358 }
1359 if (Token.isNot(MIToken::Eof))
1360 return error("expected end of string after the metadata node");
1361 return false;
1362}
1363
1364static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
1365 assert(MO.isImplicit());
1366 return MO.isDef() ? "implicit-def" : "implicit";
1367}
1368
1369static std::string getRegisterName(const TargetRegisterInfo *TRI,
1370 Register Reg) {
1371 assert(Reg.isPhysical() && "expected phys reg");
1372 return StringRef(TRI->getName(Reg)).lower();
1373}
1374
1375/// Return true if the parsed machine operands contain a given machine operand.
1376static bool isImplicitOperandIn(const MachineOperand &ImplicitOperand,
1378 for (const auto &I : Operands) {
1379 if (ImplicitOperand.isIdenticalTo(I.Operand))
1380 return true;
1381 }
1382 return false;
1383}
1384
1385bool MIParser::verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands,
1386 const MCInstrDesc &MCID) {
1387 if (MCID.isCall())
1388 // We can't verify call instructions as they can contain arbitrary implicit
1389 // register and register mask operands.
1390 return false;
1391
1392 // Gather all the expected implicit operands.
1393 SmallVector<MachineOperand, 4> ImplicitOperands;
1394 for (MCPhysReg ImpDef : MCID.implicit_defs())
1395 ImplicitOperands.push_back(MachineOperand::CreateReg(ImpDef, true, true));
1396 for (MCPhysReg ImpUse : MCID.implicit_uses())
1397 ImplicitOperands.push_back(MachineOperand::CreateReg(ImpUse, false, true));
1398
1399 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1400 assert(TRI && "Expected target register info");
1401 for (const auto &I : ImplicitOperands) {
1403 continue;
1404 return error(Operands.empty() ? Token.location() : Operands.back().End,
1405 Twine("missing implicit register operand '") +
1407 getRegisterName(TRI, I.getReg()) + "'");
1408 }
1409 return false;
1410}
1411
1412bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
1413 // Allow frame and fast math flags for OPCODE
1414 // clang-format off
1415 while (Token.is(MIToken::kw_frame_setup) ||
1416 Token.is(MIToken::kw_frame_destroy) ||
1417 Token.is(MIToken::kw_nnan) ||
1418 Token.is(MIToken::kw_ninf) ||
1419 Token.is(MIToken::kw_nsz) ||
1420 Token.is(MIToken::kw_arcp) ||
1421 Token.is(MIToken::kw_contract) ||
1422 Token.is(MIToken::kw_afn) ||
1423 Token.is(MIToken::kw_reassoc) ||
1424 Token.is(MIToken::kw_nuw) ||
1425 Token.is(MIToken::kw_nsw) ||
1426 Token.is(MIToken::kw_exact) ||
1427 Token.is(MIToken::kw_nofpexcept) ||
1428 Token.is(MIToken::kw_noconvergent) ||
1429 Token.is(MIToken::kw_unpredictable) ||
1430 Token.is(MIToken::kw_nneg) ||
1431 Token.is(MIToken::kw_disjoint) ||
1432 Token.is(MIToken::kw_nusw) ||
1433 Token.is(MIToken::kw_samesign) ||
1434 Token.is(MIToken::kw_inbounds) ||
1435 Token.is(MIToken::kw_nonnull) ||
1436 Token.is(MIToken::kw_lr_split)) {
1437 // clang-format on
1438 // Mine frame and fast math flags
1439 if (Token.is(MIToken::kw_frame_setup))
1441 if (Token.is(MIToken::kw_frame_destroy))
1443 if (Token.is(MIToken::kw_nnan))
1445 if (Token.is(MIToken::kw_ninf))
1447 if (Token.is(MIToken::kw_nsz))
1449 if (Token.is(MIToken::kw_arcp))
1451 if (Token.is(MIToken::kw_contract))
1453 if (Token.is(MIToken::kw_afn))
1455 if (Token.is(MIToken::kw_reassoc))
1457 if (Token.is(MIToken::kw_nuw))
1459 if (Token.is(MIToken::kw_nsw))
1461 if (Token.is(MIToken::kw_exact))
1463 if (Token.is(MIToken::kw_nofpexcept))
1465 if (Token.is(MIToken::kw_unpredictable))
1467 if (Token.is(MIToken::kw_noconvergent))
1469 if (Token.is(MIToken::kw_nneg))
1471 if (Token.is(MIToken::kw_disjoint))
1473 if (Token.is(MIToken::kw_nusw))
1475 if (Token.is(MIToken::kw_samesign))
1477 if (Token.is(MIToken::kw_inbounds))
1479 if (Token.is(MIToken::kw_nonnull))
1481 if (Token.is(MIToken::kw_lr_split))
1483
1484 lex();
1485 }
1486 if (Token.isNot(MIToken::Identifier))
1487 return error("expected a machine instruction");
1488 StringRef InstrName = Token.stringValue();
1489 if (PFS.Target.parseInstrName(InstrName, OpCode))
1490 return error(Twine("unknown machine instruction name '") + InstrName + "'");
1491 lex();
1492 return false;
1493}
1494
1495bool MIParser::parseNamedRegister(Register &Reg) {
1496 assert(Token.is(MIToken::NamedRegister) && "Needs NamedRegister token");
1497 StringRef Name = Token.stringValue();
1498 if (PFS.Target.getRegisterByName(Name, Reg))
1499 return error(Twine("unknown register name '") + Name + "'");
1500 return false;
1501}
1502
1503bool MIParser::parseNamedVirtualRegister(VRegInfo *&Info) {
1504 assert(Token.is(MIToken::NamedVirtualRegister) && "Expected NamedVReg token");
1505 StringRef Name = Token.stringValue();
1506 // TODO: Check that the VReg name is not the same as a physical register name.
1507 // If it is, then print a warning (when warnings are implemented).
1508 Info = &PFS.getVRegInfoNamed(Name);
1509 return false;
1510}
1511
1512bool MIParser::parseVirtualRegister(VRegInfo *&Info) {
1513 if (Token.is(MIToken::NamedVirtualRegister))
1514 return parseNamedVirtualRegister(Info);
1515 assert(Token.is(MIToken::VirtualRegister) && "Needs VirtualRegister token");
1516 unsigned ID;
1517 if (getUnsigned(ID))
1518 return true;
1519 Info = &PFS.getVRegInfo(ID);
1520 return false;
1521}
1522
1523bool MIParser::parseRegister(Register &Reg, VRegInfo *&Info) {
1524 switch (Token.kind()) {
1526 Reg = 0;
1527 return false;
1529 return parseNamedRegister(Reg);
1532 if (parseVirtualRegister(Info))
1533 return true;
1534 Reg = Info->VReg;
1535 return false;
1536 // TODO: Parse other register kinds.
1537 default:
1538 llvm_unreachable("The current token should be a register");
1539 }
1540}
1541
1542bool MIParser::parseRegisterClassOrBank(VRegInfo &RegInfo) {
1543 if (Token.isNot(MIToken::Identifier) && Token.isNot(MIToken::underscore))
1544 return error("expected '_', register class, or register bank name");
1545 StringRef::iterator Loc = Token.location();
1546 StringRef Name = Token.stringValue();
1547
1548 // Was it a register class?
1549 const TargetRegisterClass *RC = PFS.Target.getRegClass(Name);
1550 if (RC) {
1551 lex();
1552
1553 switch (RegInfo.Kind) {
1554 case VRegInfo::UNKNOWN:
1555 case VRegInfo::NORMAL:
1556 RegInfo.Kind = VRegInfo::NORMAL;
1557 if (RegInfo.Explicit && RegInfo.D.RC != RC) {
1558 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1559 return error(Loc, Twine("conflicting register classes, previously: ") +
1560 Twine(TRI.getRegClassName(RegInfo.D.RC)));
1561 }
1562 RegInfo.D.RC = RC;
1563 RegInfo.Explicit = true;
1564 return false;
1565
1566 case VRegInfo::GENERIC:
1567 case VRegInfo::REGBANK:
1568 return error(Loc, "register class specification on generic register");
1569 }
1570 llvm_unreachable("Unexpected register kind");
1571 }
1572
1573 // Should be a register bank or a generic register.
1574 const RegisterBank *RegBank = nullptr;
1575 if (Name != "_") {
1576 RegBank = PFS.Target.getRegBank(Name);
1577 if (!RegBank)
1578 return error(Loc, "expected '_', register class, or register bank name");
1579 }
1580
1581 lex();
1582
1583 switch (RegInfo.Kind) {
1584 case VRegInfo::UNKNOWN:
1585 case VRegInfo::GENERIC:
1586 case VRegInfo::REGBANK:
1587 RegInfo.Kind = RegBank ? VRegInfo::REGBANK : VRegInfo::GENERIC;
1588 if (RegInfo.Explicit && RegInfo.D.RegBank != RegBank)
1589 return error(Loc, "conflicting generic register banks");
1590 RegInfo.D.RegBank = RegBank;
1591 RegInfo.Explicit = true;
1592 return false;
1593
1594 case VRegInfo::NORMAL:
1595 return error(Loc, "register bank specification on normal register");
1596 }
1597 llvm_unreachable("Unexpected register kind");
1598}
1599
1600bool MIParser::parseRegisterFlag(RegState &Flags) {
1601 const RegState OldFlags = Flags;
1602 switch (Token.kind()) {
1605 break;
1608 break;
1609 case MIToken::kw_def:
1611 break;
1612 case MIToken::kw_dead:
1614 break;
1615 case MIToken::kw_killed:
1617 break;
1618 case MIToken::kw_undef:
1620 break;
1623 break;
1626 break;
1629 break;
1632 break;
1633 default:
1634 llvm_unreachable("The current token should be a register flag");
1635 }
1636 if (OldFlags == Flags)
1637 // We know that the same flag is specified more than once when the flags
1638 // weren't modified.
1639 return error("duplicate '" + Token.stringValue() + "' register flag");
1640 lex();
1641 return false;
1642}
1643
1644bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
1645 assert(Token.is(MIToken::dot));
1646 lex();
1647 if (Token.isNot(MIToken::Identifier))
1648 return error("expected a subregister index after '.'");
1649 auto Name = Token.stringValue();
1650 SubReg = PFS.Target.getSubRegIndex(Name);
1651 if (!SubReg)
1652 return error(Twine("use of unknown subregister index '") + Name + "'");
1653 lex();
1654 return false;
1655}
1656
1657bool MIParser::parseRegisterTiedDefIndex(unsigned &TiedDefIdx) {
1658 assert(Token.is(MIToken::kw_tied_def));
1659 lex();
1660 if (Token.isNot(MIToken::IntegerLiteral))
1661 return error("expected an integer literal after 'tied-def'");
1662 if (getUnsigned(TiedDefIdx))
1663 return true;
1664 lex();
1665 return expectAndConsume(MIToken::rparen);
1666}
1667
1668bool MIParser::assignRegisterTies(MachineInstr &MI,
1670 SmallVector<std::pair<unsigned, unsigned>, 4> TiedRegisterPairs;
1671 for (unsigned I = 0, E = Operands.size(); I != E; ++I) {
1672 if (!Operands[I].TiedDefIdx)
1673 continue;
1674 // The parser ensures that this operand is a register use, so we just have
1675 // to check the tied-def operand.
1676 unsigned DefIdx = *Operands[I].TiedDefIdx;
1677 if (DefIdx >= E)
1678 return error(Operands[I].Begin,
1679 Twine("use of invalid tied-def operand index '" +
1680 Twine(DefIdx) + "'; instruction has only ") +
1681 Twine(E) + " operands");
1682 const auto &DefOperand = Operands[DefIdx].Operand;
1683 if (!DefOperand.isReg() || !DefOperand.isDef())
1684 // FIXME: add note with the def operand.
1685 return error(Operands[I].Begin,
1686 Twine("use of invalid tied-def operand index '") +
1687 Twine(DefIdx) + "'; the operand #" + Twine(DefIdx) +
1688 " isn't a defined register");
1689 // Check that the tied-def operand wasn't tied elsewhere.
1690 for (const auto &TiedPair : TiedRegisterPairs) {
1691 if (TiedPair.first == DefIdx)
1692 return error(Operands[I].Begin,
1693 Twine("the tied-def operand #") + Twine(DefIdx) +
1694 " is already tied with another register operand");
1695 }
1696 TiedRegisterPairs.push_back(std::make_pair(DefIdx, I));
1697 }
1698 // FIXME: Verify that for non INLINEASM instructions, the def and use tied
1699 // indices must be less than tied max.
1700 for (const auto &TiedPair : TiedRegisterPairs)
1701 MI.tieOperands(TiedPair.first, TiedPair.second);
1702 return false;
1703}
1704
1705bool MIParser::parseRegisterOperand(MachineOperand &Dest,
1706 std::optional<unsigned> &TiedDefIdx,
1707 bool IsDef) {
1708 RegState Flags = getDefRegState(IsDef);
1709 while (Token.isRegisterFlag()) {
1710 if (parseRegisterFlag(Flags))
1711 return true;
1712 }
1713 // Update IsDef as we may have read a def flag.
1714 IsDef = hasRegState(Flags, RegState::Define);
1715 if (!Token.isRegister())
1716 return error("expected a register after register flags");
1717 Register Reg;
1718 VRegInfo *RegInfo;
1719 if (parseRegister(Reg, RegInfo))
1720 return true;
1721 lex();
1722 unsigned SubReg = 0;
1723 if (Token.is(MIToken::dot)) {
1724 if (parseSubRegisterIndex(SubReg))
1725 return true;
1726 if (!Reg.isVirtual())
1727 return error("subregister index expects a virtual register");
1728 }
1729 if (Token.is(MIToken::colon)) {
1730 if (!Reg.isVirtual())
1731 return error("register class specification expects a virtual register");
1732 lex();
1733 if (parseRegisterClassOrBank(*RegInfo))
1734 return true;
1735 }
1736
1737 if (consumeIfPresent(MIToken::lparen)) {
1738 // For a def, we only expect a type. For use we expect either a type or a
1739 // tied-def. Additionally, for physical registers, we don't expect a type.
1740 if (Token.is(MIToken::kw_tied_def)) {
1741 if (IsDef)
1742 return error("tied-def not supported for defs");
1743 unsigned Idx;
1744 if (parseRegisterTiedDefIndex(Idx))
1745 return true;
1746 TiedDefIdx = Idx;
1747 } else {
1748 if (!Reg.isVirtual())
1749 return error("unexpected type on physical register");
1750
1751 LLT Ty;
1752 // If type parsing fails, forwad the parse error for defs.
1753 if (parseLowLevelType(Token.location(), Ty))
1754 return IsDef ? true
1755 : error("expected tied-def or low-level type after '('");
1756
1757 if (expectAndConsume(MIToken::rparen))
1758 return true;
1759
1760 MachineRegisterInfo &MRI = MF.getRegInfo();
1761 if (MRI.getType(Reg).isValid() && MRI.getType(Reg) != Ty)
1762 return error("inconsistent type for generic virtual register");
1763
1764 MRI.setRegClassOrRegBank(Reg, static_cast<RegisterBank *>(nullptr));
1765 MRI.setType(Reg, Ty);
1767 }
1768 } else if (IsDef && Reg.isVirtual()) {
1769 // Generic virtual registers defs must have a type.
1770 if (RegInfo->Kind == VRegInfo::GENERIC ||
1771 RegInfo->Kind == VRegInfo::REGBANK)
1772 return error("generic virtual registers must have a type");
1773 }
1774
1775 if (IsDef) {
1776 if (hasRegState(Flags, RegState::Kill))
1777 return error("cannot have a killed def operand");
1778 } else {
1779 if (hasRegState(Flags, RegState::Dead))
1780 return error("cannot have a dead use operand");
1781 }
1782
1784 Reg, IsDef, hasRegState(Flags, RegState::Implicit),
1787 hasRegState(Flags, RegState::EarlyClobber), SubReg,
1791
1792 return false;
1793}
1794
1795bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
1797 const APSInt &Int = Token.integerValue();
1798 if (auto SImm = Int.trySExtValue(); Int.isSigned() && SImm.has_value())
1799 Dest = MachineOperand::CreateImm(*SImm);
1800 else if (auto UImm = Int.tryZExtValue(); !Int.isSigned() && UImm.has_value())
1801 Dest = MachineOperand::CreateImm(*UImm);
1802 else
1803 return error("integer literal is too large to be an immediate operand");
1804 lex();
1805 return false;
1806}
1807
1808bool MIParser::parseSymbolicInlineAsmOperand(unsigned OpIdx,
1809 MachineOperand &Dest) {
1811 assert(Token.is(MIToken::Identifier) &&
1812 "expected symbolic inline asm operand");
1813
1814 // Parse ExtraInfo flags.
1815 if (OpIdx == InlineAsm::MIOp_ExtraInfo) {
1816 unsigned ExtraInfo = 0;
1817 for (;;) {
1818 if (Token.isNot(MIToken::Identifier))
1819 break;
1820
1821 StringRef FlagName = Token.stringValue();
1822 unsigned Flag = StringSwitch<unsigned>(FlagName)
1824 .Case("mayload", InlineAsm::Extra_MayLoad)
1825 .Case("maystore", InlineAsm::Extra_MayStore)
1826 .Case("isconvergent", InlineAsm::Extra_IsConvergent)
1827 .Case("alignstack", InlineAsm::Extra_IsAlignStack)
1829 .Case("attdialect", 0)
1830 .Case("inteldialect", InlineAsm::Extra_AsmDialect)
1831 .Default(~0u);
1832 if (Flag == ~0u)
1833 return error("unknown inline asm extra info flag '" + FlagName + "'");
1834
1835 ExtraInfo |= Flag;
1836 lex();
1837 }
1838
1839 Dest = MachineOperand::CreateImm(ExtraInfo);
1840 return false;
1841 }
1842
1843 // Parse symbolic form: kind[:constraint].
1844 StringRef KindStr = Token.stringValue();
1845 constexpr auto InvalidKind = static_cast<InlineAsm::Kind>(0);
1848 .Case("regdef", InlineAsm::Kind::RegDef)
1849 .Case("reguse", InlineAsm::Kind::RegUse)
1851 .Case("clobber", InlineAsm::Kind::Clobber)
1852 .Case("imm", InlineAsm::Kind::Imm)
1853 .Case("mem", InlineAsm::Kind::Mem)
1854 .Default(InvalidKind);
1855 if (K == InvalidKind)
1856 return error("unknown inline asm operand kind '" + KindStr + "'");
1857
1858 lex();
1859
1860 // Create the flag with default of 1 operand.
1861 InlineAsm::Flag F(K, 1);
1862
1863 // Parse optional tiedto constraint: tiedto:$N.
1864 if (Token.is(MIToken::Identifier) && Token.stringValue() == "tiedto") {
1865 lex();
1866 if (Token.isNot(MIToken::colon))
1867 return error("expected ':' after 'tiedto'");
1868 lex();
1869 if (Token.isNot(MIToken::NamedRegister))
1870 return error("expected '$N' operand number after 'tiedto:'");
1871 unsigned OperandNo;
1872 if (Token.stringValue().getAsInteger(10, OperandNo))
1873 return error("invalid operand number in tiedto constraint");
1874 lex();
1875
1876 F.setMatchingOp(OperandNo);
1877
1879 return false;
1880 }
1881
1882 // Parse an optional constraint after ':'.
1883 if (Token.is(MIToken::colon)) {
1884 lex();
1885
1886 if (Token.isNot(MIToken::Identifier))
1887 return error(
1888 "expected register class or memory constraint name after ':'");
1889
1890 StringRef ConstraintStr = Token.stringValue();
1891 if (F.isMemKind()) {
1925 return error("unknown memory constraint '" + ConstraintStr + "'");
1926 F.setMemConstraint(CC);
1927 } else if (F.isRegDefKind() || F.isRegUseKind() ||
1928 F.isRegDefEarlyClobberKind()) {
1929 const TargetRegisterClass *RC =
1930 PFS.Target.getRegClass(ConstraintStr.lower());
1931 if (!RC)
1932 return error("unknown register class '" + ConstraintStr + "'");
1933 F.setRegClass(RC->getID());
1934 }
1935
1936 lex();
1937 }
1938
1939 // Parse an optional 'foldable' marker: the register allocator may fold the
1940 // operand's register to a stack slot (see
1941 // InlineAsm::Flag::setRegMayBeFolded()).
1942 if (Token.is(MIToken::Identifier) && Token.stringValue() == "foldable") {
1943 if (!F.isRegDefKind() && !F.isRegUseKind() && !F.isRegDefEarlyClobberKind())
1944 return error("only a register operand can be 'foldable'");
1945
1946 F.setRegMayBeFolded(true);
1947 lex();
1948 }
1949
1951 return false;
1952}
1953
1954bool MIParser::parseTargetImmMnemonic(const unsigned OpCode,
1955 const unsigned OpIdx,
1956 MachineOperand &Dest,
1957 const MIRFormatter &MF) {
1958 assert(Token.is(MIToken::dot));
1959 auto Loc = Token.location(); // record start position
1960 size_t Len = 1; // for "."
1961 lex();
1962
1963 // Handle the case that mnemonic starts with number.
1964 if (Token.is(MIToken::IntegerLiteral)) {
1965 Len += Token.range().size();
1966 lex();
1967 }
1968
1969 StringRef Src;
1970 if (Token.is(MIToken::comma))
1971 Src = StringRef(Loc, Len);
1972 else {
1973 assert(Token.is(MIToken::Identifier));
1974 Src = StringRef(Loc, Len + Token.stringValue().size());
1975 }
1976 int64_t Val;
1977 if (MF.parseImmMnemonic(OpCode, OpIdx, Src, Val,
1978 [this](StringRef::iterator Loc, const Twine &Msg)
1979 -> bool { return error(Loc, Msg); }))
1980 return true;
1981
1982 Dest = MachineOperand::CreateImm(Val);
1983 if (!Token.is(MIToken::comma))
1984 lex();
1985 return false;
1986}
1987
1989 PerFunctionMIParsingState &PFS, const Constant *&C,
1990 ErrorCallbackType ErrCB) {
1991 auto Source = StringValue.str(); // The source has to be null terminated.
1992 SMDiagnostic Err;
1993 C = parseConstantValue(Source, Err, *PFS.MF.getFunction().getParent(),
1994 &PFS.IRSlots);
1995 if (!C)
1996 return ErrCB(Loc + Err.getColumnNo(), Err.getMessage());
1997 return false;
1998}
1999
2000bool MIParser::parseIRConstant(StringRef::iterator Loc, StringRef StringValue,
2001 const Constant *&C) {
2002 return ::parseIRConstant(
2003 Loc, StringValue, PFS, C,
2004 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
2005 return error(Loc, Msg);
2006 });
2007}
2008
2009bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
2010 if (parseIRConstant(Loc, StringRef(Loc, Token.range().end() - Loc), C))
2011 return true;
2012 lex();
2013 return false;
2014}
2015
2016// See LLT implementation for bit size limits.
2018 return Size != 0 && isUInt<16>(Size);
2019}
2020
2021static bool verifyVectorElementCount(uint64_t NumElts, bool HasVScale) {
2022 // A fixed-length vector needs at least two elements.
2023 return NumElts != 0 && (HasVScale || NumElts != 1) && isUInt<16>(NumElts);
2024}
2025
2026static bool verifyAddrSpace(uint64_t AddrSpace) {
2027 return isUInt<24>(AddrSpace);
2028}
2029
2030bool MIParser::parseLowLevelType(StringRef::iterator Loc, LLT &Ty) {
2031 StringRef TypeDigits = Token.range();
2032 if (TypeDigits.consume_front("s") || TypeDigits.consume_front("i") ||
2033 TypeDigits.consume_front("f") || TypeDigits.consume_front("p") ||
2034 TypeDigits.consume_front("bf")) {
2035 if (TypeDigits.empty() || !llvm::all_of(TypeDigits, isdigit))
2036 return error(
2037 "expected integers after 's'/'i'/'f'/'bf'/'p' type identifier");
2038 }
2039
2040 bool Scalar = Token.range().starts_with("s");
2041 if (Scalar || Token.range().starts_with("i")) {
2042 auto ScalarSize = APSInt(TypeDigits).getZExtValue();
2043 if (!ScalarSize) {
2044 Ty = LLT::token();
2045 lex();
2046 return false;
2047 }
2048
2049 if (!verifyScalarSize(ScalarSize))
2050 return error("invalid size for scalar type");
2051
2052 Ty = Scalar ? LLT::scalar(ScalarSize) : LLT::integer(ScalarSize);
2053 lex();
2054 return false;
2055 }
2056
2057 if (Token.range().starts_with("p")) {
2058 const DataLayout &DL = MF.getDataLayout();
2059 uint64_t AS = APSInt(TypeDigits).getZExtValue();
2060 if (!verifyAddrSpace(AS))
2061 return error("invalid address space number");
2062
2063 Ty = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
2064 lex();
2065 return false;
2066 }
2067
2068 if (Token.range().starts_with("f") || Token.range().starts_with("bf")) {
2069 auto ScalarSize = APSInt(TypeDigits).getZExtValue();
2070 if (!ScalarSize || !verifyScalarSize(ScalarSize))
2071 return error("invalid size for scalar type");
2072
2073 if (Token.range().starts_with("bf") && ScalarSize != 16)
2074 return error("invalid size for bfloat");
2075
2076 Ty = Token.range().starts_with("bf") ? LLT::bfloat16()
2077 : LLT::floatIEEE(ScalarSize);
2078 lex();
2079 return false;
2080 }
2081
2082 // Now we're looking for a vector.
2083 if (Token.isNot(MIToken::less))
2084 return error(Loc, "expected tN, pA, <M x tN>, <M x pA>, <vscale x M x tN>, "
2085 "or <vscale x M x pA> for GlobalISel type, "
2086 "where t = {'s', 'i', 'f', 'bf'}");
2087 lex();
2088
2089 bool HasVScale =
2090 Token.is(MIToken::Identifier) && Token.stringValue() == "vscale";
2091 if (HasVScale) {
2092 lex();
2093 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != "x")
2094 return error(
2095 "expected <vscale x M x tN>, where t = {'s', 'i', 'f', 'bf', 'p'}");
2096 lex();
2097 }
2098
2099 auto GetError = [this, &HasVScale, Loc]() {
2100 if (HasVScale)
2101 return error(Loc, "expected <vscale x M x tN> for vector type, where t = "
2102 "{'s', 'i', 'f', 'bf', 'p'}");
2103 return error(Loc, "expected <M x tN> for vector type, where t = {'s', 'i', "
2104 "'f', 'bf', 'p'}");
2105 };
2106
2107 if (Token.isNot(MIToken::IntegerLiteral))
2108 return GetError();
2109 uint64_t NumElements = Token.integerValue().getZExtValue();
2110 if (!verifyVectorElementCount(NumElements, HasVScale))
2111 return error("invalid number of vector elements");
2112
2113 lex();
2114
2115 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != "x")
2116 return GetError();
2117 lex();
2118
2119 StringRef VectorTyDigits = Token.range();
2120 if (!VectorTyDigits.consume_front("s") &&
2121 !VectorTyDigits.consume_front("i") &&
2122 !VectorTyDigits.consume_front("f") &&
2123 !VectorTyDigits.consume_front("p") && !VectorTyDigits.consume_front("bf"))
2124 return GetError();
2125
2126 if (VectorTyDigits.empty() || !llvm::all_of(VectorTyDigits, isdigit))
2127 return error(
2128 "expected integers after 's'/'i'/'f'/'bf'/'p' type identifier");
2129
2130 Scalar = Token.range().starts_with("s");
2131 if (Scalar || Token.range().starts_with("i")) {
2132 auto ScalarSize = APSInt(VectorTyDigits).getZExtValue();
2133 if (!verifyScalarSize(ScalarSize))
2134 return error("invalid size for scalar element in vector");
2135 Ty = Scalar ? LLT::scalar(ScalarSize) : LLT::integer(ScalarSize);
2136 } else if (Token.range().starts_with("p")) {
2137 const DataLayout &DL = MF.getDataLayout();
2138 uint64_t AS = APSInt(VectorTyDigits).getZExtValue();
2139 if (!verifyAddrSpace(AS))
2140 return error("invalid address space number");
2141
2142 Ty = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
2143 } else if (Token.range().starts_with("f")) {
2144 auto ScalarSize = APSInt(VectorTyDigits).getZExtValue();
2145 if (!verifyScalarSize(ScalarSize))
2146 return error("invalid size for float element in vector");
2147 Ty = LLT::floatIEEE(ScalarSize);
2148 } else if (Token.range().starts_with("bf")) {
2149 auto ScalarSize = APSInt(VectorTyDigits).getZExtValue();
2150 if (!verifyScalarSize(ScalarSize))
2151 return error("invalid size for bfloat element in vector");
2152 Ty = LLT::bfloat16();
2153 } else {
2154 return GetError();
2155 }
2156 lex();
2157
2158 if (Token.isNot(MIToken::greater))
2159 return GetError();
2160
2161 lex();
2162
2163 Ty = LLT::vector(ElementCount::get(NumElements, HasVScale), Ty);
2164 return false;
2165}
2166
2167bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) {
2168 assert(Token.is(MIToken::Identifier));
2169 StringRef TypeDigits = Token.range();
2170 if (!TypeDigits.consume_front("i") && !TypeDigits.consume_front("s") &&
2171 !TypeDigits.consume_front("p") && !TypeDigits.consume_front("f") &&
2172 !TypeDigits.consume_front("bf"))
2173 return error("a typed immediate operand should start with one of 'i', "
2174 "'s', 'f', 'bf', or 'p'");
2175 if (TypeDigits.empty() || !llvm::all_of(TypeDigits, isdigit))
2176 return error(
2177 "expected integers after 'i'/'s'/'f'/'bf'/'p' type identifier");
2178
2179 auto Loc = Token.location();
2180 lex();
2181 if (Token.isNot(MIToken::IntegerLiteral)) {
2182 if (Token.isNot(MIToken::Identifier) ||
2183 !(Token.range() == "true" || Token.range() == "false"))
2184 return error("expected an integer literal");
2185 }
2186 const Constant *C = nullptr;
2187 if (parseIRConstant(Loc, C))
2188 return true;
2190 return false;
2191}
2192
2193bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
2194 auto Loc = Token.location();
2195 lex();
2196 if (Token.isNot(MIToken::FloatingPointLiteral) &&
2197 Token.isNot(MIToken::HexLiteral))
2198 return error("expected a floating point literal");
2199 const Constant *C = nullptr;
2200 if (parseIRConstant(Loc, C))
2201 return true;
2203 return false;
2204}
2205
2206static bool getHexUint(const MIToken &Token, APInt &Result) {
2208 StringRef S = Token.range();
2209 assert(S[0] == '0' && tolower(S[1]) == 'x');
2210 // This could be a floating point literal with a special prefix.
2211 if (!isxdigit(S[2]))
2212 return true;
2213 StringRef V = S.substr(2);
2214 APInt A(V.size()*4, V, 16);
2215
2216 // If A is 0, then A.getActiveBits() is 0. This isn't a valid bitwidth. Make
2217 // sure it isn't the case before constructing result.
2218 unsigned NumBits = (A == 0) ? 32 : A.getActiveBits();
2219 Result = APInt(NumBits, ArrayRef<uint64_t>(A.getRawData(), A.getNumWords()));
2220 return false;
2221}
2222
2223static bool getUnsigned(const MIToken &Token, unsigned &Result,
2224 ErrorCallbackType ErrCB) {
2225 if (Token.hasIntegerValue()) {
2226 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
2227 const APSInt &SInt = Token.integerValue();
2228 if (SInt.isNegative())
2229 return ErrCB(Token.location(), "expected unsigned integer");
2230 uint64_t Val64 = SInt.getLimitedValue(Limit);
2231 if (Val64 == Limit)
2232 return ErrCB(Token.location(), "expected 32-bit integer (too large)");
2233 Result = Val64;
2234 return false;
2235 }
2236 if (Token.is(MIToken::HexLiteral)) {
2237 APInt A;
2238 if (getHexUint(Token, A))
2239 return true;
2240 if (A.getBitWidth() > 32)
2241 return ErrCB(Token.location(), "expected 32-bit integer (too large)");
2242 Result = A.getZExtValue();
2243 return false;
2244 }
2245 return true;
2246}
2247
2248bool MIParser::getUnsigned(unsigned &Result) {
2249 return ::getUnsigned(
2250 Token, Result, [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
2251 return error(Loc, Msg);
2252 });
2253}
2254
2255bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
2258 unsigned Number;
2259 if (getUnsigned(Number))
2260 return true;
2261 auto MBBInfo = PFS.MBBSlots.find(Number);
2262 if (MBBInfo == PFS.MBBSlots.end())
2263 return error(Twine("use of undefined machine basic block #") +
2264 Twine(Number));
2265 MBB = MBBInfo->second;
2266 // TODO: Only parse the name if it's a MachineBasicBlockLabel. Deprecate once
2267 // we drop the <irname> from the bb.<id>.<irname> format.
2268 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
2269 return error(Twine("the name of machine basic block #") + Twine(Number) +
2270 " isn't '" + Token.stringValue() + "'");
2271 return false;
2272}
2273
2274bool MIParser::parseMBBOperand(MachineOperand &Dest) {
2277 return true;
2279 lex();
2280 return false;
2281}
2282
2283bool MIParser::parseStackFrameIndex(int &FI) {
2284 assert(Token.is(MIToken::StackObject));
2285 unsigned ID;
2286 if (getUnsigned(ID))
2287 return true;
2288 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
2289 if (ObjectInfo == PFS.StackObjectSlots.end())
2290 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
2291 "'");
2293 if (const auto *Alloca =
2294 MF.getFrameInfo().getObjectAllocation(ObjectInfo->second))
2295 Name = Alloca->getName();
2296 if (!Token.stringValue().empty() && Token.stringValue() != Name)
2297 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
2298 "' isn't '" + Token.stringValue() + "'");
2299 lex();
2300 FI = ObjectInfo->second;
2301 return false;
2302}
2303
2304bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
2305 int FI;
2306 if (parseStackFrameIndex(FI))
2307 return true;
2308 Dest = MachineOperand::CreateFI(FI);
2309 return false;
2310}
2311
2312bool MIParser::parseFixedStackFrameIndex(int &FI) {
2314 unsigned ID;
2315 if (getUnsigned(ID))
2316 return true;
2317 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
2318 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
2319 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
2320 Twine(ID) + "'");
2321 lex();
2322 FI = ObjectInfo->second;
2323 return false;
2324}
2325
2326bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
2327 int FI;
2328 if (parseFixedStackFrameIndex(FI))
2329 return true;
2330 Dest = MachineOperand::CreateFI(FI);
2331 return false;
2332}
2333
2334static bool parseGlobalValue(const MIToken &Token,
2336 ErrorCallbackType ErrCB) {
2337 switch (Token.kind()) {
2339 const Module *M = PFS.MF.getFunction().getParent();
2340 GV = M->getNamedValue(Token.stringValue());
2341 if (!GV)
2342 return ErrCB(Token.location(), Twine("use of undefined global value '") +
2343 Token.range() + "'");
2344 break;
2345 }
2346 case MIToken::GlobalValue: {
2347 unsigned GVIdx;
2348 if (getUnsigned(Token, GVIdx, ErrCB))
2349 return true;
2350 GV = PFS.IRSlots.GlobalValues.get(GVIdx);
2351 if (!GV)
2352 return ErrCB(Token.location(), Twine("use of undefined global value '@") +
2353 Twine(GVIdx) + "'");
2354 break;
2355 }
2356 default:
2357 llvm_unreachable("The current token should be a global value");
2358 }
2359 return false;
2360}
2361
2362bool MIParser::parseGlobalValue(GlobalValue *&GV) {
2363 return ::parseGlobalValue(
2364 Token, PFS, GV,
2365 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
2366 return error(Loc, Msg);
2367 });
2368}
2369
2370bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
2371 GlobalValue *GV = nullptr;
2372 if (parseGlobalValue(GV))
2373 return true;
2374 lex();
2375 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
2376 if (parseOperandsOffset(Dest))
2377 return true;
2378 return false;
2379}
2380
2381bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
2383 unsigned ID;
2384 if (getUnsigned(ID))
2385 return true;
2386 auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
2387 if (ConstantInfo == PFS.ConstantPoolSlots.end())
2388 return error("use of undefined constant '%const." + Twine(ID) + "'");
2389 lex();
2390 Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
2391 if (parseOperandsOffset(Dest))
2392 return true;
2393 return false;
2394}
2395
2396bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
2398 unsigned ID;
2399 if (getUnsigned(ID))
2400 return true;
2401 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
2402 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
2403 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
2404 lex();
2405 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
2406 return false;
2407}
2408
2409bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
2411 const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
2412 lex();
2413 Dest = MachineOperand::CreateES(Symbol);
2414 if (parseOperandsOffset(Dest))
2415 return true;
2416 return false;
2417}
2418
2419bool MIParser::parseMCSymbolOperand(MachineOperand &Dest) {
2420 assert(Token.is(MIToken::MCSymbol));
2421 MCSymbol *Symbol = getOrCreateMCSymbol(Token.stringValue());
2422 lex();
2423 Dest = MachineOperand::CreateMCSymbol(Symbol);
2424 if (parseOperandsOffset(Dest))
2425 return true;
2426 return false;
2427}
2428
2429bool MIParser::parseSubRegisterIndexOperand(MachineOperand &Dest) {
2431 StringRef Name = Token.stringValue();
2432 unsigned SubRegIndex = PFS.Target.getSubRegIndex(Token.stringValue());
2433 if (SubRegIndex == 0)
2434 return error(Twine("unknown subregister index '") + Name + "'");
2435 lex();
2436 Dest = MachineOperand::CreateImm(SubRegIndex);
2437 return false;
2438}
2439
2440bool MIParser::parseMDNode(MDNode *&Node) {
2441 assert(Token.is(MIToken::exclaim));
2442
2443 auto Loc = Token.location();
2444 lex();
2445 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
2446 return error("expected metadata id after '!'");
2447 unsigned ID;
2448 if (getUnsigned(ID))
2449 return true;
2450 auto NodeInfo = PFS.IRSlots.MetadataNodes.find(ID);
2451 if (NodeInfo == PFS.IRSlots.MetadataNodes.end()) {
2452 NodeInfo = PFS.MachineMetadataNodes.find(ID);
2453 if (NodeInfo == PFS.MachineMetadataNodes.end())
2454 return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
2455 }
2456 lex();
2457 Node = NodeInfo->second.get();
2458 return false;
2459}
2460
2461bool MIParser::parseDIExpression(MDNode *&Expr) {
2462 unsigned Read;
2464 CurrentSource, Read, Error, *PFS.MF.getFunction().getParent(),
2465 &PFS.IRSlots);
2466 CurrentSource = CurrentSource.substr(Read);
2467 lex();
2468 if (!Expr)
2469 return error(Error.getMessage());
2470 return false;
2471}
2472
2473bool MIParser::parseDILocation(MDNode *&Loc) {
2474 assert(Token.is(MIToken::md_dilocation));
2475 lex();
2476
2477 bool HaveLine = false;
2478 unsigned Line = 0;
2479 unsigned Column = 0;
2480 MDNode *Scope = nullptr;
2481 MDNode *InlinedAt = nullptr;
2482 bool ImplicitCode = false;
2483 uint64_t AtomGroup = 0;
2484 uint64_t AtomRank = 0;
2485 MDNode *IRLayers = nullptr;
2486
2487 if (expectAndConsume(MIToken::lparen))
2488 return true;
2489
2490 if (Token.isNot(MIToken::rparen)) {
2491 do {
2492 if (Token.is(MIToken::Identifier)) {
2493 if (Token.stringValue() == "line") {
2494 lex();
2495 if (expectAndConsume(MIToken::colon))
2496 return true;
2497 if (Token.isNot(MIToken::IntegerLiteral) ||
2498 Token.integerValue().isSigned())
2499 return error("expected unsigned integer");
2500 Line = Token.integerValue().getZExtValue();
2501 HaveLine = true;
2502 lex();
2503 continue;
2504 }
2505 if (Token.stringValue() == "column") {
2506 lex();
2507 if (expectAndConsume(MIToken::colon))
2508 return true;
2509 if (Token.isNot(MIToken::IntegerLiteral) ||
2510 Token.integerValue().isSigned())
2511 return error("expected unsigned integer");
2512 Column = Token.integerValue().getZExtValue();
2513 lex();
2514 continue;
2515 }
2516 if (Token.stringValue() == "scope") {
2517 lex();
2518 if (expectAndConsume(MIToken::colon))
2519 return true;
2520 if (parseMDNode(Scope))
2521 return error("expected metadata node");
2522 if (!isa<DIScope>(Scope))
2523 return error("expected DIScope node");
2524 continue;
2525 }
2526 if (Token.stringValue() == "inlinedAt") {
2527 lex();
2528 if (expectAndConsume(MIToken::colon))
2529 return true;
2530 if (Token.is(MIToken::exclaim)) {
2531 if (parseMDNode(InlinedAt))
2532 return true;
2533 } else if (Token.is(MIToken::md_dilocation)) {
2534 if (parseDILocation(InlinedAt))
2535 return true;
2536 } else {
2537 return error("expected metadata node");
2538 }
2539 if (!isa<DILocation>(InlinedAt))
2540 return error("expected DILocation node");
2541 continue;
2542 }
2543 if (Token.stringValue() == "isImplicitCode") {
2544 lex();
2545 if (expectAndConsume(MIToken::colon))
2546 return true;
2547 if (!Token.is(MIToken::Identifier))
2548 return error("expected true/false");
2549 // As far as I can see, we don't have any existing need for parsing
2550 // true/false in MIR yet. Do it ad-hoc until there's something else
2551 // that needs it.
2552 if (Token.stringValue() == "true")
2553 ImplicitCode = true;
2554 else if (Token.stringValue() == "false")
2555 ImplicitCode = false;
2556 else
2557 return error("expected true/false");
2558 lex();
2559 continue;
2560 }
2561 if (Token.stringValue() == "atomGroup") {
2562 lex();
2563 if (expectAndConsume(MIToken::colon))
2564 return true;
2565 if (Token.isNot(MIToken::IntegerLiteral) ||
2566 Token.integerValue().isSigned())
2567 return error("expected unsigned integer");
2568 AtomGroup = Token.integerValue().getZExtValue();
2569 lex();
2570 continue;
2571 }
2572 if (Token.stringValue() == "atomRank") {
2573 lex();
2574 if (expectAndConsume(MIToken::colon))
2575 return true;
2576 if (Token.isNot(MIToken::IntegerLiteral) ||
2577 Token.integerValue().isSigned())
2578 return error("expected unsigned integer");
2579 AtomRank = Token.integerValue().getZExtValue();
2580 lex();
2581 continue;
2582 }
2583 if (Token.stringValue() == "irlayers") {
2584 lex();
2585 if (expectAndConsume(MIToken::colon))
2586 return true;
2587 if (parseMDNode(IRLayers))
2588 return error("expected metadata node");
2589 if (!isa<DILayerLocList>(IRLayers))
2590 return error("expected DILayerLocList node");
2591 continue;
2592 }
2593 }
2594 return error(Twine("invalid DILocation argument '") +
2595 Token.stringValue() + "'");
2596 } while (consumeIfPresent(MIToken::comma));
2597 }
2598
2599 if (expectAndConsume(MIToken::rparen))
2600 return true;
2601
2602 if (!HaveLine)
2603 return error("DILocation requires line number");
2604 if (!Scope)
2605 return error("DILocation requires a scope");
2606
2607 Loc = DILocation::get(MF.getFunction().getContext(), Line, Column, Scope,
2608 InlinedAt, ImplicitCode, AtomGroup, AtomRank, IRLayers);
2609 return false;
2610}
2611
2612bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
2613 MDNode *Node = nullptr;
2614 if (Token.is(MIToken::exclaim)) {
2615 if (parseMDNode(Node))
2616 return true;
2617 } else if (Token.is(MIToken::md_diexpr)) {
2618 if (parseDIExpression(Node))
2619 return true;
2620 }
2621 Dest = MachineOperand::CreateMetadata(Node);
2622 return false;
2623}
2624
2625bool MIParser::parseCFIOffset(int &Offset) {
2626 if (Token.isNot(MIToken::IntegerLiteral))
2627 return error("expected a cfi offset");
2628 if (Token.integerValue().getSignificantBits() > 32)
2629 return error("expected a 32 bit integer (the cfi offset is too large)");
2630 Offset = (int)Token.integerValue().getExtValue();
2631 lex();
2632 return false;
2633}
2634
2635bool MIParser::parseCFIUnsigned(unsigned &Value) {
2636 if (getUnsigned(Value))
2637 return true;
2638 lex();
2639 return false;
2640}
2641
2642bool MIParser::parseCFIRegister(unsigned &Reg) {
2643 if (Token.isNot(MIToken::NamedRegister))
2644 return error("expected a cfi register");
2645 Register LLVMReg;
2646 if (parseNamedRegister(LLVMReg))
2647 return true;
2648 const auto *TRI = MF.getSubtarget().getRegisterInfo();
2649 assert(TRI && "Expected target register info");
2650 int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
2651 if (DwarfReg < 0)
2652 return error("invalid DWARF register");
2653 Reg = (unsigned)DwarfReg;
2654 lex();
2655 return false;
2656}
2657
2658bool MIParser::parseCFIAddressSpace(unsigned &AddressSpace) {
2659 if (Token.isNot(MIToken::IntegerLiteral))
2660 return error("expected a cfi address space literal");
2661 if (Token.integerValue().isSigned())
2662 return error("expected an unsigned integer (cfi address space)");
2663 AddressSpace = Token.integerValue().getZExtValue();
2664 lex();
2665 return false;
2666}
2667
2668bool MIParser::parseCFIEscapeValues(std::string &Values) {
2669 do {
2670 if (Token.isNot(MIToken::HexLiteral))
2671 return error("expected a hexadecimal literal");
2672 unsigned Value;
2673 if (getUnsigned(Value))
2674 return true;
2675 if (Value > UINT8_MAX)
2676 return error("expected a 8-bit integer (too large)");
2677 Values.push_back(static_cast<uint8_t>(Value));
2678 lex();
2679 } while (consumeIfPresent(MIToken::comma));
2680 return false;
2681}
2682
2683bool MIParser::parseCFIOperand(MachineOperand &Dest) {
2684 auto Kind = Token.kind();
2685 lex();
2686 int Offset;
2687 unsigned Reg;
2688 unsigned AddressSpace;
2689 unsigned CFIIndex;
2690 switch (Kind) {
2692 if (parseCFIRegister(Reg))
2693 return true;
2694 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(nullptr, Reg));
2695 break;
2697 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2698 parseCFIOffset(Offset))
2699 return true;
2700 CFIIndex =
2701 MF.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
2702 break;
2704 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2705 parseCFIOffset(Offset))
2706 return true;
2707 CFIIndex = MF.addFrameInst(
2709 break;
2711 if (parseCFIRegister(Reg))
2712 return true;
2713 CFIIndex =
2714 MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
2715 break;
2717 if (parseCFIOffset(Offset))
2718 return true;
2719 CFIIndex =
2720 MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, Offset));
2721 break;
2723 if (parseCFIOffset(Offset))
2724 return true;
2725 CFIIndex = MF.addFrameInst(
2727 break;
2729 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2730 parseCFIOffset(Offset))
2731 return true;
2732 CFIIndex =
2733 MF.addFrameInst(MCCFIInstruction::cfiDefCfa(nullptr, Reg, Offset));
2734 break;
2736 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2737 parseCFIOffset(Offset) || expectAndConsume(MIToken::comma) ||
2738 parseCFIAddressSpace(AddressSpace))
2739 return true;
2740 CFIIndex = MF.addFrameInst(MCCFIInstruction::createLLVMDefAspaceCfa(
2741 nullptr, Reg, Offset, AddressSpace, SMLoc()));
2742 break;
2744 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRememberState(nullptr));
2745 break;
2747 if (parseCFIRegister(Reg))
2748 return true;
2749 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, Reg));
2750 break;
2752 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestoreState(nullptr));
2753 break;
2755 if (parseCFIRegister(Reg))
2756 return true;
2757 CFIIndex = MF.addFrameInst(MCCFIInstruction::createUndefined(nullptr, Reg));
2758 break;
2760 unsigned Reg2;
2761 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2762 parseCFIRegister(Reg2))
2763 return true;
2764
2765 CFIIndex =
2766 MF.addFrameInst(MCCFIInstruction::createRegister(nullptr, Reg, Reg2));
2767 break;
2768 }
2770 CFIIndex = MF.addFrameInst(MCCFIInstruction::createWindowSave(nullptr));
2771 break;
2773 CFIIndex = MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
2774 break;
2776 CFIIndex =
2777 MF.addFrameInst(MCCFIInstruction::createNegateRAStateWithPC(nullptr));
2778 break;
2780 unsigned State;
2781 MCSymbol *PACSym = nullptr;
2782 if (parseCFIUnsigned(State) || expectAndConsume(MIToken::comma))
2783 return true;
2784 if (Token.is(MIToken::MCSymbol)) {
2785 PACSym = getOrCreateMCSymbol(Token.stringValue());
2786 lex();
2787 CFIIndex = MF.addFrameInst(
2788 MCCFIInstruction::createSetRAState(nullptr, State, PACSym));
2789 } else if (Token.is(MIToken::IntegerLiteral)) {
2790 int Offset;
2791 if (parseCFIOffset(Offset))
2792 return true;
2793 CFIIndex = MF.addFrameInst(
2795 } else {
2796 return error("expected '<mcsymbol ...>' or integer offset for "
2797 "cfi_set_ra_state");
2798 }
2799 break;
2800 }
2802 unsigned Reg, R1, R2;
2803 unsigned R1Size, R2Size;
2804 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2805 parseCFIRegister(R1) || expectAndConsume(MIToken::comma) ||
2806 parseCFIUnsigned(R1Size) || expectAndConsume(MIToken::comma) ||
2807 parseCFIRegister(R2) || expectAndConsume(MIToken::comma) ||
2808 parseCFIUnsigned(R2Size))
2809 return true;
2810
2811 CFIIndex = MF.addFrameInst(MCCFIInstruction::createLLVMRegisterPair(
2812 nullptr, Reg, R1, R1Size, R2, R2Size));
2813 break;
2814 }
2816 std::vector<MCCFIInstruction::VectorRegisterWithLane> VectorRegisters;
2817 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma))
2818 return true;
2819 do {
2820 unsigned VR;
2821 unsigned Lane, Size;
2822 if (parseCFIRegister(VR) || expectAndConsume(MIToken::comma) ||
2823 parseCFIUnsigned(Lane) || expectAndConsume(MIToken::comma) ||
2824 parseCFIUnsigned(Size))
2825 return true;
2826 VectorRegisters.push_back({VR, Lane, Size});
2827 } while (consumeIfPresent(MIToken::comma));
2828
2829 CFIIndex = MF.addFrameInst(MCCFIInstruction::createLLVMVectorRegisters(
2830 nullptr, Reg, std::move(VectorRegisters)));
2831 break;
2832 }
2834 unsigned Reg, MaskReg;
2835 unsigned RegSize, MaskRegSize;
2836 int Offset = 0;
2837
2838 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2839 parseCFIUnsigned(RegSize) || expectAndConsume(MIToken::comma) ||
2840 parseCFIRegister(MaskReg) || expectAndConsume(MIToken::comma) ||
2841 parseCFIUnsigned(MaskRegSize) || expectAndConsume(MIToken::comma) ||
2842 parseCFIOffset(Offset))
2843 return true;
2844
2845 CFIIndex = MF.addFrameInst(MCCFIInstruction::createLLVMVectorOffset(
2846 nullptr, Reg, RegSize, MaskReg, MaskRegSize, Offset));
2847 break;
2848 }
2850 unsigned Reg, SpillReg, MaskReg;
2851 unsigned SpillRegLaneSize, MaskRegSize;
2852
2853 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2854 parseCFIRegister(SpillReg) || expectAndConsume(MIToken::comma) ||
2855 parseCFIUnsigned(SpillRegLaneSize) ||
2856 expectAndConsume(MIToken::comma) || parseCFIRegister(MaskReg) ||
2857 expectAndConsume(MIToken::comma) || parseCFIUnsigned(MaskRegSize))
2858 return true;
2859
2860 CFIIndex = MF.addFrameInst(MCCFIInstruction::createLLVMVectorRegisterMask(
2861 nullptr, Reg, SpillReg, SpillRegLaneSize, MaskReg, MaskRegSize));
2862 break;
2863 }
2865 std::string Values;
2866 if (parseCFIEscapeValues(Values))
2867 return true;
2868 CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape(nullptr, Values));
2869 break;
2870 }
2871 default:
2872 // TODO: Parse the other CFI operands.
2873 llvm_unreachable("The current token should be a cfi operand");
2874 }
2875 Dest = MachineOperand::CreateCFIIndex(CFIIndex);
2876 return false;
2877}
2878
2879bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
2880 switch (Token.kind()) {
2881 case MIToken::NamedIRBlock: {
2883 F.getValueSymbolTable()->lookup(Token.stringValue()));
2884 if (!BB)
2885 return error(Twine("use of undefined IR block '") + Token.range() + "'");
2886 break;
2887 }
2888 case MIToken::IRBlock: {
2889 unsigned SlotNumber = 0;
2890 if (getUnsigned(SlotNumber))
2891 return true;
2892 BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F));
2893 if (!BB)
2894 return error(Twine("use of undefined IR block '%ir-block.") +
2895 Twine(SlotNumber) + "'");
2896 break;
2897 }
2898 default:
2899 llvm_unreachable("The current token should be an IR block reference");
2900 }
2901 return false;
2902}
2903
2904bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
2906 lex();
2907 if (expectAndConsume(MIToken::lparen))
2908 return true;
2909 if (Token.isNot(MIToken::GlobalValue) &&
2910 Token.isNot(MIToken::NamedGlobalValue))
2911 return error("expected a global value");
2912 GlobalValue *GV = nullptr;
2913 if (parseGlobalValue(GV))
2914 return true;
2915 auto *F = dyn_cast<Function>(GV);
2916 if (!F)
2917 return error("expected an IR function reference");
2918 lex();
2919 if (expectAndConsume(MIToken::comma))
2920 return true;
2921 BasicBlock *BB = nullptr;
2922 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
2923 return error("expected an IR block reference");
2924 if (parseIRBlock(BB, *F))
2925 return true;
2926 lex();
2927 if (expectAndConsume(MIToken::rparen))
2928 return true;
2929 Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
2930 if (parseOperandsOffset(Dest))
2931 return true;
2932 return false;
2933}
2934
2935bool MIParser::parseIntrinsicOperand(MachineOperand &Dest) {
2936 assert(Token.is(MIToken::kw_intrinsic));
2937 lex();
2938 if (expectAndConsume(MIToken::lparen))
2939 return error("expected syntax intrinsic(@llvm.whatever)");
2940
2941 if (Token.isNot(MIToken::NamedGlobalValue))
2942 return error("expected syntax intrinsic(@llvm.whatever)");
2943
2944 std::string Name = std::string(Token.stringValue());
2945 lex();
2946
2947 if (expectAndConsume(MIToken::rparen))
2948 return error("expected ')' to terminate intrinsic name");
2949
2950 // Find out what intrinsic we're dealing with.
2952 if (ID == Intrinsic::not_intrinsic)
2953 return error("unknown intrinsic name");
2955
2956 return false;
2957}
2958
2959bool MIParser::parsePredicateOperand(MachineOperand &Dest) {
2960 assert(Token.is(MIToken::kw_intpred) || Token.is(MIToken::kw_floatpred));
2961 bool IsFloat = Token.is(MIToken::kw_floatpred);
2962 lex();
2963
2964 if (expectAndConsume(MIToken::lparen))
2965 return error("expected syntax intpred(whatever) or floatpred(whatever");
2966
2967 if (Token.isNot(MIToken::Identifier))
2968 return error("whatever");
2969
2970 CmpInst::Predicate Pred;
2971 if (IsFloat) {
2972 Pred = StringSwitch<CmpInst::Predicate>(Token.stringValue())
2973 .Case("false", CmpInst::FCMP_FALSE)
2974 .Case("oeq", CmpInst::FCMP_OEQ)
2975 .Case("ogt", CmpInst::FCMP_OGT)
2976 .Case("oge", CmpInst::FCMP_OGE)
2977 .Case("olt", CmpInst::FCMP_OLT)
2978 .Case("ole", CmpInst::FCMP_OLE)
2979 .Case("one", CmpInst::FCMP_ONE)
2980 .Case("ord", CmpInst::FCMP_ORD)
2981 .Case("uno", CmpInst::FCMP_UNO)
2982 .Case("ueq", CmpInst::FCMP_UEQ)
2983 .Case("ugt", CmpInst::FCMP_UGT)
2984 .Case("uge", CmpInst::FCMP_UGE)
2985 .Case("ult", CmpInst::FCMP_ULT)
2986 .Case("ule", CmpInst::FCMP_ULE)
2987 .Case("une", CmpInst::FCMP_UNE)
2988 .Case("true", CmpInst::FCMP_TRUE)
2990 if (!CmpInst::isFPPredicate(Pred))
2991 return error("invalid floating-point predicate");
2992 } else {
2993 Pred = StringSwitch<CmpInst::Predicate>(Token.stringValue())
2994 .Case("eq", CmpInst::ICMP_EQ)
2995 .Case("ne", CmpInst::ICMP_NE)
2996 .Case("sgt", CmpInst::ICMP_SGT)
2997 .Case("sge", CmpInst::ICMP_SGE)
2998 .Case("slt", CmpInst::ICMP_SLT)
2999 .Case("sle", CmpInst::ICMP_SLE)
3000 .Case("ugt", CmpInst::ICMP_UGT)
3001 .Case("uge", CmpInst::ICMP_UGE)
3002 .Case("ult", CmpInst::ICMP_ULT)
3003 .Case("ule", CmpInst::ICMP_ULE)
3005 if (!CmpInst::isIntPredicate(Pred))
3006 return error("invalid integer predicate");
3007 }
3008
3009 lex();
3011 if (expectAndConsume(MIToken::rparen))
3012 return error("predicate should be terminated by ')'.");
3013
3014 return false;
3015}
3016
3017bool MIParser::parseShuffleMaskOperand(MachineOperand &Dest) {
3019
3020 lex();
3021 if (expectAndConsume(MIToken::lparen))
3022 return error("expected syntax shufflemask(<integer or undef>, ...)");
3023
3024 SmallVector<int, 32> ShufMask;
3025 do {
3026 if (Token.is(MIToken::kw_undef)) {
3027 ShufMask.push_back(-1);
3028 } else if (Token.is(MIToken::IntegerLiteral)) {
3029 const APSInt &Int = Token.integerValue();
3030 ShufMask.push_back(Int.getExtValue());
3031 } else {
3032 return error("expected integer constant");
3033 }
3034
3035 lex();
3036 } while (consumeIfPresent(MIToken::comma));
3037
3038 if (expectAndConsume(MIToken::rparen))
3039 return error("shufflemask should be terminated by ')'.");
3040
3041 if (ShufMask.size() < 2)
3042 return error("shufflemask should have > 1 element");
3043
3044 ArrayRef<int> MaskAlloc = MF.allocateShuffleMask(ShufMask);
3045 Dest = MachineOperand::CreateShuffleMask(MaskAlloc);
3046 return false;
3047}
3048
3049bool MIParser::parseDbgInstrRefOperand(MachineOperand &Dest) {
3051
3052 lex();
3053 if (expectAndConsume(MIToken::lparen))
3054 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
3055
3056 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isNegative())
3057 return error("expected unsigned integer for instruction index");
3058 uint64_t InstrIdx = Token.integerValue().getZExtValue();
3059 assert(InstrIdx <= std::numeric_limits<unsigned>::max() &&
3060 "Instruction reference's instruction index is too large");
3061 lex();
3062
3063 if (expectAndConsume(MIToken::comma))
3064 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
3065
3066 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isNegative())
3067 return error("expected unsigned integer for operand index");
3068 uint64_t OpIdx = Token.integerValue().getZExtValue();
3069 assert(OpIdx <= std::numeric_limits<unsigned>::max() &&
3070 "Instruction reference's operand index is too large");
3071 lex();
3072
3073 if (expectAndConsume(MIToken::rparen))
3074 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
3075
3076 Dest = MachineOperand::CreateDbgInstrRef(InstrIdx, OpIdx);
3077 return false;
3078}
3079
3080bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
3082 lex();
3083 if (expectAndConsume(MIToken::lparen))
3084 return true;
3085 if (Token.isNot(MIToken::Identifier))
3086 return error("expected the name of the target index");
3087 int Index = 0;
3088 if (PFS.Target.getTargetIndex(Token.stringValue(), Index))
3089 return error("use of undefined target index '" + Token.stringValue() + "'");
3090 lex();
3091 if (expectAndConsume(MIToken::rparen))
3092 return true;
3093 Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
3094 if (parseOperandsOffset(Dest))
3095 return true;
3096 return false;
3097}
3098
3099bool MIParser::parseCustomRegisterMaskOperand(MachineOperand &Dest) {
3100 assert(Token.stringValue() == "CustomRegMask" && "Expected a custom RegMask");
3101 lex();
3102 if (expectAndConsume(MIToken::lparen))
3103 return true;
3104
3105 uint32_t *Mask = MF.allocateRegMask();
3106 do {
3107 if (Token.isNot(MIToken::rparen)) {
3108 if (Token.isNot(MIToken::NamedRegister))
3109 return error("expected a named register");
3110 Register Reg;
3111 if (parseNamedRegister(Reg))
3112 return true;
3113 lex();
3114 Mask[Reg.id() / 32] |= 1U << (Reg.id() % 32);
3115 }
3116
3117 // TODO: Report an error if the same register is used more than once.
3118 } while (consumeIfPresent(MIToken::comma));
3119
3120 if (expectAndConsume(MIToken::rparen))
3121 return true;
3122 Dest = MachineOperand::CreateRegMask(Mask);
3123 return false;
3124}
3125
3126bool MIParser::parseLaneMaskOperand(MachineOperand &Dest) {
3127 assert(Token.is(MIToken::kw_lanemask));
3128
3129 lex();
3130 if (expectAndConsume(MIToken::lparen))
3131 return true;
3132
3133 // Parse lanemask.
3134 if (Token.isNot(MIToken::IntegerLiteral) && Token.isNot(MIToken::HexLiteral))
3135 return error("expected a valid lane mask value");
3136 static_assert(sizeof(LaneBitmask::Type) == sizeof(uint64_t),
3137 "Use correct get-function for lane mask.");
3139 if (getUint64(V))
3140 return true;
3141 LaneBitmask LaneMask(V);
3142 lex();
3143
3144 if (expectAndConsume(MIToken::rparen))
3145 return true;
3146
3147 Dest = MachineOperand::CreateLaneMask(LaneMask);
3148 return false;
3149}
3150
3151bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) {
3152 assert(Token.is(MIToken::kw_liveout));
3153 uint32_t *Mask = MF.allocateRegMask();
3154 lex();
3155 if (expectAndConsume(MIToken::lparen))
3156 return true;
3157 while (true) {
3158 if (Token.isNot(MIToken::NamedRegister))
3159 return error("expected a named register");
3160 Register Reg;
3161 if (parseNamedRegister(Reg))
3162 return true;
3163 lex();
3164 Mask[Reg.id() / 32] |= 1U << (Reg.id() % 32);
3165 // TODO: Report an error if the same register is used more than once.
3166 if (Token.isNot(MIToken::comma))
3167 break;
3168 lex();
3169 }
3170 if (expectAndConsume(MIToken::rparen))
3171 return true;
3173 return false;
3174}
3175
3176bool MIParser::parseMachineOperand(const unsigned OpCode, const unsigned OpIdx,
3177 MachineOperand &Dest,
3178 std::optional<unsigned> &TiedDefIdx) {
3179 switch (Token.kind()) {
3182 case MIToken::kw_def:
3183 case MIToken::kw_dead:
3184 case MIToken::kw_killed:
3185 case MIToken::kw_undef:
3194 return parseRegisterOperand(Dest, TiedDefIdx);
3196 // TODO: Forbid numeric operands for INLINEASM once the transition to the
3197 // symbolic form is over.
3198 return parseImmediateOperand(Dest);
3199 case MIToken::kw_half:
3200 case MIToken::kw_bfloat:
3201 case MIToken::kw_float:
3202 case MIToken::kw_double:
3204 case MIToken::kw_fp128:
3206 return parseFPImmediateOperand(Dest);
3208 return parseMBBOperand(Dest);
3210 return parseStackObjectOperand(Dest);
3212 return parseFixedStackObjectOperand(Dest);
3215 return parseGlobalAddressOperand(Dest);
3217 return parseConstantPoolIndexOperand(Dest);
3219 return parseJumpTableIndexOperand(Dest);
3221 return parseExternalSymbolOperand(Dest);
3222 case MIToken::MCSymbol:
3223 return parseMCSymbolOperand(Dest);
3225 return parseSubRegisterIndexOperand(Dest);
3226 case MIToken::md_diexpr:
3227 case MIToken::exclaim:
3228 return parseMetadataOperand(Dest);
3251 return parseCFIOperand(Dest);
3253 return parseBlockAddressOperand(Dest);
3255 return parseIntrinsicOperand(Dest);
3257 return parseTargetIndexOperand(Dest);
3259 return parseLaneMaskOperand(Dest);
3261 return parseLiveoutRegisterMaskOperand(Dest);
3264 return parsePredicateOperand(Dest);
3266 return parseShuffleMaskOperand(Dest);
3268 return parseDbgInstrRefOperand(Dest);
3269 case MIToken::Error:
3270 return true;
3271 case MIToken::Identifier: {
3272 bool IsInlineAsm = OpCode == TargetOpcode::INLINEASM ||
3273 OpCode == TargetOpcode::INLINEASM_BR;
3274 if (IsInlineAsm)
3275 return parseSymbolicInlineAsmOperand(OpIdx, Dest);
3276
3277 StringRef Id = Token.stringValue();
3278 if (const auto *RegMask = PFS.Target.getRegMask(Id)) {
3279 Dest = MachineOperand::CreateRegMask(RegMask);
3280 lex();
3281 break;
3282 } else if (Id == "CustomRegMask") {
3283 return parseCustomRegisterMaskOperand(Dest);
3284 } else {
3285 return parseTypedImmediateOperand(Dest);
3286 }
3287 }
3288 case MIToken::dot: {
3289 const auto *TII = MF.getSubtarget().getInstrInfo();
3290 if (const auto *Formatter = TII->getMIRFormatter()) {
3291 return parseTargetImmMnemonic(OpCode, OpIdx, Dest, *Formatter);
3292 }
3293 [[fallthrough]];
3294 }
3295 default:
3296 // FIXME: Parse the MCSymbol machine operand.
3297 return error("expected a machine operand");
3298 }
3299 return false;
3300}
3301
3302bool MIParser::parseMachineOperandAndTargetFlags(
3303 const unsigned OpCode, const unsigned OpIdx, MachineOperand &Dest,
3304 std::optional<unsigned> &TiedDefIdx) {
3305 unsigned TF = 0;
3306 bool HasTargetFlags = false;
3307 if (Token.is(MIToken::kw_target_flags)) {
3308 HasTargetFlags = true;
3309 lex();
3310 if (expectAndConsume(MIToken::lparen))
3311 return true;
3312 if (Token.isNot(MIToken::Identifier))
3313 return error("expected the name of the target flag");
3314 if (PFS.Target.getDirectTargetFlag(Token.stringValue(), TF)) {
3315 if (PFS.Target.getBitmaskTargetFlag(Token.stringValue(), TF))
3316 return error("use of undefined target flag '" + Token.stringValue() +
3317 "'");
3318 }
3319 lex();
3320 while (Token.is(MIToken::comma)) {
3321 lex();
3322 if (Token.isNot(MIToken::Identifier))
3323 return error("expected the name of the target flag");
3324 unsigned BitFlag = 0;
3325 if (PFS.Target.getBitmaskTargetFlag(Token.stringValue(), BitFlag))
3326 return error("use of undefined target flag '" + Token.stringValue() +
3327 "'");
3328 // TODO: Report an error when using a duplicate bit target flag.
3329 TF |= BitFlag;
3330 lex();
3331 }
3332 if (expectAndConsume(MIToken::rparen))
3333 return true;
3334 }
3335 auto Loc = Token.location();
3336 if (parseMachineOperand(OpCode, OpIdx, Dest, TiedDefIdx))
3337 return true;
3338 if (!HasTargetFlags)
3339 return false;
3340 if (Dest.isReg())
3341 return error(Loc, "register operands can't have target flags");
3342 Dest.setTargetFlags(TF);
3343 return false;
3344}
3345
3346bool MIParser::parseOffset(int64_t &Offset) {
3347 if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
3348 return false;
3349 StringRef Sign = Token.range();
3350 bool IsNegative = Token.is(MIToken::minus);
3351 lex();
3352 if (Token.isNot(MIToken::IntegerLiteral))
3353 return error("expected an integer literal after '" + Sign + "'");
3354 if (Token.integerValue().getSignificantBits() > 64)
3355 return error("expected 64-bit integer (too large)");
3356 Offset = Token.integerValue().getExtValue();
3357 if (IsNegative)
3358 Offset = -Offset;
3359 lex();
3360 return false;
3361}
3362
3363bool MIParser::parseIRBlockAddressTaken(BasicBlock *&BB) {
3365 lex();
3366 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
3367 return error("expected basic block after 'ir_block_address_taken'");
3368
3369 if (parseIRBlock(BB, MF.getFunction()))
3370 return true;
3371
3372 lex();
3373 return false;
3374}
3375
3376bool MIParser::parseAlignment(uint64_t &Alignment) {
3377 assert(Token.is(MIToken::kw_align) || Token.is(MIToken::kw_basealign));
3378 lex();
3379 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
3380 return error("expected an integer literal after 'align'");
3381 if (getUint64(Alignment))
3382 return true;
3383 lex();
3384
3385 if (!isPowerOf2_64(Alignment))
3386 return error("expected a power-of-2 literal after 'align'");
3387
3388 return false;
3389}
3390
3391bool MIParser::parseAddrspace(unsigned &Addrspace) {
3392 assert(Token.is(MIToken::kw_addrspace));
3393 lex();
3394 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
3395 return error("expected an integer literal after 'addrspace'");
3396 if (getUnsigned(Addrspace))
3397 return true;
3398 lex();
3399 return false;
3400}
3401
3402bool MIParser::parseOperandsOffset(MachineOperand &Op) {
3403 int64_t Offset = 0;
3404 if (parseOffset(Offset))
3405 return true;
3406 Op.setOffset(Offset);
3407 return false;
3408}
3409
3410static bool parseIRValue(const MIToken &Token, PerFunctionMIParsingState &PFS,
3411 const Value *&V, ErrorCallbackType ErrCB) {
3412 switch (Token.kind()) {
3413 case MIToken::NamedIRValue: {
3414 V = PFS.MF.getFunction().getValueSymbolTable()->lookup(Token.stringValue());
3415 break;
3416 }
3417 case MIToken::IRValue: {
3418 unsigned SlotNumber = 0;
3419 if (getUnsigned(Token, SlotNumber, ErrCB))
3420 return true;
3421 V = PFS.getIRValue(SlotNumber);
3422 break;
3423 }
3425 case MIToken::GlobalValue: {
3426 GlobalValue *GV = nullptr;
3427 if (parseGlobalValue(Token, PFS, GV, ErrCB))
3428 return true;
3429 V = GV;
3430 break;
3431 }
3433 const Constant *C = nullptr;
3434 if (parseIRConstant(Token.location(), Token.stringValue(), PFS, C, ErrCB))
3435 return true;
3436 V = C;
3437 break;
3438 }
3440 V = nullptr;
3441 return false;
3442 default:
3443 llvm_unreachable("The current token should be an IR block reference");
3444 }
3445 if (!V)
3446 return ErrCB(Token.location(), Twine("use of undefined IR value '") + Token.range() + "'");
3447 return false;
3448}
3449
3450bool MIParser::parseIRValue(const Value *&V) {
3451 return ::parseIRValue(
3452 Token, PFS, V, [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
3453 return error(Loc, Msg);
3454 });
3455}
3456
3457bool MIParser::getUint64(uint64_t &Result) {
3458 if (Token.hasIntegerValue()) {
3459 if (Token.integerValue().getActiveBits() > 64)
3460 return error("expected 64-bit integer (too large)");
3461 Result = Token.integerValue().getZExtValue();
3462 return false;
3463 }
3464 if (Token.is(MIToken::HexLiteral)) {
3465 APInt A;
3466 if (getHexUint(A))
3467 return true;
3468 if (A.getBitWidth() > 64)
3469 return error("expected 64-bit integer (too large)");
3470 Result = A.getZExtValue();
3471 return false;
3472 }
3473 return true;
3474}
3475
3476bool MIParser::getHexUint(APInt &Result) {
3477 return ::getHexUint(Token, Result);
3478}
3479
3480bool MIParser::parseMemoryOperandFlag(MachineMemOperand::Flags &Flags) {
3481 const auto OldFlags = Flags;
3482 switch (Token.kind()) {
3485 break;
3488 break;
3491 break;
3494 break;
3497 if (PFS.Target.getMMOTargetFlag(Token.stringValue(), TF))
3498 return error("use of undefined target MMO flag '" + Token.stringValue() +
3499 "'");
3500 Flags |= TF;
3501 break;
3502 }
3503 default:
3504 llvm_unreachable("The current token should be a memory operand flag");
3505 }
3506 if (OldFlags == Flags)
3507 // We know that the same flag is specified more than once when the flags
3508 // weren't modified.
3509 return error("duplicate '" + Token.stringValue() + "' memory operand flag");
3510 lex();
3511 return false;
3512}
3513
3514bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV) {
3515 switch (Token.kind()) {
3516 case MIToken::kw_stack:
3517 PSV = MF.getPSVManager().getStack();
3518 break;
3519 case MIToken::kw_got:
3520 PSV = MF.getPSVManager().getGOT();
3521 break;
3523 PSV = MF.getPSVManager().getJumpTable();
3524 break;
3526 PSV = MF.getPSVManager().getConstantPool();
3527 break;
3529 int FI;
3530 if (parseFixedStackFrameIndex(FI))
3531 return true;
3532 PSV = MF.getPSVManager().getFixedStack(FI);
3533 // The token was already consumed, so use return here instead of break.
3534 return false;
3535 }
3536 case MIToken::StackObject: {
3537 int FI;
3538 if (parseStackFrameIndex(FI))
3539 return true;
3540 PSV = MF.getPSVManager().getFixedStack(FI);
3541 // The token was already consumed, so use return here instead of break.
3542 return false;
3543 }
3545 lex();
3546 switch (Token.kind()) {
3549 GlobalValue *GV = nullptr;
3550 if (parseGlobalValue(GV))
3551 return true;
3552 PSV = MF.getPSVManager().getGlobalValueCallEntry(GV);
3553 break;
3554 }
3556 PSV = MF.getPSVManager().getExternalSymbolCallEntry(
3557 MF.createExternalSymbolName(Token.stringValue()));
3558 break;
3559 default:
3560 return error(
3561 "expected a global value or an external symbol after 'call-entry'");
3562 }
3563 break;
3564 case MIToken::kw_custom: {
3565 lex();
3566 const auto *TII = MF.getSubtarget().getInstrInfo();
3567 if (const auto *Formatter = TII->getMIRFormatter()) {
3568 if (Formatter->parseCustomPseudoSourceValue(
3569 Token.stringValue(), MF, PFS, PSV,
3570 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
3571 return error(Loc, Msg);
3572 }))
3573 return true;
3574 } else {
3575 return error("unable to parse target custom pseudo source value");
3576 }
3577 break;
3578 }
3579 default:
3580 llvm_unreachable("The current token should be pseudo source value");
3581 }
3582 lex();
3583 return false;
3584}
3585
3586bool MIParser::parseMachinePointerInfo(MachinePointerInfo &Dest) {
3587 if (Token.is(MIToken::kw_constant_pool) || Token.is(MIToken::kw_stack) ||
3588 Token.is(MIToken::kw_got) || Token.is(MIToken::kw_jump_table) ||
3589 Token.is(MIToken::FixedStackObject) || Token.is(MIToken::StackObject) ||
3590 Token.is(MIToken::kw_call_entry) || Token.is(MIToken::kw_custom)) {
3591 const PseudoSourceValue *PSV = nullptr;
3592 if (parseMemoryPseudoSourceValue(PSV))
3593 return true;
3594 int64_t Offset = 0;
3595 if (parseOffset(Offset))
3596 return true;
3597 Dest = MachinePointerInfo(PSV, Offset);
3598 return false;
3599 }
3600 if (Token.isNot(MIToken::NamedIRValue) && Token.isNot(MIToken::IRValue) &&
3601 Token.isNot(MIToken::GlobalValue) &&
3602 Token.isNot(MIToken::NamedGlobalValue) &&
3603 Token.isNot(MIToken::QuotedIRValue) &&
3604 Token.isNot(MIToken::kw_unknown_address))
3605 return error("expected an IR value reference");
3606 const Value *V = nullptr;
3607 if (parseIRValue(V))
3608 return true;
3609 if (V && !V->getType()->isPointerTy())
3610 return error("expected a pointer IR value");
3611 lex();
3612 int64_t Offset = 0;
3613 if (parseOffset(Offset))
3614 return true;
3615 Dest = MachinePointerInfo(V, Offset);
3616 return false;
3617}
3618
3619bool MIParser::parseOptionalScope(LLVMContext &Context,
3620 SyncScope::ID &SSID) {
3621 SSID = SyncScope::System;
3622 if (Token.is(MIToken::Identifier) && Token.stringValue() == "syncscope") {
3623 lex();
3624 if (expectAndConsume(MIToken::lparen))
3625 return error("expected '(' in syncscope");
3626
3627 std::string SSN;
3628 if (parseStringConstant(SSN))
3629 return true;
3630
3631 SSID = Context.getOrInsertSyncScopeID(SSN);
3632 if (expectAndConsume(MIToken::rparen))
3633 return error("expected ')' in syncscope");
3634 }
3635
3636 return false;
3637}
3638
3639bool MIParser::parseOptionalAtomicOrdering(AtomicOrdering &Order) {
3641 if (Token.isNot(MIToken::Identifier))
3642 return false;
3643
3644 Order = StringSwitch<AtomicOrdering>(Token.stringValue())
3645 .Case("unordered", AtomicOrdering::Unordered)
3646 .Case("monotonic", AtomicOrdering::Monotonic)
3647 .Case("acquire", AtomicOrdering::Acquire)
3648 .Case("release", AtomicOrdering::Release)
3652
3653 if (Order != AtomicOrdering::NotAtomic) {
3654 lex();
3655 return false;
3656 }
3657
3658 return error("expected an atomic scope, ordering or a size specification");
3659}
3660
3661bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
3662 if (expectAndConsume(MIToken::lparen))
3663 return true;
3665 while (Token.isMemoryOperandFlag()) {
3666 if (parseMemoryOperandFlag(Flags))
3667 return true;
3668 }
3669 if (Token.isNot(MIToken::Identifier) ||
3670 (Token.stringValue() != "load" && Token.stringValue() != "store"))
3671 return error("expected 'load' or 'store' memory operation");
3672 if (Token.stringValue() == "load")
3674 else
3676 lex();
3677
3678 // Optional 'store' for operands that both load and store.
3679 if (Token.is(MIToken::Identifier) && Token.stringValue() == "store") {
3681 lex();
3682 }
3683
3684 // Optional synchronization scope.
3685 SyncScope::ID SSID;
3686 if (parseOptionalScope(MF.getFunction().getContext(), SSID))
3687 return true;
3688
3689 // Up to two atomic orderings (cmpxchg provides guarantees on failure).
3690 AtomicOrdering Order, FailureOrder;
3691 if (parseOptionalAtomicOrdering(Order))
3692 return true;
3693
3694 if (parseOptionalAtomicOrdering(FailureOrder))
3695 return true;
3696
3697 if (Token.isNot(MIToken::IntegerLiteral) &&
3698 Token.isNot(MIToken::kw_unknown_size) &&
3699 Token.isNot(MIToken::lparen))
3700 return error("expected memory LLT, the size integer literal or 'unknown-size' after "
3701 "memory operation");
3702
3704 if (Token.is(MIToken::IntegerLiteral)) {
3705 uint64_t Size;
3706 if (getUint64(Size))
3707 return true;
3708
3709 // Convert from bytes to bits for storage.
3711 lex();
3712 } else if (Token.is(MIToken::kw_unknown_size)) {
3713 lex();
3714 } else {
3715 if (expectAndConsume(MIToken::lparen))
3716 return true;
3717 if (parseLowLevelType(Token.location(), MemoryType))
3718 return true;
3719 if (expectAndConsume(MIToken::rparen))
3720 return true;
3721 }
3722
3724 if (Token.is(MIToken::Identifier)) {
3725 const char *Word =
3728 ? "on"
3729 : Flags & MachineMemOperand::MOLoad ? "from" : "into";
3730 if (Token.stringValue() != Word)
3731 return error(Twine("expected '") + Word + "'");
3732 lex();
3733
3734 if (parseMachinePointerInfo(Ptr))
3735 return true;
3736 }
3737 uint64_t BaseAlignment =
3738 MemoryType.isValid()
3739 ? PowerOf2Ceil(MemoryType.getSizeInBytes().getKnownMinValue())
3740 : 1;
3741 AAMDNodes AAInfo;
3742 MDNode *Range = nullptr;
3743 MDNode *MemCacheHint = nullptr;
3744 while (consumeIfPresent(MIToken::comma)) {
3745 switch (Token.kind()) {
3746 case MIToken::kw_align: {
3747 // align is printed if it is different than size.
3749 if (parseAlignment(Alignment))
3750 return true;
3751 if (Ptr.Offset & (Alignment - 1)) {
3752 // MachineMemOperand::getAlign never returns a value greater than the
3753 // alignment of offset, so this just guards against hand-written MIR
3754 // that specifies a large "align" value when it should probably use
3755 // "basealign" instead.
3756 return error("specified alignment is more aligned than offset");
3757 }
3758 BaseAlignment = Alignment;
3759 break;
3760 }
3762 // basealign is printed if it is different than align.
3763 if (parseAlignment(BaseAlignment))
3764 return true;
3765 break;
3767 if (parseAddrspace(Ptr.AddrSpace))
3768 return true;
3769 break;
3770 case MIToken::md_tbaa:
3771 lex();
3772 if (parseMDNode(AAInfo.TBAA))
3773 return true;
3774 break;
3776 lex();
3777 if (parseMDNode(AAInfo.Scope))
3778 return true;
3779 break;
3781 lex();
3782 if (parseMDNode(AAInfo.NoAlias))
3783 return true;
3784 break;
3786 lex();
3787 if (parseMDNode(AAInfo.NoAliasAddrSpace))
3788 return true;
3789 break;
3790 case MIToken::md_range:
3791 lex();
3792 if (parseMDNode(Range))
3793 return true;
3794 break;
3796 lex();
3797 if (parseMDNode(MemCacheHint))
3798 return true;
3799 break;
3800 // TODO: Report an error on duplicate metadata nodes.
3801 default:
3802 return error("expected 'align' or '!tbaa' or '!alias.scope' or "
3803 "'!noalias' or '!range' or '!mem.cache_hint' or "
3804 "'!noalias.addrspace'");
3805 }
3806 }
3807 if (expectAndConsume(MIToken::rparen))
3808 return true;
3809 Dest = MF.getMachineMemOperand(Ptr, Flags, MemoryType, Align(BaseAlignment),
3810 MMOMetadata(AAInfo, Range, MemCacheHint), SSID,
3811 Order, FailureOrder);
3812 return false;
3813}
3814
3815bool MIParser::parsePreOrPostInstrSymbol(MCSymbol *&Symbol) {
3817 Token.is(MIToken::kw_post_instr_symbol)) &&
3818 "Invalid token for a pre- post-instruction symbol!");
3819 lex();
3820 if (Token.isNot(MIToken::MCSymbol))
3821 return error("expected a symbol after 'pre-instr-symbol'");
3822 Symbol = getOrCreateMCSymbol(Token.stringValue());
3823 lex();
3824 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3825 Token.is(MIToken::lbrace))
3826 return false;
3827 if (Token.isNot(MIToken::comma))
3828 return error("expected ',' before the next machine operand");
3829 lex();
3830 return false;
3831}
3832
3833bool MIParser::parseHeapAllocMarker(MDNode *&Node) {
3835 "Invalid token for a heap alloc marker!");
3836 lex();
3837 if (parseMDNode(Node))
3838 return true;
3839 if (!Node)
3840 return error("expected a MDNode after 'heap-alloc-marker'");
3841 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3842 Token.is(MIToken::lbrace))
3843 return false;
3844 if (Token.isNot(MIToken::comma))
3845 return error("expected ',' before the next machine operand");
3846 lex();
3847 return false;
3848}
3849
3850bool MIParser::parsePCSections(MDNode *&Node) {
3851 assert(Token.is(MIToken::kw_pcsections) &&
3852 "Invalid token for a PC sections!");
3853 lex();
3854 if (parseMDNode(Node))
3855 return true;
3856 if (!Node)
3857 return error("expected a MDNode after 'pcsections'");
3858 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3859 Token.is(MIToken::lbrace))
3860 return false;
3861 if (Token.isNot(MIToken::comma))
3862 return error("expected ',' before the next machine operand");
3863 lex();
3864 return false;
3865}
3866
3867bool MIParser::parseMMRA(MDNode *&Node) {
3868 assert(Token.is(MIToken::kw_mmra) && "Invalid token for MMRA!");
3869 lex();
3870 if (parseMDNode(Node))
3871 return true;
3872 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3873 Token.is(MIToken::lbrace))
3874 return false;
3875 if (Token.isNot(MIToken::comma))
3876 return error("expected ',' before the next machine operand");
3877 lex();
3878 return false;
3879}
3880
3882 const Function &F,
3883 DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
3884 ModuleSlotTracker MST(F.getParent());
3886 for (const auto &BB : F) {
3887 if (BB.hasName())
3888 continue;
3889 int Slot = MST.getLocalSlot(&BB);
3890 if (Slot == -1)
3891 continue;
3892 Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
3893 }
3894}
3895
3897 unsigned Slot,
3898 const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
3899 return Slots2BasicBlocks.lookup(Slot);
3900}
3901
3902const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
3903 if (Slots2BasicBlocks.empty())
3904 initSlots2BasicBlocks(MF.getFunction(), Slots2BasicBlocks);
3905 return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
3906}
3907
3908const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
3909 if (&F == &MF.getFunction())
3910 return getIRBlock(Slot);
3911 DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
3912 initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
3913 return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
3914}
3915
3916MCSymbol *MIParser::getOrCreateMCSymbol(StringRef Name) {
3917 // FIXME: Currently we can't recognize temporary or local symbols and call all
3918 // of the appropriate forms to create them. However, this handles basic cases
3919 // well as most of the special aspects are recognized by a prefix on their
3920 // name, and the input names should already be unique. For test cases, keeping
3921 // the symbol name out of the symbol table isn't terribly important.
3922 return MF.getContext().getOrCreateSymbol(Name);
3923}
3924
3925bool MIParser::parseStringConstant(std::string &Result) {
3926 if (Token.isNot(MIToken::StringConstant))
3927 return error("expected string constant");
3928 Result = std::string(Token.stringValue());
3929 lex();
3930 return false;
3931}
3932
3934 StringRef Src,
3936 return MIParser(PFS, Error, Src).parseBasicBlockDefinitions(PFS.MBBSlots);
3937}
3938
3941 return MIParser(PFS, Error, Src).parseBasicBlocks();
3942}
3943
3947 return MIParser(PFS, Error, Src).parseStandaloneMBB(MBB);
3948}
3949
3951 Register &Reg, StringRef Src,
3953 return MIParser(PFS, Error, Src).parseStandaloneRegister(Reg);
3954}
3955
3957 Register &Reg, StringRef Src,
3959 return MIParser(PFS, Error, Src).parseStandaloneNamedRegister(Reg);
3960}
3961
3963 VRegInfo *&Info, StringRef Src,
3965 return MIParser(PFS, Error, Src).parseStandaloneVirtualRegister(Info);
3966}
3967
3970 return MIParser(PFS, Error, Src).parseStandaloneStackObject(FI);
3971}
3972
3976 return MIParser(PFS, Error, Src).parsePrefetchTarget(Target);
3977}
3980 return MIParser(PFS, Error, Src).parseStandaloneMDNode(Node);
3981}
3982
3984 PerFunctionMIParsingState &PFS, const Value *&V,
3985 ErrorCallbackType ErrorCallback) {
3986 MIToken Token;
3987 Src = lexMIToken(Src, Token, [&](StringRef::iterator Loc, const Twine &Msg) {
3988 ErrorCallback(Loc, Msg);
3989 });
3990 V = nullptr;
3991
3992 return ::parseIRValue(Token, PFS, V, ErrorCallback);
3993}
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
uint64_t 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 bool verifyVectorElementCount(uint64_t NumElts, bool HasVScale)
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 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:606
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))
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
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:1560
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:471
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:44
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:793
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:312
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:76
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:1081
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
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.
void setIsCleanupFuncletEntry(bool V=true)
Indicates if this is the entry block of a cleanup funclet.
void setLabelMustBeEmitted()
Set this block to reflect that, regardless how we flow to it, we need its label be emitted.
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 setMaxBytesForAlignment(unsigned MaxBytes)
Set the maximum amount of padding allowed for aligning the 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 setIsEHContTarget(bool V=true)
Indicates if this is a target of Windows EH Continuation Guard.
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 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:307
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:34
unsigned getMainFileID() const
Definition SourceMgr.h:150
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition SourceMgr.h:141
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:263
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:83
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:66
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:1755
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)
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
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:774
MDNode * NoAliasAddrSpace
The tag specifying the noalias address spaces.
Definition Metadata.h:803
MDNode * Scope
The tag for alias scope specification (used with noalias).
Definition Metadata.h:797
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:791
MDNode * NoAlias
The tag specifying the noalias scope.
Definition Metadata.h:800
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:222
bool hasIntegerValue() const
Definition MILexer.h:262
bool is(TokenKind K) const
Definition MILexer.h:249
StringRef stringValue() const
Return the token's string value.
Definition MILexer.h:258
@ kw_pre_instr_symbol
Definition MILexer.h:144
@ kw_deactivation_symbol
Definition MILexer.h:149
@ kw_call_frame_size
Definition MILexer.h:157
@ 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:181
@ kw_dbg_instr_ref
Definition MILexer.h:85
@ NamedVirtualRegister
Definition MILexer.h:179
@ kw_early_clobber
Definition MILexer.h:59
@ kw_cleanup_funclet_entry
Definition MILexer.h:137
@ kw_unpredictable
Definition MILexer.h:77
@ FloatingPointLiteral
Definition MILexer.h:191
@ 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:180
@ 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_label_must_be_emitted
Definition MILexer.h:156
@ 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_max_bytes_for_alignment
Definition MILexer.h:158
@ kw_cfi_def_cfa_offset
Definition MILexer.h:90
@ md_mem_cache_hint
Definition MILexer.h:172
@ kw_machine_block_address_taken
Definition MILexer.h:155
@ kw_cfi_remember_state
Definition MILexer.h:96
@ kw_debug_instr_number
Definition MILexer.h:84
@ kw_post_instr_symbol
Definition MILexer.h:145
@ kw_cfi_restore_state
Definition MILexer.h:98
@ kw_ir_block_address_taken
Definition MILexer.h:154
@ kw_unknown_address
Definition MILexer.h:153
@ md_noalias_addrspace
Definition MILexer.h:170
@ kw_debug_location
Definition MILexer.h:83
@ kw_heap_alloc_marker
Definition MILexer.h:146
StringRef range() const
Definition MILexer.h:255
StringRef::iterator location() const
Definition MILexer.h:253
const APSInt & integerValue() const
Definition MILexer.h:260
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:173
LLVM_ABI const Value * getIRValue(unsigned Slot)
Definition MIParser.cpp:374
DenseMap< unsigned, MachineBasicBlock * > MBBSlots
Definition MIParser.h:178
StringMap< VRegInfo * > VRegInfosNamed
Definition MIParser.h:180
DenseMap< unsigned, const Value * > Slots2Values
Maps from slot numbers to function's unnamed values.
Definition MIParser.h:187
LLVM_ABI PerFunctionMIParsingState(MachineFunction &MF, SourceMgr &SM, const SlotMapping &IRSlots, PerTargetMIParsingState &Target)
Definition MIParser.cpp:324
PerTargetMIParsingState & Target
Definition MIParser.h:174
DenseMap< Register, VRegInfo * > VRegInfos
Definition MIParser.h:179
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