LLVM 22.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/InstrTypes.h"
51#include "llvm/IR/Intrinsics.h"
52#include "llvm/IR/Metadata.h"
53#include "llvm/IR/Module.h"
55#include "llvm/IR/Type.h"
56#include "llvm/IR/Value.h"
58#include "llvm/MC/LaneBitmask.h"
59#include "llvm/MC/MCContext.h"
60#include "llvm/MC/MCDwarf.h"
61#include "llvm/MC/MCInstrDesc.h"
67#include "llvm/Support/SMLoc.h"
70#include <cassert>
71#include <cctype>
72#include <cstddef>
73#include <cstdint>
74#include <limits>
75#include <string>
76#include <utility>
77
78using namespace llvm;
79
81 const TargetSubtargetInfo &NewSubtarget) {
82
83 // If the subtarget changed, over conservatively assume everything is invalid.
84 if (&Subtarget == &NewSubtarget)
85 return;
86
87 Names2InstrOpCodes.clear();
88 Names2Regs.clear();
89 Names2RegMasks.clear();
90 Names2SubRegIndices.clear();
91 Names2TargetIndices.clear();
92 Names2DirectTargetFlags.clear();
93 Names2BitmaskTargetFlags.clear();
94 Names2MMOTargetFlags.clear();
95
96 initNames2RegClasses();
97 initNames2RegBanks();
98}
99
100void PerTargetMIParsingState::initNames2Regs() {
101 if (!Names2Regs.empty())
102 return;
103
104 // The '%noreg' register is the register 0.
105 Names2Regs.insert(std::make_pair("noreg", 0));
106 const auto *TRI = Subtarget.getRegisterInfo();
107 assert(TRI && "Expected target register info");
108
109 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
110 bool WasInserted =
111 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
112 .second;
113 (void)WasInserted;
114 assert(WasInserted && "Expected registers to be unique case-insensitively");
115 }
116}
117
119 Register &Reg) {
120 initNames2Regs();
121 auto RegInfo = Names2Regs.find(RegName);
122 if (RegInfo == Names2Regs.end())
123 return true;
124 Reg = RegInfo->getValue();
125 return false;
126}
127
129 uint8_t &FlagValue) const {
130 const auto *TRI = Subtarget.getRegisterInfo();
131 std::optional<uint8_t> FV = TRI->getVRegFlagValue(FlagName);
132 if (!FV)
133 return true;
134 FlagValue = *FV;
135 return false;
136}
137
138void PerTargetMIParsingState::initNames2InstrOpCodes() {
139 if (!Names2InstrOpCodes.empty())
140 return;
141 const auto *TII = Subtarget.getInstrInfo();
142 assert(TII && "Expected target instruction info");
143 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
144 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
145}
146
148 unsigned &OpCode) {
149 initNames2InstrOpCodes();
150 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
151 if (InstrInfo == Names2InstrOpCodes.end())
152 return true;
153 OpCode = InstrInfo->getValue();
154 return false;
155}
156
157void PerTargetMIParsingState::initNames2RegMasks() {
158 if (!Names2RegMasks.empty())
159 return;
160 const auto *TRI = Subtarget.getRegisterInfo();
161 assert(TRI && "Expected target register info");
162 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
163 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
164 assert(RegMasks.size() == RegMaskNames.size());
165 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
166 Names2RegMasks.insert(
167 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
168}
169
171 initNames2RegMasks();
172 auto RegMaskInfo = Names2RegMasks.find(Identifier);
173 if (RegMaskInfo == Names2RegMasks.end())
174 return nullptr;
175 return RegMaskInfo->getValue();
176}
177
178void PerTargetMIParsingState::initNames2SubRegIndices() {
179 if (!Names2SubRegIndices.empty())
180 return;
181 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
182 for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
183 Names2SubRegIndices.insert(
184 std::make_pair(TRI->getSubRegIndexName(I), I));
185}
186
188 initNames2SubRegIndices();
189 auto SubRegInfo = Names2SubRegIndices.find(Name);
190 if (SubRegInfo == Names2SubRegIndices.end())
191 return 0;
192 return SubRegInfo->getValue();
193}
194
195void PerTargetMIParsingState::initNames2TargetIndices() {
196 if (!Names2TargetIndices.empty())
197 return;
198 const auto *TII = Subtarget.getInstrInfo();
199 assert(TII && "Expected target instruction info");
200 auto Indices = TII->getSerializableTargetIndices();
201 for (const auto &I : Indices)
202 Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
203}
204
206 initNames2TargetIndices();
207 auto IndexInfo = Names2TargetIndices.find(Name);
208 if (IndexInfo == Names2TargetIndices.end())
209 return true;
210 Index = IndexInfo->second;
211 return false;
212}
213
214void PerTargetMIParsingState::initNames2DirectTargetFlags() {
215 if (!Names2DirectTargetFlags.empty())
216 return;
217
218 const auto *TII = Subtarget.getInstrInfo();
219 assert(TII && "Expected target instruction info");
220 auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
221 for (const auto &I : Flags)
222 Names2DirectTargetFlags.insert(
223 std::make_pair(StringRef(I.second), I.first));
224}
225
227 unsigned &Flag) {
228 initNames2DirectTargetFlags();
229 auto FlagInfo = Names2DirectTargetFlags.find(Name);
230 if (FlagInfo == Names2DirectTargetFlags.end())
231 return true;
232 Flag = FlagInfo->second;
233 return false;
234}
235
236void PerTargetMIParsingState::initNames2BitmaskTargetFlags() {
237 if (!Names2BitmaskTargetFlags.empty())
238 return;
239
240 const auto *TII = Subtarget.getInstrInfo();
241 assert(TII && "Expected target instruction info");
242 auto Flags = TII->getSerializableBitmaskMachineOperandTargetFlags();
243 for (const auto &I : Flags)
244 Names2BitmaskTargetFlags.insert(
245 std::make_pair(StringRef(I.second), I.first));
246}
247
249 unsigned &Flag) {
250 initNames2BitmaskTargetFlags();
251 auto FlagInfo = Names2BitmaskTargetFlags.find(Name);
252 if (FlagInfo == Names2BitmaskTargetFlags.end())
253 return true;
254 Flag = FlagInfo->second;
255 return false;
256}
257
258void PerTargetMIParsingState::initNames2MMOTargetFlags() {
259 if (!Names2MMOTargetFlags.empty())
260 return;
261
262 const auto *TII = Subtarget.getInstrInfo();
263 assert(TII && "Expected target instruction info");
264 auto Flags = TII->getSerializableMachineMemOperandTargetFlags();
265 for (const auto &I : Flags)
266 Names2MMOTargetFlags.insert(std::make_pair(StringRef(I.second), I.first));
267}
268
271 initNames2MMOTargetFlags();
272 auto FlagInfo = Names2MMOTargetFlags.find(Name);
273 if (FlagInfo == Names2MMOTargetFlags.end())
274 return true;
275 Flag = FlagInfo->second;
276 return false;
277}
278
279void PerTargetMIParsingState::initNames2RegClasses() {
280 if (!Names2RegClasses.empty())
281 return;
282
283 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
284 for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) {
285 const auto *RC = TRI->getRegClass(I);
286 Names2RegClasses.insert(
287 std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC));
288 }
289}
290
291void PerTargetMIParsingState::initNames2RegBanks() {
292 if (!Names2RegBanks.empty())
293 return;
294
295 const RegisterBankInfo *RBI = Subtarget.getRegBankInfo();
296 // If the target does not support GlobalISel, we may not have a
297 // register bank info.
298 if (!RBI)
299 return;
300
301 for (unsigned I = 0, E = RBI->getNumRegBanks(); I < E; ++I) {
302 const auto &RegBank = RBI->getRegBank(I);
303 Names2RegBanks.insert(
304 std::make_pair(StringRef(RegBank.getName()).lower(), &RegBank));
305 }
306}
307
310 auto RegClassInfo = Names2RegClasses.find(Name);
311 if (RegClassInfo == Names2RegClasses.end())
312 return nullptr;
313 return RegClassInfo->getValue();
314}
315
317 auto RegBankInfo = Names2RegBanks.find(Name);
318 if (RegBankInfo == Names2RegBanks.end())
319 return nullptr;
320 return RegBankInfo->getValue();
321}
322
327
329 auto I = VRegInfos.try_emplace(Num);
330 if (I.second) {
331 MachineRegisterInfo &MRI = MF.getRegInfo();
332 VRegInfo *Info = new (Allocator) VRegInfo;
333 Info->VReg = MRI.createIncompleteVirtualRegister();
334 I.first->second = Info;
335 }
336 return *I.first->second;
337}
338
340 assert(RegName != "" && "Expected named reg.");
341
342 auto I = VRegInfosNamed.try_emplace(RegName.str());
343 if (I.second) {
344 VRegInfo *Info = new (Allocator) VRegInfo;
345 Info->VReg = MF.getRegInfo().createIncompleteVirtualRegister(RegName);
346 I.first->second = Info;
347 }
348 return *I.first->second;
349}
350
351static void mapValueToSlot(const Value *V, ModuleSlotTracker &MST,
352 DenseMap<unsigned, const Value *> &Slots2Values) {
353 int Slot = MST.getLocalSlot(V);
354 if (Slot == -1)
355 return;
356 Slots2Values.insert(std::make_pair(unsigned(Slot), V));
357}
358
359/// Creates the mapping from slot numbers to function's unnamed IR values.
360static void initSlots2Values(const Function &F,
361 DenseMap<unsigned, const Value *> &Slots2Values) {
362 ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
364 for (const auto &Arg : F.args())
365 mapValueToSlot(&Arg, MST, Slots2Values);
366 for (const auto &BB : F) {
367 mapValueToSlot(&BB, MST, Slots2Values);
368 for (const auto &I : BB)
369 mapValueToSlot(&I, MST, Slots2Values);
370 }
371}
372
374 if (Slots2Values.empty())
375 initSlots2Values(MF.getFunction(), Slots2Values);
376 return Slots2Values.lookup(Slot);
377}
378
379namespace {
380
381/// A wrapper struct around the 'MachineOperand' struct that includes a source
382/// range and other attributes.
383struct ParsedMachineOperand {
384 MachineOperand Operand;
387 std::optional<unsigned> TiedDefIdx;
388
389 ParsedMachineOperand(const MachineOperand &Operand, StringRef::iterator Begin,
391 std::optional<unsigned> &TiedDefIdx)
392 : Operand(Operand), Begin(Begin), End(End), TiedDefIdx(TiedDefIdx) {
393 if (TiedDefIdx)
394 assert(Operand.isReg() && Operand.isUse() &&
395 "Only used register operands can be tied");
396 }
397};
398
399class MIParser {
400 MachineFunction &MF;
401 SMDiagnostic &Error;
402 StringRef Source, CurrentSource;
403 SMRange SourceRange;
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 MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
413 StringRef Source, SMRange SourceRange);
414
415 /// \p SkipChar gives the number of characters to skip before looking
416 /// for the next token.
417 void lex(unsigned SkipChar = 0);
418
419 /// Report an error at the current location with the given message.
420 ///
421 /// This function always return true.
422 bool error(const Twine &Msg);
423
424 /// Report an error at the given location with the given message.
425 ///
426 /// This function always return true.
427 bool error(StringRef::iterator Loc, const Twine &Msg);
428
429 bool
430 parseBasicBlockDefinitions(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
431 bool parseBasicBlocks();
432 bool parse(MachineInstr *&MI);
433 bool parseStandaloneMBB(MachineBasicBlock *&MBB);
434 bool parseStandaloneNamedRegister(Register &Reg);
435 bool parseStandaloneVirtualRegister(VRegInfo *&Info);
436 bool parseStandaloneRegister(Register &Reg);
437 bool parseStandaloneStackObject(int &FI);
438 bool parseStandaloneMDNode(MDNode *&Node);
440 bool parseMDTuple(MDNode *&MD, bool IsDistinct);
441 bool parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts);
442 bool parseMetadata(Metadata *&MD);
443
444 bool
445 parseBasicBlockDefinition(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
446 bool parseBasicBlock(MachineBasicBlock &MBB,
447 MachineBasicBlock *&AddFalthroughFrom);
448 bool parseBasicBlockLiveins(MachineBasicBlock &MBB);
449 bool parseBasicBlockSuccessors(MachineBasicBlock &MBB);
450
451 bool parseNamedRegister(Register &Reg);
452 bool parseVirtualRegister(VRegInfo *&Info);
453 bool parseNamedVirtualRegister(VRegInfo *&Info);
454 bool parseRegister(Register &Reg, VRegInfo *&VRegInfo);
455 bool parseRegisterFlag(unsigned &Flags);
456 bool parseRegisterClassOrBank(VRegInfo &RegInfo);
457 bool parseSubRegisterIndex(unsigned &SubReg);
458 bool parseRegisterTiedDefIndex(unsigned &TiedDefIdx);
459 bool parseRegisterOperand(MachineOperand &Dest,
460 std::optional<unsigned> &TiedDefIdx,
461 bool IsDef = false);
462 bool parseImmediateOperand(MachineOperand &Dest);
463 bool parseIRConstant(StringRef::iterator Loc, StringRef StringValue,
464 const Constant *&C);
465 bool parseIRConstant(StringRef::iterator Loc, const Constant *&C);
466 bool parseLowLevelType(StringRef::iterator Loc, LLT &Ty);
467 bool parseTypedImmediateOperand(MachineOperand &Dest);
468 bool parseFPImmediateOperand(MachineOperand &Dest);
469 bool parseMBBReference(MachineBasicBlock *&MBB);
470 bool parseMBBOperand(MachineOperand &Dest);
471 bool parseStackFrameIndex(int &FI);
472 bool parseStackObjectOperand(MachineOperand &Dest);
473 bool parseFixedStackFrameIndex(int &FI);
474 bool parseFixedStackObjectOperand(MachineOperand &Dest);
475 bool parseGlobalValue(GlobalValue *&GV);
476 bool parseGlobalAddressOperand(MachineOperand &Dest);
477 bool parseConstantPoolIndexOperand(MachineOperand &Dest);
478 bool parseSubRegisterIndexOperand(MachineOperand &Dest);
479 bool parseJumpTableIndexOperand(MachineOperand &Dest);
480 bool parseExternalSymbolOperand(MachineOperand &Dest);
481 bool parseMCSymbolOperand(MachineOperand &Dest);
482 [[nodiscard]] bool parseMDNode(MDNode *&Node);
483 bool parseDIExpression(MDNode *&Expr);
484 bool parseDILocation(MDNode *&Expr);
485 bool parseMetadataOperand(MachineOperand &Dest);
486 bool parseCFIOffset(int &Offset);
487 bool parseCFIRegister(unsigned &Reg);
488 bool parseCFIAddressSpace(unsigned &AddressSpace);
489 bool parseCFIEscapeValues(std::string& Values);
490 bool parseCFIOperand(MachineOperand &Dest);
491 bool parseIRBlock(BasicBlock *&BB, const Function &F);
492 bool parseBlockAddressOperand(MachineOperand &Dest);
493 bool parseIntrinsicOperand(MachineOperand &Dest);
494 bool parsePredicateOperand(MachineOperand &Dest);
495 bool parseShuffleMaskOperand(MachineOperand &Dest);
496 bool parseTargetIndexOperand(MachineOperand &Dest);
497 bool parseDbgInstrRefOperand(MachineOperand &Dest);
498 bool parseCustomRegisterMaskOperand(MachineOperand &Dest);
499 bool parseLaneMaskOperand(MachineOperand &Dest);
500 bool parseLiveoutRegisterMaskOperand(MachineOperand &Dest);
501 bool parseMachineOperand(const unsigned OpCode, const unsigned OpIdx,
502 MachineOperand &Dest,
503 std::optional<unsigned> &TiedDefIdx);
504 bool parseMachineOperandAndTargetFlags(const unsigned OpCode,
505 const unsigned OpIdx,
506 MachineOperand &Dest,
507 std::optional<unsigned> &TiedDefIdx);
508 bool parseOffset(int64_t &Offset);
509 bool parseIRBlockAddressTaken(BasicBlock *&BB);
510 bool parseAlignment(uint64_t &Alignment);
511 bool parseAddrspace(unsigned &Addrspace);
512 bool parseSectionID(std::optional<MBBSectionID> &SID);
513 bool parseBBID(std::optional<UniqueBBID> &BBID);
514 bool parseCallFrameSize(unsigned &CallFrameSize);
515 bool parseOperandsOffset(MachineOperand &Op);
516 bool parseIRValue(const Value *&V);
517 bool parseMemoryOperandFlag(MachineMemOperand::Flags &Flags);
518 bool parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV);
519 bool parseMachinePointerInfo(MachinePointerInfo &Dest);
520 bool parseOptionalScope(LLVMContext &Context, SyncScope::ID &SSID);
521 bool parseOptionalAtomicOrdering(AtomicOrdering &Order);
522 bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
523 bool parsePreOrPostInstrSymbol(MCSymbol *&Symbol);
524 bool parseHeapAllocMarker(MDNode *&Node);
525 bool parsePCSections(MDNode *&Node);
526
527 bool parseTargetImmMnemonic(const unsigned OpCode, const unsigned OpIdx,
528 MachineOperand &Dest, const MIRFormatter &MF);
529
530private:
531 /// Convert the integer literal in the current token into an unsigned integer.
532 ///
533 /// Return true if an error occurred.
534 bool getUnsigned(unsigned &Result);
535
536 /// Convert the integer literal in the current token into an uint64.
537 ///
538 /// Return true if an error occurred.
539 bool getUint64(uint64_t &Result);
540
541 /// Convert the hexadecimal literal in the current token into an unsigned
542 /// APInt with a minimum bitwidth required to represent the value.
543 ///
544 /// Return true if the literal does not represent an integer value.
545 bool getHexUint(APInt &Result);
546
547 /// If the current token is of the given kind, consume it and return false.
548 /// Otherwise report an error and return true.
549 bool expectAndConsume(MIToken::TokenKind TokenKind);
550
551 /// If the current token is of the given kind, consume it and return true.
552 /// Otherwise return false.
553 bool consumeIfPresent(MIToken::TokenKind TokenKind);
554
555 bool parseInstruction(unsigned &OpCode, unsigned &Flags);
556
557 bool assignRegisterTies(MachineInstr &MI,
559
560 bool verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands,
561 const MCInstrDesc &MCID);
562
563 const BasicBlock *getIRBlock(unsigned Slot);
564 const BasicBlock *getIRBlock(unsigned Slot, const Function &F);
565
566 /// Get or create an MCSymbol for a given name.
567 MCSymbol *getOrCreateMCSymbol(StringRef Name);
568
569 /// parseStringConstant
570 /// ::= StringConstant
571 bool parseStringConstant(std::string &Result);
572
573 /// Map the location in the MI string to the corresponding location specified
574 /// in `SourceRange`.
575 SMLoc mapSMLoc(StringRef::iterator Loc);
576};
577
578} // end anonymous namespace
579
580MIParser::MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
581 StringRef Source)
582 : MF(PFS.MF), Error(Error), Source(Source), CurrentSource(Source), PFS(PFS)
583{}
584
585MIParser::MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
586 StringRef Source, SMRange SourceRange)
587 : MF(PFS.MF), Error(Error), Source(Source), CurrentSource(Source),
588 SourceRange(SourceRange), PFS(PFS) {}
589
590void MIParser::lex(unsigned SkipChar) {
591 CurrentSource = lexMIToken(
592 CurrentSource.substr(SkipChar), Token,
593 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
594}
595
596bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
597
598bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
599 const SourceMgr &SM = *PFS.SM;
600 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
601 const MemoryBuffer &Buffer = *SM.getMemoryBuffer(SM.getMainFileID());
602 if (Loc >= Buffer.getBufferStart() && Loc <= Buffer.getBufferEnd()) {
603 // Create an ordinary diagnostic when the source manager's buffer is the
604 // source string.
606 return true;
607 }
608 // Create a diagnostic for a YAML string literal.
609 Error = SMDiagnostic(SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
610 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(),
611 Source, {}, {});
612 return true;
613}
614
615SMLoc MIParser::mapSMLoc(StringRef::iterator Loc) {
616 assert(SourceRange.isValid() && "Invalid source range");
617 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
618 return SMLoc::getFromPointer(SourceRange.Start.getPointer() +
619 (Loc - Source.data()));
620}
621
622typedef function_ref<bool(StringRef::iterator Loc, const Twine &)>
624
625static const char *toString(MIToken::TokenKind TokenKind) {
626 switch (TokenKind) {
627 case MIToken::comma:
628 return "','";
629 case MIToken::equal:
630 return "'='";
631 case MIToken::colon:
632 return "':'";
633 case MIToken::lparen:
634 return "'('";
635 case MIToken::rparen:
636 return "')'";
637 default:
638 return "<unknown token>";
639 }
640}
641
642bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
643 if (Token.isNot(TokenKind))
644 return error(Twine("expected ") + toString(TokenKind));
645 lex();
646 return false;
647}
648
649bool MIParser::consumeIfPresent(MIToken::TokenKind TokenKind) {
650 if (Token.isNot(TokenKind))
651 return false;
652 lex();
653 return true;
654}
655
656// Parse Machine Basic Block Section ID.
657bool MIParser::parseSectionID(std::optional<MBBSectionID> &SID) {
659 lex();
660 if (Token.is(MIToken::IntegerLiteral)) {
661 unsigned Value = 0;
662 if (getUnsigned(Value))
663 return error("Unknown Section ID");
664 SID = MBBSectionID{Value};
665 } else {
666 const StringRef &S = Token.stringValue();
667 if (S == "Exception")
669 else if (S == "Cold")
671 else
672 return error("Unknown Section ID");
673 }
674 lex();
675 return false;
676}
677
678// Parse Machine Basic Block ID.
679bool MIParser::parseBBID(std::optional<UniqueBBID> &BBID) {
680 assert(Token.is(MIToken::kw_bb_id));
681 lex();
682 unsigned BaseID = 0;
683 unsigned CloneID = 0;
684 if (getUnsigned(BaseID))
685 return error("Unknown BB ID");
686 lex();
687 if (Token.is(MIToken::IntegerLiteral)) {
688 if (getUnsigned(CloneID))
689 return error("Unknown Clone ID");
690 lex();
691 }
692 BBID = {BaseID, CloneID};
693 return false;
694}
695
696// Parse basic block call frame size.
697bool MIParser::parseCallFrameSize(unsigned &CallFrameSize) {
699 lex();
700 unsigned Value = 0;
701 if (getUnsigned(Value))
702 return error("Unknown call frame size");
703 CallFrameSize = Value;
704 lex();
705 return false;
706}
707
708bool MIParser::parseBasicBlockDefinition(
711 unsigned ID = 0;
712 if (getUnsigned(ID))
713 return true;
714 auto Loc = Token.location();
715 auto Name = Token.stringValue();
716 lex();
717 bool MachineBlockAddressTaken = false;
718 BasicBlock *AddressTakenIRBlock = nullptr;
719 bool IsLandingPad = false;
720 bool IsInlineAsmBrIndirectTarget = false;
721 bool IsEHFuncletEntry = false;
722 std::optional<MBBSectionID> SectionID;
723 uint64_t Alignment = 0;
724 std::optional<UniqueBBID> BBID;
725 unsigned CallFrameSize = 0;
726 BasicBlock *BB = nullptr;
727 if (consumeIfPresent(MIToken::lparen)) {
728 do {
729 // TODO: Report an error when multiple same attributes are specified.
730 switch (Token.kind()) {
732 MachineBlockAddressTaken = true;
733 lex();
734 break;
736 if (parseIRBlockAddressTaken(AddressTakenIRBlock))
737 return true;
738 break;
740 IsLandingPad = true;
741 lex();
742 break;
744 IsInlineAsmBrIndirectTarget = true;
745 lex();
746 break;
748 IsEHFuncletEntry = true;
749 lex();
750 break;
752 if (parseAlignment(Alignment))
753 return true;
754 break;
755 case MIToken::IRBlock:
757 // TODO: Report an error when both name and ir block are specified.
758 if (parseIRBlock(BB, MF.getFunction()))
759 return true;
760 lex();
761 break;
763 if (parseSectionID(SectionID))
764 return true;
765 break;
767 if (parseBBID(BBID))
768 return true;
769 break;
771 if (parseCallFrameSize(CallFrameSize))
772 return true;
773 break;
774 default:
775 break;
776 }
777 } while (consumeIfPresent(MIToken::comma));
778 if (expectAndConsume(MIToken::rparen))
779 return true;
780 }
781 if (expectAndConsume(MIToken::colon))
782 return true;
783
784 if (!Name.empty()) {
786 MF.getFunction().getValueSymbolTable()->lookup(Name));
787 if (!BB)
788 return error(Loc, Twine("basic block '") + Name +
789 "' is not defined in the function '" +
790 MF.getName() + "'");
791 }
792 auto *MBB = MF.CreateMachineBasicBlock(BB, BBID);
793 MF.insert(MF.end(), MBB);
794 bool WasInserted = MBBSlots.insert(std::make_pair(ID, MBB)).second;
795 if (!WasInserted)
796 return error(Loc, Twine("redefinition of machine basic block with id #") +
797 Twine(ID));
798 if (Alignment)
799 MBB->setAlignment(Align(Alignment));
800 if (MachineBlockAddressTaken)
802 if (AddressTakenIRBlock)
803 MBB->setAddressTakenIRBlock(AddressTakenIRBlock);
804 MBB->setIsEHPad(IsLandingPad);
805 MBB->setIsInlineAsmBrIndirectTarget(IsInlineAsmBrIndirectTarget);
806 MBB->setIsEHFuncletEntry(IsEHFuncletEntry);
807 if (SectionID) {
808 MBB->setSectionID(*SectionID);
809 MF.setBBSectionsType(BasicBlockSection::List);
810 }
811 MBB->setCallFrameSize(CallFrameSize);
812 return false;
813}
814
815bool MIParser::parseBasicBlockDefinitions(
817 lex();
818 // Skip until the first machine basic block.
819 while (Token.is(MIToken::Newline))
820 lex();
821 if (Token.isErrorOrEOF())
822 return Token.isError();
823 if (Token.isNot(MIToken::MachineBasicBlockLabel))
824 return error("expected a basic block definition before instructions");
825 unsigned BraceDepth = 0;
826 do {
827 if (parseBasicBlockDefinition(MBBSlots))
828 return true;
829 bool IsAfterNewline = false;
830 // Skip until the next machine basic block.
831 while (true) {
832 if ((Token.is(MIToken::MachineBasicBlockLabel) && IsAfterNewline) ||
833 Token.isErrorOrEOF())
834 break;
835 else if (Token.is(MIToken::MachineBasicBlockLabel))
836 return error("basic block definition should be located at the start of "
837 "the line");
838 else if (consumeIfPresent(MIToken::Newline)) {
839 IsAfterNewline = true;
840 continue;
841 }
842 IsAfterNewline = false;
843 if (Token.is(MIToken::lbrace))
844 ++BraceDepth;
845 if (Token.is(MIToken::rbrace)) {
846 if (!BraceDepth)
847 return error("extraneous closing brace ('}')");
848 --BraceDepth;
849 }
850 lex();
851 }
852 // Verify that we closed all of the '{' at the end of a file or a block.
853 if (!Token.isError() && BraceDepth)
854 return error("expected '}'"); // FIXME: Report a note that shows '{'.
855 } while (!Token.isErrorOrEOF());
856 return Token.isError();
857}
858
859bool MIParser::parseBasicBlockLiveins(MachineBasicBlock &MBB) {
860 assert(Token.is(MIToken::kw_liveins));
861 lex();
862 if (expectAndConsume(MIToken::colon))
863 return true;
864 if (Token.isNewlineOrEOF()) // Allow an empty list of liveins.
865 return false;
866 do {
867 if (Token.isNot(MIToken::NamedRegister))
868 return error("expected a named register");
870 if (parseNamedRegister(Reg))
871 return true;
872 lex();
874 if (consumeIfPresent(MIToken::colon)) {
875 // Parse lane mask.
876 if (Token.isNot(MIToken::IntegerLiteral) &&
877 Token.isNot(MIToken::HexLiteral))
878 return error("expected a lane mask");
879 static_assert(sizeof(LaneBitmask::Type) == sizeof(uint64_t),
880 "Use correct get-function for lane mask");
882 if (getUint64(V))
883 return error("invalid lane mask value");
884 Mask = LaneBitmask(V);
885 lex();
886 }
887 MBB.addLiveIn(Reg, Mask);
888 } while (consumeIfPresent(MIToken::comma));
889 return false;
890}
891
892bool MIParser::parseBasicBlockSuccessors(MachineBasicBlock &MBB) {
894 lex();
895 if (expectAndConsume(MIToken::colon))
896 return true;
897 if (Token.isNewlineOrEOF()) // Allow an empty list of successors.
898 return false;
899 do {
900 if (Token.isNot(MIToken::MachineBasicBlock))
901 return error("expected a machine basic block reference");
902 MachineBasicBlock *SuccMBB = nullptr;
903 if (parseMBBReference(SuccMBB))
904 return true;
905 lex();
906 unsigned Weight = 0;
907 if (consumeIfPresent(MIToken::lparen)) {
908 if (Token.isNot(MIToken::IntegerLiteral) &&
909 Token.isNot(MIToken::HexLiteral))
910 return error("expected an integer literal after '('");
911 if (getUnsigned(Weight))
912 return true;
913 lex();
914 if (expectAndConsume(MIToken::rparen))
915 return true;
916 }
918 } while (consumeIfPresent(MIToken::comma));
920 return false;
921}
922
923bool MIParser::parseBasicBlock(MachineBasicBlock &MBB,
924 MachineBasicBlock *&AddFalthroughFrom) {
925 // Skip the definition.
927 lex();
928 if (consumeIfPresent(MIToken::lparen)) {
929 while (Token.isNot(MIToken::rparen) && !Token.isErrorOrEOF())
930 lex();
931 consumeIfPresent(MIToken::rparen);
932 }
933 consumeIfPresent(MIToken::colon);
934
935 // Parse the liveins and successors.
936 // N.B: Multiple lists of successors and liveins are allowed and they're
937 // merged into one.
938 // Example:
939 // liveins: $edi
940 // liveins: $esi
941 //
942 // is equivalent to
943 // liveins: $edi, $esi
944 bool ExplicitSuccessors = false;
945 while (true) {
946 if (Token.is(MIToken::kw_successors)) {
947 if (parseBasicBlockSuccessors(MBB))
948 return true;
949 ExplicitSuccessors = true;
950 } else if (Token.is(MIToken::kw_liveins)) {
951 if (parseBasicBlockLiveins(MBB))
952 return true;
953 } else if (consumeIfPresent(MIToken::Newline)) {
954 continue;
955 } else
956 break;
957 if (!Token.isNewlineOrEOF())
958 return error("expected line break at the end of a list");
959 lex();
960 }
961
962 // Parse the instructions.
963 bool IsInBundle = false;
964 MachineInstr *PrevMI = nullptr;
965 while (!Token.is(MIToken::MachineBasicBlockLabel) &&
966 !Token.is(MIToken::Eof)) {
967 if (consumeIfPresent(MIToken::Newline))
968 continue;
969 if (consumeIfPresent(MIToken::rbrace)) {
970 // The first parsing pass should verify that all closing '}' have an
971 // opening '{'.
972 assert(IsInBundle);
973 IsInBundle = false;
974 continue;
975 }
976 MachineInstr *MI = nullptr;
977 if (parse(MI))
978 return true;
979 MBB.insert(MBB.end(), MI);
980 if (IsInBundle) {
983 }
984 PrevMI = MI;
985 if (Token.is(MIToken::lbrace)) {
986 if (IsInBundle)
987 return error("nested instruction bundles are not allowed");
988 lex();
989 // This instruction is the start of the bundle.
991 IsInBundle = true;
992 if (!Token.is(MIToken::Newline))
993 // The next instruction can be on the same line.
994 continue;
995 }
996 assert(Token.isNewlineOrEOF() && "MI is not fully parsed");
997 lex();
998 }
999
1000 // Construct successor list by searching for basic block machine operands.
1001 if (!ExplicitSuccessors) {
1003 bool IsFallthrough;
1004 guessSuccessors(MBB, Successors, IsFallthrough);
1005 for (MachineBasicBlock *Succ : Successors)
1006 MBB.addSuccessor(Succ);
1007
1008 if (IsFallthrough) {
1009 AddFalthroughFrom = &MBB;
1010 } else {
1012 }
1013 }
1014
1015 return false;
1016}
1017
1018bool MIParser::parseBasicBlocks() {
1019 lex();
1020 // Skip until the first machine basic block.
1021 while (Token.is(MIToken::Newline))
1022 lex();
1023 if (Token.isErrorOrEOF())
1024 return Token.isError();
1025 // The first parsing pass should have verified that this token is a MBB label
1026 // in the 'parseBasicBlockDefinitions' method.
1028 MachineBasicBlock *AddFalthroughFrom = nullptr;
1029 do {
1030 MachineBasicBlock *MBB = nullptr;
1032 return true;
1033 if (AddFalthroughFrom) {
1034 if (!AddFalthroughFrom->isSuccessor(MBB))
1035 AddFalthroughFrom->addSuccessor(MBB);
1036 AddFalthroughFrom->normalizeSuccProbs();
1037 AddFalthroughFrom = nullptr;
1038 }
1039 if (parseBasicBlock(*MBB, AddFalthroughFrom))
1040 return true;
1041 // The method 'parseBasicBlock' should parse the whole block until the next
1042 // block or the end of file.
1043 assert(Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof));
1044 } while (Token.isNot(MIToken::Eof));
1045 return false;
1046}
1047
1048bool MIParser::parse(MachineInstr *&MI) {
1049 // Parse any register operands before '='
1052 while (Token.isRegister() || Token.isRegisterFlag()) {
1053 auto Loc = Token.location();
1054 std::optional<unsigned> TiedDefIdx;
1055 if (parseRegisterOperand(MO, TiedDefIdx, /*IsDef=*/true))
1056 return true;
1057 Operands.push_back(
1058 ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx));
1059 if (Token.isNot(MIToken::comma))
1060 break;
1061 lex();
1062 }
1063 if (!Operands.empty() && expectAndConsume(MIToken::equal))
1064 return true;
1065
1066 unsigned OpCode, Flags = 0;
1067 if (Token.isError() || parseInstruction(OpCode, Flags))
1068 return true;
1069
1070 // Parse the remaining machine operands.
1071 while (!Token.isNewlineOrEOF() && Token.isNot(MIToken::kw_pre_instr_symbol) &&
1072 Token.isNot(MIToken::kw_post_instr_symbol) &&
1073 Token.isNot(MIToken::kw_heap_alloc_marker) &&
1074 Token.isNot(MIToken::kw_pcsections) &&
1075 Token.isNot(MIToken::kw_cfi_type) &&
1076 Token.isNot(MIToken::kw_deactivation_symbol) &&
1077 Token.isNot(MIToken::kw_debug_location) &&
1078 Token.isNot(MIToken::kw_debug_instr_number) &&
1079 Token.isNot(MIToken::coloncolon) && Token.isNot(MIToken::lbrace)) {
1080 auto Loc = Token.location();
1081 std::optional<unsigned> TiedDefIdx;
1082 if (parseMachineOperandAndTargetFlags(OpCode, Operands.size(), MO, TiedDefIdx))
1083 return true;
1084 Operands.push_back(
1085 ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx));
1086 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
1087 Token.is(MIToken::lbrace))
1088 break;
1089 if (Token.isNot(MIToken::comma))
1090 return error("expected ',' before the next machine operand");
1091 lex();
1092 }
1093
1094 MCSymbol *PreInstrSymbol = nullptr;
1095 if (Token.is(MIToken::kw_pre_instr_symbol))
1096 if (parsePreOrPostInstrSymbol(PreInstrSymbol))
1097 return true;
1098 MCSymbol *PostInstrSymbol = nullptr;
1099 if (Token.is(MIToken::kw_post_instr_symbol))
1100 if (parsePreOrPostInstrSymbol(PostInstrSymbol))
1101 return true;
1102 MDNode *HeapAllocMarker = nullptr;
1103 if (Token.is(MIToken::kw_heap_alloc_marker))
1104 if (parseHeapAllocMarker(HeapAllocMarker))
1105 return true;
1106 MDNode *PCSections = nullptr;
1107 if (Token.is(MIToken::kw_pcsections))
1108 if (parsePCSections(PCSections))
1109 return true;
1110
1111 unsigned CFIType = 0;
1112 if (Token.is(MIToken::kw_cfi_type)) {
1113 lex();
1114 if (Token.isNot(MIToken::IntegerLiteral))
1115 return error("expected an integer literal after 'cfi-type'");
1116 // getUnsigned is sufficient for 32-bit integers.
1117 if (getUnsigned(CFIType))
1118 return true;
1119 lex();
1120 // Lex past trailing comma if present.
1121 if (Token.is(MIToken::comma))
1122 lex();
1123 }
1124
1125 GlobalValue *DS = nullptr;
1126 if (Token.is(MIToken::kw_deactivation_symbol)) {
1127 lex();
1128 if (parseGlobalValue(DS))
1129 return true;
1130 lex();
1131 }
1132
1133 unsigned InstrNum = 0;
1134 if (Token.is(MIToken::kw_debug_instr_number)) {
1135 lex();
1136 if (Token.isNot(MIToken::IntegerLiteral))
1137 return error("expected an integer literal after 'debug-instr-number'");
1138 if (getUnsigned(InstrNum))
1139 return true;
1140 lex();
1141 // Lex past trailing comma if present.
1142 if (Token.is(MIToken::comma))
1143 lex();
1144 }
1145
1146 DebugLoc DebugLocation;
1147 if (Token.is(MIToken::kw_debug_location)) {
1148 lex();
1149 MDNode *Node = nullptr;
1150 if (Token.is(MIToken::exclaim)) {
1151 if (parseMDNode(Node))
1152 return true;
1153 } else if (Token.is(MIToken::md_dilocation)) {
1154 if (parseDILocation(Node))
1155 return true;
1156 } else
1157 return error("expected a metadata node after 'debug-location'");
1158 if (!isa<DILocation>(Node))
1159 return error("referenced metadata is not a DILocation");
1160 DebugLocation = DebugLoc(Node);
1161 }
1162
1163 // Parse the machine memory operands.
1165 if (Token.is(MIToken::coloncolon)) {
1166 lex();
1167 while (!Token.isNewlineOrEOF()) {
1168 MachineMemOperand *MemOp = nullptr;
1169 if (parseMachineMemoryOperand(MemOp))
1170 return true;
1171 MemOperands.push_back(MemOp);
1172 if (Token.isNewlineOrEOF())
1173 break;
1174 if (OpCode == TargetOpcode::BUNDLE && Token.is(MIToken::lbrace))
1175 break;
1176 if (Token.isNot(MIToken::comma))
1177 return error("expected ',' before the next machine memory operand");
1178 lex();
1179 }
1180 }
1181
1182 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
1183 if (!MCID.isVariadic()) {
1184 // FIXME: Move the implicit operand verification to the machine verifier.
1185 if (verifyImplicitOperands(Operands, MCID))
1186 return true;
1187 }
1188
1189 MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
1190 MI->setFlags(Flags);
1191
1192 // Don't check the operands make sense, let the verifier catch any
1193 // improprieties.
1194 for (const auto &Operand : Operands)
1195 MI->addOperand(MF, Operand.Operand);
1196
1197 if (assignRegisterTies(*MI, Operands))
1198 return true;
1199 if (PreInstrSymbol)
1200 MI->setPreInstrSymbol(MF, PreInstrSymbol);
1201 if (PostInstrSymbol)
1202 MI->setPostInstrSymbol(MF, PostInstrSymbol);
1203 if (HeapAllocMarker)
1204 MI->setHeapAllocMarker(MF, HeapAllocMarker);
1205 if (PCSections)
1206 MI->setPCSections(MF, PCSections);
1207 if (CFIType)
1208 MI->setCFIType(MF, CFIType);
1209 if (DS)
1210 MI->setDeactivationSymbol(MF, DS);
1211 if (!MemOperands.empty())
1212 MI->setMemRefs(MF, MemOperands);
1213 if (InstrNum)
1214 MI->setDebugInstrNum(InstrNum);
1215 return false;
1216}
1217
1218bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
1219 lex();
1220 if (Token.isNot(MIToken::MachineBasicBlock))
1221 return error("expected a machine basic block reference");
1223 return true;
1224 lex();
1225 if (Token.isNot(MIToken::Eof))
1226 return error(
1227 "expected end of string after the machine basic block reference");
1228 return false;
1229}
1230
1231bool MIParser::parseStandaloneNamedRegister(Register &Reg) {
1232 lex();
1233 if (Token.isNot(MIToken::NamedRegister))
1234 return error("expected a named register");
1235 if (parseNamedRegister(Reg))
1236 return true;
1237 lex();
1238 if (Token.isNot(MIToken::Eof))
1239 return error("expected end of string after the register reference");
1240 return false;
1241}
1242
1243bool MIParser::parseStandaloneVirtualRegister(VRegInfo *&Info) {
1244 lex();
1245 if (Token.isNot(MIToken::VirtualRegister))
1246 return error("expected a virtual register");
1247 if (parseVirtualRegister(Info))
1248 return true;
1249 lex();
1250 if (Token.isNot(MIToken::Eof))
1251 return error("expected end of string after the register reference");
1252 return false;
1253}
1254
1255bool MIParser::parseStandaloneRegister(Register &Reg) {
1256 lex();
1257 if (Token.isNot(MIToken::NamedRegister) &&
1258 Token.isNot(MIToken::VirtualRegister))
1259 return error("expected either a named or virtual register");
1260
1261 VRegInfo *Info;
1262 if (parseRegister(Reg, Info))
1263 return true;
1264
1265 lex();
1266 if (Token.isNot(MIToken::Eof))
1267 return error("expected end of string after the register reference");
1268 return false;
1269}
1270
1271bool MIParser::parseStandaloneStackObject(int &FI) {
1272 lex();
1273 if (Token.isNot(MIToken::StackObject))
1274 return error("expected a stack object");
1275 if (parseStackFrameIndex(FI))
1276 return true;
1277 if (Token.isNot(MIToken::Eof))
1278 return error("expected end of string after the stack object reference");
1279 return false;
1280}
1281
1282bool MIParser::parseStandaloneMDNode(MDNode *&Node) {
1283 lex();
1284 if (Token.is(MIToken::exclaim)) {
1285 if (parseMDNode(Node))
1286 return true;
1287 } else if (Token.is(MIToken::md_diexpr)) {
1288 if (parseDIExpression(Node))
1289 return true;
1290 } else if (Token.is(MIToken::md_dilocation)) {
1291 if (parseDILocation(Node))
1292 return true;
1293 } else
1294 return error("expected a metadata node");
1295 if (Token.isNot(MIToken::Eof))
1296 return error("expected end of string after the metadata node");
1297 return false;
1298}
1299
1300bool MIParser::parseMachineMetadata() {
1301 lex();
1302 if (Token.isNot(MIToken::exclaim))
1303 return error("expected a metadata node");
1304
1305 lex();
1306 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1307 return error("expected metadata id after '!'");
1308 unsigned ID = 0;
1309 if (getUnsigned(ID))
1310 return true;
1311 lex();
1312 if (expectAndConsume(MIToken::equal))
1313 return true;
1314 bool IsDistinct = Token.is(MIToken::kw_distinct);
1315 if (IsDistinct)
1316 lex();
1317 if (Token.isNot(MIToken::exclaim))
1318 return error("expected a metadata node");
1319 lex();
1320
1321 MDNode *MD;
1322 if (parseMDTuple(MD, IsDistinct))
1323 return true;
1324
1325 auto FI = PFS.MachineForwardRefMDNodes.find(ID);
1326 if (FI != PFS.MachineForwardRefMDNodes.end()) {
1327 FI->second.first->replaceAllUsesWith(MD);
1328 PFS.MachineForwardRefMDNodes.erase(FI);
1329
1330 assert(PFS.MachineMetadataNodes[ID] == MD && "Tracking VH didn't work");
1331 } else {
1332 auto [It, Inserted] = PFS.MachineMetadataNodes.try_emplace(ID);
1333 if (!Inserted)
1334 return error("Metadata id is already used");
1335 It->second.reset(MD);
1336 }
1337
1338 return false;
1339}
1340
1341bool MIParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
1343 if (parseMDNodeVector(Elts))
1344 return true;
1345 MD = (IsDistinct ? MDTuple::getDistinct
1346 : MDTuple::get)(MF.getFunction().getContext(), Elts);
1347 return false;
1348}
1349
1350bool MIParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
1351 if (Token.isNot(MIToken::lbrace))
1352 return error("expected '{' here");
1353 lex();
1354
1355 if (Token.is(MIToken::rbrace)) {
1356 lex();
1357 return false;
1358 }
1359
1360 do {
1361 Metadata *MD;
1362 if (parseMetadata(MD))
1363 return true;
1364
1365 Elts.push_back(MD);
1366
1367 if (Token.isNot(MIToken::comma))
1368 break;
1369 lex();
1370 } while (true);
1371
1372 if (Token.isNot(MIToken::rbrace))
1373 return error("expected end of metadata node");
1374 lex();
1375
1376 return false;
1377}
1378
1379// ::= !42
1380// ::= !"string"
1381bool MIParser::parseMetadata(Metadata *&MD) {
1382 if (Token.isNot(MIToken::exclaim))
1383 return error("expected '!' here");
1384 lex();
1385
1386 if (Token.is(MIToken::StringConstant)) {
1387 std::string Str;
1388 if (parseStringConstant(Str))
1389 return true;
1390 MD = MDString::get(MF.getFunction().getContext(), Str);
1391 return false;
1392 }
1393
1394 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1395 return error("expected metadata id after '!'");
1396
1397 SMLoc Loc = mapSMLoc(Token.location());
1398
1399 unsigned ID = 0;
1400 if (getUnsigned(ID))
1401 return true;
1402 lex();
1403
1404 auto NodeInfo = PFS.IRSlots.MetadataNodes.find(ID);
1405 if (NodeInfo != PFS.IRSlots.MetadataNodes.end()) {
1406 MD = NodeInfo->second.get();
1407 return false;
1408 }
1409 // Check machine metadata.
1410 NodeInfo = PFS.MachineMetadataNodes.find(ID);
1411 if (NodeInfo != PFS.MachineMetadataNodes.end()) {
1412 MD = NodeInfo->second.get();
1413 return false;
1414 }
1415 // Forward reference.
1416 auto &FwdRef = PFS.MachineForwardRefMDNodes[ID];
1417 FwdRef = std::make_pair(
1418 MDTuple::getTemporary(MF.getFunction().getContext(), {}), Loc);
1419 PFS.MachineMetadataNodes[ID].reset(FwdRef.first.get());
1420 MD = FwdRef.first.get();
1421
1422 return false;
1423}
1424
1425static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
1426 assert(MO.isImplicit());
1427 return MO.isDef() ? "implicit-def" : "implicit";
1428}
1429
1430static std::string getRegisterName(const TargetRegisterInfo *TRI,
1431 Register Reg) {
1432 assert(Reg.isPhysical() && "expected phys reg");
1433 return StringRef(TRI->getName(Reg)).lower();
1434}
1435
1436/// Return true if the parsed machine operands contain a given machine operand.
1437static bool isImplicitOperandIn(const MachineOperand &ImplicitOperand,
1439 for (const auto &I : Operands) {
1440 if (ImplicitOperand.isIdenticalTo(I.Operand))
1441 return true;
1442 }
1443 return false;
1444}
1445
1446bool MIParser::verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands,
1447 const MCInstrDesc &MCID) {
1448 if (MCID.isCall())
1449 // We can't verify call instructions as they can contain arbitrary implicit
1450 // register and register mask operands.
1451 return false;
1452
1453 // Gather all the expected implicit operands.
1454 SmallVector<MachineOperand, 4> ImplicitOperands;
1455 for (MCPhysReg ImpDef : MCID.implicit_defs())
1456 ImplicitOperands.push_back(MachineOperand::CreateReg(ImpDef, true, true));
1457 for (MCPhysReg ImpUse : MCID.implicit_uses())
1458 ImplicitOperands.push_back(MachineOperand::CreateReg(ImpUse, false, true));
1459
1460 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1461 assert(TRI && "Expected target register info");
1462 for (const auto &I : ImplicitOperands) {
1463 if (isImplicitOperandIn(I, Operands))
1464 continue;
1465 return error(Operands.empty() ? Token.location() : Operands.back().End,
1466 Twine("missing implicit register operand '") +
1468 getRegisterName(TRI, I.getReg()) + "'");
1469 }
1470 return false;
1471}
1472
1473bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
1474 // Allow frame and fast math flags for OPCODE
1475 // clang-format off
1476 while (Token.is(MIToken::kw_frame_setup) ||
1477 Token.is(MIToken::kw_frame_destroy) ||
1478 Token.is(MIToken::kw_nnan) ||
1479 Token.is(MIToken::kw_ninf) ||
1480 Token.is(MIToken::kw_nsz) ||
1481 Token.is(MIToken::kw_arcp) ||
1482 Token.is(MIToken::kw_contract) ||
1483 Token.is(MIToken::kw_afn) ||
1484 Token.is(MIToken::kw_reassoc) ||
1485 Token.is(MIToken::kw_nuw) ||
1486 Token.is(MIToken::kw_nsw) ||
1487 Token.is(MIToken::kw_exact) ||
1488 Token.is(MIToken::kw_nofpexcept) ||
1489 Token.is(MIToken::kw_noconvergent) ||
1490 Token.is(MIToken::kw_unpredictable) ||
1491 Token.is(MIToken::kw_nneg) ||
1492 Token.is(MIToken::kw_disjoint) ||
1493 Token.is(MIToken::kw_nusw) ||
1494 Token.is(MIToken::kw_samesign) ||
1495 Token.is(MIToken::kw_inbounds)) {
1496 // clang-format on
1497 // Mine frame and fast math flags
1498 if (Token.is(MIToken::kw_frame_setup))
1500 if (Token.is(MIToken::kw_frame_destroy))
1502 if (Token.is(MIToken::kw_nnan))
1504 if (Token.is(MIToken::kw_ninf))
1506 if (Token.is(MIToken::kw_nsz))
1508 if (Token.is(MIToken::kw_arcp))
1510 if (Token.is(MIToken::kw_contract))
1512 if (Token.is(MIToken::kw_afn))
1514 if (Token.is(MIToken::kw_reassoc))
1516 if (Token.is(MIToken::kw_nuw))
1518 if (Token.is(MIToken::kw_nsw))
1520 if (Token.is(MIToken::kw_exact))
1522 if (Token.is(MIToken::kw_nofpexcept))
1524 if (Token.is(MIToken::kw_unpredictable))
1526 if (Token.is(MIToken::kw_noconvergent))
1528 if (Token.is(MIToken::kw_nneg))
1530 if (Token.is(MIToken::kw_disjoint))
1532 if (Token.is(MIToken::kw_nusw))
1534 if (Token.is(MIToken::kw_samesign))
1536 if (Token.is(MIToken::kw_inbounds))
1538
1539 lex();
1540 }
1541 if (Token.isNot(MIToken::Identifier))
1542 return error("expected a machine instruction");
1543 StringRef InstrName = Token.stringValue();
1544 if (PFS.Target.parseInstrName(InstrName, OpCode))
1545 return error(Twine("unknown machine instruction name '") + InstrName + "'");
1546 lex();
1547 return false;
1548}
1549
1550bool MIParser::parseNamedRegister(Register &Reg) {
1551 assert(Token.is(MIToken::NamedRegister) && "Needs NamedRegister token");
1552 StringRef Name = Token.stringValue();
1553 if (PFS.Target.getRegisterByName(Name, Reg))
1554 return error(Twine("unknown register name '") + Name + "'");
1555 return false;
1556}
1557
1558bool MIParser::parseNamedVirtualRegister(VRegInfo *&Info) {
1559 assert(Token.is(MIToken::NamedVirtualRegister) && "Expected NamedVReg token");
1560 StringRef Name = Token.stringValue();
1561 // TODO: Check that the VReg name is not the same as a physical register name.
1562 // If it is, then print a warning (when warnings are implemented).
1563 Info = &PFS.getVRegInfoNamed(Name);
1564 return false;
1565}
1566
1567bool MIParser::parseVirtualRegister(VRegInfo *&Info) {
1568 if (Token.is(MIToken::NamedVirtualRegister))
1569 return parseNamedVirtualRegister(Info);
1570 assert(Token.is(MIToken::VirtualRegister) && "Needs VirtualRegister token");
1571 unsigned ID;
1572 if (getUnsigned(ID))
1573 return true;
1574 Info = &PFS.getVRegInfo(ID);
1575 return false;
1576}
1577
1578bool MIParser::parseRegister(Register &Reg, VRegInfo *&Info) {
1579 switch (Token.kind()) {
1581 Reg = 0;
1582 return false;
1584 return parseNamedRegister(Reg);
1587 if (parseVirtualRegister(Info))
1588 return true;
1589 Reg = Info->VReg;
1590 return false;
1591 // TODO: Parse other register kinds.
1592 default:
1593 llvm_unreachable("The current token should be a register");
1594 }
1595}
1596
1597bool MIParser::parseRegisterClassOrBank(VRegInfo &RegInfo) {
1598 if (Token.isNot(MIToken::Identifier) && Token.isNot(MIToken::underscore))
1599 return error("expected '_', register class, or register bank name");
1600 StringRef::iterator Loc = Token.location();
1601 StringRef Name = Token.stringValue();
1602
1603 // Was it a register class?
1604 const TargetRegisterClass *RC = PFS.Target.getRegClass(Name);
1605 if (RC) {
1606 lex();
1607
1608 switch (RegInfo.Kind) {
1609 case VRegInfo::UNKNOWN:
1610 case VRegInfo::NORMAL:
1611 RegInfo.Kind = VRegInfo::NORMAL;
1612 if (RegInfo.Explicit && RegInfo.D.RC != RC) {
1613 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1614 return error(Loc, Twine("conflicting register classes, previously: ") +
1615 Twine(TRI.getRegClassName(RegInfo.D.RC)));
1616 }
1617 RegInfo.D.RC = RC;
1618 RegInfo.Explicit = true;
1619 return false;
1620
1621 case VRegInfo::GENERIC:
1622 case VRegInfo::REGBANK:
1623 return error(Loc, "register class specification on generic register");
1624 }
1625 llvm_unreachable("Unexpected register kind");
1626 }
1627
1628 // Should be a register bank or a generic register.
1629 const RegisterBank *RegBank = nullptr;
1630 if (Name != "_") {
1631 RegBank = PFS.Target.getRegBank(Name);
1632 if (!RegBank)
1633 return error(Loc, "expected '_', register class, or register bank name");
1634 }
1635
1636 lex();
1637
1638 switch (RegInfo.Kind) {
1639 case VRegInfo::UNKNOWN:
1640 case VRegInfo::GENERIC:
1641 case VRegInfo::REGBANK:
1642 RegInfo.Kind = RegBank ? VRegInfo::REGBANK : VRegInfo::GENERIC;
1643 if (RegInfo.Explicit && RegInfo.D.RegBank != RegBank)
1644 return error(Loc, "conflicting generic register banks");
1645 RegInfo.D.RegBank = RegBank;
1646 RegInfo.Explicit = true;
1647 return false;
1648
1649 case VRegInfo::NORMAL:
1650 return error(Loc, "register bank specification on normal register");
1651 }
1652 llvm_unreachable("Unexpected register kind");
1653}
1654
1655bool MIParser::parseRegisterFlag(unsigned &Flags) {
1656 const unsigned OldFlags = Flags;
1657 switch (Token.kind()) {
1660 break;
1663 break;
1664 case MIToken::kw_def:
1666 break;
1667 case MIToken::kw_dead:
1669 break;
1670 case MIToken::kw_killed:
1672 break;
1673 case MIToken::kw_undef:
1675 break;
1678 break;
1681 break;
1684 break;
1687 break;
1688 default:
1689 llvm_unreachable("The current token should be a register flag");
1690 }
1691 if (OldFlags == Flags)
1692 // We know that the same flag is specified more than once when the flags
1693 // weren't modified.
1694 return error("duplicate '" + Token.stringValue() + "' register flag");
1695 lex();
1696 return false;
1697}
1698
1699bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
1700 assert(Token.is(MIToken::dot));
1701 lex();
1702 if (Token.isNot(MIToken::Identifier))
1703 return error("expected a subregister index after '.'");
1704 auto Name = Token.stringValue();
1705 SubReg = PFS.Target.getSubRegIndex(Name);
1706 if (!SubReg)
1707 return error(Twine("use of unknown subregister index '") + Name + "'");
1708 lex();
1709 return false;
1710}
1711
1712bool MIParser::parseRegisterTiedDefIndex(unsigned &TiedDefIdx) {
1713 if (!consumeIfPresent(MIToken::kw_tied_def))
1714 return true;
1715 if (Token.isNot(MIToken::IntegerLiteral))
1716 return error("expected an integer literal after 'tied-def'");
1717 if (getUnsigned(TiedDefIdx))
1718 return true;
1719 lex();
1720 if (expectAndConsume(MIToken::rparen))
1721 return true;
1722 return false;
1723}
1724
1725bool MIParser::assignRegisterTies(MachineInstr &MI,
1727 SmallVector<std::pair<unsigned, unsigned>, 4> TiedRegisterPairs;
1728 for (unsigned I = 0, E = Operands.size(); I != E; ++I) {
1729 if (!Operands[I].TiedDefIdx)
1730 continue;
1731 // The parser ensures that this operand is a register use, so we just have
1732 // to check the tied-def operand.
1733 unsigned DefIdx = *Operands[I].TiedDefIdx;
1734 if (DefIdx >= E)
1735 return error(Operands[I].Begin,
1736 Twine("use of invalid tied-def operand index '" +
1737 Twine(DefIdx) + "'; instruction has only ") +
1738 Twine(E) + " operands");
1739 const auto &DefOperand = Operands[DefIdx].Operand;
1740 if (!DefOperand.isReg() || !DefOperand.isDef())
1741 // FIXME: add note with the def operand.
1742 return error(Operands[I].Begin,
1743 Twine("use of invalid tied-def operand index '") +
1744 Twine(DefIdx) + "'; the operand #" + Twine(DefIdx) +
1745 " isn't a defined register");
1746 // Check that the tied-def operand wasn't tied elsewhere.
1747 for (const auto &TiedPair : TiedRegisterPairs) {
1748 if (TiedPair.first == DefIdx)
1749 return error(Operands[I].Begin,
1750 Twine("the tied-def operand #") + Twine(DefIdx) +
1751 " is already tied with another register operand");
1752 }
1753 TiedRegisterPairs.push_back(std::make_pair(DefIdx, I));
1754 }
1755 // FIXME: Verify that for non INLINEASM instructions, the def and use tied
1756 // indices must be less than tied max.
1757 for (const auto &TiedPair : TiedRegisterPairs)
1758 MI.tieOperands(TiedPair.first, TiedPair.second);
1759 return false;
1760}
1761
1762bool MIParser::parseRegisterOperand(MachineOperand &Dest,
1763 std::optional<unsigned> &TiedDefIdx,
1764 bool IsDef) {
1765 unsigned Flags = IsDef ? RegState::Define : 0;
1766 while (Token.isRegisterFlag()) {
1767 if (parseRegisterFlag(Flags))
1768 return true;
1769 }
1770 if (!Token.isRegister())
1771 return error("expected a register after register flags");
1772 Register Reg;
1773 VRegInfo *RegInfo;
1774 if (parseRegister(Reg, RegInfo))
1775 return true;
1776 lex();
1777 unsigned SubReg = 0;
1778 if (Token.is(MIToken::dot)) {
1779 if (parseSubRegisterIndex(SubReg))
1780 return true;
1781 if (!Reg.isVirtual())
1782 return error("subregister index expects a virtual register");
1783 }
1784 if (Token.is(MIToken::colon)) {
1785 if (!Reg.isVirtual())
1786 return error("register class specification expects a virtual register");
1787 lex();
1788 if (parseRegisterClassOrBank(*RegInfo))
1789 return true;
1790 }
1791 MachineRegisterInfo &MRI = MF.getRegInfo();
1792 if ((Flags & RegState::Define) == 0) {
1793 if (consumeIfPresent(MIToken::lparen)) {
1794 unsigned Idx;
1795 if (!parseRegisterTiedDefIndex(Idx))
1796 TiedDefIdx = Idx;
1797 else {
1798 // Try a redundant low-level type.
1799 LLT Ty;
1800 if (parseLowLevelType(Token.location(), Ty))
1801 return error("expected tied-def or low-level type after '('");
1802
1803 if (expectAndConsume(MIToken::rparen))
1804 return true;
1805
1806 if (MRI.getType(Reg).isValid() && MRI.getType(Reg) != Ty)
1807 return error("inconsistent type for generic virtual register");
1808
1809 MRI.setRegClassOrRegBank(Reg, static_cast<RegisterBank *>(nullptr));
1810 MRI.setType(Reg, Ty);
1811 MRI.noteNewVirtualRegister(Reg);
1812 }
1813 }
1814 } else if (consumeIfPresent(MIToken::lparen)) {
1815 // Virtual registers may have a tpe with GlobalISel.
1816 if (!Reg.isVirtual())
1817 return error("unexpected type on physical register");
1818
1819 LLT Ty;
1820 if (parseLowLevelType(Token.location(), Ty))
1821 return true;
1822
1823 if (expectAndConsume(MIToken::rparen))
1824 return true;
1825
1826 if (MRI.getType(Reg).isValid() && MRI.getType(Reg) != Ty)
1827 return error("inconsistent type for generic virtual register");
1828
1829 MRI.setRegClassOrRegBank(Reg, static_cast<RegisterBank *>(nullptr));
1830 MRI.setType(Reg, Ty);
1831 } else if (Reg.isVirtual()) {
1832 // Generic virtual registers must have a type.
1833 // If we end up here this means the type hasn't been specified and
1834 // this is bad!
1835 if (RegInfo->Kind == VRegInfo::GENERIC ||
1836 RegInfo->Kind == VRegInfo::REGBANK)
1837 return error("generic virtual registers must have a type");
1838 }
1839
1840 if (Flags & RegState::Define) {
1841 if (Flags & RegState::Kill)
1842 return error("cannot have a killed def operand");
1843 } else {
1844 if (Flags & RegState::Dead)
1845 return error("cannot have a dead use operand");
1846 }
1847
1849 Reg, Flags & RegState::Define, Flags & RegState::Implicit,
1850 Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
1853
1854 return false;
1855}
1856
1857bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
1859 const APSInt &Int = Token.integerValue();
1860 if (auto SImm = Int.trySExtValue(); Int.isSigned() && SImm.has_value())
1861 Dest = MachineOperand::CreateImm(*SImm);
1862 else if (auto UImm = Int.tryZExtValue(); !Int.isSigned() && UImm.has_value())
1863 Dest = MachineOperand::CreateImm(*UImm);
1864 else
1865 return error("integer literal is too large to be an immediate operand");
1866 lex();
1867 return false;
1868}
1869
1870bool MIParser::parseTargetImmMnemonic(const unsigned OpCode,
1871 const unsigned OpIdx,
1872 MachineOperand &Dest,
1873 const MIRFormatter &MF) {
1874 assert(Token.is(MIToken::dot));
1875 auto Loc = Token.location(); // record start position
1876 size_t Len = 1; // for "."
1877 lex();
1878
1879 // Handle the case that mnemonic starts with number.
1880 if (Token.is(MIToken::IntegerLiteral)) {
1881 Len += Token.range().size();
1882 lex();
1883 }
1884
1885 StringRef Src;
1886 if (Token.is(MIToken::comma))
1887 Src = StringRef(Loc, Len);
1888 else {
1889 assert(Token.is(MIToken::Identifier));
1890 Src = StringRef(Loc, Len + Token.stringValue().size());
1891 }
1892 int64_t Val;
1893 if (MF.parseImmMnemonic(OpCode, OpIdx, Src, Val,
1894 [this](StringRef::iterator Loc, const Twine &Msg)
1895 -> bool { return error(Loc, Msg); }))
1896 return true;
1897
1898 Dest = MachineOperand::CreateImm(Val);
1899 if (!Token.is(MIToken::comma))
1900 lex();
1901 return false;
1902}
1903
1905 PerFunctionMIParsingState &PFS, const Constant *&C,
1906 ErrorCallbackType ErrCB) {
1907 auto Source = StringValue.str(); // The source has to be null terminated.
1908 SMDiagnostic Err;
1909 C = parseConstantValue(Source, Err, *PFS.MF.getFunction().getParent(),
1910 &PFS.IRSlots);
1911 if (!C)
1912 return ErrCB(Loc + Err.getColumnNo(), Err.getMessage());
1913 return false;
1914}
1915
1916bool MIParser::parseIRConstant(StringRef::iterator Loc, StringRef StringValue,
1917 const Constant *&C) {
1918 return ::parseIRConstant(
1919 Loc, StringValue, PFS, C,
1920 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
1921 return error(Loc, Msg);
1922 });
1923}
1924
1925bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
1926 if (parseIRConstant(Loc, StringRef(Loc, Token.range().end() - Loc), C))
1927 return true;
1928 lex();
1929 return false;
1930}
1931
1932// See LLT implementation for bit size limits.
1934 return Size != 0 && isUInt<16>(Size);
1935}
1936
1938 return NumElts != 0 && isUInt<16>(NumElts);
1939}
1940
1941static bool verifyAddrSpace(uint64_t AddrSpace) {
1942 return isUInt<24>(AddrSpace);
1943}
1944
1945bool MIParser::parseLowLevelType(StringRef::iterator Loc, LLT &Ty) {
1946 if (Token.range().front() == 's' || Token.range().front() == 'p') {
1947 StringRef SizeStr = Token.range().drop_front();
1948 if (SizeStr.size() == 0 || !llvm::all_of(SizeStr, isdigit))
1949 return error("expected integers after 's'/'p' type character");
1950 }
1951
1952 if (Token.range().front() == 's') {
1953 auto ScalarSize = APSInt(Token.range().drop_front()).getZExtValue();
1954 if (ScalarSize) {
1955 if (!verifyScalarSize(ScalarSize))
1956 return error("invalid size for scalar type");
1957 Ty = LLT::scalar(ScalarSize);
1958 } else {
1959 Ty = LLT::token();
1960 }
1961 lex();
1962 return false;
1963 } else if (Token.range().front() == 'p') {
1964 const DataLayout &DL = MF.getDataLayout();
1965 uint64_t AS = APSInt(Token.range().drop_front()).getZExtValue();
1966 if (!verifyAddrSpace(AS))
1967 return error("invalid address space number");
1968
1969 Ty = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
1970 lex();
1971 return false;
1972 }
1973
1974 // Now we're looking for a vector.
1975 if (Token.isNot(MIToken::less))
1976 return error(Loc, "expected sN, pA, <M x sN>, <M x pA>, <vscale x M x sN>, "
1977 "or <vscale x M x pA> for GlobalISel type");
1978 lex();
1979
1980 bool HasVScale =
1981 Token.is(MIToken::Identifier) && Token.stringValue() == "vscale";
1982 if (HasVScale) {
1983 lex();
1984 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != "x")
1985 return error("expected <vscale x M x sN> or <vscale x M x pA>");
1986 lex();
1987 }
1988
1989 auto GetError = [this, &HasVScale, Loc]() {
1990 if (HasVScale)
1991 return error(
1992 Loc, "expected <vscale x M x sN> or <vscale M x pA> for vector type");
1993 return error(Loc, "expected <M x sN> or <M x pA> for vector type");
1994 };
1995
1996 if (Token.isNot(MIToken::IntegerLiteral))
1997 return GetError();
1998 uint64_t NumElements = Token.integerValue().getZExtValue();
1999 if (!verifyVectorElementCount(NumElements))
2000 return error("invalid number of vector elements");
2001
2002 lex();
2003
2004 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != "x")
2005 return GetError();
2006 lex();
2007
2008 if (Token.range().front() != 's' && Token.range().front() != 'p')
2009 return GetError();
2010
2011 StringRef SizeStr = Token.range().drop_front();
2012 if (SizeStr.size() == 0 || !llvm::all_of(SizeStr, isdigit))
2013 return error("expected integers after 's'/'p' type character");
2014
2015 if (Token.range().front() == 's') {
2016 auto ScalarSize = APSInt(Token.range().drop_front()).getZExtValue();
2017 if (!verifyScalarSize(ScalarSize))
2018 return error("invalid size for scalar element in vector");
2019 Ty = LLT::scalar(ScalarSize);
2020 } else if (Token.range().front() == 'p') {
2021 const DataLayout &DL = MF.getDataLayout();
2022 uint64_t AS = APSInt(Token.range().drop_front()).getZExtValue();
2023 if (!verifyAddrSpace(AS))
2024 return error("invalid address space number");
2025
2026 Ty = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
2027 } else
2028 return GetError();
2029 lex();
2030
2031 if (Token.isNot(MIToken::greater))
2032 return GetError();
2033
2034 lex();
2035
2036 Ty = LLT::vector(ElementCount::get(NumElements, HasVScale), Ty);
2037 return false;
2038}
2039
2040bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) {
2041 assert(Token.is(MIToken::Identifier));
2042 StringRef TypeStr = Token.range();
2043 if (TypeStr.front() != 'i' && TypeStr.front() != 's' &&
2044 TypeStr.front() != 'p')
2045 return error(
2046 "a typed immediate operand should start with one of 'i', 's', or 'p'");
2047 StringRef SizeStr = Token.range().drop_front();
2048 if (SizeStr.size() == 0 || !llvm::all_of(SizeStr, isdigit))
2049 return error("expected integers after 'i'/'s'/'p' type character");
2050
2051 auto Loc = Token.location();
2052 lex();
2053 if (Token.isNot(MIToken::IntegerLiteral)) {
2054 if (Token.isNot(MIToken::Identifier) ||
2055 !(Token.range() == "true" || Token.range() == "false"))
2056 return error("expected an integer literal");
2057 }
2058 const Constant *C = nullptr;
2059 if (parseIRConstant(Loc, C))
2060 return true;
2062 return false;
2063}
2064
2065bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
2066 auto Loc = Token.location();
2067 lex();
2068 if (Token.isNot(MIToken::FloatingPointLiteral) &&
2069 Token.isNot(MIToken::HexLiteral))
2070 return error("expected a floating point literal");
2071 const Constant *C = nullptr;
2072 if (parseIRConstant(Loc, C))
2073 return true;
2075 return false;
2076}
2077
2078static bool getHexUint(const MIToken &Token, APInt &Result) {
2080 StringRef S = Token.range();
2081 assert(S[0] == '0' && tolower(S[1]) == 'x');
2082 // This could be a floating point literal with a special prefix.
2083 if (!isxdigit(S[2]))
2084 return true;
2085 StringRef V = S.substr(2);
2086 APInt A(V.size()*4, V, 16);
2087
2088 // If A is 0, then A.getActiveBits() is 0. This isn't a valid bitwidth. Make
2089 // sure it isn't the case before constructing result.
2090 unsigned NumBits = (A == 0) ? 32 : A.getActiveBits();
2091 Result = APInt(NumBits, ArrayRef<uint64_t>(A.getRawData(), A.getNumWords()));
2092 return false;
2093}
2094
2095static bool getUnsigned(const MIToken &Token, unsigned &Result,
2096 ErrorCallbackType ErrCB) {
2097 if (Token.hasIntegerValue()) {
2098 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
2099 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
2100 if (Val64 == Limit)
2101 return ErrCB(Token.location(), "expected 32-bit integer (too large)");
2102 Result = Val64;
2103 return false;
2104 }
2105 if (Token.is(MIToken::HexLiteral)) {
2106 APInt A;
2107 if (getHexUint(Token, A))
2108 return true;
2109 if (A.getBitWidth() > 32)
2110 return ErrCB(Token.location(), "expected 32-bit integer (too large)");
2111 Result = A.getZExtValue();
2112 return false;
2113 }
2114 return true;
2115}
2116
2117bool MIParser::getUnsigned(unsigned &Result) {
2118 return ::getUnsigned(
2119 Token, Result, [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
2120 return error(Loc, Msg);
2121 });
2122}
2123
2124bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
2127 unsigned Number;
2128 if (getUnsigned(Number))
2129 return true;
2130 auto MBBInfo = PFS.MBBSlots.find(Number);
2131 if (MBBInfo == PFS.MBBSlots.end())
2132 return error(Twine("use of undefined machine basic block #") +
2133 Twine(Number));
2134 MBB = MBBInfo->second;
2135 // TODO: Only parse the name if it's a MachineBasicBlockLabel. Deprecate once
2136 // we drop the <irname> from the bb.<id>.<irname> format.
2137 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
2138 return error(Twine("the name of machine basic block #") + Twine(Number) +
2139 " isn't '" + Token.stringValue() + "'");
2140 return false;
2141}
2142
2143bool MIParser::parseMBBOperand(MachineOperand &Dest) {
2146 return true;
2148 lex();
2149 return false;
2150}
2151
2152bool MIParser::parseStackFrameIndex(int &FI) {
2153 assert(Token.is(MIToken::StackObject));
2154 unsigned ID;
2155 if (getUnsigned(ID))
2156 return true;
2157 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
2158 if (ObjectInfo == PFS.StackObjectSlots.end())
2159 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
2160 "'");
2162 if (const auto *Alloca =
2163 MF.getFrameInfo().getObjectAllocation(ObjectInfo->second))
2164 Name = Alloca->getName();
2165 if (!Token.stringValue().empty() && Token.stringValue() != Name)
2166 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
2167 "' isn't '" + Token.stringValue() + "'");
2168 lex();
2169 FI = ObjectInfo->second;
2170 return false;
2171}
2172
2173bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
2174 int FI;
2175 if (parseStackFrameIndex(FI))
2176 return true;
2177 Dest = MachineOperand::CreateFI(FI);
2178 return false;
2179}
2180
2181bool MIParser::parseFixedStackFrameIndex(int &FI) {
2183 unsigned ID;
2184 if (getUnsigned(ID))
2185 return true;
2186 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
2187 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
2188 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
2189 Twine(ID) + "'");
2190 lex();
2191 FI = ObjectInfo->second;
2192 return false;
2193}
2194
2195bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
2196 int FI;
2197 if (parseFixedStackFrameIndex(FI))
2198 return true;
2199 Dest = MachineOperand::CreateFI(FI);
2200 return false;
2201}
2202
2203static bool parseGlobalValue(const MIToken &Token,
2205 ErrorCallbackType ErrCB) {
2206 switch (Token.kind()) {
2208 const Module *M = PFS.MF.getFunction().getParent();
2209 GV = M->getNamedValue(Token.stringValue());
2210 if (!GV)
2211 return ErrCB(Token.location(), Twine("use of undefined global value '") +
2212 Token.range() + "'");
2213 break;
2214 }
2215 case MIToken::GlobalValue: {
2216 unsigned GVIdx;
2217 if (getUnsigned(Token, GVIdx, ErrCB))
2218 return true;
2219 GV = PFS.IRSlots.GlobalValues.get(GVIdx);
2220 if (!GV)
2221 return ErrCB(Token.location(), Twine("use of undefined global value '@") +
2222 Twine(GVIdx) + "'");
2223 break;
2224 }
2225 default:
2226 llvm_unreachable("The current token should be a global value");
2227 }
2228 return false;
2229}
2230
2231bool MIParser::parseGlobalValue(GlobalValue *&GV) {
2232 return ::parseGlobalValue(
2233 Token, PFS, GV,
2234 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
2235 return error(Loc, Msg);
2236 });
2237}
2238
2239bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
2240 GlobalValue *GV = nullptr;
2241 if (parseGlobalValue(GV))
2242 return true;
2243 lex();
2244 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
2245 if (parseOperandsOffset(Dest))
2246 return true;
2247 return false;
2248}
2249
2250bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
2252 unsigned ID;
2253 if (getUnsigned(ID))
2254 return true;
2255 auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
2256 if (ConstantInfo == PFS.ConstantPoolSlots.end())
2257 return error("use of undefined constant '%const." + Twine(ID) + "'");
2258 lex();
2259 Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
2260 if (parseOperandsOffset(Dest))
2261 return true;
2262 return false;
2263}
2264
2265bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
2267 unsigned ID;
2268 if (getUnsigned(ID))
2269 return true;
2270 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
2271 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
2272 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
2273 lex();
2274 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
2275 return false;
2276}
2277
2278bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
2280 const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
2281 lex();
2282 Dest = MachineOperand::CreateES(Symbol);
2283 if (parseOperandsOffset(Dest))
2284 return true;
2285 return false;
2286}
2287
2288bool MIParser::parseMCSymbolOperand(MachineOperand &Dest) {
2289 assert(Token.is(MIToken::MCSymbol));
2290 MCSymbol *Symbol = getOrCreateMCSymbol(Token.stringValue());
2291 lex();
2292 Dest = MachineOperand::CreateMCSymbol(Symbol);
2293 if (parseOperandsOffset(Dest))
2294 return true;
2295 return false;
2296}
2297
2298bool MIParser::parseSubRegisterIndexOperand(MachineOperand &Dest) {
2300 StringRef Name = Token.stringValue();
2301 unsigned SubRegIndex = PFS.Target.getSubRegIndex(Token.stringValue());
2302 if (SubRegIndex == 0)
2303 return error(Twine("unknown subregister index '") + Name + "'");
2304 lex();
2305 Dest = MachineOperand::CreateImm(SubRegIndex);
2306 return false;
2307}
2308
2309bool MIParser::parseMDNode(MDNode *&Node) {
2310 assert(Token.is(MIToken::exclaim));
2311
2312 auto Loc = Token.location();
2313 lex();
2314 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
2315 return error("expected metadata id after '!'");
2316 unsigned ID;
2317 if (getUnsigned(ID))
2318 return true;
2319 auto NodeInfo = PFS.IRSlots.MetadataNodes.find(ID);
2320 if (NodeInfo == PFS.IRSlots.MetadataNodes.end()) {
2321 NodeInfo = PFS.MachineMetadataNodes.find(ID);
2322 if (NodeInfo == PFS.MachineMetadataNodes.end())
2323 return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
2324 }
2325 lex();
2326 Node = NodeInfo->second.get();
2327 return false;
2328}
2329
2330bool MIParser::parseDIExpression(MDNode *&Expr) {
2331 unsigned Read;
2333 CurrentSource, Read, Error, *PFS.MF.getFunction().getParent(),
2334 &PFS.IRSlots);
2335 CurrentSource = CurrentSource.substr(Read);
2336 lex();
2337 if (!Expr)
2338 return error(Error.getMessage());
2339 return false;
2340}
2341
2342bool MIParser::parseDILocation(MDNode *&Loc) {
2343 assert(Token.is(MIToken::md_dilocation));
2344 lex();
2345
2346 bool HaveLine = false;
2347 unsigned Line = 0;
2348 unsigned Column = 0;
2349 MDNode *Scope = nullptr;
2350 MDNode *InlinedAt = nullptr;
2351 bool ImplicitCode = false;
2352 uint64_t AtomGroup = 0;
2353 uint64_t AtomRank = 0;
2354
2355 if (expectAndConsume(MIToken::lparen))
2356 return true;
2357
2358 if (Token.isNot(MIToken::rparen)) {
2359 do {
2360 if (Token.is(MIToken::Identifier)) {
2361 if (Token.stringValue() == "line") {
2362 lex();
2363 if (expectAndConsume(MIToken::colon))
2364 return true;
2365 if (Token.isNot(MIToken::IntegerLiteral) ||
2366 Token.integerValue().isSigned())
2367 return error("expected unsigned integer");
2368 Line = Token.integerValue().getZExtValue();
2369 HaveLine = true;
2370 lex();
2371 continue;
2372 }
2373 if (Token.stringValue() == "column") {
2374 lex();
2375 if (expectAndConsume(MIToken::colon))
2376 return true;
2377 if (Token.isNot(MIToken::IntegerLiteral) ||
2378 Token.integerValue().isSigned())
2379 return error("expected unsigned integer");
2380 Column = Token.integerValue().getZExtValue();
2381 lex();
2382 continue;
2383 }
2384 if (Token.stringValue() == "scope") {
2385 lex();
2386 if (expectAndConsume(MIToken::colon))
2387 return true;
2388 if (parseMDNode(Scope))
2389 return error("expected metadata node");
2390 if (!isa<DIScope>(Scope))
2391 return error("expected DIScope node");
2392 continue;
2393 }
2394 if (Token.stringValue() == "inlinedAt") {
2395 lex();
2396 if (expectAndConsume(MIToken::colon))
2397 return true;
2398 if (Token.is(MIToken::exclaim)) {
2399 if (parseMDNode(InlinedAt))
2400 return true;
2401 } else if (Token.is(MIToken::md_dilocation)) {
2402 if (parseDILocation(InlinedAt))
2403 return true;
2404 } else
2405 return error("expected metadata node");
2406 if (!isa<DILocation>(InlinedAt))
2407 return error("expected DILocation node");
2408 continue;
2409 }
2410 if (Token.stringValue() == "isImplicitCode") {
2411 lex();
2412 if (expectAndConsume(MIToken::colon))
2413 return true;
2414 if (!Token.is(MIToken::Identifier))
2415 return error("expected true/false");
2416 // As far as I can see, we don't have any existing need for parsing
2417 // true/false in MIR yet. Do it ad-hoc until there's something else
2418 // that needs it.
2419 if (Token.stringValue() == "true")
2420 ImplicitCode = true;
2421 else if (Token.stringValue() == "false")
2422 ImplicitCode = false;
2423 else
2424 return error("expected true/false");
2425 lex();
2426 continue;
2427 }
2428 if (Token.stringValue() == "atomGroup") {
2429 lex();
2430 if (expectAndConsume(MIToken::colon))
2431 return true;
2432 if (Token.isNot(MIToken::IntegerLiteral) ||
2433 Token.integerValue().isSigned())
2434 return error("expected unsigned integer");
2435 AtomGroup = Token.integerValue().getZExtValue();
2436 lex();
2437 continue;
2438 }
2439 if (Token.stringValue() == "atomRank") {
2440 lex();
2441 if (expectAndConsume(MIToken::colon))
2442 return true;
2443 if (Token.isNot(MIToken::IntegerLiteral) ||
2444 Token.integerValue().isSigned())
2445 return error("expected unsigned integer");
2446 AtomRank = Token.integerValue().getZExtValue();
2447 lex();
2448 continue;
2449 }
2450 }
2451 return error(Twine("invalid DILocation argument '") +
2452 Token.stringValue() + "'");
2453 } while (consumeIfPresent(MIToken::comma));
2454 }
2455
2456 if (expectAndConsume(MIToken::rparen))
2457 return true;
2458
2459 if (!HaveLine)
2460 return error("DILocation requires line number");
2461 if (!Scope)
2462 return error("DILocation requires a scope");
2463
2464 Loc = DILocation::get(MF.getFunction().getContext(), Line, Column, Scope,
2465 InlinedAt, ImplicitCode, AtomGroup, AtomRank);
2466 return false;
2467}
2468
2469bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
2470 MDNode *Node = nullptr;
2471 if (Token.is(MIToken::exclaim)) {
2472 if (parseMDNode(Node))
2473 return true;
2474 } else if (Token.is(MIToken::md_diexpr)) {
2475 if (parseDIExpression(Node))
2476 return true;
2477 }
2478 Dest = MachineOperand::CreateMetadata(Node);
2479 return false;
2480}
2481
2482bool MIParser::parseCFIOffset(int &Offset) {
2483 if (Token.isNot(MIToken::IntegerLiteral))
2484 return error("expected a cfi offset");
2485 if (Token.integerValue().getSignificantBits() > 32)
2486 return error("expected a 32 bit integer (the cfi offset is too large)");
2487 Offset = (int)Token.integerValue().getExtValue();
2488 lex();
2489 return false;
2490}
2491
2492bool MIParser::parseCFIRegister(unsigned &Reg) {
2493 if (Token.isNot(MIToken::NamedRegister))
2494 return error("expected a cfi register");
2495 Register LLVMReg;
2496 if (parseNamedRegister(LLVMReg))
2497 return true;
2498 const auto *TRI = MF.getSubtarget().getRegisterInfo();
2499 assert(TRI && "Expected target register info");
2500 int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
2501 if (DwarfReg < 0)
2502 return error("invalid DWARF register");
2503 Reg = (unsigned)DwarfReg;
2504 lex();
2505 return false;
2506}
2507
2508bool MIParser::parseCFIAddressSpace(unsigned &AddressSpace) {
2509 if (Token.isNot(MIToken::IntegerLiteral))
2510 return error("expected a cfi address space literal");
2511 if (Token.integerValue().isSigned())
2512 return error("expected an unsigned integer (cfi address space)");
2513 AddressSpace = Token.integerValue().getZExtValue();
2514 lex();
2515 return false;
2516}
2517
2518bool MIParser::parseCFIEscapeValues(std::string &Values) {
2519 do {
2520 if (Token.isNot(MIToken::HexLiteral))
2521 return error("expected a hexadecimal literal");
2522 unsigned Value;
2523 if (getUnsigned(Value))
2524 return true;
2525 if (Value > UINT8_MAX)
2526 return error("expected a 8-bit integer (too large)");
2527 Values.push_back(static_cast<uint8_t>(Value));
2528 lex();
2529 } while (consumeIfPresent(MIToken::comma));
2530 return false;
2531}
2532
2533bool MIParser::parseCFIOperand(MachineOperand &Dest) {
2534 auto Kind = Token.kind();
2535 lex();
2536 int Offset;
2537 unsigned Reg;
2538 unsigned AddressSpace;
2539 unsigned CFIIndex;
2540 switch (Kind) {
2542 if (parseCFIRegister(Reg))
2543 return true;
2544 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(nullptr, Reg));
2545 break;
2547 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2548 parseCFIOffset(Offset))
2549 return true;
2550 CFIIndex =
2551 MF.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
2552 break;
2554 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2555 parseCFIOffset(Offset))
2556 return true;
2557 CFIIndex = MF.addFrameInst(
2559 break;
2561 if (parseCFIRegister(Reg))
2562 return true;
2563 CFIIndex =
2564 MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
2565 break;
2567 if (parseCFIOffset(Offset))
2568 return true;
2569 CFIIndex =
2570 MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, Offset));
2571 break;
2573 if (parseCFIOffset(Offset))
2574 return true;
2575 CFIIndex = MF.addFrameInst(
2577 break;
2579 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2580 parseCFIOffset(Offset))
2581 return true;
2582 CFIIndex =
2583 MF.addFrameInst(MCCFIInstruction::cfiDefCfa(nullptr, Reg, Offset));
2584 break;
2586 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2587 parseCFIOffset(Offset) || expectAndConsume(MIToken::comma) ||
2588 parseCFIAddressSpace(AddressSpace))
2589 return true;
2590 CFIIndex = MF.addFrameInst(MCCFIInstruction::createLLVMDefAspaceCfa(
2591 nullptr, Reg, Offset, AddressSpace, SMLoc()));
2592 break;
2594 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRememberState(nullptr));
2595 break;
2597 if (parseCFIRegister(Reg))
2598 return true;
2599 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, Reg));
2600 break;
2602 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestoreState(nullptr));
2603 break;
2605 if (parseCFIRegister(Reg))
2606 return true;
2607 CFIIndex = MF.addFrameInst(MCCFIInstruction::createUndefined(nullptr, Reg));
2608 break;
2610 unsigned Reg2;
2611 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2612 parseCFIRegister(Reg2))
2613 return true;
2614
2615 CFIIndex =
2616 MF.addFrameInst(MCCFIInstruction::createRegister(nullptr, Reg, Reg2));
2617 break;
2618 }
2620 CFIIndex = MF.addFrameInst(MCCFIInstruction::createWindowSave(nullptr));
2621 break;
2623 CFIIndex = MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
2624 break;
2626 CFIIndex =
2627 MF.addFrameInst(MCCFIInstruction::createNegateRAStateWithPC(nullptr));
2628 break;
2630 std::string Values;
2631 if (parseCFIEscapeValues(Values))
2632 return true;
2633 CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape(nullptr, Values));
2634 break;
2635 }
2636 default:
2637 // TODO: Parse the other CFI operands.
2638 llvm_unreachable("The current token should be a cfi operand");
2639 }
2640 Dest = MachineOperand::CreateCFIIndex(CFIIndex);
2641 return false;
2642}
2643
2644bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
2645 switch (Token.kind()) {
2646 case MIToken::NamedIRBlock: {
2648 F.getValueSymbolTable()->lookup(Token.stringValue()));
2649 if (!BB)
2650 return error(Twine("use of undefined IR block '") + Token.range() + "'");
2651 break;
2652 }
2653 case MIToken::IRBlock: {
2654 unsigned SlotNumber = 0;
2655 if (getUnsigned(SlotNumber))
2656 return true;
2657 BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F));
2658 if (!BB)
2659 return error(Twine("use of undefined IR block '%ir-block.") +
2660 Twine(SlotNumber) + "'");
2661 break;
2662 }
2663 default:
2664 llvm_unreachable("The current token should be an IR block reference");
2665 }
2666 return false;
2667}
2668
2669bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
2671 lex();
2672 if (expectAndConsume(MIToken::lparen))
2673 return true;
2674 if (Token.isNot(MIToken::GlobalValue) &&
2675 Token.isNot(MIToken::NamedGlobalValue))
2676 return error("expected a global value");
2677 GlobalValue *GV = nullptr;
2678 if (parseGlobalValue(GV))
2679 return true;
2680 auto *F = dyn_cast<Function>(GV);
2681 if (!F)
2682 return error("expected an IR function reference");
2683 lex();
2684 if (expectAndConsume(MIToken::comma))
2685 return true;
2686 BasicBlock *BB = nullptr;
2687 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
2688 return error("expected an IR block reference");
2689 if (parseIRBlock(BB, *F))
2690 return true;
2691 lex();
2692 if (expectAndConsume(MIToken::rparen))
2693 return true;
2694 Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
2695 if (parseOperandsOffset(Dest))
2696 return true;
2697 return false;
2698}
2699
2700bool MIParser::parseIntrinsicOperand(MachineOperand &Dest) {
2701 assert(Token.is(MIToken::kw_intrinsic));
2702 lex();
2703 if (expectAndConsume(MIToken::lparen))
2704 return error("expected syntax intrinsic(@llvm.whatever)");
2705
2706 if (Token.isNot(MIToken::NamedGlobalValue))
2707 return error("expected syntax intrinsic(@llvm.whatever)");
2708
2709 std::string Name = std::string(Token.stringValue());
2710 lex();
2711
2712 if (expectAndConsume(MIToken::rparen))
2713 return error("expected ')' to terminate intrinsic name");
2714
2715 // Find out what intrinsic we're dealing with.
2718 return error("unknown intrinsic name");
2720
2721 return false;
2722}
2723
2724bool MIParser::parsePredicateOperand(MachineOperand &Dest) {
2725 assert(Token.is(MIToken::kw_intpred) || Token.is(MIToken::kw_floatpred));
2726 bool IsFloat = Token.is(MIToken::kw_floatpred);
2727 lex();
2728
2729 if (expectAndConsume(MIToken::lparen))
2730 return error("expected syntax intpred(whatever) or floatpred(whatever");
2731
2732 if (Token.isNot(MIToken::Identifier))
2733 return error("whatever");
2734
2735 CmpInst::Predicate Pred;
2736 if (IsFloat) {
2737 Pred = StringSwitch<CmpInst::Predicate>(Token.stringValue())
2738 .Case("false", CmpInst::FCMP_FALSE)
2739 .Case("oeq", CmpInst::FCMP_OEQ)
2740 .Case("ogt", CmpInst::FCMP_OGT)
2741 .Case("oge", CmpInst::FCMP_OGE)
2742 .Case("olt", CmpInst::FCMP_OLT)
2743 .Case("ole", CmpInst::FCMP_OLE)
2744 .Case("one", CmpInst::FCMP_ONE)
2745 .Case("ord", CmpInst::FCMP_ORD)
2746 .Case("uno", CmpInst::FCMP_UNO)
2747 .Case("ueq", CmpInst::FCMP_UEQ)
2748 .Case("ugt", CmpInst::FCMP_UGT)
2749 .Case("uge", CmpInst::FCMP_UGE)
2750 .Case("ult", CmpInst::FCMP_ULT)
2751 .Case("ule", CmpInst::FCMP_ULE)
2752 .Case("une", CmpInst::FCMP_UNE)
2753 .Case("true", CmpInst::FCMP_TRUE)
2755 if (!CmpInst::isFPPredicate(Pred))
2756 return error("invalid floating-point predicate");
2757 } else {
2758 Pred = StringSwitch<CmpInst::Predicate>(Token.stringValue())
2759 .Case("eq", CmpInst::ICMP_EQ)
2760 .Case("ne", CmpInst::ICMP_NE)
2761 .Case("sgt", CmpInst::ICMP_SGT)
2762 .Case("sge", CmpInst::ICMP_SGE)
2763 .Case("slt", CmpInst::ICMP_SLT)
2764 .Case("sle", CmpInst::ICMP_SLE)
2765 .Case("ugt", CmpInst::ICMP_UGT)
2766 .Case("uge", CmpInst::ICMP_UGE)
2767 .Case("ult", CmpInst::ICMP_ULT)
2768 .Case("ule", CmpInst::ICMP_ULE)
2770 if (!CmpInst::isIntPredicate(Pred))
2771 return error("invalid integer predicate");
2772 }
2773
2774 lex();
2776 if (expectAndConsume(MIToken::rparen))
2777 return error("predicate should be terminated by ')'.");
2778
2779 return false;
2780}
2781
2782bool MIParser::parseShuffleMaskOperand(MachineOperand &Dest) {
2784
2785 lex();
2786 if (expectAndConsume(MIToken::lparen))
2787 return error("expected syntax shufflemask(<integer or undef>, ...)");
2788
2789 SmallVector<int, 32> ShufMask;
2790 do {
2791 if (Token.is(MIToken::kw_undef)) {
2792 ShufMask.push_back(-1);
2793 } else if (Token.is(MIToken::IntegerLiteral)) {
2794 const APSInt &Int = Token.integerValue();
2795 ShufMask.push_back(Int.getExtValue());
2796 } else
2797 return error("expected integer constant");
2798
2799 lex();
2800 } while (consumeIfPresent(MIToken::comma));
2801
2802 if (expectAndConsume(MIToken::rparen))
2803 return error("shufflemask should be terminated by ')'.");
2804
2805 if (ShufMask.size() < 2)
2806 return error("shufflemask should have > 1 element");
2807
2808 ArrayRef<int> MaskAlloc = MF.allocateShuffleMask(ShufMask);
2809 Dest = MachineOperand::CreateShuffleMask(MaskAlloc);
2810 return false;
2811}
2812
2813bool MIParser::parseDbgInstrRefOperand(MachineOperand &Dest) {
2815
2816 lex();
2817 if (expectAndConsume(MIToken::lparen))
2818 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
2819
2820 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isNegative())
2821 return error("expected unsigned integer for instruction index");
2822 uint64_t InstrIdx = Token.integerValue().getZExtValue();
2823 assert(InstrIdx <= std::numeric_limits<unsigned>::max() &&
2824 "Instruction reference's instruction index is too large");
2825 lex();
2826
2827 if (expectAndConsume(MIToken::comma))
2828 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
2829
2830 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isNegative())
2831 return error("expected unsigned integer for operand index");
2832 uint64_t OpIdx = Token.integerValue().getZExtValue();
2833 assert(OpIdx <= std::numeric_limits<unsigned>::max() &&
2834 "Instruction reference's operand index is too large");
2835 lex();
2836
2837 if (expectAndConsume(MIToken::rparen))
2838 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
2839
2840 Dest = MachineOperand::CreateDbgInstrRef(InstrIdx, OpIdx);
2841 return false;
2842}
2843
2844bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
2846 lex();
2847 if (expectAndConsume(MIToken::lparen))
2848 return true;
2849 if (Token.isNot(MIToken::Identifier))
2850 return error("expected the name of the target index");
2851 int Index = 0;
2852 if (PFS.Target.getTargetIndex(Token.stringValue(), Index))
2853 return error("use of undefined target index '" + Token.stringValue() + "'");
2854 lex();
2855 if (expectAndConsume(MIToken::rparen))
2856 return true;
2857 Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
2858 if (parseOperandsOffset(Dest))
2859 return true;
2860 return false;
2861}
2862
2863bool MIParser::parseCustomRegisterMaskOperand(MachineOperand &Dest) {
2864 assert(Token.stringValue() == "CustomRegMask" && "Expected a custom RegMask");
2865 lex();
2866 if (expectAndConsume(MIToken::lparen))
2867 return true;
2868
2869 uint32_t *Mask = MF.allocateRegMask();
2870 do {
2871 if (Token.isNot(MIToken::rparen)) {
2872 if (Token.isNot(MIToken::NamedRegister))
2873 return error("expected a named register");
2874 Register Reg;
2875 if (parseNamedRegister(Reg))
2876 return true;
2877 lex();
2878 Mask[Reg.id() / 32] |= 1U << (Reg.id() % 32);
2879 }
2880
2881 // TODO: Report an error if the same register is used more than once.
2882 } while (consumeIfPresent(MIToken::comma));
2883
2884 if (expectAndConsume(MIToken::rparen))
2885 return true;
2886 Dest = MachineOperand::CreateRegMask(Mask);
2887 return false;
2888}
2889
2890bool MIParser::parseLaneMaskOperand(MachineOperand &Dest) {
2891 assert(Token.is(MIToken::kw_lanemask));
2892
2893 lex();
2894 if (expectAndConsume(MIToken::lparen))
2895 return true;
2896
2897 // Parse lanemask.
2898 if (Token.isNot(MIToken::IntegerLiteral) && Token.isNot(MIToken::HexLiteral))
2899 return error("expected a valid lane mask value");
2900 static_assert(sizeof(LaneBitmask::Type) == sizeof(uint64_t),
2901 "Use correct get-function for lane mask.");
2903 if (getUint64(V))
2904 return true;
2905 LaneBitmask LaneMask(V);
2906 lex();
2907
2908 if (expectAndConsume(MIToken::rparen))
2909 return true;
2910
2911 Dest = MachineOperand::CreateLaneMask(LaneMask);
2912 return false;
2913}
2914
2915bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) {
2916 assert(Token.is(MIToken::kw_liveout));
2917 uint32_t *Mask = MF.allocateRegMask();
2918 lex();
2919 if (expectAndConsume(MIToken::lparen))
2920 return true;
2921 while (true) {
2922 if (Token.isNot(MIToken::NamedRegister))
2923 return error("expected a named register");
2924 Register Reg;
2925 if (parseNamedRegister(Reg))
2926 return true;
2927 lex();
2928 Mask[Reg.id() / 32] |= 1U << (Reg.id() % 32);
2929 // TODO: Report an error if the same register is used more than once.
2930 if (Token.isNot(MIToken::comma))
2931 break;
2932 lex();
2933 }
2934 if (expectAndConsume(MIToken::rparen))
2935 return true;
2937 return false;
2938}
2939
2940bool MIParser::parseMachineOperand(const unsigned OpCode, const unsigned OpIdx,
2941 MachineOperand &Dest,
2942 std::optional<unsigned> &TiedDefIdx) {
2943 switch (Token.kind()) {
2946 case MIToken::kw_def:
2947 case MIToken::kw_dead:
2948 case MIToken::kw_killed:
2949 case MIToken::kw_undef:
2958 return parseRegisterOperand(Dest, TiedDefIdx);
2960 return parseImmediateOperand(Dest);
2961 case MIToken::kw_half:
2962 case MIToken::kw_bfloat:
2963 case MIToken::kw_float:
2964 case MIToken::kw_double:
2966 case MIToken::kw_fp128:
2968 return parseFPImmediateOperand(Dest);
2970 return parseMBBOperand(Dest);
2972 return parseStackObjectOperand(Dest);
2974 return parseFixedStackObjectOperand(Dest);
2977 return parseGlobalAddressOperand(Dest);
2979 return parseConstantPoolIndexOperand(Dest);
2981 return parseJumpTableIndexOperand(Dest);
2983 return parseExternalSymbolOperand(Dest);
2984 case MIToken::MCSymbol:
2985 return parseMCSymbolOperand(Dest);
2987 return parseSubRegisterIndexOperand(Dest);
2988 case MIToken::md_diexpr:
2989 case MIToken::exclaim:
2990 return parseMetadataOperand(Dest);
3008 return parseCFIOperand(Dest);
3010 return parseBlockAddressOperand(Dest);
3012 return parseIntrinsicOperand(Dest);
3014 return parseTargetIndexOperand(Dest);
3016 return parseLaneMaskOperand(Dest);
3018 return parseLiveoutRegisterMaskOperand(Dest);
3021 return parsePredicateOperand(Dest);
3023 return parseShuffleMaskOperand(Dest);
3025 return parseDbgInstrRefOperand(Dest);
3026 case MIToken::Error:
3027 return true;
3029 if (const auto *RegMask = PFS.Target.getRegMask(Token.stringValue())) {
3030 Dest = MachineOperand::CreateRegMask(RegMask);
3031 lex();
3032 break;
3033 } else if (Token.stringValue() == "CustomRegMask") {
3034 return parseCustomRegisterMaskOperand(Dest);
3035 } else
3036 return parseTypedImmediateOperand(Dest);
3037 case MIToken::dot: {
3038 const auto *TII = MF.getSubtarget().getInstrInfo();
3039 if (const auto *Formatter = TII->getMIRFormatter()) {
3040 return parseTargetImmMnemonic(OpCode, OpIdx, Dest, *Formatter);
3041 }
3042 [[fallthrough]];
3043 }
3044 default:
3045 // FIXME: Parse the MCSymbol machine operand.
3046 return error("expected a machine operand");
3047 }
3048 return false;
3049}
3050
3051bool MIParser::parseMachineOperandAndTargetFlags(
3052 const unsigned OpCode, const unsigned OpIdx, MachineOperand &Dest,
3053 std::optional<unsigned> &TiedDefIdx) {
3054 unsigned TF = 0;
3055 bool HasTargetFlags = false;
3056 if (Token.is(MIToken::kw_target_flags)) {
3057 HasTargetFlags = true;
3058 lex();
3059 if (expectAndConsume(MIToken::lparen))
3060 return true;
3061 if (Token.isNot(MIToken::Identifier))
3062 return error("expected the name of the target flag");
3063 if (PFS.Target.getDirectTargetFlag(Token.stringValue(), TF)) {
3064 if (PFS.Target.getBitmaskTargetFlag(Token.stringValue(), TF))
3065 return error("use of undefined target flag '" + Token.stringValue() +
3066 "'");
3067 }
3068 lex();
3069 while (Token.is(MIToken::comma)) {
3070 lex();
3071 if (Token.isNot(MIToken::Identifier))
3072 return error("expected the name of the target flag");
3073 unsigned BitFlag = 0;
3074 if (PFS.Target.getBitmaskTargetFlag(Token.stringValue(), BitFlag))
3075 return error("use of undefined target flag '" + Token.stringValue() +
3076 "'");
3077 // TODO: Report an error when using a duplicate bit target flag.
3078 TF |= BitFlag;
3079 lex();
3080 }
3081 if (expectAndConsume(MIToken::rparen))
3082 return true;
3083 }
3084 auto Loc = Token.location();
3085 if (parseMachineOperand(OpCode, OpIdx, Dest, TiedDefIdx))
3086 return true;
3087 if (!HasTargetFlags)
3088 return false;
3089 if (Dest.isReg())
3090 return error(Loc, "register operands can't have target flags");
3091 Dest.setTargetFlags(TF);
3092 return false;
3093}
3094
3095bool MIParser::parseOffset(int64_t &Offset) {
3096 if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
3097 return false;
3098 StringRef Sign = Token.range();
3099 bool IsNegative = Token.is(MIToken::minus);
3100 lex();
3101 if (Token.isNot(MIToken::IntegerLiteral))
3102 return error("expected an integer literal after '" + Sign + "'");
3103 if (Token.integerValue().getSignificantBits() > 64)
3104 return error("expected 64-bit integer (too large)");
3105 Offset = Token.integerValue().getExtValue();
3106 if (IsNegative)
3107 Offset = -Offset;
3108 lex();
3109 return false;
3110}
3111
3112bool MIParser::parseIRBlockAddressTaken(BasicBlock *&BB) {
3114 lex();
3115 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
3116 return error("expected basic block after 'ir_block_address_taken'");
3117
3118 if (parseIRBlock(BB, MF.getFunction()))
3119 return true;
3120
3121 lex();
3122 return false;
3123}
3124
3125bool MIParser::parseAlignment(uint64_t &Alignment) {
3126 assert(Token.is(MIToken::kw_align) || Token.is(MIToken::kw_basealign));
3127 lex();
3128 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
3129 return error("expected an integer literal after 'align'");
3130 if (getUint64(Alignment))
3131 return true;
3132 lex();
3133
3134 if (!isPowerOf2_64(Alignment))
3135 return error("expected a power-of-2 literal after 'align'");
3136
3137 return false;
3138}
3139
3140bool MIParser::parseAddrspace(unsigned &Addrspace) {
3141 assert(Token.is(MIToken::kw_addrspace));
3142 lex();
3143 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
3144 return error("expected an integer literal after 'addrspace'");
3145 if (getUnsigned(Addrspace))
3146 return true;
3147 lex();
3148 return false;
3149}
3150
3151bool MIParser::parseOperandsOffset(MachineOperand &Op) {
3152 int64_t Offset = 0;
3153 if (parseOffset(Offset))
3154 return true;
3155 Op.setOffset(Offset);
3156 return false;
3157}
3158
3159static bool parseIRValue(const MIToken &Token, PerFunctionMIParsingState &PFS,
3160 const Value *&V, ErrorCallbackType ErrCB) {
3161 switch (Token.kind()) {
3162 case MIToken::NamedIRValue: {
3163 V = PFS.MF.getFunction().getValueSymbolTable()->lookup(Token.stringValue());
3164 break;
3165 }
3166 case MIToken::IRValue: {
3167 unsigned SlotNumber = 0;
3168 if (getUnsigned(Token, SlotNumber, ErrCB))
3169 return true;
3170 V = PFS.getIRValue(SlotNumber);
3171 break;
3172 }
3174 case MIToken::GlobalValue: {
3175 GlobalValue *GV = nullptr;
3176 if (parseGlobalValue(Token, PFS, GV, ErrCB))
3177 return true;
3178 V = GV;
3179 break;
3180 }
3182 const Constant *C = nullptr;
3183 if (parseIRConstant(Token.location(), Token.stringValue(), PFS, C, ErrCB))
3184 return true;
3185 V = C;
3186 break;
3187 }
3189 V = nullptr;
3190 return false;
3191 default:
3192 llvm_unreachable("The current token should be an IR block reference");
3193 }
3194 if (!V)
3195 return ErrCB(Token.location(), Twine("use of undefined IR value '") + Token.range() + "'");
3196 return false;
3197}
3198
3199bool MIParser::parseIRValue(const Value *&V) {
3200 return ::parseIRValue(
3201 Token, PFS, V, [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
3202 return error(Loc, Msg);
3203 });
3204}
3205
3206bool MIParser::getUint64(uint64_t &Result) {
3207 if (Token.hasIntegerValue()) {
3208 if (Token.integerValue().getActiveBits() > 64)
3209 return error("expected 64-bit integer (too large)");
3210 Result = Token.integerValue().getZExtValue();
3211 return false;
3212 }
3213 if (Token.is(MIToken::HexLiteral)) {
3214 APInt A;
3215 if (getHexUint(A))
3216 return true;
3217 if (A.getBitWidth() > 64)
3218 return error("expected 64-bit integer (too large)");
3219 Result = A.getZExtValue();
3220 return false;
3221 }
3222 return true;
3223}
3224
3225bool MIParser::getHexUint(APInt &Result) {
3226 return ::getHexUint(Token, Result);
3227}
3228
3229bool MIParser::parseMemoryOperandFlag(MachineMemOperand::Flags &Flags) {
3230 const auto OldFlags = Flags;
3231 switch (Token.kind()) {
3234 break;
3237 break;
3240 break;
3243 break;
3246 if (PFS.Target.getMMOTargetFlag(Token.stringValue(), TF))
3247 return error("use of undefined target MMO flag '" + Token.stringValue() +
3248 "'");
3249 Flags |= TF;
3250 break;
3251 }
3252 default:
3253 llvm_unreachable("The current token should be a memory operand flag");
3254 }
3255 if (OldFlags == Flags)
3256 // We know that the same flag is specified more than once when the flags
3257 // weren't modified.
3258 return error("duplicate '" + Token.stringValue() + "' memory operand flag");
3259 lex();
3260 return false;
3261}
3262
3263bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV) {
3264 switch (Token.kind()) {
3265 case MIToken::kw_stack:
3266 PSV = MF.getPSVManager().getStack();
3267 break;
3268 case MIToken::kw_got:
3269 PSV = MF.getPSVManager().getGOT();
3270 break;
3272 PSV = MF.getPSVManager().getJumpTable();
3273 break;
3275 PSV = MF.getPSVManager().getConstantPool();
3276 break;
3278 int FI;
3279 if (parseFixedStackFrameIndex(FI))
3280 return true;
3281 PSV = MF.getPSVManager().getFixedStack(FI);
3282 // The token was already consumed, so use return here instead of break.
3283 return false;
3284 }
3285 case MIToken::StackObject: {
3286 int FI;
3287 if (parseStackFrameIndex(FI))
3288 return true;
3289 PSV = MF.getPSVManager().getFixedStack(FI);
3290 // The token was already consumed, so use return here instead of break.
3291 return false;
3292 }
3294 lex();
3295 switch (Token.kind()) {
3298 GlobalValue *GV = nullptr;
3299 if (parseGlobalValue(GV))
3300 return true;
3301 PSV = MF.getPSVManager().getGlobalValueCallEntry(GV);
3302 break;
3303 }
3305 PSV = MF.getPSVManager().getExternalSymbolCallEntry(
3306 MF.createExternalSymbolName(Token.stringValue()));
3307 break;
3308 default:
3309 return error(
3310 "expected a global value or an external symbol after 'call-entry'");
3311 }
3312 break;
3313 case MIToken::kw_custom: {
3314 lex();
3315 const auto *TII = MF.getSubtarget().getInstrInfo();
3316 if (const auto *Formatter = TII->getMIRFormatter()) {
3317 if (Formatter->parseCustomPseudoSourceValue(
3318 Token.stringValue(), MF, PFS, PSV,
3319 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
3320 return error(Loc, Msg);
3321 }))
3322 return true;
3323 } else
3324 return error("unable to parse target custom pseudo source value");
3325 break;
3326 }
3327 default:
3328 llvm_unreachable("The current token should be pseudo source value");
3329 }
3330 lex();
3331 return false;
3332}
3333
3334bool MIParser::parseMachinePointerInfo(MachinePointerInfo &Dest) {
3335 if (Token.is(MIToken::kw_constant_pool) || Token.is(MIToken::kw_stack) ||
3336 Token.is(MIToken::kw_got) || Token.is(MIToken::kw_jump_table) ||
3337 Token.is(MIToken::FixedStackObject) || Token.is(MIToken::StackObject) ||
3338 Token.is(MIToken::kw_call_entry) || Token.is(MIToken::kw_custom)) {
3339 const PseudoSourceValue *PSV = nullptr;
3340 if (parseMemoryPseudoSourceValue(PSV))
3341 return true;
3342 int64_t Offset = 0;
3343 if (parseOffset(Offset))
3344 return true;
3345 Dest = MachinePointerInfo(PSV, Offset);
3346 return false;
3347 }
3348 if (Token.isNot(MIToken::NamedIRValue) && Token.isNot(MIToken::IRValue) &&
3349 Token.isNot(MIToken::GlobalValue) &&
3350 Token.isNot(MIToken::NamedGlobalValue) &&
3351 Token.isNot(MIToken::QuotedIRValue) &&
3352 Token.isNot(MIToken::kw_unknown_address))
3353 return error("expected an IR value reference");
3354 const Value *V = nullptr;
3355 if (parseIRValue(V))
3356 return true;
3357 if (V && !V->getType()->isPointerTy())
3358 return error("expected a pointer IR value");
3359 lex();
3360 int64_t Offset = 0;
3361 if (parseOffset(Offset))
3362 return true;
3363 Dest = MachinePointerInfo(V, Offset);
3364 return false;
3365}
3366
3367bool MIParser::parseOptionalScope(LLVMContext &Context,
3368 SyncScope::ID &SSID) {
3369 SSID = SyncScope::System;
3370 if (Token.is(MIToken::Identifier) && Token.stringValue() == "syncscope") {
3371 lex();
3372 if (expectAndConsume(MIToken::lparen))
3373 return error("expected '(' in syncscope");
3374
3375 std::string SSN;
3376 if (parseStringConstant(SSN))
3377 return true;
3378
3379 SSID = Context.getOrInsertSyncScopeID(SSN);
3380 if (expectAndConsume(MIToken::rparen))
3381 return error("expected ')' in syncscope");
3382 }
3383
3384 return false;
3385}
3386
3387bool MIParser::parseOptionalAtomicOrdering(AtomicOrdering &Order) {
3389 if (Token.isNot(MIToken::Identifier))
3390 return false;
3391
3392 Order = StringSwitch<AtomicOrdering>(Token.stringValue())
3393 .Case("unordered", AtomicOrdering::Unordered)
3394 .Case("monotonic", AtomicOrdering::Monotonic)
3395 .Case("acquire", AtomicOrdering::Acquire)
3396 .Case("release", AtomicOrdering::Release)
3400
3401 if (Order != AtomicOrdering::NotAtomic) {
3402 lex();
3403 return false;
3404 }
3405
3406 return error("expected an atomic scope, ordering or a size specification");
3407}
3408
3409bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
3410 if (expectAndConsume(MIToken::lparen))
3411 return true;
3413 while (Token.isMemoryOperandFlag()) {
3414 if (parseMemoryOperandFlag(Flags))
3415 return true;
3416 }
3417 if (Token.isNot(MIToken::Identifier) ||
3418 (Token.stringValue() != "load" && Token.stringValue() != "store"))
3419 return error("expected 'load' or 'store' memory operation");
3420 if (Token.stringValue() == "load")
3422 else
3424 lex();
3425
3426 // Optional 'store' for operands that both load and store.
3427 if (Token.is(MIToken::Identifier) && Token.stringValue() == "store") {
3429 lex();
3430 }
3431
3432 // Optional synchronization scope.
3433 SyncScope::ID SSID;
3434 if (parseOptionalScope(MF.getFunction().getContext(), SSID))
3435 return true;
3436
3437 // Up to two atomic orderings (cmpxchg provides guarantees on failure).
3438 AtomicOrdering Order, FailureOrder;
3439 if (parseOptionalAtomicOrdering(Order))
3440 return true;
3441
3442 if (parseOptionalAtomicOrdering(FailureOrder))
3443 return true;
3444
3445 if (Token.isNot(MIToken::IntegerLiteral) &&
3446 Token.isNot(MIToken::kw_unknown_size) &&
3447 Token.isNot(MIToken::lparen))
3448 return error("expected memory LLT, the size integer literal or 'unknown-size' after "
3449 "memory operation");
3450
3452 if (Token.is(MIToken::IntegerLiteral)) {
3453 uint64_t Size;
3454 if (getUint64(Size))
3455 return true;
3456
3457 // Convert from bytes to bits for storage.
3459 lex();
3460 } else if (Token.is(MIToken::kw_unknown_size)) {
3461 lex();
3462 } else {
3463 if (expectAndConsume(MIToken::lparen))
3464 return true;
3465 if (parseLowLevelType(Token.location(), MemoryType))
3466 return true;
3467 if (expectAndConsume(MIToken::rparen))
3468 return true;
3469 }
3470
3472 if (Token.is(MIToken::Identifier)) {
3473 const char *Word =
3476 ? "on"
3477 : Flags & MachineMemOperand::MOLoad ? "from" : "into";
3478 if (Token.stringValue() != Word)
3479 return error(Twine("expected '") + Word + "'");
3480 lex();
3481
3482 if (parseMachinePointerInfo(Ptr))
3483 return true;
3484 }
3485 uint64_t BaseAlignment =
3486 MemoryType.isValid()
3487 ? PowerOf2Ceil(MemoryType.getSizeInBytes().getKnownMinValue())
3488 : 1;
3489 AAMDNodes AAInfo;
3490 MDNode *Range = nullptr;
3491 while (consumeIfPresent(MIToken::comma)) {
3492 switch (Token.kind()) {
3493 case MIToken::kw_align: {
3494 // align is printed if it is different than size.
3495 uint64_t Alignment;
3496 if (parseAlignment(Alignment))
3497 return true;
3498 if (Ptr.Offset & (Alignment - 1)) {
3499 // MachineMemOperand::getAlign never returns a value greater than the
3500 // alignment of offset, so this just guards against hand-written MIR
3501 // that specifies a large "align" value when it should probably use
3502 // "basealign" instead.
3503 return error("specified alignment is more aligned than offset");
3504 }
3505 BaseAlignment = Alignment;
3506 break;
3507 }
3509 // basealign is printed if it is different than align.
3510 if (parseAlignment(BaseAlignment))
3511 return true;
3512 break;
3514 if (parseAddrspace(Ptr.AddrSpace))
3515 return true;
3516 break;
3517 case MIToken::md_tbaa:
3518 lex();
3519 if (parseMDNode(AAInfo.TBAA))
3520 return true;
3521 break;
3523 lex();
3524 if (parseMDNode(AAInfo.Scope))
3525 return true;
3526 break;
3528 lex();
3529 if (parseMDNode(AAInfo.NoAlias))
3530 return true;
3531 break;
3533 lex();
3534 if (parseMDNode(AAInfo.NoAliasAddrSpace))
3535 return true;
3536 break;
3537 case MIToken::md_range:
3538 lex();
3539 if (parseMDNode(Range))
3540 return true;
3541 break;
3542 // TODO: Report an error on duplicate metadata nodes.
3543 default:
3544 return error("expected 'align' or '!tbaa' or '!alias.scope' or "
3545 "'!noalias' or '!range' or '!noalias.addrspace'");
3546 }
3547 }
3548 if (expectAndConsume(MIToken::rparen))
3549 return true;
3550 Dest = MF.getMachineMemOperand(Ptr, Flags, MemoryType, Align(BaseAlignment),
3551 AAInfo, Range, SSID, Order, FailureOrder);
3552 return false;
3553}
3554
3555bool MIParser::parsePreOrPostInstrSymbol(MCSymbol *&Symbol) {
3557 Token.is(MIToken::kw_post_instr_symbol)) &&
3558 "Invalid token for a pre- post-instruction symbol!");
3559 lex();
3560 if (Token.isNot(MIToken::MCSymbol))
3561 return error("expected a symbol after 'pre-instr-symbol'");
3562 Symbol = getOrCreateMCSymbol(Token.stringValue());
3563 lex();
3564 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3565 Token.is(MIToken::lbrace))
3566 return false;
3567 if (Token.isNot(MIToken::comma))
3568 return error("expected ',' before the next machine operand");
3569 lex();
3570 return false;
3571}
3572
3573bool MIParser::parseHeapAllocMarker(MDNode *&Node) {
3575 "Invalid token for a heap alloc marker!");
3576 lex();
3577 if (parseMDNode(Node))
3578 return true;
3579 if (!Node)
3580 return error("expected a MDNode after 'heap-alloc-marker'");
3581 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3582 Token.is(MIToken::lbrace))
3583 return false;
3584 if (Token.isNot(MIToken::comma))
3585 return error("expected ',' before the next machine operand");
3586 lex();
3587 return false;
3588}
3589
3590bool MIParser::parsePCSections(MDNode *&Node) {
3591 assert(Token.is(MIToken::kw_pcsections) &&
3592 "Invalid token for a PC sections!");
3593 lex();
3594 if (parseMDNode(Node))
3595 return true;
3596 if (!Node)
3597 return error("expected a MDNode after 'pcsections'");
3598 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3599 Token.is(MIToken::lbrace))
3600 return false;
3601 if (Token.isNot(MIToken::comma))
3602 return error("expected ',' before the next machine operand");
3603 lex();
3604 return false;
3605}
3606
3608 const Function &F,
3609 DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
3610 ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
3612 for (const auto &BB : F) {
3613 if (BB.hasName())
3614 continue;
3615 int Slot = MST.getLocalSlot(&BB);
3616 if (Slot == -1)
3617 continue;
3618 Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
3619 }
3620}
3621
3623 unsigned Slot,
3624 const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
3625 return Slots2BasicBlocks.lookup(Slot);
3626}
3627
3628const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
3629 if (Slots2BasicBlocks.empty())
3630 initSlots2BasicBlocks(MF.getFunction(), Slots2BasicBlocks);
3631 return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
3632}
3633
3634const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
3635 if (&F == &MF.getFunction())
3636 return getIRBlock(Slot);
3637 DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
3638 initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
3639 return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
3640}
3641
3642MCSymbol *MIParser::getOrCreateMCSymbol(StringRef Name) {
3643 // FIXME: Currently we can't recognize temporary or local symbols and call all
3644 // of the appropriate forms to create them. However, this handles basic cases
3645 // well as most of the special aspects are recognized by a prefix on their
3646 // name, and the input names should already be unique. For test cases, keeping
3647 // the symbol name out of the symbol table isn't terribly important.
3648 return MF.getContext().getOrCreateSymbol(Name);
3649}
3650
3651bool MIParser::parseStringConstant(std::string &Result) {
3652 if (Token.isNot(MIToken::StringConstant))
3653 return error("expected string constant");
3654 Result = std::string(Token.stringValue());
3655 lex();
3656 return false;
3657}
3658
3660 StringRef Src,
3662 return MIParser(PFS, Error, Src).parseBasicBlockDefinitions(PFS.MBBSlots);
3663}
3664
3667 return MIParser(PFS, Error, Src).parseBasicBlocks();
3668}
3669
3673 return MIParser(PFS, Error, Src).parseStandaloneMBB(MBB);
3674}
3675
3677 Register &Reg, StringRef Src,
3679 return MIParser(PFS, Error, Src).parseStandaloneRegister(Reg);
3680}
3681
3683 Register &Reg, StringRef Src,
3685 return MIParser(PFS, Error, Src).parseStandaloneNamedRegister(Reg);
3686}
3687
3689 VRegInfo *&Info, StringRef Src,
3691 return MIParser(PFS, Error, Src).parseStandaloneVirtualRegister(Info);
3692}
3693
3695 int &FI, StringRef Src,
3697 return MIParser(PFS, Error, Src).parseStandaloneStackObject(FI);
3698}
3699
3702 return MIParser(PFS, Error, Src).parseStandaloneMDNode(Node);
3703}
3704
3706 SMRange SrcRange, SMDiagnostic &Error) {
3707 return MIParser(PFS, Error, Src, SrcRange).parseMachineMetadata();
3708}
3709
3711 PerFunctionMIParsingState &PFS, const Value *&V,
3712 ErrorCallbackType ErrorCallback) {
3713 MIToken Token;
3714 Src = lexMIToken(Src, Token, [&](StringRef::iterator Loc, const Twine &Msg) {
3715 ErrorCallback(Loc, Msg);
3716 });
3717 V = nullptr;
3718
3719 return ::parseIRValue(Token, PFS, V, ErrorCallback);
3720}
unsigned SubReg
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const TargetInstrInfo & TII
This file defines the StringMap class.
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.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Analysis containing CSE Info
Definition CSEInfo.cpp:27
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil translate DXIL Translate Metadata
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.
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(DataExtractor &Data, uint64_t BaseAddr, LineEntryCallback const &Callback)
Definition LineTable.cpp:54
Implement a low-level type suitable for MachineInstr level instruction selection.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static const char * printImplicitRegisterFlag(const MachineOperand &MO)
static const BasicBlock * getIRBlockFromSlot(unsigned Slot, const DenseMap< unsigned, const BasicBlock * > &Slots2BasicBlocks)
static std::string getRegisterName(const TargetRegisterInfo *TRI, Register Reg)
static bool parseIRConstant(StringRef::iterator Loc, StringRef StringValue, PerFunctionMIParsingState &PFS, const Constant *&C, ErrorCallbackType ErrCB)
static void initSlots2Values(const Function &F, DenseMap< unsigned, const Value * > &Slots2Values)
Creates the mapping from slot numbers to function's unnamed IR values.
Definition MIParser.cpp:360
static bool parseIRValue(const MIToken &Token, PerFunctionMIParsingState &PFS, const Value *&V, ErrorCallbackType ErrCB)
static bool verifyScalarSize(uint64_t Size)
static bool getUnsigned(const MIToken &Token, unsigned &Result, ErrorCallbackType ErrCB)
static bool getHexUint(const MIToken &Token, APInt &Result)
static bool verifyVectorElementCount(uint64_t NumElts)
static void mapValueToSlot(const Value *V, ModuleSlotTracker &MST, DenseMap< unsigned, const Value * > &Slots2Values)
Definition MIParser.cpp:351
static void initSlots2BasicBlocks(const Function &F, DenseMap< unsigned, const BasicBlock * > &Slots2BasicBlocks)
function_ref< bool(StringRef::iterator Loc, const Twine &)> ErrorCallbackType
Definition MIParser.cpp:623
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
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file contains the declarations for metadata subclasses.
#define T
MachineInstr unsigned OpIdx
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
static bool parseMetadata(const StringRef &Input, uint64_t &FunctionHash, uint32_t &Attributes)
Parse Input that contains metadata.
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:1541
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:476
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & back() const
back - Get the last element.
Definition ArrayRef.h:151
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
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 BranchProbability getRaw(uint32_t N)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:679
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:693
@ ICMP_SLT
signed less than
Definition InstrTypes.h:705
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:706
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:682
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:691
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:680
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:681
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:700
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:703
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:690
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:684
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:687
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:688
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:683
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:685
@ ICMP_NE
not equal
Definition InstrTypes.h:698
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:704
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:692
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:702
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:689
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:678
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:686
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:770
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:776
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
A debug info location.
Definition DebugLoc.h:123
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition DenseMap.h:205
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:241
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:315
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:815
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".
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).
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
static MCCFIInstruction createDefCfaRegister(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_def_cfa_register modifies a rule for computing CFA.
Definition MCDwarf.h:592
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:673
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:666
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:617
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:642
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:585
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:627
static MCCFIInstruction createNegateRAStateWithPC(MCSymbol *L, SMLoc Loc={})
.cfi_negate_ra_state_with_pc AArch64 negate RA state with PC.
Definition MCDwarf.h:658
static MCCFIInstruction createNegateRAState(MCSymbol *L, SMLoc Loc={})
.cfi_negate_ra_state AArch64 negate RA state.
Definition MCDwarf.h:653
static MCCFIInstruction createRememberState(MCSymbol *L, SMLoc Loc={})
.cfi_remember_state Save all current rules for all registers.
Definition MCDwarf.h:686
static MCCFIInstruction cfiDefCfaOffset(MCSymbol *L, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa_offset modifies a rule for computing CFA.
Definition MCDwarf.h:600
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:697
static MCCFIInstruction createWindowSave(MCSymbol *L, SMLoc Loc={})
.cfi_window_save SPARC register window is saved.
Definition MCDwarf.h:648
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:608
static MCCFIInstruction createRestoreState(MCSymbol *L, SMLoc Loc={})
.cfi_restore_state Restore the previously saved state.
Definition MCDwarf.h:691
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:680
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:635
Describe properties that are true of each instruction in the target description file.
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:1078
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1569
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:608
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1537
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1526
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1546
MIRFormater - Interface to format MIR operand based on target.
virtual bool parseImmMnemonic(const unsigned OpCode, const unsigned OpIdx, StringRef Src, int64_t &Imm, ErrorCallbackType ErrorCallback) const
Implement target specific parsing of immediate mnemonics.
function_ref< bool(StringRef::iterator Loc, const Twine &)> ErrorCallbackType
static LLVM_ABI bool parseIRValue(StringRef Src, MachineFunction &MF, PerFunctionMIParsingState &PFS, const Value *&V, ErrorCallbackType ErrorCallback)
Helper functions to parse IR value from MIR serialization format which will be useful for target spec...
void normalizeSuccProbs()
Normalize probabilities of all successors so that the sum of them becomes one.
void setAddressTakenIRBlock(BasicBlock *BB)
Set this block to reflect that it corresponds to an IR-level basic block with a BlockAddress.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
void setCallFrameSize(unsigned N)
Set the call frame size on entry to this basic block.
void setAlignment(Align A)
Set alignment of the basic block.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
void setSectionID(MBBSectionID V)
Sets the section ID for this basic block.
void setIsInlineAsmBrIndirectTarget(bool V=true)
Indicates if this is the indirect dest of an INLINEASM_BR.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
void setIsEHFuncletEntry(bool V=true)
Indicates if this is the entry block of an EH funclet.
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
void 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,...
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
Root of the metadata hierarchy.
Definition Metadata.h:64
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:67
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:297
Represents a location in source code.
Definition SMLoc.h:22
static SMLoc getFromPointer(const char *Ptr)
Definition SMLoc.h:35
Represents a range in source code.
Definition SMLoc.h:47
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling.
Definition SourceMgr.h:37
unsigned getMainFileID() const
Definition SourceMgr.h:148
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:108
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition StringMap.h:321
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
const char * iterator
Definition StringRef.h:59
std::string str() const
str - Get the contents as an std::string.
Definition StringRef.h:225
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:573
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:611
constexpr size_t size() const
size - Get the string size.
Definition StringRef.h:146
char front() const
front - Get the first character in the string.
Definition StringRef.h:149
LLVM_ABI std::string lower() const
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
virtual const MIRFormatter * getMIRFormatter() const
Return MIR formatter to format/parse MIR operands.
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.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
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:262
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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Debug
Register 'use' is for debugging purpose.
@ Dead
Unused definition.
@ Renamable
Register that may be renamed.
@ Define
Register definition.
@ InternalRead
Register reads a value that is defined inside the same instruction or bundle.
@ Kill
The last use of a register.
@ Undef
Value of the register doesn't matter.
@ EarlyClobber
Register definition happens before uses.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
support::ulittle32_t Word
Definition IRSymtab.h:53
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:532
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
bool parseStackObjectReference(PerFunctionMIParsingState &PFS, int &FI, StringRef Src, SMDiagnostic &Error)
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:1737
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:284
bool parseMachineBasicBlockDefinitions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine basic block definitions, and skip the machine instructions.
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...
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:385
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:236
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:189
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
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)
bool parseMachineInstructions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine instructions.
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:195
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool parseMachineMetadata(PerFunctionMIParsingState &PFS, StringRef Src, SMRange SourceRange, SMDiagnostic &Error)
bool parseVirtualRegisterReference(PerFunctionMIParsingState &PFS, VRegInfo *&Info, StringRef Src, SMDiagnostic &Error)
bool parseNamedRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:761
MDNode * NoAliasAddrSpace
The tag specifying the noalias address spaces.
Definition Metadata.h:790
MDNode * Scope
The tag for alias scope specification (used with noalias).
Definition Metadata.h:784
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:778
MDNode * NoAlias
The tag specifying the noalias scope.
Definition Metadata.h:787
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:208
bool hasIntegerValue() const
Definition MILexer.h:248
bool is(TokenKind K) const
Definition MILexer.h:235
StringRef stringValue() const
Return the token's string value.
Definition MILexer.h:244
@ kw_pre_instr_symbol
Definition MILexer.h:135
@ kw_deactivation_symbol
Definition MILexer.h:140
@ kw_call_frame_size
Definition MILexer.h:147
@ kw_cfi_aarch64_negate_ra_sign_state
Definition MILexer.h:100
@ kw_cfi_llvm_def_aspace_cfa
Definition MILexer.h:93
@ MachineBasicBlock
Definition MILexer.h:167
@ kw_dbg_instr_ref
Definition MILexer.h:84
@ NamedVirtualRegister
Definition MILexer.h:165
@ kw_early_clobber
Definition MILexer.h:59
@ kw_unpredictable
Definition MILexer.h:77
@ FloatingPointLiteral
Definition MILexer.h:177
@ kw_cfi_window_save
Definition MILexer.h:99
@ kw_frame_destroy
Definition MILexer.h:64
@ kw_cfi_undefined
Definition MILexer.h:98
@ MachineBasicBlockLabel
Definition MILexer.h:166
@ kw_cfi_register
Definition MILexer.h:94
@ kw_inlineasm_br_indirect_target
Definition MILexer.h:128
@ kw_cfi_rel_offset
Definition MILexer.h:87
@ kw_ehfunclet_entry
Definition MILexer.h:129
@ kw_cfi_aarch64_negate_ra_sign_state_with_pc
Definition MILexer.h:101
@ kw_cfi_def_cfa_register
Definition MILexer.h:88
@ kw_cfi_same_value
Definition MILexer.h:85
@ kw_cfi_adjust_cfa_offset
Definition MILexer.h:90
@ kw_dereferenceable
Definition MILexer.h:55
@ kw_implicit_define
Definition MILexer.h:52
@ kw_cfi_def_cfa_offset
Definition MILexer.h:89
@ kw_machine_block_address_taken
Definition MILexer.h:146
@ kw_cfi_remember_state
Definition MILexer.h:95
@ kw_debug_instr_number
Definition MILexer.h:83
@ kw_post_instr_symbol
Definition MILexer.h:136
@ kw_cfi_restore_state
Definition MILexer.h:97
@ kw_ir_block_address_taken
Definition MILexer.h:145
@ kw_unknown_address
Definition MILexer.h:144
@ md_noalias_addrspace
Definition MILexer.h:157
@ kw_debug_location
Definition MILexer.h:82
@ kw_heap_alloc_marker
Definition MILexer.h:137
StringRef range() const
Definition MILexer.h:241
StringRef::iterator location() const
Definition MILexer.h:239
const APSInt & integerValue() const
Definition MILexer.h:246
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*.
VRegInfo & getVRegInfo(Register Num)
Definition MIParser.cpp:328
const SlotMapping & IRSlots
Definition MIParser.h:169
const Value * getIRValue(unsigned Slot)
Definition MIParser.cpp:373
DenseMap< unsigned, MachineBasicBlock * > MBBSlots
Definition MIParser.h:175
StringMap< VRegInfo * > VRegInfosNamed
Definition MIParser.h:177
DenseMap< unsigned, const Value * > Slots2Values
Maps from slot numbers to function's unnamed values.
Definition MIParser.h:184
PerFunctionMIParsingState(MachineFunction &MF, SourceMgr &SM, const SlotMapping &IRSlots, PerTargetMIParsingState &Target)
Definition MIParser.cpp:323
PerTargetMIParsingState & Target
Definition MIParser.h:170
DenseMap< Register, VRegInfo * > VRegInfos
Definition MIParser.h:176
VRegInfo & getVRegInfoNamed(StringRef RegName)
Definition MIParser.cpp:339
bool getVRegFlagValue(StringRef FlagName, uint8_t &FlagValue) const
Definition MIParser.cpp:128
bool getDirectTargetFlag(StringRef Name, unsigned &Flag)
Try to convert a name of a direct target flag to the corresponding target flag.
Definition MIParser.cpp:226
const RegisterBank * getRegBank(StringRef Name)
Check if the given identifier is a name of a register bank.
Definition MIParser.cpp:316
bool parseInstrName(StringRef InstrName, unsigned &OpCode)
Try to convert an instruction name to an opcode.
Definition MIParser.cpp:147
unsigned getSubRegIndex(StringRef Name)
Check if the given identifier is a name of a subregister index.
Definition MIParser.cpp:187
bool getTargetIndex(StringRef Name, int &Index)
Try to convert a name of target index to the corresponding target index.
Definition MIParser.cpp:205
void setTarget(const TargetSubtargetInfo &NewSubtarget)
Definition MIParser.cpp:80
bool getRegisterByName(StringRef RegName, Register &Reg)
Try to convert a register name to a register number.
Definition MIParser.cpp:118
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:269
bool getBitmaskTargetFlag(StringRef Name, unsigned &Flag)
Try to convert a name of a bitmask target flag to the corresponding target flag.
Definition MIParser.cpp:248
const TargetRegisterClass * getRegClass(StringRef Name)
Check if the given identifier is a name of a register class.
Definition MIParser.cpp:309
const uint32_t * getRegMask(StringRef Identifier)
Check if the given identifier is a name of a register mask.
Definition MIParser.cpp:170
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:44
union llvm::VRegInfo::@127225073067155374133234315364317264041071000132 D
const TargetRegisterClass * RC
Definition MIParser.h:43
enum llvm::VRegInfo::@374354327266250320012227113300214031244227062232 Kind
Register VReg
Definition MIParser.h:46
bool Explicit
VReg was explicitly specified in the .mir file.
Definition MIParser.h:41