1 //===- MIParser.cpp - Machine instructions parser implementation ----------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the parsing of machine instructions.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/MIRParser/MIParser.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"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/MemoryLocation.h"
27 #include "llvm/AsmParser/Parser.h"
28 #include "llvm/AsmParser/SlotMapping.h"
29 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
30 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
31 #include "llvm/CodeGen/MIRFormatter.h"
32 #include "llvm/CodeGen/MIRPrinter.h"
33 #include "llvm/CodeGen/MachineBasicBlock.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineFunction.h"
36 #include "llvm/CodeGen/MachineInstr.h"
37 #include "llvm/CodeGen/MachineInstrBuilder.h"
38 #include "llvm/CodeGen/MachineMemOperand.h"
39 #include "llvm/CodeGen/MachineOperand.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/TargetInstrInfo.h"
42 #include "llvm/CodeGen/TargetRegisterInfo.h"
43 #include "llvm/CodeGen/TargetSubtargetInfo.h"
44 #include "llvm/IR/BasicBlock.h"
45 #include "llvm/IR/Constants.h"
46 #include "llvm/IR/DataLayout.h"
47 #include "llvm/IR/DebugInfoMetadata.h"
48 #include "llvm/IR/DebugLoc.h"
49 #include "llvm/IR/Function.h"
50 #include "llvm/IR/InstrTypes.h"
51 #include "llvm/IR/Instructions.h"
52 #include "llvm/IR/Intrinsics.h"
53 #include "llvm/IR/Metadata.h"
54 #include "llvm/IR/Module.h"
55 #include "llvm/IR/ModuleSlotTracker.h"
56 #include "llvm/IR/Type.h"
57 #include "llvm/IR/Value.h"
58 #include "llvm/IR/ValueSymbolTable.h"
59 #include "llvm/MC/LaneBitmask.h"
60 #include "llvm/MC/MCContext.h"
61 #include "llvm/MC/MCDwarf.h"
62 #include "llvm/MC/MCInstrDesc.h"
63 #include "llvm/MC/MCRegisterInfo.h"
64 #include "llvm/Support/AtomicOrdering.h"
65 #include "llvm/Support/BranchProbability.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/ErrorHandling.h"
68 #include "llvm/Support/LowLevelTypeImpl.h"
69 #include "llvm/Support/MemoryBuffer.h"
70 #include "llvm/Support/SMLoc.h"
71 #include "llvm/Support/SourceMgr.h"
72 #include "llvm/Support/raw_ostream.h"
73 #include "llvm/Target/TargetIntrinsicInfo.h"
74 #include "llvm/Target/TargetMachine.h"
86 void PerTargetMIParsingState::setTarget(
87 const TargetSubtargetInfo
&NewSubtarget
) {
89 // If the subtarget changed, over conservatively assume everything is invalid.
90 if (&Subtarget
== &NewSubtarget
)
93 Names2InstrOpCodes
.clear();
95 Names2RegMasks
.clear();
96 Names2SubRegIndices
.clear();
97 Names2TargetIndices
.clear();
98 Names2DirectTargetFlags
.clear();
99 Names2BitmaskTargetFlags
.clear();
100 Names2MMOTargetFlags
.clear();
102 initNames2RegClasses();
103 initNames2RegBanks();
106 void PerTargetMIParsingState::initNames2Regs() {
107 if (!Names2Regs
.empty())
110 // The '%noreg' register is the register 0.
111 Names2Regs
.insert(std::make_pair("noreg", 0));
112 const auto *TRI
= Subtarget
.getRegisterInfo();
113 assert(TRI
&& "Expected target register info");
115 for (unsigned I
= 0, E
= TRI
->getNumRegs(); I
< E
; ++I
) {
117 Names2Regs
.insert(std::make_pair(StringRef(TRI
->getName(I
)).lower(), I
))
120 assert(WasInserted
&& "Expected registers to be unique case-insensitively");
124 bool PerTargetMIParsingState::getRegisterByName(StringRef RegName
,
127 auto RegInfo
= Names2Regs
.find(RegName
);
128 if (RegInfo
== Names2Regs
.end())
130 Reg
= RegInfo
->getValue();
134 void PerTargetMIParsingState::initNames2InstrOpCodes() {
135 if (!Names2InstrOpCodes
.empty())
137 const auto *TII
= Subtarget
.getInstrInfo();
138 assert(TII
&& "Expected target instruction info");
139 for (unsigned I
= 0, E
= TII
->getNumOpcodes(); I
< E
; ++I
)
140 Names2InstrOpCodes
.insert(std::make_pair(StringRef(TII
->getName(I
)), I
));
143 bool PerTargetMIParsingState::parseInstrName(StringRef InstrName
,
145 initNames2InstrOpCodes();
146 auto InstrInfo
= Names2InstrOpCodes
.find(InstrName
);
147 if (InstrInfo
== Names2InstrOpCodes
.end())
149 OpCode
= InstrInfo
->getValue();
153 void PerTargetMIParsingState::initNames2RegMasks() {
154 if (!Names2RegMasks
.empty())
156 const auto *TRI
= Subtarget
.getRegisterInfo();
157 assert(TRI
&& "Expected target register info");
158 ArrayRef
<const uint32_t *> RegMasks
= TRI
->getRegMasks();
159 ArrayRef
<const char *> RegMaskNames
= TRI
->getRegMaskNames();
160 assert(RegMasks
.size() == RegMaskNames
.size());
161 for (size_t I
= 0, E
= RegMasks
.size(); I
< E
; ++I
)
162 Names2RegMasks
.insert(
163 std::make_pair(StringRef(RegMaskNames
[I
]).lower(), RegMasks
[I
]));
166 const uint32_t *PerTargetMIParsingState::getRegMask(StringRef Identifier
) {
167 initNames2RegMasks();
168 auto RegMaskInfo
= Names2RegMasks
.find(Identifier
);
169 if (RegMaskInfo
== Names2RegMasks
.end())
171 return RegMaskInfo
->getValue();
174 void PerTargetMIParsingState::initNames2SubRegIndices() {
175 if (!Names2SubRegIndices
.empty())
177 const TargetRegisterInfo
*TRI
= Subtarget
.getRegisterInfo();
178 for (unsigned I
= 1, E
= TRI
->getNumSubRegIndices(); I
< E
; ++I
)
179 Names2SubRegIndices
.insert(
180 std::make_pair(TRI
->getSubRegIndexName(I
), I
));
183 unsigned PerTargetMIParsingState::getSubRegIndex(StringRef Name
) {
184 initNames2SubRegIndices();
185 auto SubRegInfo
= Names2SubRegIndices
.find(Name
);
186 if (SubRegInfo
== Names2SubRegIndices
.end())
188 return SubRegInfo
->getValue();
191 void PerTargetMIParsingState::initNames2TargetIndices() {
192 if (!Names2TargetIndices
.empty())
194 const auto *TII
= Subtarget
.getInstrInfo();
195 assert(TII
&& "Expected target instruction info");
196 auto Indices
= TII
->getSerializableTargetIndices();
197 for (const auto &I
: Indices
)
198 Names2TargetIndices
.insert(std::make_pair(StringRef(I
.second
), I
.first
));
201 bool PerTargetMIParsingState::getTargetIndex(StringRef Name
, int &Index
) {
202 initNames2TargetIndices();
203 auto IndexInfo
= Names2TargetIndices
.find(Name
);
204 if (IndexInfo
== Names2TargetIndices
.end())
206 Index
= IndexInfo
->second
;
210 void PerTargetMIParsingState::initNames2DirectTargetFlags() {
211 if (!Names2DirectTargetFlags
.empty())
214 const auto *TII
= Subtarget
.getInstrInfo();
215 assert(TII
&& "Expected target instruction info");
216 auto Flags
= TII
->getSerializableDirectMachineOperandTargetFlags();
217 for (const auto &I
: Flags
)
218 Names2DirectTargetFlags
.insert(
219 std::make_pair(StringRef(I
.second
), I
.first
));
222 bool PerTargetMIParsingState::getDirectTargetFlag(StringRef Name
,
224 initNames2DirectTargetFlags();
225 auto FlagInfo
= Names2DirectTargetFlags
.find(Name
);
226 if (FlagInfo
== Names2DirectTargetFlags
.end())
228 Flag
= FlagInfo
->second
;
232 void PerTargetMIParsingState::initNames2BitmaskTargetFlags() {
233 if (!Names2BitmaskTargetFlags
.empty())
236 const auto *TII
= Subtarget
.getInstrInfo();
237 assert(TII
&& "Expected target instruction info");
238 auto Flags
= TII
->getSerializableBitmaskMachineOperandTargetFlags();
239 for (const auto &I
: Flags
)
240 Names2BitmaskTargetFlags
.insert(
241 std::make_pair(StringRef(I
.second
), I
.first
));
244 bool PerTargetMIParsingState::getBitmaskTargetFlag(StringRef Name
,
246 initNames2BitmaskTargetFlags();
247 auto FlagInfo
= Names2BitmaskTargetFlags
.find(Name
);
248 if (FlagInfo
== Names2BitmaskTargetFlags
.end())
250 Flag
= FlagInfo
->second
;
254 void PerTargetMIParsingState::initNames2MMOTargetFlags() {
255 if (!Names2MMOTargetFlags
.empty())
258 const auto *TII
= Subtarget
.getInstrInfo();
259 assert(TII
&& "Expected target instruction info");
260 auto Flags
= TII
->getSerializableMachineMemOperandTargetFlags();
261 for (const auto &I
: Flags
)
262 Names2MMOTargetFlags
.insert(std::make_pair(StringRef(I
.second
), I
.first
));
265 bool PerTargetMIParsingState::getMMOTargetFlag(StringRef Name
,
266 MachineMemOperand::Flags
&Flag
) {
267 initNames2MMOTargetFlags();
268 auto FlagInfo
= Names2MMOTargetFlags
.find(Name
);
269 if (FlagInfo
== Names2MMOTargetFlags
.end())
271 Flag
= FlagInfo
->second
;
275 void PerTargetMIParsingState::initNames2RegClasses() {
276 if (!Names2RegClasses
.empty())
279 const TargetRegisterInfo
*TRI
= Subtarget
.getRegisterInfo();
280 for (unsigned I
= 0, E
= TRI
->getNumRegClasses(); I
< E
; ++I
) {
281 const auto *RC
= TRI
->getRegClass(I
);
282 Names2RegClasses
.insert(
283 std::make_pair(StringRef(TRI
->getRegClassName(RC
)).lower(), RC
));
287 void PerTargetMIParsingState::initNames2RegBanks() {
288 if (!Names2RegBanks
.empty())
291 const RegisterBankInfo
*RBI
= Subtarget
.getRegBankInfo();
292 // If the target does not support GlobalISel, we may not have a
293 // register bank info.
297 for (unsigned I
= 0, E
= RBI
->getNumRegBanks(); I
< E
; ++I
) {
298 const auto &RegBank
= RBI
->getRegBank(I
);
299 Names2RegBanks
.insert(
300 std::make_pair(StringRef(RegBank
.getName()).lower(), &RegBank
));
304 const TargetRegisterClass
*
305 PerTargetMIParsingState::getRegClass(StringRef Name
) {
306 auto RegClassInfo
= Names2RegClasses
.find(Name
);
307 if (RegClassInfo
== Names2RegClasses
.end())
309 return RegClassInfo
->getValue();
312 const RegisterBank
*PerTargetMIParsingState::getRegBank(StringRef Name
) {
313 auto RegBankInfo
= Names2RegBanks
.find(Name
);
314 if (RegBankInfo
== Names2RegBanks
.end())
316 return RegBankInfo
->getValue();
319 PerFunctionMIParsingState::PerFunctionMIParsingState(MachineFunction
&MF
,
320 SourceMgr
&SM
, const SlotMapping
&IRSlots
, PerTargetMIParsingState
&T
)
321 : MF(MF
), SM(&SM
), IRSlots(IRSlots
), Target(T
) {
324 VRegInfo
&PerFunctionMIParsingState::getVRegInfo(Register Num
) {
325 auto I
= VRegInfos
.insert(std::make_pair(Num
, nullptr));
327 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
328 VRegInfo
*Info
= new (Allocator
) VRegInfo
;
329 Info
->VReg
= MRI
.createIncompleteVirtualRegister();
330 I
.first
->second
= Info
;
332 return *I
.first
->second
;
335 VRegInfo
&PerFunctionMIParsingState::getVRegInfoNamed(StringRef RegName
) {
336 assert(RegName
!= "" && "Expected named reg.");
338 auto I
= VRegInfosNamed
.insert(std::make_pair(RegName
.str(), nullptr));
340 VRegInfo
*Info
= new (Allocator
) VRegInfo
;
341 Info
->VReg
= MF
.getRegInfo().createIncompleteVirtualRegister(RegName
);
342 I
.first
->second
= Info
;
344 return *I
.first
->second
;
347 static void mapValueToSlot(const Value
*V
, ModuleSlotTracker
&MST
,
348 DenseMap
<unsigned, const Value
*> &Slots2Values
) {
349 int Slot
= MST
.getLocalSlot(V
);
352 Slots2Values
.insert(std::make_pair(unsigned(Slot
), V
));
355 /// Creates the mapping from slot numbers to function's unnamed IR values.
356 static void initSlots2Values(const Function
&F
,
357 DenseMap
<unsigned, const Value
*> &Slots2Values
) {
358 ModuleSlotTracker
MST(F
.getParent(), /*ShouldInitializeAllMetadata=*/false);
359 MST
.incorporateFunction(F
);
360 for (const auto &Arg
: F
.args())
361 mapValueToSlot(&Arg
, MST
, Slots2Values
);
362 for (const auto &BB
: F
) {
363 mapValueToSlot(&BB
, MST
, Slots2Values
);
364 for (const auto &I
: BB
)
365 mapValueToSlot(&I
, MST
, Slots2Values
);
369 const Value
* PerFunctionMIParsingState::getIRValue(unsigned Slot
) {
370 if (Slots2Values
.empty())
371 initSlots2Values(MF
.getFunction(), Slots2Values
);
372 return Slots2Values
.lookup(Slot
);
377 /// A wrapper struct around the 'MachineOperand' struct that includes a source
378 /// range and other attributes.
379 struct ParsedMachineOperand
{
380 MachineOperand Operand
;
381 StringRef::iterator Begin
;
382 StringRef::iterator End
;
383 Optional
<unsigned> TiedDefIdx
;
385 ParsedMachineOperand(const MachineOperand
&Operand
, StringRef::iterator Begin
,
386 StringRef::iterator End
, Optional
<unsigned> &TiedDefIdx
)
387 : Operand(Operand
), Begin(Begin
), End(End
), TiedDefIdx(TiedDefIdx
) {
389 assert(Operand
.isReg() && Operand
.isUse() &&
390 "Only used register operands can be tied");
397 StringRef Source
, CurrentSource
;
400 PerFunctionMIParsingState
&PFS
;
401 /// Maps from slot numbers to function's unnamed basic blocks.
402 DenseMap
<unsigned, const BasicBlock
*> Slots2BasicBlocks
;
405 MIParser(PerFunctionMIParsingState
&PFS
, SMDiagnostic
&Error
,
407 MIParser(PerFunctionMIParsingState
&PFS
, SMDiagnostic
&Error
,
408 StringRef Source
, SMRange SourceRange
);
410 /// \p SkipChar gives the number of characters to skip before looking
411 /// for the next token.
412 void lex(unsigned SkipChar
= 0);
414 /// Report an error at the current location with the given message.
416 /// This function always return true.
417 bool error(const Twine
&Msg
);
419 /// Report an error at the given location with the given message.
421 /// This function always return true.
422 bool error(StringRef::iterator Loc
, const Twine
&Msg
);
425 parseBasicBlockDefinitions(DenseMap
<unsigned, MachineBasicBlock
*> &MBBSlots
);
426 bool parseBasicBlocks();
427 bool parse(MachineInstr
*&MI
);
428 bool parseStandaloneMBB(MachineBasicBlock
*&MBB
);
429 bool parseStandaloneNamedRegister(Register
&Reg
);
430 bool parseStandaloneVirtualRegister(VRegInfo
*&Info
);
431 bool parseStandaloneRegister(Register
&Reg
);
432 bool parseStandaloneStackObject(int &FI
);
433 bool parseStandaloneMDNode(MDNode
*&Node
);
434 bool parseMachineMetadata();
435 bool parseMDTuple(MDNode
*&MD
, bool IsDistinct
);
436 bool parseMDNodeVector(SmallVectorImpl
<Metadata
*> &Elts
);
437 bool parseMetadata(Metadata
*&MD
);
440 parseBasicBlockDefinition(DenseMap
<unsigned, MachineBasicBlock
*> &MBBSlots
);
441 bool parseBasicBlock(MachineBasicBlock
&MBB
,
442 MachineBasicBlock
*&AddFalthroughFrom
);
443 bool parseBasicBlockLiveins(MachineBasicBlock
&MBB
);
444 bool parseBasicBlockSuccessors(MachineBasicBlock
&MBB
);
446 bool parseNamedRegister(Register
&Reg
);
447 bool parseVirtualRegister(VRegInfo
*&Info
);
448 bool parseNamedVirtualRegister(VRegInfo
*&Info
);
449 bool parseRegister(Register
&Reg
, VRegInfo
*&VRegInfo
);
450 bool parseRegisterFlag(unsigned &Flags
);
451 bool parseRegisterClassOrBank(VRegInfo
&RegInfo
);
452 bool parseSubRegisterIndex(unsigned &SubReg
);
453 bool parseRegisterTiedDefIndex(unsigned &TiedDefIdx
);
454 bool parseRegisterOperand(MachineOperand
&Dest
,
455 Optional
<unsigned> &TiedDefIdx
, bool IsDef
= false);
456 bool parseImmediateOperand(MachineOperand
&Dest
);
457 bool parseIRConstant(StringRef::iterator Loc
, StringRef StringValue
,
459 bool parseIRConstant(StringRef::iterator Loc
, const Constant
*&C
);
460 bool parseLowLevelType(StringRef::iterator Loc
, LLT
&Ty
);
461 bool parseTypedImmediateOperand(MachineOperand
&Dest
);
462 bool parseFPImmediateOperand(MachineOperand
&Dest
);
463 bool parseMBBReference(MachineBasicBlock
*&MBB
);
464 bool parseMBBOperand(MachineOperand
&Dest
);
465 bool parseStackFrameIndex(int &FI
);
466 bool parseStackObjectOperand(MachineOperand
&Dest
);
467 bool parseFixedStackFrameIndex(int &FI
);
468 bool parseFixedStackObjectOperand(MachineOperand
&Dest
);
469 bool parseGlobalValue(GlobalValue
*&GV
);
470 bool parseGlobalAddressOperand(MachineOperand
&Dest
);
471 bool parseConstantPoolIndexOperand(MachineOperand
&Dest
);
472 bool parseSubRegisterIndexOperand(MachineOperand
&Dest
);
473 bool parseJumpTableIndexOperand(MachineOperand
&Dest
);
474 bool parseExternalSymbolOperand(MachineOperand
&Dest
);
475 bool parseMCSymbolOperand(MachineOperand
&Dest
);
476 bool parseMDNode(MDNode
*&Node
);
477 bool parseDIExpression(MDNode
*&Expr
);
478 bool parseDILocation(MDNode
*&Expr
);
479 bool parseMetadataOperand(MachineOperand
&Dest
);
480 bool parseCFIOffset(int &Offset
);
481 bool parseCFIRegister(Register
&Reg
);
482 bool parseCFIAddressSpace(unsigned &AddressSpace
);
483 bool parseCFIEscapeValues(std::string
& Values
);
484 bool parseCFIOperand(MachineOperand
&Dest
);
485 bool parseIRBlock(BasicBlock
*&BB
, const Function
&F
);
486 bool parseBlockAddressOperand(MachineOperand
&Dest
);
487 bool parseIntrinsicOperand(MachineOperand
&Dest
);
488 bool parsePredicateOperand(MachineOperand
&Dest
);
489 bool parseShuffleMaskOperand(MachineOperand
&Dest
);
490 bool parseTargetIndexOperand(MachineOperand
&Dest
);
491 bool parseCustomRegisterMaskOperand(MachineOperand
&Dest
);
492 bool parseLiveoutRegisterMaskOperand(MachineOperand
&Dest
);
493 bool parseMachineOperand(const unsigned OpCode
, const unsigned OpIdx
,
494 MachineOperand
&Dest
,
495 Optional
<unsigned> &TiedDefIdx
);
496 bool parseMachineOperandAndTargetFlags(const unsigned OpCode
,
497 const unsigned OpIdx
,
498 MachineOperand
&Dest
,
499 Optional
<unsigned> &TiedDefIdx
);
500 bool parseOffset(int64_t &Offset
);
501 bool parseAlignment(unsigned &Alignment
);
502 bool parseAddrspace(unsigned &Addrspace
);
503 bool parseSectionID(Optional
<MBBSectionID
> &SID
);
504 bool parseOperandsOffset(MachineOperand
&Op
);
505 bool parseIRValue(const Value
*&V
);
506 bool parseMemoryOperandFlag(MachineMemOperand::Flags
&Flags
);
507 bool parseMemoryPseudoSourceValue(const PseudoSourceValue
*&PSV
);
508 bool parseMachinePointerInfo(MachinePointerInfo
&Dest
);
509 bool parseOptionalScope(LLVMContext
&Context
, SyncScope::ID
&SSID
);
510 bool parseOptionalAtomicOrdering(AtomicOrdering
&Order
);
511 bool parseMachineMemoryOperand(MachineMemOperand
*&Dest
);
512 bool parsePreOrPostInstrSymbol(MCSymbol
*&Symbol
);
513 bool parseHeapAllocMarker(MDNode
*&Node
);
515 bool parseTargetImmMnemonic(const unsigned OpCode
, const unsigned OpIdx
,
516 MachineOperand
&Dest
, const MIRFormatter
&MF
);
519 /// Convert the integer literal in the current token into an unsigned integer.
521 /// Return true if an error occurred.
522 bool getUnsigned(unsigned &Result
);
524 /// Convert the integer literal in the current token into an uint64.
526 /// Return true if an error occurred.
527 bool getUint64(uint64_t &Result
);
529 /// Convert the hexadecimal literal in the current token into an unsigned
530 /// APInt with a minimum bitwidth required to represent the value.
532 /// Return true if the literal does not represent an integer value.
533 bool getHexUint(APInt
&Result
);
535 /// If the current token is of the given kind, consume it and return false.
536 /// Otherwise report an error and return true.
537 bool expectAndConsume(MIToken::TokenKind TokenKind
);
539 /// If the current token is of the given kind, consume it and return true.
540 /// Otherwise return false.
541 bool consumeIfPresent(MIToken::TokenKind TokenKind
);
543 bool parseInstruction(unsigned &OpCode
, unsigned &Flags
);
545 bool assignRegisterTies(MachineInstr
&MI
,
546 ArrayRef
<ParsedMachineOperand
> Operands
);
548 bool verifyImplicitOperands(ArrayRef
<ParsedMachineOperand
> Operands
,
549 const MCInstrDesc
&MCID
);
551 const BasicBlock
*getIRBlock(unsigned Slot
);
552 const BasicBlock
*getIRBlock(unsigned Slot
, const Function
&F
);
554 /// Get or create an MCSymbol for a given name.
555 MCSymbol
*getOrCreateMCSymbol(StringRef Name
);
557 /// parseStringConstant
558 /// ::= StringConstant
559 bool parseStringConstant(std::string
&Result
);
561 /// Map the location in the MI string to the corresponding location specified
562 /// in `SourceRange`.
563 SMLoc
mapSMLoc(StringRef::iterator Loc
);
566 } // end anonymous namespace
568 MIParser::MIParser(PerFunctionMIParsingState
&PFS
, SMDiagnostic
&Error
,
570 : MF(PFS
.MF
), Error(Error
), Source(Source
), CurrentSource(Source
), PFS(PFS
)
573 MIParser::MIParser(PerFunctionMIParsingState
&PFS
, SMDiagnostic
&Error
,
574 StringRef Source
, SMRange SourceRange
)
575 : MF(PFS
.MF
), Error(Error
), Source(Source
), CurrentSource(Source
),
576 SourceRange(SourceRange
), PFS(PFS
) {}
578 void MIParser::lex(unsigned SkipChar
) {
579 CurrentSource
= lexMIToken(
580 CurrentSource
.slice(SkipChar
, StringRef::npos
), Token
,
581 [this](StringRef::iterator Loc
, const Twine
&Msg
) { error(Loc
, Msg
); });
584 bool MIParser::error(const Twine
&Msg
) { return error(Token
.location(), Msg
); }
586 bool MIParser::error(StringRef::iterator Loc
, const Twine
&Msg
) {
587 const SourceMgr
&SM
= *PFS
.SM
;
588 assert(Loc
>= Source
.data() && Loc
<= (Source
.data() + Source
.size()));
589 const MemoryBuffer
&Buffer
= *SM
.getMemoryBuffer(SM
.getMainFileID());
590 if (Loc
>= Buffer
.getBufferStart() && Loc
<= Buffer
.getBufferEnd()) {
591 // Create an ordinary diagnostic when the source manager's buffer is the
593 Error
= SM
.GetMessage(SMLoc::getFromPointer(Loc
), SourceMgr::DK_Error
, Msg
);
596 // Create a diagnostic for a YAML string literal.
597 Error
= SMDiagnostic(SM
, SMLoc(), Buffer
.getBufferIdentifier(), 1,
598 Loc
- Source
.data(), SourceMgr::DK_Error
, Msg
.str(),
603 SMLoc
MIParser::mapSMLoc(StringRef::iterator Loc
) {
604 assert(SourceRange
.isValid() && "Invalid source range");
605 assert(Loc
>= Source
.data() && Loc
<= (Source
.data() + Source
.size()));
606 return SMLoc::getFromPointer(SourceRange
.Start
.getPointer() +
607 (Loc
- Source
.data()));
610 typedef function_ref
<bool(StringRef::iterator Loc
, const Twine
&)>
613 static const char *toString(MIToken::TokenKind TokenKind
) {
621 case MIToken::lparen
:
623 case MIToken::rparen
:
626 return "<unknown token>";
630 bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind
) {
631 if (Token
.isNot(TokenKind
))
632 return error(Twine("expected ") + toString(TokenKind
));
637 bool MIParser::consumeIfPresent(MIToken::TokenKind TokenKind
) {
638 if (Token
.isNot(TokenKind
))
644 // Parse Machine Basic Block Section ID.
645 bool MIParser::parseSectionID(Optional
<MBBSectionID
> &SID
) {
646 assert(Token
.is(MIToken::kw_bbsections
));
648 if (Token
.is(MIToken::IntegerLiteral
)) {
650 if (getUnsigned(Value
))
651 return error("Unknown Section ID");
652 SID
= MBBSectionID
{Value
};
654 const StringRef
&S
= Token
.stringValue();
655 if (S
== "Exception")
656 SID
= MBBSectionID::ExceptionSectionID
;
657 else if (S
== "Cold")
658 SID
= MBBSectionID::ColdSectionID
;
660 return error("Unknown Section ID");
666 bool MIParser::parseBasicBlockDefinition(
667 DenseMap
<unsigned, MachineBasicBlock
*> &MBBSlots
) {
668 assert(Token
.is(MIToken::MachineBasicBlockLabel
));
672 auto Loc
= Token
.location();
673 auto Name
= Token
.stringValue();
675 bool HasAddressTaken
= false;
676 bool IsLandingPad
= false;
677 bool IsEHFuncletEntry
= false;
678 Optional
<MBBSectionID
> SectionID
;
679 unsigned Alignment
= 0;
680 BasicBlock
*BB
= nullptr;
681 if (consumeIfPresent(MIToken::lparen
)) {
683 // TODO: Report an error when multiple same attributes are specified.
684 switch (Token
.kind()) {
685 case MIToken::kw_address_taken
:
686 HasAddressTaken
= true;
689 case MIToken::kw_landing_pad
:
693 case MIToken::kw_ehfunclet_entry
:
694 IsEHFuncletEntry
= true;
697 case MIToken::kw_align
:
698 if (parseAlignment(Alignment
))
701 case MIToken::IRBlock
:
702 // TODO: Report an error when both name and ir block are specified.
703 if (parseIRBlock(BB
, MF
.getFunction()))
707 case MIToken::kw_bbsections
:
708 if (parseSectionID(SectionID
))
714 } while (consumeIfPresent(MIToken::comma
));
715 if (expectAndConsume(MIToken::rparen
))
718 if (expectAndConsume(MIToken::colon
))
722 BB
= dyn_cast_or_null
<BasicBlock
>(
723 MF
.getFunction().getValueSymbolTable()->lookup(Name
));
725 return error(Loc
, Twine("basic block '") + Name
+
726 "' is not defined in the function '" +
729 auto *MBB
= MF
.CreateMachineBasicBlock(BB
);
730 MF
.insert(MF
.end(), MBB
);
731 bool WasInserted
= MBBSlots
.insert(std::make_pair(ID
, MBB
)).second
;
733 return error(Loc
, Twine("redefinition of machine basic block with id #") +
736 MBB
->setAlignment(Align(Alignment
));
738 MBB
->setHasAddressTaken();
739 MBB
->setIsEHPad(IsLandingPad
);
740 MBB
->setIsEHFuncletEntry(IsEHFuncletEntry
);
741 if (SectionID
.hasValue()) {
742 MBB
->setSectionID(SectionID
.getValue());
743 MF
.setBBSectionsType(BasicBlockSection::List
);
748 bool MIParser::parseBasicBlockDefinitions(
749 DenseMap
<unsigned, MachineBasicBlock
*> &MBBSlots
) {
751 // Skip until the first machine basic block.
752 while (Token
.is(MIToken::Newline
))
754 if (Token
.isErrorOrEOF())
755 return Token
.isError();
756 if (Token
.isNot(MIToken::MachineBasicBlockLabel
))
757 return error("expected a basic block definition before instructions");
758 unsigned BraceDepth
= 0;
760 if (parseBasicBlockDefinition(MBBSlots
))
762 bool IsAfterNewline
= false;
763 // Skip until the next machine basic block.
765 if ((Token
.is(MIToken::MachineBasicBlockLabel
) && IsAfterNewline
) ||
766 Token
.isErrorOrEOF())
768 else if (Token
.is(MIToken::MachineBasicBlockLabel
))
769 return error("basic block definition should be located at the start of "
771 else if (consumeIfPresent(MIToken::Newline
)) {
772 IsAfterNewline
= true;
775 IsAfterNewline
= false;
776 if (Token
.is(MIToken::lbrace
))
778 if (Token
.is(MIToken::rbrace
)) {
780 return error("extraneous closing brace ('}')");
785 // Verify that we closed all of the '{' at the end of a file or a block.
786 if (!Token
.isError() && BraceDepth
)
787 return error("expected '}'"); // FIXME: Report a note that shows '{'.
788 } while (!Token
.isErrorOrEOF());
789 return Token
.isError();
792 bool MIParser::parseBasicBlockLiveins(MachineBasicBlock
&MBB
) {
793 assert(Token
.is(MIToken::kw_liveins
));
795 if (expectAndConsume(MIToken::colon
))
797 if (Token
.isNewlineOrEOF()) // Allow an empty list of liveins.
800 if (Token
.isNot(MIToken::NamedRegister
))
801 return error("expected a named register");
803 if (parseNamedRegister(Reg
))
806 LaneBitmask Mask
= LaneBitmask::getAll();
807 if (consumeIfPresent(MIToken::colon
)) {
809 if (Token
.isNot(MIToken::IntegerLiteral
) &&
810 Token
.isNot(MIToken::HexLiteral
))
811 return error("expected a lane mask");
812 static_assert(sizeof(LaneBitmask::Type
) == sizeof(uint64_t),
813 "Use correct get-function for lane mask");
816 return error("invalid lane mask value");
817 Mask
= LaneBitmask(V
);
820 MBB
.addLiveIn(Reg
, Mask
);
821 } while (consumeIfPresent(MIToken::comma
));
825 bool MIParser::parseBasicBlockSuccessors(MachineBasicBlock
&MBB
) {
826 assert(Token
.is(MIToken::kw_successors
));
828 if (expectAndConsume(MIToken::colon
))
830 if (Token
.isNewlineOrEOF()) // Allow an empty list of successors.
833 if (Token
.isNot(MIToken::MachineBasicBlock
))
834 return error("expected a machine basic block reference");
835 MachineBasicBlock
*SuccMBB
= nullptr;
836 if (parseMBBReference(SuccMBB
))
840 if (consumeIfPresent(MIToken::lparen
)) {
841 if (Token
.isNot(MIToken::IntegerLiteral
) &&
842 Token
.isNot(MIToken::HexLiteral
))
843 return error("expected an integer literal after '('");
844 if (getUnsigned(Weight
))
847 if (expectAndConsume(MIToken::rparen
))
850 MBB
.addSuccessor(SuccMBB
, BranchProbability::getRaw(Weight
));
851 } while (consumeIfPresent(MIToken::comma
));
852 MBB
.normalizeSuccProbs();
856 bool MIParser::parseBasicBlock(MachineBasicBlock
&MBB
,
857 MachineBasicBlock
*&AddFalthroughFrom
) {
858 // Skip the definition.
859 assert(Token
.is(MIToken::MachineBasicBlockLabel
));
861 if (consumeIfPresent(MIToken::lparen
)) {
862 while (Token
.isNot(MIToken::rparen
) && !Token
.isErrorOrEOF())
864 consumeIfPresent(MIToken::rparen
);
866 consumeIfPresent(MIToken::colon
);
868 // Parse the liveins and successors.
869 // N.B: Multiple lists of successors and liveins are allowed and they're
876 // liveins: %edi, %esi
877 bool ExplicitSuccessors
= false;
879 if (Token
.is(MIToken::kw_successors
)) {
880 if (parseBasicBlockSuccessors(MBB
))
882 ExplicitSuccessors
= true;
883 } else if (Token
.is(MIToken::kw_liveins
)) {
884 if (parseBasicBlockLiveins(MBB
))
886 } else if (consumeIfPresent(MIToken::Newline
)) {
890 if (!Token
.isNewlineOrEOF())
891 return error("expected line break at the end of a list");
895 // Parse the instructions.
896 bool IsInBundle
= false;
897 MachineInstr
*PrevMI
= nullptr;
898 while (!Token
.is(MIToken::MachineBasicBlockLabel
) &&
899 !Token
.is(MIToken::Eof
)) {
900 if (consumeIfPresent(MIToken::Newline
))
902 if (consumeIfPresent(MIToken::rbrace
)) {
903 // The first parsing pass should verify that all closing '}' have an
909 MachineInstr
*MI
= nullptr;
912 MBB
.insert(MBB
.end(), MI
);
914 PrevMI
->setFlag(MachineInstr::BundledSucc
);
915 MI
->setFlag(MachineInstr::BundledPred
);
918 if (Token
.is(MIToken::lbrace
)) {
920 return error("nested instruction bundles are not allowed");
922 // This instruction is the start of the bundle.
923 MI
->setFlag(MachineInstr::BundledSucc
);
925 if (!Token
.is(MIToken::Newline
))
926 // The next instruction can be on the same line.
929 assert(Token
.isNewlineOrEOF() && "MI is not fully parsed");
933 // Construct successor list by searching for basic block machine operands.
934 if (!ExplicitSuccessors
) {
935 SmallVector
<MachineBasicBlock
*,4> Successors
;
937 guessSuccessors(MBB
, Successors
, IsFallthrough
);
938 for (MachineBasicBlock
*Succ
: Successors
)
939 MBB
.addSuccessor(Succ
);
942 AddFalthroughFrom
= &MBB
;
944 MBB
.normalizeSuccProbs();
951 bool MIParser::parseBasicBlocks() {
953 // Skip until the first machine basic block.
954 while (Token
.is(MIToken::Newline
))
956 if (Token
.isErrorOrEOF())
957 return Token
.isError();
958 // The first parsing pass should have verified that this token is a MBB label
959 // in the 'parseBasicBlockDefinitions' method.
960 assert(Token
.is(MIToken::MachineBasicBlockLabel
));
961 MachineBasicBlock
*AddFalthroughFrom
= nullptr;
963 MachineBasicBlock
*MBB
= nullptr;
964 if (parseMBBReference(MBB
))
966 if (AddFalthroughFrom
) {
967 if (!AddFalthroughFrom
->isSuccessor(MBB
))
968 AddFalthroughFrom
->addSuccessor(MBB
);
969 AddFalthroughFrom
->normalizeSuccProbs();
970 AddFalthroughFrom
= nullptr;
972 if (parseBasicBlock(*MBB
, AddFalthroughFrom
))
974 // The method 'parseBasicBlock' should parse the whole block until the next
975 // block or the end of file.
976 assert(Token
.is(MIToken::MachineBasicBlockLabel
) || Token
.is(MIToken::Eof
));
977 } while (Token
.isNot(MIToken::Eof
));
981 bool MIParser::parse(MachineInstr
*&MI
) {
982 // Parse any register operands before '='
983 MachineOperand MO
= MachineOperand::CreateImm(0);
984 SmallVector
<ParsedMachineOperand
, 8> Operands
;
985 while (Token
.isRegister() || Token
.isRegisterFlag()) {
986 auto Loc
= Token
.location();
987 Optional
<unsigned> TiedDefIdx
;
988 if (parseRegisterOperand(MO
, TiedDefIdx
, /*IsDef=*/true))
991 ParsedMachineOperand(MO
, Loc
, Token
.location(), TiedDefIdx
));
992 if (Token
.isNot(MIToken::comma
))
996 if (!Operands
.empty() && expectAndConsume(MIToken::equal
))
999 unsigned OpCode
, Flags
= 0;
1000 if (Token
.isError() || parseInstruction(OpCode
, Flags
))
1003 // Parse the remaining machine operands.
1004 while (!Token
.isNewlineOrEOF() && Token
.isNot(MIToken::kw_pre_instr_symbol
) &&
1005 Token
.isNot(MIToken::kw_post_instr_symbol
) &&
1006 Token
.isNot(MIToken::kw_heap_alloc_marker
) &&
1007 Token
.isNot(MIToken::kw_debug_location
) &&
1008 Token
.isNot(MIToken::kw_debug_instr_number
) &&
1009 Token
.isNot(MIToken::coloncolon
) && Token
.isNot(MIToken::lbrace
)) {
1010 auto Loc
= Token
.location();
1011 Optional
<unsigned> TiedDefIdx
;
1012 if (parseMachineOperandAndTargetFlags(OpCode
, Operands
.size(), MO
, TiedDefIdx
))
1014 if ((OpCode
== TargetOpcode::DBG_VALUE
||
1015 OpCode
== TargetOpcode::DBG_VALUE_LIST
) &&
1019 ParsedMachineOperand(MO
, Loc
, Token
.location(), TiedDefIdx
));
1020 if (Token
.isNewlineOrEOF() || Token
.is(MIToken::coloncolon
) ||
1021 Token
.is(MIToken::lbrace
))
1023 if (Token
.isNot(MIToken::comma
))
1024 return error("expected ',' before the next machine operand");
1028 MCSymbol
*PreInstrSymbol
= nullptr;
1029 if (Token
.is(MIToken::kw_pre_instr_symbol
))
1030 if (parsePreOrPostInstrSymbol(PreInstrSymbol
))
1032 MCSymbol
*PostInstrSymbol
= nullptr;
1033 if (Token
.is(MIToken::kw_post_instr_symbol
))
1034 if (parsePreOrPostInstrSymbol(PostInstrSymbol
))
1036 MDNode
*HeapAllocMarker
= nullptr;
1037 if (Token
.is(MIToken::kw_heap_alloc_marker
))
1038 if (parseHeapAllocMarker(HeapAllocMarker
))
1041 unsigned InstrNum
= 0;
1042 if (Token
.is(MIToken::kw_debug_instr_number
)) {
1044 if (Token
.isNot(MIToken::IntegerLiteral
))
1045 return error("expected an integer literal after 'debug-instr-number'");
1046 if (getUnsigned(InstrNum
))
1049 // Lex past trailing comma if present.
1050 if (Token
.is(MIToken::comma
))
1054 DebugLoc DebugLocation
;
1055 if (Token
.is(MIToken::kw_debug_location
)) {
1057 MDNode
*Node
= nullptr;
1058 if (Token
.is(MIToken::exclaim
)) {
1059 if (parseMDNode(Node
))
1061 } else if (Token
.is(MIToken::md_dilocation
)) {
1062 if (parseDILocation(Node
))
1065 return error("expected a metadata node after 'debug-location'");
1066 if (!isa
<DILocation
>(Node
))
1067 return error("referenced metadata is not a DILocation");
1068 DebugLocation
= DebugLoc(Node
);
1071 // Parse the machine memory operands.
1072 SmallVector
<MachineMemOperand
*, 2> MemOperands
;
1073 if (Token
.is(MIToken::coloncolon
)) {
1075 while (!Token
.isNewlineOrEOF()) {
1076 MachineMemOperand
*MemOp
= nullptr;
1077 if (parseMachineMemoryOperand(MemOp
))
1079 MemOperands
.push_back(MemOp
);
1080 if (Token
.isNewlineOrEOF())
1082 if (Token
.isNot(MIToken::comma
))
1083 return error("expected ',' before the next machine memory operand");
1088 const auto &MCID
= MF
.getSubtarget().getInstrInfo()->get(OpCode
);
1089 if (!MCID
.isVariadic()) {
1090 // FIXME: Move the implicit operand verification to the machine verifier.
1091 if (verifyImplicitOperands(Operands
, MCID
))
1095 // TODO: Check for extraneous machine operands.
1096 MI
= MF
.CreateMachineInstr(MCID
, DebugLocation
, /*NoImplicit=*/true);
1097 MI
->setFlags(Flags
);
1098 for (const auto &Operand
: Operands
)
1099 MI
->addOperand(MF
, Operand
.Operand
);
1100 if (assignRegisterTies(*MI
, Operands
))
1103 MI
->setPreInstrSymbol(MF
, PreInstrSymbol
);
1104 if (PostInstrSymbol
)
1105 MI
->setPostInstrSymbol(MF
, PostInstrSymbol
);
1106 if (HeapAllocMarker
)
1107 MI
->setHeapAllocMarker(MF
, HeapAllocMarker
);
1108 if (!MemOperands
.empty())
1109 MI
->setMemRefs(MF
, MemOperands
);
1111 MI
->setDebugInstrNum(InstrNum
);
1115 bool MIParser::parseStandaloneMBB(MachineBasicBlock
*&MBB
) {
1117 if (Token
.isNot(MIToken::MachineBasicBlock
))
1118 return error("expected a machine basic block reference");
1119 if (parseMBBReference(MBB
))
1122 if (Token
.isNot(MIToken::Eof
))
1124 "expected end of string after the machine basic block reference");
1128 bool MIParser::parseStandaloneNamedRegister(Register
&Reg
) {
1130 if (Token
.isNot(MIToken::NamedRegister
))
1131 return error("expected a named register");
1132 if (parseNamedRegister(Reg
))
1135 if (Token
.isNot(MIToken::Eof
))
1136 return error("expected end of string after the register reference");
1140 bool MIParser::parseStandaloneVirtualRegister(VRegInfo
*&Info
) {
1142 if (Token
.isNot(MIToken::VirtualRegister
))
1143 return error("expected a virtual register");
1144 if (parseVirtualRegister(Info
))
1147 if (Token
.isNot(MIToken::Eof
))
1148 return error("expected end of string after the register reference");
1152 bool MIParser::parseStandaloneRegister(Register
&Reg
) {
1154 if (Token
.isNot(MIToken::NamedRegister
) &&
1155 Token
.isNot(MIToken::VirtualRegister
))
1156 return error("expected either a named or virtual register");
1159 if (parseRegister(Reg
, Info
))
1163 if (Token
.isNot(MIToken::Eof
))
1164 return error("expected end of string after the register reference");
1168 bool MIParser::parseStandaloneStackObject(int &FI
) {
1170 if (Token
.isNot(MIToken::StackObject
))
1171 return error("expected a stack object");
1172 if (parseStackFrameIndex(FI
))
1174 if (Token
.isNot(MIToken::Eof
))
1175 return error("expected end of string after the stack object reference");
1179 bool MIParser::parseStandaloneMDNode(MDNode
*&Node
) {
1181 if (Token
.is(MIToken::exclaim
)) {
1182 if (parseMDNode(Node
))
1184 } else if (Token
.is(MIToken::md_diexpr
)) {
1185 if (parseDIExpression(Node
))
1187 } else if (Token
.is(MIToken::md_dilocation
)) {
1188 if (parseDILocation(Node
))
1191 return error("expected a metadata node");
1192 if (Token
.isNot(MIToken::Eof
))
1193 return error("expected end of string after the metadata node");
1197 bool MIParser::parseMachineMetadata() {
1199 if (Token
.isNot(MIToken::exclaim
))
1200 return error("expected a metadata node");
1203 if (Token
.isNot(MIToken::IntegerLiteral
) || Token
.integerValue().isSigned())
1204 return error("expected metadata id after '!'");
1206 if (getUnsigned(ID
))
1209 if (expectAndConsume(MIToken::equal
))
1211 bool IsDistinct
= Token
.is(MIToken::kw_distinct
);
1214 if (Token
.isNot(MIToken::exclaim
))
1215 return error("expected a metadata node");
1219 if (parseMDTuple(MD
, IsDistinct
))
1222 auto FI
= PFS
.MachineForwardRefMDNodes
.find(ID
);
1223 if (FI
!= PFS
.MachineForwardRefMDNodes
.end()) {
1224 FI
->second
.first
->replaceAllUsesWith(MD
);
1225 PFS
.MachineForwardRefMDNodes
.erase(FI
);
1227 assert(PFS
.MachineMetadataNodes
[ID
] == MD
&& "Tracking VH didn't work");
1229 if (PFS
.MachineMetadataNodes
.count(ID
))
1230 return error("Metadata id is already used");
1231 PFS
.MachineMetadataNodes
[ID
].reset(MD
);
1237 bool MIParser::parseMDTuple(MDNode
*&MD
, bool IsDistinct
) {
1238 SmallVector
<Metadata
*, 16> Elts
;
1239 if (parseMDNodeVector(Elts
))
1241 MD
= (IsDistinct
? MDTuple::getDistinct
1242 : MDTuple::get
)(MF
.getFunction().getContext(), Elts
);
1246 bool MIParser::parseMDNodeVector(SmallVectorImpl
<Metadata
*> &Elts
) {
1247 if (Token
.isNot(MIToken::lbrace
))
1248 return error("expected '{' here");
1251 if (Token
.is(MIToken::rbrace
)) {
1258 if (parseMetadata(MD
))
1263 if (Token
.isNot(MIToken::comma
))
1268 if (Token
.isNot(MIToken::rbrace
))
1269 return error("expected end of metadata node");
1277 bool MIParser::parseMetadata(Metadata
*&MD
) {
1278 if (Token
.isNot(MIToken::exclaim
))
1279 return error("expected '!' here");
1282 if (Token
.is(MIToken::StringConstant
)) {
1284 if (parseStringConstant(Str
))
1286 MD
= MDString::get(MF
.getFunction().getContext(), Str
);
1290 if (Token
.isNot(MIToken::IntegerLiteral
) || Token
.integerValue().isSigned())
1291 return error("expected metadata id after '!'");
1293 SMLoc Loc
= mapSMLoc(Token
.location());
1296 if (getUnsigned(ID
))
1300 auto NodeInfo
= PFS
.IRSlots
.MetadataNodes
.find(ID
);
1301 if (NodeInfo
!= PFS
.IRSlots
.MetadataNodes
.end()) {
1302 MD
= NodeInfo
->second
.get();
1305 // Check machine metadata.
1306 NodeInfo
= PFS
.MachineMetadataNodes
.find(ID
);
1307 if (NodeInfo
!= PFS
.MachineMetadataNodes
.end()) {
1308 MD
= NodeInfo
->second
.get();
1311 // Forward reference.
1312 auto &FwdRef
= PFS
.MachineForwardRefMDNodes
[ID
];
1313 FwdRef
= std::make_pair(
1314 MDTuple::getTemporary(MF
.getFunction().getContext(), None
), Loc
);
1315 PFS
.MachineMetadataNodes
[ID
].reset(FwdRef
.first
.get());
1316 MD
= FwdRef
.first
.get();
1321 static const char *printImplicitRegisterFlag(const MachineOperand
&MO
) {
1322 assert(MO
.isImplicit());
1323 return MO
.isDef() ? "implicit-def" : "implicit";
1326 static std::string
getRegisterName(const TargetRegisterInfo
*TRI
,
1328 assert(Register::isPhysicalRegister(Reg
) && "expected phys reg");
1329 return StringRef(TRI
->getName(Reg
)).lower();
1332 /// Return true if the parsed machine operands contain a given machine operand.
1333 static bool isImplicitOperandIn(const MachineOperand
&ImplicitOperand
,
1334 ArrayRef
<ParsedMachineOperand
> Operands
) {
1335 for (const auto &I
: Operands
) {
1336 if (ImplicitOperand
.isIdenticalTo(I
.Operand
))
1342 bool MIParser::verifyImplicitOperands(ArrayRef
<ParsedMachineOperand
> Operands
,
1343 const MCInstrDesc
&MCID
) {
1345 // We can't verify call instructions as they can contain arbitrary implicit
1346 // register and register mask operands.
1349 // Gather all the expected implicit operands.
1350 SmallVector
<MachineOperand
, 4> ImplicitOperands
;
1351 if (MCID
.ImplicitDefs
)
1352 for (const MCPhysReg
*ImpDefs
= MCID
.getImplicitDefs(); *ImpDefs
; ++ImpDefs
)
1353 ImplicitOperands
.push_back(
1354 MachineOperand::CreateReg(*ImpDefs
, true, true));
1355 if (MCID
.ImplicitUses
)
1356 for (const MCPhysReg
*ImpUses
= MCID
.getImplicitUses(); *ImpUses
; ++ImpUses
)
1357 ImplicitOperands
.push_back(
1358 MachineOperand::CreateReg(*ImpUses
, false, true));
1360 const auto *TRI
= MF
.getSubtarget().getRegisterInfo();
1361 assert(TRI
&& "Expected target register info");
1362 for (const auto &I
: ImplicitOperands
) {
1363 if (isImplicitOperandIn(I
, Operands
))
1365 return error(Operands
.empty() ? Token
.location() : Operands
.back().End
,
1366 Twine("missing implicit register operand '") +
1367 printImplicitRegisterFlag(I
) + " $" +
1368 getRegisterName(TRI
, I
.getReg()) + "'");
1373 bool MIParser::parseInstruction(unsigned &OpCode
, unsigned &Flags
) {
1374 // Allow frame and fast math flags for OPCODE
1375 while (Token
.is(MIToken::kw_frame_setup
) ||
1376 Token
.is(MIToken::kw_frame_destroy
) ||
1377 Token
.is(MIToken::kw_nnan
) ||
1378 Token
.is(MIToken::kw_ninf
) ||
1379 Token
.is(MIToken::kw_nsz
) ||
1380 Token
.is(MIToken::kw_arcp
) ||
1381 Token
.is(MIToken::kw_contract
) ||
1382 Token
.is(MIToken::kw_afn
) ||
1383 Token
.is(MIToken::kw_reassoc
) ||
1384 Token
.is(MIToken::kw_nuw
) ||
1385 Token
.is(MIToken::kw_nsw
) ||
1386 Token
.is(MIToken::kw_exact
) ||
1387 Token
.is(MIToken::kw_nofpexcept
)) {
1388 // Mine frame and fast math flags
1389 if (Token
.is(MIToken::kw_frame_setup
))
1390 Flags
|= MachineInstr::FrameSetup
;
1391 if (Token
.is(MIToken::kw_frame_destroy
))
1392 Flags
|= MachineInstr::FrameDestroy
;
1393 if (Token
.is(MIToken::kw_nnan
))
1394 Flags
|= MachineInstr::FmNoNans
;
1395 if (Token
.is(MIToken::kw_ninf
))
1396 Flags
|= MachineInstr::FmNoInfs
;
1397 if (Token
.is(MIToken::kw_nsz
))
1398 Flags
|= MachineInstr::FmNsz
;
1399 if (Token
.is(MIToken::kw_arcp
))
1400 Flags
|= MachineInstr::FmArcp
;
1401 if (Token
.is(MIToken::kw_contract
))
1402 Flags
|= MachineInstr::FmContract
;
1403 if (Token
.is(MIToken::kw_afn
))
1404 Flags
|= MachineInstr::FmAfn
;
1405 if (Token
.is(MIToken::kw_reassoc
))
1406 Flags
|= MachineInstr::FmReassoc
;
1407 if (Token
.is(MIToken::kw_nuw
))
1408 Flags
|= MachineInstr::NoUWrap
;
1409 if (Token
.is(MIToken::kw_nsw
))
1410 Flags
|= MachineInstr::NoSWrap
;
1411 if (Token
.is(MIToken::kw_exact
))
1412 Flags
|= MachineInstr::IsExact
;
1413 if (Token
.is(MIToken::kw_nofpexcept
))
1414 Flags
|= MachineInstr::NoFPExcept
;
1418 if (Token
.isNot(MIToken::Identifier
))
1419 return error("expected a machine instruction");
1420 StringRef InstrName
= Token
.stringValue();
1421 if (PFS
.Target
.parseInstrName(InstrName
, OpCode
))
1422 return error(Twine("unknown machine instruction name '") + InstrName
+ "'");
1427 bool MIParser::parseNamedRegister(Register
&Reg
) {
1428 assert(Token
.is(MIToken::NamedRegister
) && "Needs NamedRegister token");
1429 StringRef Name
= Token
.stringValue();
1430 if (PFS
.Target
.getRegisterByName(Name
, Reg
))
1431 return error(Twine("unknown register name '") + Name
+ "'");
1435 bool MIParser::parseNamedVirtualRegister(VRegInfo
*&Info
) {
1436 assert(Token
.is(MIToken::NamedVirtualRegister
) && "Expected NamedVReg token");
1437 StringRef Name
= Token
.stringValue();
1438 // TODO: Check that the VReg name is not the same as a physical register name.
1439 // If it is, then print a warning (when warnings are implemented).
1440 Info
= &PFS
.getVRegInfoNamed(Name
);
1444 bool MIParser::parseVirtualRegister(VRegInfo
*&Info
) {
1445 if (Token
.is(MIToken::NamedVirtualRegister
))
1446 return parseNamedVirtualRegister(Info
);
1447 assert(Token
.is(MIToken::VirtualRegister
) && "Needs VirtualRegister token");
1449 if (getUnsigned(ID
))
1451 Info
= &PFS
.getVRegInfo(ID
);
1455 bool MIParser::parseRegister(Register
&Reg
, VRegInfo
*&Info
) {
1456 switch (Token
.kind()) {
1457 case MIToken::underscore
:
1460 case MIToken::NamedRegister
:
1461 return parseNamedRegister(Reg
);
1462 case MIToken::NamedVirtualRegister
:
1463 case MIToken::VirtualRegister
:
1464 if (parseVirtualRegister(Info
))
1468 // TODO: Parse other register kinds.
1470 llvm_unreachable("The current token should be a register");
1474 bool MIParser::parseRegisterClassOrBank(VRegInfo
&RegInfo
) {
1475 if (Token
.isNot(MIToken::Identifier
) && Token
.isNot(MIToken::underscore
))
1476 return error("expected '_', register class, or register bank name");
1477 StringRef::iterator Loc
= Token
.location();
1478 StringRef Name
= Token
.stringValue();
1480 // Was it a register class?
1481 const TargetRegisterClass
*RC
= PFS
.Target
.getRegClass(Name
);
1485 switch (RegInfo
.Kind
) {
1486 case VRegInfo::UNKNOWN
:
1487 case VRegInfo::NORMAL
:
1488 RegInfo
.Kind
= VRegInfo::NORMAL
;
1489 if (RegInfo
.Explicit
&& RegInfo
.D
.RC
!= RC
) {
1490 const TargetRegisterInfo
&TRI
= *MF
.getSubtarget().getRegisterInfo();
1491 return error(Loc
, Twine("conflicting register classes, previously: ") +
1492 Twine(TRI
.getRegClassName(RegInfo
.D
.RC
)));
1495 RegInfo
.Explicit
= true;
1498 case VRegInfo::GENERIC
:
1499 case VRegInfo::REGBANK
:
1500 return error(Loc
, "register class specification on generic register");
1502 llvm_unreachable("Unexpected register kind");
1505 // Should be a register bank or a generic register.
1506 const RegisterBank
*RegBank
= nullptr;
1508 RegBank
= PFS
.Target
.getRegBank(Name
);
1510 return error(Loc
, "expected '_', register class, or register bank name");
1515 switch (RegInfo
.Kind
) {
1516 case VRegInfo::UNKNOWN
:
1517 case VRegInfo::GENERIC
:
1518 case VRegInfo::REGBANK
:
1519 RegInfo
.Kind
= RegBank
? VRegInfo::REGBANK
: VRegInfo::GENERIC
;
1520 if (RegInfo
.Explicit
&& RegInfo
.D
.RegBank
!= RegBank
)
1521 return error(Loc
, "conflicting generic register banks");
1522 RegInfo
.D
.RegBank
= RegBank
;
1523 RegInfo
.Explicit
= true;
1526 case VRegInfo::NORMAL
:
1527 return error(Loc
, "register bank specification on normal register");
1529 llvm_unreachable("Unexpected register kind");
1532 bool MIParser::parseRegisterFlag(unsigned &Flags
) {
1533 const unsigned OldFlags
= Flags
;
1534 switch (Token
.kind()) {
1535 case MIToken::kw_implicit
:
1536 Flags
|= RegState::Implicit
;
1538 case MIToken::kw_implicit_define
:
1539 Flags
|= RegState::ImplicitDefine
;
1541 case MIToken::kw_def
:
1542 Flags
|= RegState::Define
;
1544 case MIToken::kw_dead
:
1545 Flags
|= RegState::Dead
;
1547 case MIToken::kw_killed
:
1548 Flags
|= RegState::Kill
;
1550 case MIToken::kw_undef
:
1551 Flags
|= RegState::Undef
;
1553 case MIToken::kw_internal
:
1554 Flags
|= RegState::InternalRead
;
1556 case MIToken::kw_early_clobber
:
1557 Flags
|= RegState::EarlyClobber
;
1559 case MIToken::kw_debug_use
:
1560 Flags
|= RegState::Debug
;
1562 case MIToken::kw_renamable
:
1563 Flags
|= RegState::Renamable
;
1566 llvm_unreachable("The current token should be a register flag");
1568 if (OldFlags
== Flags
)
1569 // We know that the same flag is specified more than once when the flags
1570 // weren't modified.
1571 return error("duplicate '" + Token
.stringValue() + "' register flag");
1576 bool MIParser::parseSubRegisterIndex(unsigned &SubReg
) {
1577 assert(Token
.is(MIToken::dot
));
1579 if (Token
.isNot(MIToken::Identifier
))
1580 return error("expected a subregister index after '.'");
1581 auto Name
= Token
.stringValue();
1582 SubReg
= PFS
.Target
.getSubRegIndex(Name
);
1584 return error(Twine("use of unknown subregister index '") + Name
+ "'");
1589 bool MIParser::parseRegisterTiedDefIndex(unsigned &TiedDefIdx
) {
1590 if (!consumeIfPresent(MIToken::kw_tied_def
))
1592 if (Token
.isNot(MIToken::IntegerLiteral
))
1593 return error("expected an integer literal after 'tied-def'");
1594 if (getUnsigned(TiedDefIdx
))
1597 if (expectAndConsume(MIToken::rparen
))
1602 bool MIParser::assignRegisterTies(MachineInstr
&MI
,
1603 ArrayRef
<ParsedMachineOperand
> Operands
) {
1604 SmallVector
<std::pair
<unsigned, unsigned>, 4> TiedRegisterPairs
;
1605 for (unsigned I
= 0, E
= Operands
.size(); I
!= E
; ++I
) {
1606 if (!Operands
[I
].TiedDefIdx
)
1608 // The parser ensures that this operand is a register use, so we just have
1609 // to check the tied-def operand.
1610 unsigned DefIdx
= Operands
[I
].TiedDefIdx
.getValue();
1612 return error(Operands
[I
].Begin
,
1613 Twine("use of invalid tied-def operand index '" +
1614 Twine(DefIdx
) + "'; instruction has only ") +
1615 Twine(E
) + " operands");
1616 const auto &DefOperand
= Operands
[DefIdx
].Operand
;
1617 if (!DefOperand
.isReg() || !DefOperand
.isDef())
1618 // FIXME: add note with the def operand.
1619 return error(Operands
[I
].Begin
,
1620 Twine("use of invalid tied-def operand index '") +
1621 Twine(DefIdx
) + "'; the operand #" + Twine(DefIdx
) +
1622 " isn't a defined register");
1623 // Check that the tied-def operand wasn't tied elsewhere.
1624 for (const auto &TiedPair
: TiedRegisterPairs
) {
1625 if (TiedPair
.first
== DefIdx
)
1626 return error(Operands
[I
].Begin
,
1627 Twine("the tied-def operand #") + Twine(DefIdx
) +
1628 " is already tied with another register operand");
1630 TiedRegisterPairs
.push_back(std::make_pair(DefIdx
, I
));
1632 // FIXME: Verify that for non INLINEASM instructions, the def and use tied
1633 // indices must be less than tied max.
1634 for (const auto &TiedPair
: TiedRegisterPairs
)
1635 MI
.tieOperands(TiedPair
.first
, TiedPair
.second
);
1639 bool MIParser::parseRegisterOperand(MachineOperand
&Dest
,
1640 Optional
<unsigned> &TiedDefIdx
,
1642 unsigned Flags
= IsDef
? RegState::Define
: 0;
1643 while (Token
.isRegisterFlag()) {
1644 if (parseRegisterFlag(Flags
))
1647 if (!Token
.isRegister())
1648 return error("expected a register after register flags");
1651 if (parseRegister(Reg
, RegInfo
))
1654 unsigned SubReg
= 0;
1655 if (Token
.is(MIToken::dot
)) {
1656 if (parseSubRegisterIndex(SubReg
))
1658 if (!Register::isVirtualRegister(Reg
))
1659 return error("subregister index expects a virtual register");
1661 if (Token
.is(MIToken::colon
)) {
1662 if (!Register::isVirtualRegister(Reg
))
1663 return error("register class specification expects a virtual register");
1665 if (parseRegisterClassOrBank(*RegInfo
))
1668 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
1669 if ((Flags
& RegState::Define
) == 0) {
1670 if (consumeIfPresent(MIToken::lparen
)) {
1672 if (!parseRegisterTiedDefIndex(Idx
))
1675 // Try a redundant low-level type.
1677 if (parseLowLevelType(Token
.location(), Ty
))
1678 return error("expected tied-def or low-level type after '('");
1680 if (expectAndConsume(MIToken::rparen
))
1683 if (MRI
.getType(Reg
).isValid() && MRI
.getType(Reg
) != Ty
)
1684 return error("inconsistent type for generic virtual register");
1686 MRI
.setRegClassOrRegBank(Reg
, static_cast<RegisterBank
*>(nullptr));
1687 MRI
.setType(Reg
, Ty
);
1690 } else if (consumeIfPresent(MIToken::lparen
)) {
1691 // Virtual registers may have a tpe with GlobalISel.
1692 if (!Register::isVirtualRegister(Reg
))
1693 return error("unexpected type on physical register");
1696 if (parseLowLevelType(Token
.location(), Ty
))
1699 if (expectAndConsume(MIToken::rparen
))
1702 if (MRI
.getType(Reg
).isValid() && MRI
.getType(Reg
) != Ty
)
1703 return error("inconsistent type for generic virtual register");
1705 MRI
.setRegClassOrRegBank(Reg
, static_cast<RegisterBank
*>(nullptr));
1706 MRI
.setType(Reg
, Ty
);
1707 } else if (Register::isVirtualRegister(Reg
)) {
1708 // Generic virtual registers must have a type.
1709 // If we end up here this means the type hasn't been specified and
1711 if (RegInfo
->Kind
== VRegInfo::GENERIC
||
1712 RegInfo
->Kind
== VRegInfo::REGBANK
)
1713 return error("generic virtual registers must have a type");
1715 Dest
= MachineOperand::CreateReg(
1716 Reg
, Flags
& RegState::Define
, Flags
& RegState::Implicit
,
1717 Flags
& RegState::Kill
, Flags
& RegState::Dead
, Flags
& RegState::Undef
,
1718 Flags
& RegState::EarlyClobber
, SubReg
, Flags
& RegState::Debug
,
1719 Flags
& RegState::InternalRead
, Flags
& RegState::Renamable
);
1724 bool MIParser::parseImmediateOperand(MachineOperand
&Dest
) {
1725 assert(Token
.is(MIToken::IntegerLiteral
));
1726 const APSInt
&Int
= Token
.integerValue();
1727 if (Int
.getMinSignedBits() > 64)
1728 return error("integer literal is too large to be an immediate operand");
1729 Dest
= MachineOperand::CreateImm(Int
.getExtValue());
1734 bool MIParser::parseTargetImmMnemonic(const unsigned OpCode
,
1735 const unsigned OpIdx
,
1736 MachineOperand
&Dest
,
1737 const MIRFormatter
&MF
) {
1738 assert(Token
.is(MIToken::dot
));
1739 auto Loc
= Token
.location(); // record start position
1740 size_t Len
= 1; // for "."
1743 // Handle the case that mnemonic starts with number.
1744 if (Token
.is(MIToken::IntegerLiteral
)) {
1745 Len
+= Token
.range().size();
1750 if (Token
.is(MIToken::comma
))
1751 Src
= StringRef(Loc
, Len
);
1753 assert(Token
.is(MIToken::Identifier
));
1754 Src
= StringRef(Loc
, Len
+ Token
.stringValue().size());
1757 if (MF
.parseImmMnemonic(OpCode
, OpIdx
, Src
, Val
,
1758 [this](StringRef::iterator Loc
, const Twine
&Msg
)
1759 -> bool { return error(Loc
, Msg
); }))
1762 Dest
= MachineOperand::CreateImm(Val
);
1763 if (!Token
.is(MIToken::comma
))
1768 static bool parseIRConstant(StringRef::iterator Loc
, StringRef StringValue
,
1769 PerFunctionMIParsingState
&PFS
, const Constant
*&C
,
1770 ErrorCallbackType ErrCB
) {
1771 auto Source
= StringValue
.str(); // The source has to be null terminated.
1773 C
= parseConstantValue(Source
, Err
, *PFS
.MF
.getFunction().getParent(),
1776 return ErrCB(Loc
+ Err
.getColumnNo(), Err
.getMessage());
1780 bool MIParser::parseIRConstant(StringRef::iterator Loc
, StringRef StringValue
,
1781 const Constant
*&C
) {
1782 return ::parseIRConstant(
1783 Loc
, StringValue
, PFS
, C
,
1784 [this](StringRef::iterator Loc
, const Twine
&Msg
) -> bool {
1785 return error(Loc
, Msg
);
1789 bool MIParser::parseIRConstant(StringRef::iterator Loc
, const Constant
*&C
) {
1790 if (parseIRConstant(Loc
, StringRef(Loc
, Token
.range().end() - Loc
), C
))
1796 // See LLT implemntation for bit size limits.
1797 static bool verifyScalarSize(uint64_t Size
) {
1798 return Size
!= 0 && isUInt
<16>(Size
);
1801 static bool verifyVectorElementCount(uint64_t NumElts
) {
1802 return NumElts
!= 0 && isUInt
<16>(NumElts
);
1805 static bool verifyAddrSpace(uint64_t AddrSpace
) {
1806 return isUInt
<24>(AddrSpace
);
1809 bool MIParser::parseLowLevelType(StringRef::iterator Loc
, LLT
&Ty
) {
1810 if (Token
.range().front() == 's' || Token
.range().front() == 'p') {
1811 StringRef SizeStr
= Token
.range().drop_front();
1812 if (SizeStr
.size() == 0 || !llvm::all_of(SizeStr
, isdigit
))
1813 return error("expected integers after 's'/'p' type character");
1816 if (Token
.range().front() == 's') {
1817 auto ScalarSize
= APSInt(Token
.range().drop_front()).getZExtValue();
1818 if (!verifyScalarSize(ScalarSize
))
1819 return error("invalid size for scalar type");
1821 Ty
= LLT::scalar(ScalarSize
);
1824 } else if (Token
.range().front() == 'p') {
1825 const DataLayout
&DL
= MF
.getDataLayout();
1826 uint64_t AS
= APSInt(Token
.range().drop_front()).getZExtValue();
1827 if (!verifyAddrSpace(AS
))
1828 return error("invalid address space number");
1830 Ty
= LLT::pointer(AS
, DL
.getPointerSizeInBits(AS
));
1835 // Now we're looking for a vector.
1836 if (Token
.isNot(MIToken::less
))
1838 "expected sN, pA, <M x sN>, or <M x pA> for GlobalISel type");
1841 if (Token
.isNot(MIToken::IntegerLiteral
))
1842 return error(Loc
, "expected <M x sN> or <M x pA> for vector type");
1843 uint64_t NumElements
= Token
.integerValue().getZExtValue();
1844 if (!verifyVectorElementCount(NumElements
))
1845 return error("invalid number of vector elements");
1849 if (Token
.isNot(MIToken::Identifier
) || Token
.stringValue() != "x")
1850 return error(Loc
, "expected <M x sN> or <M x pA> for vector type");
1853 if (Token
.range().front() != 's' && Token
.range().front() != 'p')
1854 return error(Loc
, "expected <M x sN> or <M x pA> for vector type");
1855 StringRef SizeStr
= Token
.range().drop_front();
1856 if (SizeStr
.size() == 0 || !llvm::all_of(SizeStr
, isdigit
))
1857 return error("expected integers after 's'/'p' type character");
1859 if (Token
.range().front() == 's') {
1860 auto ScalarSize
= APSInt(Token
.range().drop_front()).getZExtValue();
1861 if (!verifyScalarSize(ScalarSize
))
1862 return error("invalid size for scalar type");
1863 Ty
= LLT::scalar(ScalarSize
);
1864 } else if (Token
.range().front() == 'p') {
1865 const DataLayout
&DL
= MF
.getDataLayout();
1866 uint64_t AS
= APSInt(Token
.range().drop_front()).getZExtValue();
1867 if (!verifyAddrSpace(AS
))
1868 return error("invalid address space number");
1870 Ty
= LLT::pointer(AS
, DL
.getPointerSizeInBits(AS
));
1872 return error(Loc
, "expected <M x sN> or <M x pA> for vector type");
1875 if (Token
.isNot(MIToken::greater
))
1876 return error(Loc
, "expected <M x sN> or <M x pA> for vector type");
1879 Ty
= LLT::fixed_vector(NumElements
, Ty
);
1883 bool MIParser::parseTypedImmediateOperand(MachineOperand
&Dest
) {
1884 assert(Token
.is(MIToken::Identifier
));
1885 StringRef TypeStr
= Token
.range();
1886 if (TypeStr
.front() != 'i' && TypeStr
.front() != 's' &&
1887 TypeStr
.front() != 'p')
1889 "a typed immediate operand should start with one of 'i', 's', or 'p'");
1890 StringRef SizeStr
= Token
.range().drop_front();
1891 if (SizeStr
.size() == 0 || !llvm::all_of(SizeStr
, isdigit
))
1892 return error("expected integers after 'i'/'s'/'p' type character");
1894 auto Loc
= Token
.location();
1896 if (Token
.isNot(MIToken::IntegerLiteral
)) {
1897 if (Token
.isNot(MIToken::Identifier
) ||
1898 !(Token
.range() == "true" || Token
.range() == "false"))
1899 return error("expected an integer literal");
1901 const Constant
*C
= nullptr;
1902 if (parseIRConstant(Loc
, C
))
1904 Dest
= MachineOperand::CreateCImm(cast
<ConstantInt
>(C
));
1908 bool MIParser::parseFPImmediateOperand(MachineOperand
&Dest
) {
1909 auto Loc
= Token
.location();
1911 if (Token
.isNot(MIToken::FloatingPointLiteral
) &&
1912 Token
.isNot(MIToken::HexLiteral
))
1913 return error("expected a floating point literal");
1914 const Constant
*C
= nullptr;
1915 if (parseIRConstant(Loc
, C
))
1917 Dest
= MachineOperand::CreateFPImm(cast
<ConstantFP
>(C
));
1921 static bool getHexUint(const MIToken
&Token
, APInt
&Result
) {
1922 assert(Token
.is(MIToken::HexLiteral
));
1923 StringRef S
= Token
.range();
1924 assert(S
[0] == '0' && tolower(S
[1]) == 'x');
1925 // This could be a floating point literal with a special prefix.
1926 if (!isxdigit(S
[2]))
1928 StringRef V
= S
.substr(2);
1929 APInt
A(V
.size()*4, V
, 16);
1931 // If A is 0, then A.getActiveBits() is 0. This isn't a valid bitwidth. Make
1932 // sure it isn't the case before constructing result.
1933 unsigned NumBits
= (A
== 0) ? 32 : A
.getActiveBits();
1934 Result
= APInt(NumBits
, ArrayRef
<uint64_t>(A
.getRawData(), A
.getNumWords()));
1938 static bool getUnsigned(const MIToken
&Token
, unsigned &Result
,
1939 ErrorCallbackType ErrCB
) {
1940 if (Token
.hasIntegerValue()) {
1941 const uint64_t Limit
= uint64_t(std::numeric_limits
<unsigned>::max()) + 1;
1942 uint64_t Val64
= Token
.integerValue().getLimitedValue(Limit
);
1944 return ErrCB(Token
.location(), "expected 32-bit integer (too large)");
1948 if (Token
.is(MIToken::HexLiteral
)) {
1950 if (getHexUint(Token
, A
))
1952 if (A
.getBitWidth() > 32)
1953 return ErrCB(Token
.location(), "expected 32-bit integer (too large)");
1954 Result
= A
.getZExtValue();
1960 bool MIParser::getUnsigned(unsigned &Result
) {
1961 return ::getUnsigned(
1962 Token
, Result
, [this](StringRef::iterator Loc
, const Twine
&Msg
) -> bool {
1963 return error(Loc
, Msg
);
1967 bool MIParser::parseMBBReference(MachineBasicBlock
*&MBB
) {
1968 assert(Token
.is(MIToken::MachineBasicBlock
) ||
1969 Token
.is(MIToken::MachineBasicBlockLabel
));
1971 if (getUnsigned(Number
))
1973 auto MBBInfo
= PFS
.MBBSlots
.find(Number
);
1974 if (MBBInfo
== PFS
.MBBSlots
.end())
1975 return error(Twine("use of undefined machine basic block #") +
1977 MBB
= MBBInfo
->second
;
1978 // TODO: Only parse the name if it's a MachineBasicBlockLabel. Deprecate once
1979 // we drop the <irname> from the bb.<id>.<irname> format.
1980 if (!Token
.stringValue().empty() && Token
.stringValue() != MBB
->getName())
1981 return error(Twine("the name of machine basic block #") + Twine(Number
) +
1982 " isn't '" + Token
.stringValue() + "'");
1986 bool MIParser::parseMBBOperand(MachineOperand
&Dest
) {
1987 MachineBasicBlock
*MBB
;
1988 if (parseMBBReference(MBB
))
1990 Dest
= MachineOperand::CreateMBB(MBB
);
1995 bool MIParser::parseStackFrameIndex(int &FI
) {
1996 assert(Token
.is(MIToken::StackObject
));
1998 if (getUnsigned(ID
))
2000 auto ObjectInfo
= PFS
.StackObjectSlots
.find(ID
);
2001 if (ObjectInfo
== PFS
.StackObjectSlots
.end())
2002 return error(Twine("use of undefined stack object '%stack.") + Twine(ID
) +
2005 if (const auto *Alloca
=
2006 MF
.getFrameInfo().getObjectAllocation(ObjectInfo
->second
))
2007 Name
= Alloca
->getName();
2008 if (!Token
.stringValue().empty() && Token
.stringValue() != Name
)
2009 return error(Twine("the name of the stack object '%stack.") + Twine(ID
) +
2010 "' isn't '" + Token
.stringValue() + "'");
2012 FI
= ObjectInfo
->second
;
2016 bool MIParser::parseStackObjectOperand(MachineOperand
&Dest
) {
2018 if (parseStackFrameIndex(FI
))
2020 Dest
= MachineOperand::CreateFI(FI
);
2024 bool MIParser::parseFixedStackFrameIndex(int &FI
) {
2025 assert(Token
.is(MIToken::FixedStackObject
));
2027 if (getUnsigned(ID
))
2029 auto ObjectInfo
= PFS
.FixedStackObjectSlots
.find(ID
);
2030 if (ObjectInfo
== PFS
.FixedStackObjectSlots
.end())
2031 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
2034 FI
= ObjectInfo
->second
;
2038 bool MIParser::parseFixedStackObjectOperand(MachineOperand
&Dest
) {
2040 if (parseFixedStackFrameIndex(FI
))
2042 Dest
= MachineOperand::CreateFI(FI
);
2046 static bool parseGlobalValue(const MIToken
&Token
,
2047 PerFunctionMIParsingState
&PFS
, GlobalValue
*&GV
,
2048 ErrorCallbackType ErrCB
) {
2049 switch (Token
.kind()) {
2050 case MIToken::NamedGlobalValue
: {
2051 const Module
*M
= PFS
.MF
.getFunction().getParent();
2052 GV
= M
->getNamedValue(Token
.stringValue());
2054 return ErrCB(Token
.location(), Twine("use of undefined global value '") +
2055 Token
.range() + "'");
2058 case MIToken::GlobalValue
: {
2060 if (getUnsigned(Token
, GVIdx
, ErrCB
))
2062 if (GVIdx
>= PFS
.IRSlots
.GlobalValues
.size())
2063 return ErrCB(Token
.location(), Twine("use of undefined global value '@") +
2064 Twine(GVIdx
) + "'");
2065 GV
= PFS
.IRSlots
.GlobalValues
[GVIdx
];
2069 llvm_unreachable("The current token should be a global value");
2074 bool MIParser::parseGlobalValue(GlobalValue
*&GV
) {
2075 return ::parseGlobalValue(
2077 [this](StringRef::iterator Loc
, const Twine
&Msg
) -> bool {
2078 return error(Loc
, Msg
);
2082 bool MIParser::parseGlobalAddressOperand(MachineOperand
&Dest
) {
2083 GlobalValue
*GV
= nullptr;
2084 if (parseGlobalValue(GV
))
2087 Dest
= MachineOperand::CreateGA(GV
, /*Offset=*/0);
2088 if (parseOperandsOffset(Dest
))
2093 bool MIParser::parseConstantPoolIndexOperand(MachineOperand
&Dest
) {
2094 assert(Token
.is(MIToken::ConstantPoolItem
));
2096 if (getUnsigned(ID
))
2098 auto ConstantInfo
= PFS
.ConstantPoolSlots
.find(ID
);
2099 if (ConstantInfo
== PFS
.ConstantPoolSlots
.end())
2100 return error("use of undefined constant '%const." + Twine(ID
) + "'");
2102 Dest
= MachineOperand::CreateCPI(ID
, /*Offset=*/0);
2103 if (parseOperandsOffset(Dest
))
2108 bool MIParser::parseJumpTableIndexOperand(MachineOperand
&Dest
) {
2109 assert(Token
.is(MIToken::JumpTableIndex
));
2111 if (getUnsigned(ID
))
2113 auto JumpTableEntryInfo
= PFS
.JumpTableSlots
.find(ID
);
2114 if (JumpTableEntryInfo
== PFS
.JumpTableSlots
.end())
2115 return error("use of undefined jump table '%jump-table." + Twine(ID
) + "'");
2117 Dest
= MachineOperand::CreateJTI(JumpTableEntryInfo
->second
);
2121 bool MIParser::parseExternalSymbolOperand(MachineOperand
&Dest
) {
2122 assert(Token
.is(MIToken::ExternalSymbol
));
2123 const char *Symbol
= MF
.createExternalSymbolName(Token
.stringValue());
2125 Dest
= MachineOperand::CreateES(Symbol
);
2126 if (parseOperandsOffset(Dest
))
2131 bool MIParser::parseMCSymbolOperand(MachineOperand
&Dest
) {
2132 assert(Token
.is(MIToken::MCSymbol
));
2133 MCSymbol
*Symbol
= getOrCreateMCSymbol(Token
.stringValue());
2135 Dest
= MachineOperand::CreateMCSymbol(Symbol
);
2136 if (parseOperandsOffset(Dest
))
2141 bool MIParser::parseSubRegisterIndexOperand(MachineOperand
&Dest
) {
2142 assert(Token
.is(MIToken::SubRegisterIndex
));
2143 StringRef Name
= Token
.stringValue();
2144 unsigned SubRegIndex
= PFS
.Target
.getSubRegIndex(Token
.stringValue());
2145 if (SubRegIndex
== 0)
2146 return error(Twine("unknown subregister index '") + Name
+ "'");
2148 Dest
= MachineOperand::CreateImm(SubRegIndex
);
2152 bool MIParser::parseMDNode(MDNode
*&Node
) {
2153 assert(Token
.is(MIToken::exclaim
));
2155 auto Loc
= Token
.location();
2157 if (Token
.isNot(MIToken::IntegerLiteral
) || Token
.integerValue().isSigned())
2158 return error("expected metadata id after '!'");
2160 if (getUnsigned(ID
))
2162 auto NodeInfo
= PFS
.IRSlots
.MetadataNodes
.find(ID
);
2163 if (NodeInfo
== PFS
.IRSlots
.MetadataNodes
.end()) {
2164 NodeInfo
= PFS
.MachineMetadataNodes
.find(ID
);
2165 if (NodeInfo
== PFS
.MachineMetadataNodes
.end())
2166 return error(Loc
, "use of undefined metadata '!" + Twine(ID
) + "'");
2169 Node
= NodeInfo
->second
.get();
2173 bool MIParser::parseDIExpression(MDNode
*&Expr
) {
2174 assert(Token
.is(MIToken::md_diexpr
));
2177 // FIXME: Share this parsing with the IL parser.
2178 SmallVector
<uint64_t, 8> Elements
;
2180 if (expectAndConsume(MIToken::lparen
))
2183 if (Token
.isNot(MIToken::rparen
)) {
2185 if (Token
.is(MIToken::Identifier
)) {
2186 if (unsigned Op
= dwarf::getOperationEncoding(Token
.stringValue())) {
2188 Elements
.push_back(Op
);
2191 if (unsigned Enc
= dwarf::getAttributeEncoding(Token
.stringValue())) {
2193 Elements
.push_back(Enc
);
2196 return error(Twine("invalid DWARF op '") + Token
.stringValue() + "'");
2199 if (Token
.isNot(MIToken::IntegerLiteral
) ||
2200 Token
.integerValue().isSigned())
2201 return error("expected unsigned integer");
2203 auto &U
= Token
.integerValue();
2204 if (U
.ugt(UINT64_MAX
))
2205 return error("element too large, limit is " + Twine(UINT64_MAX
));
2206 Elements
.push_back(U
.getZExtValue());
2209 } while (consumeIfPresent(MIToken::comma
));
2212 if (expectAndConsume(MIToken::rparen
))
2215 Expr
= DIExpression::get(MF
.getFunction().getContext(), Elements
);
2219 bool MIParser::parseDILocation(MDNode
*&Loc
) {
2220 assert(Token
.is(MIToken::md_dilocation
));
2223 bool HaveLine
= false;
2225 unsigned Column
= 0;
2226 MDNode
*Scope
= nullptr;
2227 MDNode
*InlinedAt
= nullptr;
2228 bool ImplicitCode
= false;
2230 if (expectAndConsume(MIToken::lparen
))
2233 if (Token
.isNot(MIToken::rparen
)) {
2235 if (Token
.is(MIToken::Identifier
)) {
2236 if (Token
.stringValue() == "line") {
2238 if (expectAndConsume(MIToken::colon
))
2240 if (Token
.isNot(MIToken::IntegerLiteral
) ||
2241 Token
.integerValue().isSigned())
2242 return error("expected unsigned integer");
2243 Line
= Token
.integerValue().getZExtValue();
2248 if (Token
.stringValue() == "column") {
2250 if (expectAndConsume(MIToken::colon
))
2252 if (Token
.isNot(MIToken::IntegerLiteral
) ||
2253 Token
.integerValue().isSigned())
2254 return error("expected unsigned integer");
2255 Column
= Token
.integerValue().getZExtValue();
2259 if (Token
.stringValue() == "scope") {
2261 if (expectAndConsume(MIToken::colon
))
2263 if (parseMDNode(Scope
))
2264 return error("expected metadata node");
2265 if (!isa
<DIScope
>(Scope
))
2266 return error("expected DIScope node");
2269 if (Token
.stringValue() == "inlinedAt") {
2271 if (expectAndConsume(MIToken::colon
))
2273 if (Token
.is(MIToken::exclaim
)) {
2274 if (parseMDNode(InlinedAt
))
2276 } else if (Token
.is(MIToken::md_dilocation
)) {
2277 if (parseDILocation(InlinedAt
))
2280 return error("expected metadata node");
2281 if (!isa
<DILocation
>(InlinedAt
))
2282 return error("expected DILocation node");
2285 if (Token
.stringValue() == "isImplicitCode") {
2287 if (expectAndConsume(MIToken::colon
))
2289 if (!Token
.is(MIToken::Identifier
))
2290 return error("expected true/false");
2291 // As far as I can see, we don't have any existing need for parsing
2292 // true/false in MIR yet. Do it ad-hoc until there's something else
2294 if (Token
.stringValue() == "true")
2295 ImplicitCode
= true;
2296 else if (Token
.stringValue() == "false")
2297 ImplicitCode
= false;
2299 return error("expected true/false");
2304 return error(Twine("invalid DILocation argument '") +
2305 Token
.stringValue() + "'");
2306 } while (consumeIfPresent(MIToken::comma
));
2309 if (expectAndConsume(MIToken::rparen
))
2313 return error("DILocation requires line number");
2315 return error("DILocation requires a scope");
2317 Loc
= DILocation::get(MF
.getFunction().getContext(), Line
, Column
, Scope
,
2318 InlinedAt
, ImplicitCode
);
2322 bool MIParser::parseMetadataOperand(MachineOperand
&Dest
) {
2323 MDNode
*Node
= nullptr;
2324 if (Token
.is(MIToken::exclaim
)) {
2325 if (parseMDNode(Node
))
2327 } else if (Token
.is(MIToken::md_diexpr
)) {
2328 if (parseDIExpression(Node
))
2331 Dest
= MachineOperand::CreateMetadata(Node
);
2335 bool MIParser::parseCFIOffset(int &Offset
) {
2336 if (Token
.isNot(MIToken::IntegerLiteral
))
2337 return error("expected a cfi offset");
2338 if (Token
.integerValue().getMinSignedBits() > 32)
2339 return error("expected a 32 bit integer (the cfi offset is too large)");
2340 Offset
= (int)Token
.integerValue().getExtValue();
2345 bool MIParser::parseCFIRegister(Register
&Reg
) {
2346 if (Token
.isNot(MIToken::NamedRegister
))
2347 return error("expected a cfi register");
2349 if (parseNamedRegister(LLVMReg
))
2351 const auto *TRI
= MF
.getSubtarget().getRegisterInfo();
2352 assert(TRI
&& "Expected target register info");
2353 int DwarfReg
= TRI
->getDwarfRegNum(LLVMReg
, true);
2355 return error("invalid DWARF register");
2356 Reg
= (unsigned)DwarfReg
;
2361 bool MIParser::parseCFIAddressSpace(unsigned &AddressSpace
) {
2362 if (Token
.isNot(MIToken::IntegerLiteral
))
2363 return error("expected a cfi address space literal");
2364 if (Token
.integerValue().isSigned())
2365 return error("expected an unsigned integer (cfi address space)");
2366 AddressSpace
= Token
.integerValue().getZExtValue();
2371 bool MIParser::parseCFIEscapeValues(std::string
&Values
) {
2373 if (Token
.isNot(MIToken::HexLiteral
))
2374 return error("expected a hexadecimal literal");
2376 if (getUnsigned(Value
))
2378 if (Value
> UINT8_MAX
)
2379 return error("expected a 8-bit integer (too large)");
2380 Values
.push_back(static_cast<uint8_t>(Value
));
2382 } while (consumeIfPresent(MIToken::comma
));
2386 bool MIParser::parseCFIOperand(MachineOperand
&Dest
) {
2387 auto Kind
= Token
.kind();
2391 unsigned AddressSpace
;
2394 case MIToken::kw_cfi_same_value
:
2395 if (parseCFIRegister(Reg
))
2397 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createSameValue(nullptr, Reg
));
2399 case MIToken::kw_cfi_offset
:
2400 if (parseCFIRegister(Reg
) || expectAndConsume(MIToken::comma
) ||
2401 parseCFIOffset(Offset
))
2404 MF
.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg
, Offset
));
2406 case MIToken::kw_cfi_rel_offset
:
2407 if (parseCFIRegister(Reg
) || expectAndConsume(MIToken::comma
) ||
2408 parseCFIOffset(Offset
))
2410 CFIIndex
= MF
.addFrameInst(
2411 MCCFIInstruction::createRelOffset(nullptr, Reg
, Offset
));
2413 case MIToken::kw_cfi_def_cfa_register
:
2414 if (parseCFIRegister(Reg
))
2417 MF
.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg
));
2419 case MIToken::kw_cfi_def_cfa_offset
:
2420 if (parseCFIOffset(Offset
))
2423 MF
.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, Offset
));
2425 case MIToken::kw_cfi_adjust_cfa_offset
:
2426 if (parseCFIOffset(Offset
))
2428 CFIIndex
= MF
.addFrameInst(
2429 MCCFIInstruction::createAdjustCfaOffset(nullptr, Offset
));
2431 case MIToken::kw_cfi_def_cfa
:
2432 if (parseCFIRegister(Reg
) || expectAndConsume(MIToken::comma
) ||
2433 parseCFIOffset(Offset
))
2436 MF
.addFrameInst(MCCFIInstruction::cfiDefCfa(nullptr, Reg
, Offset
));
2438 case MIToken::kw_cfi_llvm_def_aspace_cfa
:
2439 if (parseCFIRegister(Reg
) || expectAndConsume(MIToken::comma
) ||
2440 parseCFIOffset(Offset
) || expectAndConsume(MIToken::comma
) ||
2441 parseCFIAddressSpace(AddressSpace
))
2443 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createLLVMDefAspaceCfa(
2444 nullptr, Reg
, Offset
, AddressSpace
));
2446 case MIToken::kw_cfi_remember_state
:
2447 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createRememberState(nullptr));
2449 case MIToken::kw_cfi_restore
:
2450 if (parseCFIRegister(Reg
))
2452 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createRestore(nullptr, Reg
));
2454 case MIToken::kw_cfi_restore_state
:
2455 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createRestoreState(nullptr));
2457 case MIToken::kw_cfi_undefined
:
2458 if (parseCFIRegister(Reg
))
2460 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createUndefined(nullptr, Reg
));
2462 case MIToken::kw_cfi_register
: {
2464 if (parseCFIRegister(Reg
) || expectAndConsume(MIToken::comma
) ||
2465 parseCFIRegister(Reg2
))
2469 MF
.addFrameInst(MCCFIInstruction::createRegister(nullptr, Reg
, Reg2
));
2472 case MIToken::kw_cfi_window_save
:
2473 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createWindowSave(nullptr));
2475 case MIToken::kw_cfi_aarch64_negate_ra_sign_state
:
2476 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
2478 case MIToken::kw_cfi_escape
: {
2480 if (parseCFIEscapeValues(Values
))
2482 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createEscape(nullptr, Values
));
2486 // TODO: Parse the other CFI operands.
2487 llvm_unreachable("The current token should be a cfi operand");
2489 Dest
= MachineOperand::CreateCFIIndex(CFIIndex
);
2493 bool MIParser::parseIRBlock(BasicBlock
*&BB
, const Function
&F
) {
2494 switch (Token
.kind()) {
2495 case MIToken::NamedIRBlock
: {
2496 BB
= dyn_cast_or_null
<BasicBlock
>(
2497 F
.getValueSymbolTable()->lookup(Token
.stringValue()));
2499 return error(Twine("use of undefined IR block '") + Token
.range() + "'");
2502 case MIToken::IRBlock
: {
2503 unsigned SlotNumber
= 0;
2504 if (getUnsigned(SlotNumber
))
2506 BB
= const_cast<BasicBlock
*>(getIRBlock(SlotNumber
, F
));
2508 return error(Twine("use of undefined IR block '%ir-block.") +
2509 Twine(SlotNumber
) + "'");
2513 llvm_unreachable("The current token should be an IR block reference");
2518 bool MIParser::parseBlockAddressOperand(MachineOperand
&Dest
) {
2519 assert(Token
.is(MIToken::kw_blockaddress
));
2521 if (expectAndConsume(MIToken::lparen
))
2523 if (Token
.isNot(MIToken::GlobalValue
) &&
2524 Token
.isNot(MIToken::NamedGlobalValue
))
2525 return error("expected a global value");
2526 GlobalValue
*GV
= nullptr;
2527 if (parseGlobalValue(GV
))
2529 auto *F
= dyn_cast
<Function
>(GV
);
2531 return error("expected an IR function reference");
2533 if (expectAndConsume(MIToken::comma
))
2535 BasicBlock
*BB
= nullptr;
2536 if (Token
.isNot(MIToken::IRBlock
) && Token
.isNot(MIToken::NamedIRBlock
))
2537 return error("expected an IR block reference");
2538 if (parseIRBlock(BB
, *F
))
2541 if (expectAndConsume(MIToken::rparen
))
2543 Dest
= MachineOperand::CreateBA(BlockAddress::get(F
, BB
), /*Offset=*/0);
2544 if (parseOperandsOffset(Dest
))
2549 bool MIParser::parseIntrinsicOperand(MachineOperand
&Dest
) {
2550 assert(Token
.is(MIToken::kw_intrinsic
));
2552 if (expectAndConsume(MIToken::lparen
))
2553 return error("expected syntax intrinsic(@llvm.whatever)");
2555 if (Token
.isNot(MIToken::NamedGlobalValue
))
2556 return error("expected syntax intrinsic(@llvm.whatever)");
2558 std::string Name
= std::string(Token
.stringValue());
2561 if (expectAndConsume(MIToken::rparen
))
2562 return error("expected ')' to terminate intrinsic name");
2564 // Find out what intrinsic we're dealing with, first try the global namespace
2565 // and then the target's private intrinsics if that fails.
2566 const TargetIntrinsicInfo
*TII
= MF
.getTarget().getIntrinsicInfo();
2567 Intrinsic::ID ID
= Function::lookupIntrinsicID(Name
);
2568 if (ID
== Intrinsic::not_intrinsic
&& TII
)
2569 ID
= static_cast<Intrinsic::ID
>(TII
->lookupName(Name
));
2571 if (ID
== Intrinsic::not_intrinsic
)
2572 return error("unknown intrinsic name");
2573 Dest
= MachineOperand::CreateIntrinsicID(ID
);
2578 bool MIParser::parsePredicateOperand(MachineOperand
&Dest
) {
2579 assert(Token
.is(MIToken::kw_intpred
) || Token
.is(MIToken::kw_floatpred
));
2580 bool IsFloat
= Token
.is(MIToken::kw_floatpred
);
2583 if (expectAndConsume(MIToken::lparen
))
2584 return error("expected syntax intpred(whatever) or floatpred(whatever");
2586 if (Token
.isNot(MIToken::Identifier
))
2587 return error("whatever");
2589 CmpInst::Predicate Pred
;
2591 Pred
= StringSwitch
<CmpInst::Predicate
>(Token
.stringValue())
2592 .Case("false", CmpInst::FCMP_FALSE
)
2593 .Case("oeq", CmpInst::FCMP_OEQ
)
2594 .Case("ogt", CmpInst::FCMP_OGT
)
2595 .Case("oge", CmpInst::FCMP_OGE
)
2596 .Case("olt", CmpInst::FCMP_OLT
)
2597 .Case("ole", CmpInst::FCMP_OLE
)
2598 .Case("one", CmpInst::FCMP_ONE
)
2599 .Case("ord", CmpInst::FCMP_ORD
)
2600 .Case("uno", CmpInst::FCMP_UNO
)
2601 .Case("ueq", CmpInst::FCMP_UEQ
)
2602 .Case("ugt", CmpInst::FCMP_UGT
)
2603 .Case("uge", CmpInst::FCMP_UGE
)
2604 .Case("ult", CmpInst::FCMP_ULT
)
2605 .Case("ule", CmpInst::FCMP_ULE
)
2606 .Case("une", CmpInst::FCMP_UNE
)
2607 .Case("true", CmpInst::FCMP_TRUE
)
2608 .Default(CmpInst::BAD_FCMP_PREDICATE
);
2609 if (!CmpInst::isFPPredicate(Pred
))
2610 return error("invalid floating-point predicate");
2612 Pred
= StringSwitch
<CmpInst::Predicate
>(Token
.stringValue())
2613 .Case("eq", CmpInst::ICMP_EQ
)
2614 .Case("ne", CmpInst::ICMP_NE
)
2615 .Case("sgt", CmpInst::ICMP_SGT
)
2616 .Case("sge", CmpInst::ICMP_SGE
)
2617 .Case("slt", CmpInst::ICMP_SLT
)
2618 .Case("sle", CmpInst::ICMP_SLE
)
2619 .Case("ugt", CmpInst::ICMP_UGT
)
2620 .Case("uge", CmpInst::ICMP_UGE
)
2621 .Case("ult", CmpInst::ICMP_ULT
)
2622 .Case("ule", CmpInst::ICMP_ULE
)
2623 .Default(CmpInst::BAD_ICMP_PREDICATE
);
2624 if (!CmpInst::isIntPredicate(Pred
))
2625 return error("invalid integer predicate");
2629 Dest
= MachineOperand::CreatePredicate(Pred
);
2630 if (expectAndConsume(MIToken::rparen
))
2631 return error("predicate should be terminated by ')'.");
2636 bool MIParser::parseShuffleMaskOperand(MachineOperand
&Dest
) {
2637 assert(Token
.is(MIToken::kw_shufflemask
));
2640 if (expectAndConsume(MIToken::lparen
))
2641 return error("expected syntax shufflemask(<integer or undef>, ...)");
2643 SmallVector
<int, 32> ShufMask
;
2645 if (Token
.is(MIToken::kw_undef
)) {
2646 ShufMask
.push_back(-1);
2647 } else if (Token
.is(MIToken::IntegerLiteral
)) {
2648 const APSInt
&Int
= Token
.integerValue();
2649 ShufMask
.push_back(Int
.getExtValue());
2651 return error("expected integer constant");
2654 } while (consumeIfPresent(MIToken::comma
));
2656 if (expectAndConsume(MIToken::rparen
))
2657 return error("shufflemask should be terminated by ')'.");
2659 ArrayRef
<int> MaskAlloc
= MF
.allocateShuffleMask(ShufMask
);
2660 Dest
= MachineOperand::CreateShuffleMask(MaskAlloc
);
2664 bool MIParser::parseTargetIndexOperand(MachineOperand
&Dest
) {
2665 assert(Token
.is(MIToken::kw_target_index
));
2667 if (expectAndConsume(MIToken::lparen
))
2669 if (Token
.isNot(MIToken::Identifier
))
2670 return error("expected the name of the target index");
2672 if (PFS
.Target
.getTargetIndex(Token
.stringValue(), Index
))
2673 return error("use of undefined target index '" + Token
.stringValue() + "'");
2675 if (expectAndConsume(MIToken::rparen
))
2677 Dest
= MachineOperand::CreateTargetIndex(unsigned(Index
), /*Offset=*/0);
2678 if (parseOperandsOffset(Dest
))
2683 bool MIParser::parseCustomRegisterMaskOperand(MachineOperand
&Dest
) {
2684 assert(Token
.stringValue() == "CustomRegMask" && "Expected a custom RegMask");
2686 if (expectAndConsume(MIToken::lparen
))
2689 uint32_t *Mask
= MF
.allocateRegMask();
2691 if (Token
.isNot(MIToken::NamedRegister
))
2692 return error("expected a named register");
2694 if (parseNamedRegister(Reg
))
2697 Mask
[Reg
/ 32] |= 1U << (Reg
% 32);
2698 // TODO: Report an error if the same register is used more than once.
2699 if (Token
.isNot(MIToken::comma
))
2704 if (expectAndConsume(MIToken::rparen
))
2706 Dest
= MachineOperand::CreateRegMask(Mask
);
2710 bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand
&Dest
) {
2711 assert(Token
.is(MIToken::kw_liveout
));
2712 uint32_t *Mask
= MF
.allocateRegMask();
2714 if (expectAndConsume(MIToken::lparen
))
2717 if (Token
.isNot(MIToken::NamedRegister
))
2718 return error("expected a named register");
2720 if (parseNamedRegister(Reg
))
2723 Mask
[Reg
/ 32] |= 1U << (Reg
% 32);
2724 // TODO: Report an error if the same register is used more than once.
2725 if (Token
.isNot(MIToken::comma
))
2729 if (expectAndConsume(MIToken::rparen
))
2731 Dest
= MachineOperand::CreateRegLiveOut(Mask
);
2735 bool MIParser::parseMachineOperand(const unsigned OpCode
, const unsigned OpIdx
,
2736 MachineOperand
&Dest
,
2737 Optional
<unsigned> &TiedDefIdx
) {
2738 switch (Token
.kind()) {
2739 case MIToken::kw_implicit
:
2740 case MIToken::kw_implicit_define
:
2741 case MIToken::kw_def
:
2742 case MIToken::kw_dead
:
2743 case MIToken::kw_killed
:
2744 case MIToken::kw_undef
:
2745 case MIToken::kw_internal
:
2746 case MIToken::kw_early_clobber
:
2747 case MIToken::kw_debug_use
:
2748 case MIToken::kw_renamable
:
2749 case MIToken::underscore
:
2750 case MIToken::NamedRegister
:
2751 case MIToken::VirtualRegister
:
2752 case MIToken::NamedVirtualRegister
:
2753 return parseRegisterOperand(Dest
, TiedDefIdx
);
2754 case MIToken::IntegerLiteral
:
2755 return parseImmediateOperand(Dest
);
2756 case MIToken::kw_half
:
2757 case MIToken::kw_float
:
2758 case MIToken::kw_double
:
2759 case MIToken::kw_x86_fp80
:
2760 case MIToken::kw_fp128
:
2761 case MIToken::kw_ppc_fp128
:
2762 return parseFPImmediateOperand(Dest
);
2763 case MIToken::MachineBasicBlock
:
2764 return parseMBBOperand(Dest
);
2765 case MIToken::StackObject
:
2766 return parseStackObjectOperand(Dest
);
2767 case MIToken::FixedStackObject
:
2768 return parseFixedStackObjectOperand(Dest
);
2769 case MIToken::GlobalValue
:
2770 case MIToken::NamedGlobalValue
:
2771 return parseGlobalAddressOperand(Dest
);
2772 case MIToken::ConstantPoolItem
:
2773 return parseConstantPoolIndexOperand(Dest
);
2774 case MIToken::JumpTableIndex
:
2775 return parseJumpTableIndexOperand(Dest
);
2776 case MIToken::ExternalSymbol
:
2777 return parseExternalSymbolOperand(Dest
);
2778 case MIToken::MCSymbol
:
2779 return parseMCSymbolOperand(Dest
);
2780 case MIToken::SubRegisterIndex
:
2781 return parseSubRegisterIndexOperand(Dest
);
2782 case MIToken::md_diexpr
:
2783 case MIToken::exclaim
:
2784 return parseMetadataOperand(Dest
);
2785 case MIToken::kw_cfi_same_value
:
2786 case MIToken::kw_cfi_offset
:
2787 case MIToken::kw_cfi_rel_offset
:
2788 case MIToken::kw_cfi_def_cfa_register
:
2789 case MIToken::kw_cfi_def_cfa_offset
:
2790 case MIToken::kw_cfi_adjust_cfa_offset
:
2791 case MIToken::kw_cfi_escape
:
2792 case MIToken::kw_cfi_def_cfa
:
2793 case MIToken::kw_cfi_llvm_def_aspace_cfa
:
2794 case MIToken::kw_cfi_register
:
2795 case MIToken::kw_cfi_remember_state
:
2796 case MIToken::kw_cfi_restore
:
2797 case MIToken::kw_cfi_restore_state
:
2798 case MIToken::kw_cfi_undefined
:
2799 case MIToken::kw_cfi_window_save
:
2800 case MIToken::kw_cfi_aarch64_negate_ra_sign_state
:
2801 return parseCFIOperand(Dest
);
2802 case MIToken::kw_blockaddress
:
2803 return parseBlockAddressOperand(Dest
);
2804 case MIToken::kw_intrinsic
:
2805 return parseIntrinsicOperand(Dest
);
2806 case MIToken::kw_target_index
:
2807 return parseTargetIndexOperand(Dest
);
2808 case MIToken::kw_liveout
:
2809 return parseLiveoutRegisterMaskOperand(Dest
);
2810 case MIToken::kw_floatpred
:
2811 case MIToken::kw_intpred
:
2812 return parsePredicateOperand(Dest
);
2813 case MIToken::kw_shufflemask
:
2814 return parseShuffleMaskOperand(Dest
);
2815 case MIToken::Error
:
2817 case MIToken::Identifier
:
2818 if (const auto *RegMask
= PFS
.Target
.getRegMask(Token
.stringValue())) {
2819 Dest
= MachineOperand::CreateRegMask(RegMask
);
2822 } else if (Token
.stringValue() == "CustomRegMask") {
2823 return parseCustomRegisterMaskOperand(Dest
);
2825 return parseTypedImmediateOperand(Dest
);
2826 case MIToken::dot
: {
2827 const auto *TII
= MF
.getSubtarget().getInstrInfo();
2828 if (const auto *Formatter
= TII
->getMIRFormatter()) {
2829 return parseTargetImmMnemonic(OpCode
, OpIdx
, Dest
, *Formatter
);
2834 // FIXME: Parse the MCSymbol machine operand.
2835 return error("expected a machine operand");
2840 bool MIParser::parseMachineOperandAndTargetFlags(
2841 const unsigned OpCode
, const unsigned OpIdx
, MachineOperand
&Dest
,
2842 Optional
<unsigned> &TiedDefIdx
) {
2844 bool HasTargetFlags
= false;
2845 if (Token
.is(MIToken::kw_target_flags
)) {
2846 HasTargetFlags
= true;
2848 if (expectAndConsume(MIToken::lparen
))
2850 if (Token
.isNot(MIToken::Identifier
))
2851 return error("expected the name of the target flag");
2852 if (PFS
.Target
.getDirectTargetFlag(Token
.stringValue(), TF
)) {
2853 if (PFS
.Target
.getBitmaskTargetFlag(Token
.stringValue(), TF
))
2854 return error("use of undefined target flag '" + Token
.stringValue() +
2858 while (Token
.is(MIToken::comma
)) {
2860 if (Token
.isNot(MIToken::Identifier
))
2861 return error("expected the name of the target flag");
2862 unsigned BitFlag
= 0;
2863 if (PFS
.Target
.getBitmaskTargetFlag(Token
.stringValue(), BitFlag
))
2864 return error("use of undefined target flag '" + Token
.stringValue() +
2866 // TODO: Report an error when using a duplicate bit target flag.
2870 if (expectAndConsume(MIToken::rparen
))
2873 auto Loc
= Token
.location();
2874 if (parseMachineOperand(OpCode
, OpIdx
, Dest
, TiedDefIdx
))
2876 if (!HasTargetFlags
)
2879 return error(Loc
, "register operands can't have target flags");
2880 Dest
.setTargetFlags(TF
);
2884 bool MIParser::parseOffset(int64_t &Offset
) {
2885 if (Token
.isNot(MIToken::plus
) && Token
.isNot(MIToken::minus
))
2887 StringRef Sign
= Token
.range();
2888 bool IsNegative
= Token
.is(MIToken::minus
);
2890 if (Token
.isNot(MIToken::IntegerLiteral
))
2891 return error("expected an integer literal after '" + Sign
+ "'");
2892 if (Token
.integerValue().getMinSignedBits() > 64)
2893 return error("expected 64-bit integer (too large)");
2894 Offset
= Token
.integerValue().getExtValue();
2901 bool MIParser::parseAlignment(unsigned &Alignment
) {
2902 assert(Token
.is(MIToken::kw_align
) || Token
.is(MIToken::kw_basealign
));
2904 if (Token
.isNot(MIToken::IntegerLiteral
) || Token
.integerValue().isSigned())
2905 return error("expected an integer literal after 'align'");
2906 if (getUnsigned(Alignment
))
2910 if (!isPowerOf2_32(Alignment
))
2911 return error("expected a power-of-2 literal after 'align'");
2916 bool MIParser::parseAddrspace(unsigned &Addrspace
) {
2917 assert(Token
.is(MIToken::kw_addrspace
));
2919 if (Token
.isNot(MIToken::IntegerLiteral
) || Token
.integerValue().isSigned())
2920 return error("expected an integer literal after 'addrspace'");
2921 if (getUnsigned(Addrspace
))
2927 bool MIParser::parseOperandsOffset(MachineOperand
&Op
) {
2929 if (parseOffset(Offset
))
2931 Op
.setOffset(Offset
);
2935 static bool parseIRValue(const MIToken
&Token
, PerFunctionMIParsingState
&PFS
,
2936 const Value
*&V
, ErrorCallbackType ErrCB
) {
2937 switch (Token
.kind()) {
2938 case MIToken::NamedIRValue
: {
2939 V
= PFS
.MF
.getFunction().getValueSymbolTable()->lookup(Token
.stringValue());
2942 case MIToken::IRValue
: {
2943 unsigned SlotNumber
= 0;
2944 if (getUnsigned(Token
, SlotNumber
, ErrCB
))
2946 V
= PFS
.getIRValue(SlotNumber
);
2949 case MIToken::NamedGlobalValue
:
2950 case MIToken::GlobalValue
: {
2951 GlobalValue
*GV
= nullptr;
2952 if (parseGlobalValue(Token
, PFS
, GV
, ErrCB
))
2957 case MIToken::QuotedIRValue
: {
2958 const Constant
*C
= nullptr;
2959 if (parseIRConstant(Token
.location(), Token
.stringValue(), PFS
, C
, ErrCB
))
2964 case MIToken::kw_unknown_address
:
2968 llvm_unreachable("The current token should be an IR block reference");
2971 return ErrCB(Token
.location(), Twine("use of undefined IR value '") + Token
.range() + "'");
2975 bool MIParser::parseIRValue(const Value
*&V
) {
2976 return ::parseIRValue(
2977 Token
, PFS
, V
, [this](StringRef::iterator Loc
, const Twine
&Msg
) -> bool {
2978 return error(Loc
, Msg
);
2982 bool MIParser::getUint64(uint64_t &Result
) {
2983 if (Token
.hasIntegerValue()) {
2984 if (Token
.integerValue().getActiveBits() > 64)
2985 return error("expected 64-bit integer (too large)");
2986 Result
= Token
.integerValue().getZExtValue();
2989 if (Token
.is(MIToken::HexLiteral
)) {
2993 if (A
.getBitWidth() > 64)
2994 return error("expected 64-bit integer (too large)");
2995 Result
= A
.getZExtValue();
3001 bool MIParser::getHexUint(APInt
&Result
) {
3002 return ::getHexUint(Token
, Result
);
3005 bool MIParser::parseMemoryOperandFlag(MachineMemOperand::Flags
&Flags
) {
3006 const auto OldFlags
= Flags
;
3007 switch (Token
.kind()) {
3008 case MIToken::kw_volatile
:
3009 Flags
|= MachineMemOperand::MOVolatile
;
3011 case MIToken::kw_non_temporal
:
3012 Flags
|= MachineMemOperand::MONonTemporal
;
3014 case MIToken::kw_dereferenceable
:
3015 Flags
|= MachineMemOperand::MODereferenceable
;
3017 case MIToken::kw_invariant
:
3018 Flags
|= MachineMemOperand::MOInvariant
;
3020 case MIToken::StringConstant
: {
3021 MachineMemOperand::Flags TF
;
3022 if (PFS
.Target
.getMMOTargetFlag(Token
.stringValue(), TF
))
3023 return error("use of undefined target MMO flag '" + Token
.stringValue() +
3029 llvm_unreachable("The current token should be a memory operand flag");
3031 if (OldFlags
== Flags
)
3032 // We know that the same flag is specified more than once when the flags
3033 // weren't modified.
3034 return error("duplicate '" + Token
.stringValue() + "' memory operand flag");
3039 bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue
*&PSV
) {
3040 switch (Token
.kind()) {
3041 case MIToken::kw_stack
:
3042 PSV
= MF
.getPSVManager().getStack();
3044 case MIToken::kw_got
:
3045 PSV
= MF
.getPSVManager().getGOT();
3047 case MIToken::kw_jump_table
:
3048 PSV
= MF
.getPSVManager().getJumpTable();
3050 case MIToken::kw_constant_pool
:
3051 PSV
= MF
.getPSVManager().getConstantPool();
3053 case MIToken::FixedStackObject
: {
3055 if (parseFixedStackFrameIndex(FI
))
3057 PSV
= MF
.getPSVManager().getFixedStack(FI
);
3058 // The token was already consumed, so use return here instead of break.
3061 case MIToken::StackObject
: {
3063 if (parseStackFrameIndex(FI
))
3065 PSV
= MF
.getPSVManager().getFixedStack(FI
);
3066 // The token was already consumed, so use return here instead of break.
3069 case MIToken::kw_call_entry
:
3071 switch (Token
.kind()) {
3072 case MIToken::GlobalValue
:
3073 case MIToken::NamedGlobalValue
: {
3074 GlobalValue
*GV
= nullptr;
3075 if (parseGlobalValue(GV
))
3077 PSV
= MF
.getPSVManager().getGlobalValueCallEntry(GV
);
3080 case MIToken::ExternalSymbol
:
3081 PSV
= MF
.getPSVManager().getExternalSymbolCallEntry(
3082 MF
.createExternalSymbolName(Token
.stringValue()));
3086 "expected a global value or an external symbol after 'call-entry'");
3089 case MIToken::kw_custom
: {
3091 const auto *TII
= MF
.getSubtarget().getInstrInfo();
3092 if (const auto *Formatter
= TII
->getMIRFormatter()) {
3093 if (Formatter
->parseCustomPseudoSourceValue(
3094 Token
.stringValue(), MF
, PFS
, PSV
,
3095 [this](StringRef::iterator Loc
, const Twine
&Msg
) -> bool {
3096 return error(Loc
, Msg
);
3100 return error("unable to parse target custom pseudo source value");
3104 llvm_unreachable("The current token should be pseudo source value");
3110 bool MIParser::parseMachinePointerInfo(MachinePointerInfo
&Dest
) {
3111 if (Token
.is(MIToken::kw_constant_pool
) || Token
.is(MIToken::kw_stack
) ||
3112 Token
.is(MIToken::kw_got
) || Token
.is(MIToken::kw_jump_table
) ||
3113 Token
.is(MIToken::FixedStackObject
) || Token
.is(MIToken::StackObject
) ||
3114 Token
.is(MIToken::kw_call_entry
) || Token
.is(MIToken::kw_custom
)) {
3115 const PseudoSourceValue
*PSV
= nullptr;
3116 if (parseMemoryPseudoSourceValue(PSV
))
3119 if (parseOffset(Offset
))
3121 Dest
= MachinePointerInfo(PSV
, Offset
);
3124 if (Token
.isNot(MIToken::NamedIRValue
) && Token
.isNot(MIToken::IRValue
) &&
3125 Token
.isNot(MIToken::GlobalValue
) &&
3126 Token
.isNot(MIToken::NamedGlobalValue
) &&
3127 Token
.isNot(MIToken::QuotedIRValue
) &&
3128 Token
.isNot(MIToken::kw_unknown_address
))
3129 return error("expected an IR value reference");
3130 const Value
*V
= nullptr;
3131 if (parseIRValue(V
))
3133 if (V
&& !V
->getType()->isPointerTy())
3134 return error("expected a pointer IR value");
3137 if (parseOffset(Offset
))
3139 Dest
= MachinePointerInfo(V
, Offset
);
3143 bool MIParser::parseOptionalScope(LLVMContext
&Context
,
3144 SyncScope::ID
&SSID
) {
3145 SSID
= SyncScope::System
;
3146 if (Token
.is(MIToken::Identifier
) && Token
.stringValue() == "syncscope") {
3148 if (expectAndConsume(MIToken::lparen
))
3149 return error("expected '(' in syncscope");
3152 if (parseStringConstant(SSN
))
3155 SSID
= Context
.getOrInsertSyncScopeID(SSN
);
3156 if (expectAndConsume(MIToken::rparen
))
3157 return error("expected ')' in syncscope");
3163 bool MIParser::parseOptionalAtomicOrdering(AtomicOrdering
&Order
) {
3164 Order
= AtomicOrdering::NotAtomic
;
3165 if (Token
.isNot(MIToken::Identifier
))
3168 Order
= StringSwitch
<AtomicOrdering
>(Token
.stringValue())
3169 .Case("unordered", AtomicOrdering::Unordered
)
3170 .Case("monotonic", AtomicOrdering::Monotonic
)
3171 .Case("acquire", AtomicOrdering::Acquire
)
3172 .Case("release", AtomicOrdering::Release
)
3173 .Case("acq_rel", AtomicOrdering::AcquireRelease
)
3174 .Case("seq_cst", AtomicOrdering::SequentiallyConsistent
)
3175 .Default(AtomicOrdering::NotAtomic
);
3177 if (Order
!= AtomicOrdering::NotAtomic
) {
3182 return error("expected an atomic scope, ordering or a size specification");
3185 bool MIParser::parseMachineMemoryOperand(MachineMemOperand
*&Dest
) {
3186 if (expectAndConsume(MIToken::lparen
))
3188 MachineMemOperand::Flags Flags
= MachineMemOperand::MONone
;
3189 while (Token
.isMemoryOperandFlag()) {
3190 if (parseMemoryOperandFlag(Flags
))
3193 if (Token
.isNot(MIToken::Identifier
) ||
3194 (Token
.stringValue() != "load" && Token
.stringValue() != "store"))
3195 return error("expected 'load' or 'store' memory operation");
3196 if (Token
.stringValue() == "load")
3197 Flags
|= MachineMemOperand::MOLoad
;
3199 Flags
|= MachineMemOperand::MOStore
;
3202 // Optional 'store' for operands that both load and store.
3203 if (Token
.is(MIToken::Identifier
) && Token
.stringValue() == "store") {
3204 Flags
|= MachineMemOperand::MOStore
;
3208 // Optional synchronization scope.
3210 if (parseOptionalScope(MF
.getFunction().getContext(), SSID
))
3213 // Up to two atomic orderings (cmpxchg provides guarantees on failure).
3214 AtomicOrdering Order
, FailureOrder
;
3215 if (parseOptionalAtomicOrdering(Order
))
3218 if (parseOptionalAtomicOrdering(FailureOrder
))
3222 if (Token
.isNot(MIToken::IntegerLiteral
) &&
3223 Token
.isNot(MIToken::kw_unknown_size
) &&
3224 Token
.isNot(MIToken::lparen
))
3225 return error("expected memory LLT, the size integer literal or 'unknown-size' after "
3226 "memory operation");
3228 uint64_t Size
= MemoryLocation::UnknownSize
;
3229 if (Token
.is(MIToken::IntegerLiteral
)) {
3230 if (getUint64(Size
))
3233 // Convert from bytes to bits for storage.
3234 MemoryType
= LLT::scalar(8 * Size
);
3236 } else if (Token
.is(MIToken::kw_unknown_size
)) {
3237 Size
= MemoryLocation::UnknownSize
;
3240 if (expectAndConsume(MIToken::lparen
))
3242 if (parseLowLevelType(Token
.location(), MemoryType
))
3244 if (expectAndConsume(MIToken::rparen
))
3247 Size
= MemoryType
.getSizeInBytes();
3250 MachinePointerInfo Ptr
= MachinePointerInfo();
3251 if (Token
.is(MIToken::Identifier
)) {
3253 ((Flags
& MachineMemOperand::MOLoad
) &&
3254 (Flags
& MachineMemOperand::MOStore
))
3256 : Flags
& MachineMemOperand::MOLoad
? "from" : "into";
3257 if (Token
.stringValue() != Word
)
3258 return error(Twine("expected '") + Word
+ "'");
3261 if (parseMachinePointerInfo(Ptr
))
3264 unsigned BaseAlignment
=
3265 (Size
!= MemoryLocation::UnknownSize
? PowerOf2Ceil(Size
) : 1);
3267 MDNode
*Range
= nullptr;
3268 while (consumeIfPresent(MIToken::comma
)) {
3269 switch (Token
.kind()) {
3270 case MIToken::kw_align
:
3271 // align is printed if it is different than size.
3272 if (parseAlignment(BaseAlignment
))
3275 case MIToken::kw_basealign
:
3276 // basealign is printed if it is different than align.
3277 if (parseAlignment(BaseAlignment
))
3280 case MIToken::kw_addrspace
:
3281 if (parseAddrspace(Ptr
.AddrSpace
))
3284 case MIToken::md_tbaa
:
3286 if (parseMDNode(AAInfo
.TBAA
))
3289 case MIToken::md_alias_scope
:
3291 if (parseMDNode(AAInfo
.Scope
))
3294 case MIToken::md_noalias
:
3296 if (parseMDNode(AAInfo
.NoAlias
))
3299 case MIToken::md_range
:
3301 if (parseMDNode(Range
))
3304 // TODO: Report an error on duplicate metadata nodes.
3306 return error("expected 'align' or '!tbaa' or '!alias.scope' or "
3307 "'!noalias' or '!range'");
3310 if (expectAndConsume(MIToken::rparen
))
3312 Dest
= MF
.getMachineMemOperand(Ptr
, Flags
, MemoryType
, Align(BaseAlignment
),
3313 AAInfo
, Range
, SSID
, Order
, FailureOrder
);
3317 bool MIParser::parsePreOrPostInstrSymbol(MCSymbol
*&Symbol
) {
3318 assert((Token
.is(MIToken::kw_pre_instr_symbol
) ||
3319 Token
.is(MIToken::kw_post_instr_symbol
)) &&
3320 "Invalid token for a pre- post-instruction symbol!");
3322 if (Token
.isNot(MIToken::MCSymbol
))
3323 return error("expected a symbol after 'pre-instr-symbol'");
3324 Symbol
= getOrCreateMCSymbol(Token
.stringValue());
3326 if (Token
.isNewlineOrEOF() || Token
.is(MIToken::coloncolon
) ||
3327 Token
.is(MIToken::lbrace
))
3329 if (Token
.isNot(MIToken::comma
))
3330 return error("expected ',' before the next machine operand");
3335 bool MIParser::parseHeapAllocMarker(MDNode
*&Node
) {
3336 assert(Token
.is(MIToken::kw_heap_alloc_marker
) &&
3337 "Invalid token for a heap alloc marker!");
3341 return error("expected a MDNode after 'heap-alloc-marker'");
3342 if (Token
.isNewlineOrEOF() || Token
.is(MIToken::coloncolon
) ||
3343 Token
.is(MIToken::lbrace
))
3345 if (Token
.isNot(MIToken::comma
))
3346 return error("expected ',' before the next machine operand");
3351 static void initSlots2BasicBlocks(
3353 DenseMap
<unsigned, const BasicBlock
*> &Slots2BasicBlocks
) {
3354 ModuleSlotTracker
MST(F
.getParent(), /*ShouldInitializeAllMetadata=*/false);
3355 MST
.incorporateFunction(F
);
3356 for (auto &BB
: F
) {
3359 int Slot
= MST
.getLocalSlot(&BB
);
3362 Slots2BasicBlocks
.insert(std::make_pair(unsigned(Slot
), &BB
));
3366 static const BasicBlock
*getIRBlockFromSlot(
3368 const DenseMap
<unsigned, const BasicBlock
*> &Slots2BasicBlocks
) {
3369 return Slots2BasicBlocks
.lookup(Slot
);
3372 const BasicBlock
*MIParser::getIRBlock(unsigned Slot
) {
3373 if (Slots2BasicBlocks
.empty())
3374 initSlots2BasicBlocks(MF
.getFunction(), Slots2BasicBlocks
);
3375 return getIRBlockFromSlot(Slot
, Slots2BasicBlocks
);
3378 const BasicBlock
*MIParser::getIRBlock(unsigned Slot
, const Function
&F
) {
3379 if (&F
== &MF
.getFunction())
3380 return getIRBlock(Slot
);
3381 DenseMap
<unsigned, const BasicBlock
*> CustomSlots2BasicBlocks
;
3382 initSlots2BasicBlocks(F
, CustomSlots2BasicBlocks
);
3383 return getIRBlockFromSlot(Slot
, CustomSlots2BasicBlocks
);
3386 MCSymbol
*MIParser::getOrCreateMCSymbol(StringRef Name
) {
3387 // FIXME: Currently we can't recognize temporary or local symbols and call all
3388 // of the appropriate forms to create them. However, this handles basic cases
3389 // well as most of the special aspects are recognized by a prefix on their
3390 // name, and the input names should already be unique. For test cases, keeping
3391 // the symbol name out of the symbol table isn't terribly important.
3392 return MF
.getContext().getOrCreateSymbol(Name
);
3395 bool MIParser::parseStringConstant(std::string
&Result
) {
3396 if (Token
.isNot(MIToken::StringConstant
))
3397 return error("expected string constant");
3398 Result
= std::string(Token
.stringValue());
3403 bool llvm::parseMachineBasicBlockDefinitions(PerFunctionMIParsingState
&PFS
,
3405 SMDiagnostic
&Error
) {
3406 return MIParser(PFS
, Error
, Src
).parseBasicBlockDefinitions(PFS
.MBBSlots
);
3409 bool llvm::parseMachineInstructions(PerFunctionMIParsingState
&PFS
,
3410 StringRef Src
, SMDiagnostic
&Error
) {
3411 return MIParser(PFS
, Error
, Src
).parseBasicBlocks();
3414 bool llvm::parseMBBReference(PerFunctionMIParsingState
&PFS
,
3415 MachineBasicBlock
*&MBB
, StringRef Src
,
3416 SMDiagnostic
&Error
) {
3417 return MIParser(PFS
, Error
, Src
).parseStandaloneMBB(MBB
);
3420 bool llvm::parseRegisterReference(PerFunctionMIParsingState
&PFS
,
3421 Register
&Reg
, StringRef Src
,
3422 SMDiagnostic
&Error
) {
3423 return MIParser(PFS
, Error
, Src
).parseStandaloneRegister(Reg
);
3426 bool llvm::parseNamedRegisterReference(PerFunctionMIParsingState
&PFS
,
3427 Register
&Reg
, StringRef Src
,
3428 SMDiagnostic
&Error
) {
3429 return MIParser(PFS
, Error
, Src
).parseStandaloneNamedRegister(Reg
);
3432 bool llvm::parseVirtualRegisterReference(PerFunctionMIParsingState
&PFS
,
3433 VRegInfo
*&Info
, StringRef Src
,
3434 SMDiagnostic
&Error
) {
3435 return MIParser(PFS
, Error
, Src
).parseStandaloneVirtualRegister(Info
);
3438 bool llvm::parseStackObjectReference(PerFunctionMIParsingState
&PFS
,
3439 int &FI
, StringRef Src
,
3440 SMDiagnostic
&Error
) {
3441 return MIParser(PFS
, Error
, Src
).parseStandaloneStackObject(FI
);
3444 bool llvm::parseMDNode(PerFunctionMIParsingState
&PFS
,
3445 MDNode
*&Node
, StringRef Src
, SMDiagnostic
&Error
) {
3446 return MIParser(PFS
, Error
, Src
).parseStandaloneMDNode(Node
);
3449 bool llvm::parseMachineMetadata(PerFunctionMIParsingState
&PFS
, StringRef Src
,
3450 SMRange SrcRange
, SMDiagnostic
&Error
) {
3451 return MIParser(PFS
, Error
, Src
, SrcRange
).parseMachineMetadata();
3454 bool MIRFormatter::parseIRValue(StringRef Src
, MachineFunction
&MF
,
3455 PerFunctionMIParsingState
&PFS
, const Value
*&V
,
3456 ErrorCallbackType ErrorCallback
) {
3458 Src
= lexMIToken(Src
, Token
, [&](StringRef::iterator Loc
, const Twine
&Msg
) {
3459 ErrorCallback(Loc
, Msg
);
3463 return ::parseIRValue(Token
, PFS
, V
, ErrorCallback
);