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/MIRPrinter.h"
32 #include "llvm/CodeGen/MachineBasicBlock.h"
33 #include "llvm/CodeGen/MachineFrameInfo.h"
34 #include "llvm/CodeGen/MachineFunction.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineMemOperand.h"
38 #include "llvm/CodeGen/MachineOperand.h"
39 #include "llvm/CodeGen/MachineRegisterInfo.h"
40 #include "llvm/CodeGen/TargetInstrInfo.h"
41 #include "llvm/CodeGen/TargetRegisterInfo.h"
42 #include "llvm/CodeGen/TargetSubtargetInfo.h"
43 #include "llvm/IR/BasicBlock.h"
44 #include "llvm/IR/Constants.h"
45 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/DebugInfoMetadata.h"
47 #include "llvm/IR/DebugLoc.h"
48 #include "llvm/IR/Function.h"
49 #include "llvm/IR/InstrTypes.h"
50 #include "llvm/IR/Instructions.h"
51 #include "llvm/IR/Intrinsics.h"
52 #include "llvm/IR/Metadata.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/IR/ModuleSlotTracker.h"
55 #include "llvm/IR/Type.h"
56 #include "llvm/IR/Value.h"
57 #include "llvm/IR/ValueSymbolTable.h"
58 #include "llvm/MC/LaneBitmask.h"
59 #include "llvm/MC/MCContext.h"
60 #include "llvm/MC/MCDwarf.h"
61 #include "llvm/MC/MCInstrDesc.h"
62 #include "llvm/MC/MCRegisterInfo.h"
63 #include "llvm/Support/AtomicOrdering.h"
64 #include "llvm/Support/BranchProbability.h"
65 #include "llvm/Support/Casting.h"
66 #include "llvm/Support/ErrorHandling.h"
67 #include "llvm/Support/LowLevelTypeImpl.h"
68 #include "llvm/Support/MemoryBuffer.h"
69 #include "llvm/Support/SMLoc.h"
70 #include "llvm/Support/SourceMgr.h"
71 #include "llvm/Support/raw_ostream.h"
72 #include "llvm/Target/TargetIntrinsicInfo.h"
73 #include "llvm/Target/TargetMachine.h"
85 void PerTargetMIParsingState::setTarget(
86 const TargetSubtargetInfo
&NewSubtarget
) {
88 // If the subtarget changed, over conservatively assume everything is invalid.
89 if (&Subtarget
== &NewSubtarget
)
92 Names2InstrOpCodes
.clear();
94 Names2RegMasks
.clear();
95 Names2SubRegIndices
.clear();
96 Names2TargetIndices
.clear();
97 Names2DirectTargetFlags
.clear();
98 Names2BitmaskTargetFlags
.clear();
99 Names2MMOTargetFlags
.clear();
101 initNames2RegClasses();
102 initNames2RegBanks();
105 void PerTargetMIParsingState::initNames2Regs() {
106 if (!Names2Regs
.empty())
109 // The '%noreg' register is the register 0.
110 Names2Regs
.insert(std::make_pair("noreg", 0));
111 const auto *TRI
= Subtarget
.getRegisterInfo();
112 assert(TRI
&& "Expected target register info");
114 for (unsigned I
= 0, E
= TRI
->getNumRegs(); I
< E
; ++I
) {
116 Names2Regs
.insert(std::make_pair(StringRef(TRI
->getName(I
)).lower(), I
))
119 assert(WasInserted
&& "Expected registers to be unique case-insensitively");
123 bool PerTargetMIParsingState::getRegisterByName(StringRef RegName
,
126 auto RegInfo
= Names2Regs
.find(RegName
);
127 if (RegInfo
== Names2Regs
.end())
129 Reg
= RegInfo
->getValue();
133 void PerTargetMIParsingState::initNames2InstrOpCodes() {
134 if (!Names2InstrOpCodes
.empty())
136 const auto *TII
= Subtarget
.getInstrInfo();
137 assert(TII
&& "Expected target instruction info");
138 for (unsigned I
= 0, E
= TII
->getNumOpcodes(); I
< E
; ++I
)
139 Names2InstrOpCodes
.insert(std::make_pair(StringRef(TII
->getName(I
)), I
));
142 bool PerTargetMIParsingState::parseInstrName(StringRef InstrName
,
144 initNames2InstrOpCodes();
145 auto InstrInfo
= Names2InstrOpCodes
.find(InstrName
);
146 if (InstrInfo
== Names2InstrOpCodes
.end())
148 OpCode
= InstrInfo
->getValue();
152 void PerTargetMIParsingState::initNames2RegMasks() {
153 if (!Names2RegMasks
.empty())
155 const auto *TRI
= Subtarget
.getRegisterInfo();
156 assert(TRI
&& "Expected target register info");
157 ArrayRef
<const uint32_t *> RegMasks
= TRI
->getRegMasks();
158 ArrayRef
<const char *> RegMaskNames
= TRI
->getRegMaskNames();
159 assert(RegMasks
.size() == RegMaskNames
.size());
160 for (size_t I
= 0, E
= RegMasks
.size(); I
< E
; ++I
)
161 Names2RegMasks
.insert(
162 std::make_pair(StringRef(RegMaskNames
[I
]).lower(), RegMasks
[I
]));
165 const uint32_t *PerTargetMIParsingState::getRegMask(StringRef Identifier
) {
166 initNames2RegMasks();
167 auto RegMaskInfo
= Names2RegMasks
.find(Identifier
);
168 if (RegMaskInfo
== Names2RegMasks
.end())
170 return RegMaskInfo
->getValue();
173 void PerTargetMIParsingState::initNames2SubRegIndices() {
174 if (!Names2SubRegIndices
.empty())
176 const TargetRegisterInfo
*TRI
= Subtarget
.getRegisterInfo();
177 for (unsigned I
= 1, E
= TRI
->getNumSubRegIndices(); I
< E
; ++I
)
178 Names2SubRegIndices
.insert(
179 std::make_pair(TRI
->getSubRegIndexName(I
), I
));
182 unsigned PerTargetMIParsingState::getSubRegIndex(StringRef Name
) {
183 initNames2SubRegIndices();
184 auto SubRegInfo
= Names2SubRegIndices
.find(Name
);
185 if (SubRegInfo
== Names2SubRegIndices
.end())
187 return SubRegInfo
->getValue();
190 void PerTargetMIParsingState::initNames2TargetIndices() {
191 if (!Names2TargetIndices
.empty())
193 const auto *TII
= Subtarget
.getInstrInfo();
194 assert(TII
&& "Expected target instruction info");
195 auto Indices
= TII
->getSerializableTargetIndices();
196 for (const auto &I
: Indices
)
197 Names2TargetIndices
.insert(std::make_pair(StringRef(I
.second
), I
.first
));
200 bool PerTargetMIParsingState::getTargetIndex(StringRef Name
, int &Index
) {
201 initNames2TargetIndices();
202 auto IndexInfo
= Names2TargetIndices
.find(Name
);
203 if (IndexInfo
== Names2TargetIndices
.end())
205 Index
= IndexInfo
->second
;
209 void PerTargetMIParsingState::initNames2DirectTargetFlags() {
210 if (!Names2DirectTargetFlags
.empty())
213 const auto *TII
= Subtarget
.getInstrInfo();
214 assert(TII
&& "Expected target instruction info");
215 auto Flags
= TII
->getSerializableDirectMachineOperandTargetFlags();
216 for (const auto &I
: Flags
)
217 Names2DirectTargetFlags
.insert(
218 std::make_pair(StringRef(I
.second
), I
.first
));
221 bool PerTargetMIParsingState::getDirectTargetFlag(StringRef Name
,
223 initNames2DirectTargetFlags();
224 auto FlagInfo
= Names2DirectTargetFlags
.find(Name
);
225 if (FlagInfo
== Names2DirectTargetFlags
.end())
227 Flag
= FlagInfo
->second
;
231 void PerTargetMIParsingState::initNames2BitmaskTargetFlags() {
232 if (!Names2BitmaskTargetFlags
.empty())
235 const auto *TII
= Subtarget
.getInstrInfo();
236 assert(TII
&& "Expected target instruction info");
237 auto Flags
= TII
->getSerializableBitmaskMachineOperandTargetFlags();
238 for (const auto &I
: Flags
)
239 Names2BitmaskTargetFlags
.insert(
240 std::make_pair(StringRef(I
.second
), I
.first
));
243 bool PerTargetMIParsingState::getBitmaskTargetFlag(StringRef Name
,
245 initNames2BitmaskTargetFlags();
246 auto FlagInfo
= Names2BitmaskTargetFlags
.find(Name
);
247 if (FlagInfo
== Names2BitmaskTargetFlags
.end())
249 Flag
= FlagInfo
->second
;
253 void PerTargetMIParsingState::initNames2MMOTargetFlags() {
254 if (!Names2MMOTargetFlags
.empty())
257 const auto *TII
= Subtarget
.getInstrInfo();
258 assert(TII
&& "Expected target instruction info");
259 auto Flags
= TII
->getSerializableMachineMemOperandTargetFlags();
260 for (const auto &I
: Flags
)
261 Names2MMOTargetFlags
.insert(std::make_pair(StringRef(I
.second
), I
.first
));
264 bool PerTargetMIParsingState::getMMOTargetFlag(StringRef Name
,
265 MachineMemOperand::Flags
&Flag
) {
266 initNames2MMOTargetFlags();
267 auto FlagInfo
= Names2MMOTargetFlags
.find(Name
);
268 if (FlagInfo
== Names2MMOTargetFlags
.end())
270 Flag
= FlagInfo
->second
;
274 void PerTargetMIParsingState::initNames2RegClasses() {
275 if (!Names2RegClasses
.empty())
278 const TargetRegisterInfo
*TRI
= Subtarget
.getRegisterInfo();
279 for (unsigned I
= 0, E
= TRI
->getNumRegClasses(); I
< E
; ++I
) {
280 const auto *RC
= TRI
->getRegClass(I
);
281 Names2RegClasses
.insert(
282 std::make_pair(StringRef(TRI
->getRegClassName(RC
)).lower(), RC
));
286 void PerTargetMIParsingState::initNames2RegBanks() {
287 if (!Names2RegBanks
.empty())
290 const RegisterBankInfo
*RBI
= Subtarget
.getRegBankInfo();
291 // If the target does not support GlobalISel, we may not have a
292 // register bank info.
296 for (unsigned I
= 0, E
= RBI
->getNumRegBanks(); I
< E
; ++I
) {
297 const auto &RegBank
= RBI
->getRegBank(I
);
298 Names2RegBanks
.insert(
299 std::make_pair(StringRef(RegBank
.getName()).lower(), &RegBank
));
303 const TargetRegisterClass
*
304 PerTargetMIParsingState::getRegClass(StringRef Name
) {
305 auto RegClassInfo
= Names2RegClasses
.find(Name
);
306 if (RegClassInfo
== Names2RegClasses
.end())
308 return RegClassInfo
->getValue();
311 const RegisterBank
*PerTargetMIParsingState::getRegBank(StringRef Name
) {
312 auto RegBankInfo
= Names2RegBanks
.find(Name
);
313 if (RegBankInfo
== Names2RegBanks
.end())
315 return RegBankInfo
->getValue();
318 PerFunctionMIParsingState::PerFunctionMIParsingState(MachineFunction
&MF
,
319 SourceMgr
&SM
, const SlotMapping
&IRSlots
, PerTargetMIParsingState
&T
)
320 : MF(MF
), SM(&SM
), IRSlots(IRSlots
), Target(T
) {
323 VRegInfo
&PerFunctionMIParsingState::getVRegInfo(unsigned Num
) {
324 auto I
= VRegInfos
.insert(std::make_pair(Num
, nullptr));
326 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
327 VRegInfo
*Info
= new (Allocator
) VRegInfo
;
328 Info
->VReg
= MRI
.createIncompleteVirtualRegister();
329 I
.first
->second
= Info
;
331 return *I
.first
->second
;
334 VRegInfo
&PerFunctionMIParsingState::getVRegInfoNamed(StringRef RegName
) {
335 assert(RegName
!= "" && "Expected named reg.");
337 auto I
= VRegInfosNamed
.insert(std::make_pair(RegName
.str(), nullptr));
339 VRegInfo
*Info
= new (Allocator
) VRegInfo
;
340 Info
->VReg
= MF
.getRegInfo().createIncompleteVirtualRegister(RegName
);
341 I
.first
->second
= Info
;
343 return *I
.first
->second
;
348 /// A wrapper struct around the 'MachineOperand' struct that includes a source
349 /// range and other attributes.
350 struct ParsedMachineOperand
{
351 MachineOperand Operand
;
352 StringRef::iterator Begin
;
353 StringRef::iterator End
;
354 Optional
<unsigned> TiedDefIdx
;
356 ParsedMachineOperand(const MachineOperand
&Operand
, StringRef::iterator Begin
,
357 StringRef::iterator End
, Optional
<unsigned> &TiedDefIdx
)
358 : Operand(Operand
), Begin(Begin
), End(End
), TiedDefIdx(TiedDefIdx
) {
360 assert(Operand
.isReg() && Operand
.isUse() &&
361 "Only used register operands can be tied");
368 StringRef Source
, CurrentSource
;
370 PerFunctionMIParsingState
&PFS
;
371 /// Maps from slot numbers to function's unnamed basic blocks.
372 DenseMap
<unsigned, const BasicBlock
*> Slots2BasicBlocks
;
373 /// Maps from slot numbers to function's unnamed values.
374 DenseMap
<unsigned, const Value
*> Slots2Values
;
377 MIParser(PerFunctionMIParsingState
&PFS
, SMDiagnostic
&Error
,
380 /// \p SkipChar gives the number of characters to skip before looking
381 /// for the next token.
382 void lex(unsigned SkipChar
= 0);
384 /// Report an error at the current location with the given message.
386 /// This function always return true.
387 bool error(const Twine
&Msg
);
389 /// Report an error at the given location with the given message.
391 /// This function always return true.
392 bool error(StringRef::iterator Loc
, const Twine
&Msg
);
395 parseBasicBlockDefinitions(DenseMap
<unsigned, MachineBasicBlock
*> &MBBSlots
);
396 bool parseBasicBlocks();
397 bool parse(MachineInstr
*&MI
);
398 bool parseStandaloneMBB(MachineBasicBlock
*&MBB
);
399 bool parseStandaloneNamedRegister(unsigned &Reg
);
400 bool parseStandaloneVirtualRegister(VRegInfo
*&Info
);
401 bool parseStandaloneRegister(unsigned &Reg
);
402 bool parseStandaloneStackObject(int &FI
);
403 bool parseStandaloneMDNode(MDNode
*&Node
);
406 parseBasicBlockDefinition(DenseMap
<unsigned, MachineBasicBlock
*> &MBBSlots
);
407 bool parseBasicBlock(MachineBasicBlock
&MBB
,
408 MachineBasicBlock
*&AddFalthroughFrom
);
409 bool parseBasicBlockLiveins(MachineBasicBlock
&MBB
);
410 bool parseBasicBlockSuccessors(MachineBasicBlock
&MBB
);
412 bool parseNamedRegister(unsigned &Reg
);
413 bool parseVirtualRegister(VRegInfo
*&Info
);
414 bool parseNamedVirtualRegister(VRegInfo
*&Info
);
415 bool parseRegister(unsigned &Reg
, VRegInfo
*&VRegInfo
);
416 bool parseRegisterFlag(unsigned &Flags
);
417 bool parseRegisterClassOrBank(VRegInfo
&RegInfo
);
418 bool parseSubRegisterIndex(unsigned &SubReg
);
419 bool parseRegisterTiedDefIndex(unsigned &TiedDefIdx
);
420 bool parseRegisterOperand(MachineOperand
&Dest
,
421 Optional
<unsigned> &TiedDefIdx
, bool IsDef
= false);
422 bool parseImmediateOperand(MachineOperand
&Dest
);
423 bool parseIRConstant(StringRef::iterator Loc
, StringRef StringValue
,
425 bool parseIRConstant(StringRef::iterator Loc
, const Constant
*&C
);
426 bool parseLowLevelType(StringRef::iterator Loc
, LLT
&Ty
);
427 bool parseTypedImmediateOperand(MachineOperand
&Dest
);
428 bool parseFPImmediateOperand(MachineOperand
&Dest
);
429 bool parseMBBReference(MachineBasicBlock
*&MBB
);
430 bool parseMBBOperand(MachineOperand
&Dest
);
431 bool parseStackFrameIndex(int &FI
);
432 bool parseStackObjectOperand(MachineOperand
&Dest
);
433 bool parseFixedStackFrameIndex(int &FI
);
434 bool parseFixedStackObjectOperand(MachineOperand
&Dest
);
435 bool parseGlobalValue(GlobalValue
*&GV
);
436 bool parseGlobalAddressOperand(MachineOperand
&Dest
);
437 bool parseConstantPoolIndexOperand(MachineOperand
&Dest
);
438 bool parseSubRegisterIndexOperand(MachineOperand
&Dest
);
439 bool parseJumpTableIndexOperand(MachineOperand
&Dest
);
440 bool parseExternalSymbolOperand(MachineOperand
&Dest
);
441 bool parseMCSymbolOperand(MachineOperand
&Dest
);
442 bool parseMDNode(MDNode
*&Node
);
443 bool parseDIExpression(MDNode
*&Expr
);
444 bool parseDILocation(MDNode
*&Expr
);
445 bool parseMetadataOperand(MachineOperand
&Dest
);
446 bool parseCFIOffset(int &Offset
);
447 bool parseCFIRegister(unsigned &Reg
);
448 bool parseCFIEscapeValues(std::string
& Values
);
449 bool parseCFIOperand(MachineOperand
&Dest
);
450 bool parseIRBlock(BasicBlock
*&BB
, const Function
&F
);
451 bool parseBlockAddressOperand(MachineOperand
&Dest
);
452 bool parseIntrinsicOperand(MachineOperand
&Dest
);
453 bool parsePredicateOperand(MachineOperand
&Dest
);
454 bool parseShuffleMaskOperand(MachineOperand
&Dest
);
455 bool parseTargetIndexOperand(MachineOperand
&Dest
);
456 bool parseCustomRegisterMaskOperand(MachineOperand
&Dest
);
457 bool parseLiveoutRegisterMaskOperand(MachineOperand
&Dest
);
458 bool parseMachineOperand(MachineOperand
&Dest
,
459 Optional
<unsigned> &TiedDefIdx
);
460 bool parseMachineOperandAndTargetFlags(MachineOperand
&Dest
,
461 Optional
<unsigned> &TiedDefIdx
);
462 bool parseOffset(int64_t &Offset
);
463 bool parseAlignment(unsigned &Alignment
);
464 bool parseAddrspace(unsigned &Addrspace
);
465 bool parseOperandsOffset(MachineOperand
&Op
);
466 bool parseIRValue(const Value
*&V
);
467 bool parseMemoryOperandFlag(MachineMemOperand::Flags
&Flags
);
468 bool parseMemoryPseudoSourceValue(const PseudoSourceValue
*&PSV
);
469 bool parseMachinePointerInfo(MachinePointerInfo
&Dest
);
470 bool parseOptionalScope(LLVMContext
&Context
, SyncScope::ID
&SSID
);
471 bool parseOptionalAtomicOrdering(AtomicOrdering
&Order
);
472 bool parseMachineMemoryOperand(MachineMemOperand
*&Dest
);
473 bool parsePreOrPostInstrSymbol(MCSymbol
*&Symbol
);
476 /// Convert the integer literal in the current token into an unsigned integer.
478 /// Return true if an error occurred.
479 bool getUnsigned(unsigned &Result
);
481 /// Convert the integer literal in the current token into an uint64.
483 /// Return true if an error occurred.
484 bool getUint64(uint64_t &Result
);
486 /// Convert the hexadecimal literal in the current token into an unsigned
487 /// APInt with a minimum bitwidth required to represent the value.
489 /// Return true if the literal does not represent an integer value.
490 bool getHexUint(APInt
&Result
);
492 /// If the current token is of the given kind, consume it and return false.
493 /// Otherwise report an error and return true.
494 bool expectAndConsume(MIToken::TokenKind TokenKind
);
496 /// If the current token is of the given kind, consume it and return true.
497 /// Otherwise return false.
498 bool consumeIfPresent(MIToken::TokenKind TokenKind
);
500 bool parseInstruction(unsigned &OpCode
, unsigned &Flags
);
502 bool assignRegisterTies(MachineInstr
&MI
,
503 ArrayRef
<ParsedMachineOperand
> Operands
);
505 bool verifyImplicitOperands(ArrayRef
<ParsedMachineOperand
> Operands
,
506 const MCInstrDesc
&MCID
);
508 const BasicBlock
*getIRBlock(unsigned Slot
);
509 const BasicBlock
*getIRBlock(unsigned Slot
, const Function
&F
);
511 const Value
*getIRValue(unsigned Slot
);
513 /// Get or create an MCSymbol for a given name.
514 MCSymbol
*getOrCreateMCSymbol(StringRef Name
);
516 /// parseStringConstant
517 /// ::= StringConstant
518 bool parseStringConstant(std::string
&Result
);
521 } // end anonymous namespace
523 MIParser::MIParser(PerFunctionMIParsingState
&PFS
, SMDiagnostic
&Error
,
525 : MF(PFS
.MF
), Error(Error
), Source(Source
), CurrentSource(Source
), PFS(PFS
)
528 void MIParser::lex(unsigned SkipChar
) {
529 CurrentSource
= lexMIToken(
530 CurrentSource
.data() + SkipChar
, Token
,
531 [this](StringRef::iterator Loc
, const Twine
&Msg
) { error(Loc
, Msg
); });
534 bool MIParser::error(const Twine
&Msg
) { return error(Token
.location(), Msg
); }
536 bool MIParser::error(StringRef::iterator Loc
, const Twine
&Msg
) {
537 const SourceMgr
&SM
= *PFS
.SM
;
538 assert(Loc
>= Source
.data() && Loc
<= (Source
.data() + Source
.size()));
539 const MemoryBuffer
&Buffer
= *SM
.getMemoryBuffer(SM
.getMainFileID());
540 if (Loc
>= Buffer
.getBufferStart() && Loc
<= Buffer
.getBufferEnd()) {
541 // Create an ordinary diagnostic when the source manager's buffer is the
543 Error
= SM
.GetMessage(SMLoc::getFromPointer(Loc
), SourceMgr::DK_Error
, Msg
);
546 // Create a diagnostic for a YAML string literal.
547 Error
= SMDiagnostic(SM
, SMLoc(), Buffer
.getBufferIdentifier(), 1,
548 Loc
- Source
.data(), SourceMgr::DK_Error
, Msg
.str(),
553 static const char *toString(MIToken::TokenKind TokenKind
) {
561 case MIToken::lparen
:
563 case MIToken::rparen
:
566 return "<unknown token>";
570 bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind
) {
571 if (Token
.isNot(TokenKind
))
572 return error(Twine("expected ") + toString(TokenKind
));
577 bool MIParser::consumeIfPresent(MIToken::TokenKind TokenKind
) {
578 if (Token
.isNot(TokenKind
))
584 bool MIParser::parseBasicBlockDefinition(
585 DenseMap
<unsigned, MachineBasicBlock
*> &MBBSlots
) {
586 assert(Token
.is(MIToken::MachineBasicBlockLabel
));
590 auto Loc
= Token
.location();
591 auto Name
= Token
.stringValue();
593 bool HasAddressTaken
= false;
594 bool IsLandingPad
= false;
595 unsigned Alignment
= 0;
596 BasicBlock
*BB
= nullptr;
597 if (consumeIfPresent(MIToken::lparen
)) {
599 // TODO: Report an error when multiple same attributes are specified.
600 switch (Token
.kind()) {
601 case MIToken::kw_address_taken
:
602 HasAddressTaken
= true;
605 case MIToken::kw_landing_pad
:
609 case MIToken::kw_align
:
610 if (parseAlignment(Alignment
))
613 case MIToken::IRBlock
:
614 // TODO: Report an error when both name and ir block are specified.
615 if (parseIRBlock(BB
, MF
.getFunction()))
622 } while (consumeIfPresent(MIToken::comma
));
623 if (expectAndConsume(MIToken::rparen
))
626 if (expectAndConsume(MIToken::colon
))
630 BB
= dyn_cast_or_null
<BasicBlock
>(
631 MF
.getFunction().getValueSymbolTable()->lookup(Name
));
633 return error(Loc
, Twine("basic block '") + Name
+
634 "' is not defined in the function '" +
637 auto *MBB
= MF
.CreateMachineBasicBlock(BB
);
638 MF
.insert(MF
.end(), MBB
);
639 bool WasInserted
= MBBSlots
.insert(std::make_pair(ID
, MBB
)).second
;
641 return error(Loc
, Twine("redefinition of machine basic block with id #") +
644 MBB
->setAlignment(Align(Alignment
));
646 MBB
->setHasAddressTaken();
647 MBB
->setIsEHPad(IsLandingPad
);
651 bool MIParser::parseBasicBlockDefinitions(
652 DenseMap
<unsigned, MachineBasicBlock
*> &MBBSlots
) {
654 // Skip until the first machine basic block.
655 while (Token
.is(MIToken::Newline
))
657 if (Token
.isErrorOrEOF())
658 return Token
.isError();
659 if (Token
.isNot(MIToken::MachineBasicBlockLabel
))
660 return error("expected a basic block definition before instructions");
661 unsigned BraceDepth
= 0;
663 if (parseBasicBlockDefinition(MBBSlots
))
665 bool IsAfterNewline
= false;
666 // Skip until the next machine basic block.
668 if ((Token
.is(MIToken::MachineBasicBlockLabel
) && IsAfterNewline
) ||
669 Token
.isErrorOrEOF())
671 else if (Token
.is(MIToken::MachineBasicBlockLabel
))
672 return error("basic block definition should be located at the start of "
674 else if (consumeIfPresent(MIToken::Newline
)) {
675 IsAfterNewline
= true;
678 IsAfterNewline
= false;
679 if (Token
.is(MIToken::lbrace
))
681 if (Token
.is(MIToken::rbrace
)) {
683 return error("extraneous closing brace ('}')");
688 // Verify that we closed all of the '{' at the end of a file or a block.
689 if (!Token
.isError() && BraceDepth
)
690 return error("expected '}'"); // FIXME: Report a note that shows '{'.
691 } while (!Token
.isErrorOrEOF());
692 return Token
.isError();
695 bool MIParser::parseBasicBlockLiveins(MachineBasicBlock
&MBB
) {
696 assert(Token
.is(MIToken::kw_liveins
));
698 if (expectAndConsume(MIToken::colon
))
700 if (Token
.isNewlineOrEOF()) // Allow an empty list of liveins.
703 if (Token
.isNot(MIToken::NamedRegister
))
704 return error("expected a named register");
706 if (parseNamedRegister(Reg
))
709 LaneBitmask Mask
= LaneBitmask::getAll();
710 if (consumeIfPresent(MIToken::colon
)) {
712 if (Token
.isNot(MIToken::IntegerLiteral
) &&
713 Token
.isNot(MIToken::HexLiteral
))
714 return error("expected a lane mask");
715 static_assert(sizeof(LaneBitmask::Type
) == sizeof(unsigned),
716 "Use correct get-function for lane mask");
719 return error("invalid lane mask value");
720 Mask
= LaneBitmask(V
);
723 MBB
.addLiveIn(Reg
, Mask
);
724 } while (consumeIfPresent(MIToken::comma
));
728 bool MIParser::parseBasicBlockSuccessors(MachineBasicBlock
&MBB
) {
729 assert(Token
.is(MIToken::kw_successors
));
731 if (expectAndConsume(MIToken::colon
))
733 if (Token
.isNewlineOrEOF()) // Allow an empty list of successors.
736 if (Token
.isNot(MIToken::MachineBasicBlock
))
737 return error("expected a machine basic block reference");
738 MachineBasicBlock
*SuccMBB
= nullptr;
739 if (parseMBBReference(SuccMBB
))
743 if (consumeIfPresent(MIToken::lparen
)) {
744 if (Token
.isNot(MIToken::IntegerLiteral
) &&
745 Token
.isNot(MIToken::HexLiteral
))
746 return error("expected an integer literal after '('");
747 if (getUnsigned(Weight
))
750 if (expectAndConsume(MIToken::rparen
))
753 MBB
.addSuccessor(SuccMBB
, BranchProbability::getRaw(Weight
));
754 } while (consumeIfPresent(MIToken::comma
));
755 MBB
.normalizeSuccProbs();
759 bool MIParser::parseBasicBlock(MachineBasicBlock
&MBB
,
760 MachineBasicBlock
*&AddFalthroughFrom
) {
761 // Skip the definition.
762 assert(Token
.is(MIToken::MachineBasicBlockLabel
));
764 if (consumeIfPresent(MIToken::lparen
)) {
765 while (Token
.isNot(MIToken::rparen
) && !Token
.isErrorOrEOF())
767 consumeIfPresent(MIToken::rparen
);
769 consumeIfPresent(MIToken::colon
);
771 // Parse the liveins and successors.
772 // N.B: Multiple lists of successors and liveins are allowed and they're
779 // liveins: %edi, %esi
780 bool ExplicitSuccessors
= false;
782 if (Token
.is(MIToken::kw_successors
)) {
783 if (parseBasicBlockSuccessors(MBB
))
785 ExplicitSuccessors
= true;
786 } else if (Token
.is(MIToken::kw_liveins
)) {
787 if (parseBasicBlockLiveins(MBB
))
789 } else if (consumeIfPresent(MIToken::Newline
)) {
793 if (!Token
.isNewlineOrEOF())
794 return error("expected line break at the end of a list");
798 // Parse the instructions.
799 bool IsInBundle
= false;
800 MachineInstr
*PrevMI
= nullptr;
801 while (!Token
.is(MIToken::MachineBasicBlockLabel
) &&
802 !Token
.is(MIToken::Eof
)) {
803 if (consumeIfPresent(MIToken::Newline
))
805 if (consumeIfPresent(MIToken::rbrace
)) {
806 // The first parsing pass should verify that all closing '}' have an
812 MachineInstr
*MI
= nullptr;
815 MBB
.insert(MBB
.end(), MI
);
817 PrevMI
->setFlag(MachineInstr::BundledSucc
);
818 MI
->setFlag(MachineInstr::BundledPred
);
821 if (Token
.is(MIToken::lbrace
)) {
823 return error("nested instruction bundles are not allowed");
825 // This instruction is the start of the bundle.
826 MI
->setFlag(MachineInstr::BundledSucc
);
828 if (!Token
.is(MIToken::Newline
))
829 // The next instruction can be on the same line.
832 assert(Token
.isNewlineOrEOF() && "MI is not fully parsed");
836 // Construct successor list by searching for basic block machine operands.
837 if (!ExplicitSuccessors
) {
838 SmallVector
<MachineBasicBlock
*,4> Successors
;
840 guessSuccessors(MBB
, Successors
, IsFallthrough
);
841 for (MachineBasicBlock
*Succ
: Successors
)
842 MBB
.addSuccessor(Succ
);
845 AddFalthroughFrom
= &MBB
;
847 MBB
.normalizeSuccProbs();
854 bool MIParser::parseBasicBlocks() {
856 // Skip until the first machine basic block.
857 while (Token
.is(MIToken::Newline
))
859 if (Token
.isErrorOrEOF())
860 return Token
.isError();
861 // The first parsing pass should have verified that this token is a MBB label
862 // in the 'parseBasicBlockDefinitions' method.
863 assert(Token
.is(MIToken::MachineBasicBlockLabel
));
864 MachineBasicBlock
*AddFalthroughFrom
= nullptr;
866 MachineBasicBlock
*MBB
= nullptr;
867 if (parseMBBReference(MBB
))
869 if (AddFalthroughFrom
) {
870 if (!AddFalthroughFrom
->isSuccessor(MBB
))
871 AddFalthroughFrom
->addSuccessor(MBB
);
872 AddFalthroughFrom
->normalizeSuccProbs();
873 AddFalthroughFrom
= nullptr;
875 if (parseBasicBlock(*MBB
, AddFalthroughFrom
))
877 // The method 'parseBasicBlock' should parse the whole block until the next
878 // block or the end of file.
879 assert(Token
.is(MIToken::MachineBasicBlockLabel
) || Token
.is(MIToken::Eof
));
880 } while (Token
.isNot(MIToken::Eof
));
884 bool MIParser::parse(MachineInstr
*&MI
) {
885 // Parse any register operands before '='
886 MachineOperand MO
= MachineOperand::CreateImm(0);
887 SmallVector
<ParsedMachineOperand
, 8> Operands
;
888 while (Token
.isRegister() || Token
.isRegisterFlag()) {
889 auto Loc
= Token
.location();
890 Optional
<unsigned> TiedDefIdx
;
891 if (parseRegisterOperand(MO
, TiedDefIdx
, /*IsDef=*/true))
894 ParsedMachineOperand(MO
, Loc
, Token
.location(), TiedDefIdx
));
895 if (Token
.isNot(MIToken::comma
))
899 if (!Operands
.empty() && expectAndConsume(MIToken::equal
))
902 unsigned OpCode
, Flags
= 0;
903 if (Token
.isError() || parseInstruction(OpCode
, Flags
))
906 // Parse the remaining machine operands.
907 while (!Token
.isNewlineOrEOF() && Token
.isNot(MIToken::kw_pre_instr_symbol
) &&
908 Token
.isNot(MIToken::kw_post_instr_symbol
) &&
909 Token
.isNot(MIToken::kw_debug_location
) &&
910 Token
.isNot(MIToken::coloncolon
) && Token
.isNot(MIToken::lbrace
)) {
911 auto Loc
= Token
.location();
912 Optional
<unsigned> TiedDefIdx
;
913 if (parseMachineOperandAndTargetFlags(MO
, TiedDefIdx
))
915 if (OpCode
== TargetOpcode::DBG_VALUE
&& MO
.isReg())
918 ParsedMachineOperand(MO
, Loc
, Token
.location(), TiedDefIdx
));
919 if (Token
.isNewlineOrEOF() || Token
.is(MIToken::coloncolon
) ||
920 Token
.is(MIToken::lbrace
))
922 if (Token
.isNot(MIToken::comma
))
923 return error("expected ',' before the next machine operand");
927 MCSymbol
*PreInstrSymbol
= nullptr;
928 if (Token
.is(MIToken::kw_pre_instr_symbol
))
929 if (parsePreOrPostInstrSymbol(PreInstrSymbol
))
931 MCSymbol
*PostInstrSymbol
= nullptr;
932 if (Token
.is(MIToken::kw_post_instr_symbol
))
933 if (parsePreOrPostInstrSymbol(PostInstrSymbol
))
936 DebugLoc DebugLocation
;
937 if (Token
.is(MIToken::kw_debug_location
)) {
939 MDNode
*Node
= nullptr;
940 if (Token
.is(MIToken::exclaim
)) {
941 if (parseMDNode(Node
))
943 } else if (Token
.is(MIToken::md_dilocation
)) {
944 if (parseDILocation(Node
))
947 return error("expected a metadata node after 'debug-location'");
948 if (!isa
<DILocation
>(Node
))
949 return error("referenced metadata is not a DILocation");
950 DebugLocation
= DebugLoc(Node
);
953 // Parse the machine memory operands.
954 SmallVector
<MachineMemOperand
*, 2> MemOperands
;
955 if (Token
.is(MIToken::coloncolon
)) {
957 while (!Token
.isNewlineOrEOF()) {
958 MachineMemOperand
*MemOp
= nullptr;
959 if (parseMachineMemoryOperand(MemOp
))
961 MemOperands
.push_back(MemOp
);
962 if (Token
.isNewlineOrEOF())
964 if (Token
.isNot(MIToken::comma
))
965 return error("expected ',' before the next machine memory operand");
970 const auto &MCID
= MF
.getSubtarget().getInstrInfo()->get(OpCode
);
971 if (!MCID
.isVariadic()) {
972 // FIXME: Move the implicit operand verification to the machine verifier.
973 if (verifyImplicitOperands(Operands
, MCID
))
977 // TODO: Check for extraneous machine operands.
978 MI
= MF
.CreateMachineInstr(MCID
, DebugLocation
, /*NoImplicit=*/true);
980 for (const auto &Operand
: Operands
)
981 MI
->addOperand(MF
, Operand
.Operand
);
982 if (assignRegisterTies(*MI
, Operands
))
985 MI
->setPreInstrSymbol(MF
, PreInstrSymbol
);
987 MI
->setPostInstrSymbol(MF
, PostInstrSymbol
);
988 if (!MemOperands
.empty())
989 MI
->setMemRefs(MF
, MemOperands
);
993 bool MIParser::parseStandaloneMBB(MachineBasicBlock
*&MBB
) {
995 if (Token
.isNot(MIToken::MachineBasicBlock
))
996 return error("expected a machine basic block reference");
997 if (parseMBBReference(MBB
))
1000 if (Token
.isNot(MIToken::Eof
))
1002 "expected end of string after the machine basic block reference");
1006 bool MIParser::parseStandaloneNamedRegister(unsigned &Reg
) {
1008 if (Token
.isNot(MIToken::NamedRegister
))
1009 return error("expected a named register");
1010 if (parseNamedRegister(Reg
))
1013 if (Token
.isNot(MIToken::Eof
))
1014 return error("expected end of string after the register reference");
1018 bool MIParser::parseStandaloneVirtualRegister(VRegInfo
*&Info
) {
1020 if (Token
.isNot(MIToken::VirtualRegister
))
1021 return error("expected a virtual register");
1022 if (parseVirtualRegister(Info
))
1025 if (Token
.isNot(MIToken::Eof
))
1026 return error("expected end of string after the register reference");
1030 bool MIParser::parseStandaloneRegister(unsigned &Reg
) {
1032 if (Token
.isNot(MIToken::NamedRegister
) &&
1033 Token
.isNot(MIToken::VirtualRegister
))
1034 return error("expected either a named or virtual register");
1037 if (parseRegister(Reg
, Info
))
1041 if (Token
.isNot(MIToken::Eof
))
1042 return error("expected end of string after the register reference");
1046 bool MIParser::parseStandaloneStackObject(int &FI
) {
1048 if (Token
.isNot(MIToken::StackObject
))
1049 return error("expected a stack object");
1050 if (parseStackFrameIndex(FI
))
1052 if (Token
.isNot(MIToken::Eof
))
1053 return error("expected end of string after the stack object reference");
1057 bool MIParser::parseStandaloneMDNode(MDNode
*&Node
) {
1059 if (Token
.is(MIToken::exclaim
)) {
1060 if (parseMDNode(Node
))
1062 } else if (Token
.is(MIToken::md_diexpr
)) {
1063 if (parseDIExpression(Node
))
1065 } else if (Token
.is(MIToken::md_dilocation
)) {
1066 if (parseDILocation(Node
))
1069 return error("expected a metadata node");
1070 if (Token
.isNot(MIToken::Eof
))
1071 return error("expected end of string after the metadata node");
1075 static const char *printImplicitRegisterFlag(const MachineOperand
&MO
) {
1076 assert(MO
.isImplicit());
1077 return MO
.isDef() ? "implicit-def" : "implicit";
1080 static std::string
getRegisterName(const TargetRegisterInfo
*TRI
,
1082 assert(Register::isPhysicalRegister(Reg
) && "expected phys reg");
1083 return StringRef(TRI
->getName(Reg
)).lower();
1086 /// Return true if the parsed machine operands contain a given machine operand.
1087 static bool isImplicitOperandIn(const MachineOperand
&ImplicitOperand
,
1088 ArrayRef
<ParsedMachineOperand
> Operands
) {
1089 for (const auto &I
: Operands
) {
1090 if (ImplicitOperand
.isIdenticalTo(I
.Operand
))
1096 bool MIParser::verifyImplicitOperands(ArrayRef
<ParsedMachineOperand
> Operands
,
1097 const MCInstrDesc
&MCID
) {
1099 // We can't verify call instructions as they can contain arbitrary implicit
1100 // register and register mask operands.
1103 // Gather all the expected implicit operands.
1104 SmallVector
<MachineOperand
, 4> ImplicitOperands
;
1105 if (MCID
.ImplicitDefs
)
1106 for (const MCPhysReg
*ImpDefs
= MCID
.getImplicitDefs(); *ImpDefs
; ++ImpDefs
)
1107 ImplicitOperands
.push_back(
1108 MachineOperand::CreateReg(*ImpDefs
, true, true));
1109 if (MCID
.ImplicitUses
)
1110 for (const MCPhysReg
*ImpUses
= MCID
.getImplicitUses(); *ImpUses
; ++ImpUses
)
1111 ImplicitOperands
.push_back(
1112 MachineOperand::CreateReg(*ImpUses
, false, true));
1114 const auto *TRI
= MF
.getSubtarget().getRegisterInfo();
1115 assert(TRI
&& "Expected target register info");
1116 for (const auto &I
: ImplicitOperands
) {
1117 if (isImplicitOperandIn(I
, Operands
))
1119 return error(Operands
.empty() ? Token
.location() : Operands
.back().End
,
1120 Twine("missing implicit register operand '") +
1121 printImplicitRegisterFlag(I
) + " $" +
1122 getRegisterName(TRI
, I
.getReg()) + "'");
1127 bool MIParser::parseInstruction(unsigned &OpCode
, unsigned &Flags
) {
1128 // Allow frame and fast math flags for OPCODE
1129 while (Token
.is(MIToken::kw_frame_setup
) ||
1130 Token
.is(MIToken::kw_frame_destroy
) ||
1131 Token
.is(MIToken::kw_nnan
) ||
1132 Token
.is(MIToken::kw_ninf
) ||
1133 Token
.is(MIToken::kw_nsz
) ||
1134 Token
.is(MIToken::kw_arcp
) ||
1135 Token
.is(MIToken::kw_contract
) ||
1136 Token
.is(MIToken::kw_afn
) ||
1137 Token
.is(MIToken::kw_reassoc
) ||
1138 Token
.is(MIToken::kw_nuw
) ||
1139 Token
.is(MIToken::kw_nsw
) ||
1140 Token
.is(MIToken::kw_exact
) ||
1141 Token
.is(MIToken::kw_fpexcept
)) {
1142 // Mine frame and fast math flags
1143 if (Token
.is(MIToken::kw_frame_setup
))
1144 Flags
|= MachineInstr::FrameSetup
;
1145 if (Token
.is(MIToken::kw_frame_destroy
))
1146 Flags
|= MachineInstr::FrameDestroy
;
1147 if (Token
.is(MIToken::kw_nnan
))
1148 Flags
|= MachineInstr::FmNoNans
;
1149 if (Token
.is(MIToken::kw_ninf
))
1150 Flags
|= MachineInstr::FmNoInfs
;
1151 if (Token
.is(MIToken::kw_nsz
))
1152 Flags
|= MachineInstr::FmNsz
;
1153 if (Token
.is(MIToken::kw_arcp
))
1154 Flags
|= MachineInstr::FmArcp
;
1155 if (Token
.is(MIToken::kw_contract
))
1156 Flags
|= MachineInstr::FmContract
;
1157 if (Token
.is(MIToken::kw_afn
))
1158 Flags
|= MachineInstr::FmAfn
;
1159 if (Token
.is(MIToken::kw_reassoc
))
1160 Flags
|= MachineInstr::FmReassoc
;
1161 if (Token
.is(MIToken::kw_nuw
))
1162 Flags
|= MachineInstr::NoUWrap
;
1163 if (Token
.is(MIToken::kw_nsw
))
1164 Flags
|= MachineInstr::NoSWrap
;
1165 if (Token
.is(MIToken::kw_exact
))
1166 Flags
|= MachineInstr::IsExact
;
1167 if (Token
.is(MIToken::kw_fpexcept
))
1168 Flags
|= MachineInstr::FPExcept
;
1172 if (Token
.isNot(MIToken::Identifier
))
1173 return error("expected a machine instruction");
1174 StringRef InstrName
= Token
.stringValue();
1175 if (PFS
.Target
.parseInstrName(InstrName
, OpCode
))
1176 return error(Twine("unknown machine instruction name '") + InstrName
+ "'");
1181 bool MIParser::parseNamedRegister(unsigned &Reg
) {
1182 assert(Token
.is(MIToken::NamedRegister
) && "Needs NamedRegister token");
1183 StringRef Name
= Token
.stringValue();
1184 if (PFS
.Target
.getRegisterByName(Name
, Reg
))
1185 return error(Twine("unknown register name '") + Name
+ "'");
1189 bool MIParser::parseNamedVirtualRegister(VRegInfo
*&Info
) {
1190 assert(Token
.is(MIToken::NamedVirtualRegister
) && "Expected NamedVReg token");
1191 StringRef Name
= Token
.stringValue();
1192 // TODO: Check that the VReg name is not the same as a physical register name.
1193 // If it is, then print a warning (when warnings are implemented).
1194 Info
= &PFS
.getVRegInfoNamed(Name
);
1198 bool MIParser::parseVirtualRegister(VRegInfo
*&Info
) {
1199 if (Token
.is(MIToken::NamedVirtualRegister
))
1200 return parseNamedVirtualRegister(Info
);
1201 assert(Token
.is(MIToken::VirtualRegister
) && "Needs VirtualRegister token");
1203 if (getUnsigned(ID
))
1205 Info
= &PFS
.getVRegInfo(ID
);
1209 bool MIParser::parseRegister(unsigned &Reg
, VRegInfo
*&Info
) {
1210 switch (Token
.kind()) {
1211 case MIToken::underscore
:
1214 case MIToken::NamedRegister
:
1215 return parseNamedRegister(Reg
);
1216 case MIToken::NamedVirtualRegister
:
1217 case MIToken::VirtualRegister
:
1218 if (parseVirtualRegister(Info
))
1222 // TODO: Parse other register kinds.
1224 llvm_unreachable("The current token should be a register");
1228 bool MIParser::parseRegisterClassOrBank(VRegInfo
&RegInfo
) {
1229 if (Token
.isNot(MIToken::Identifier
) && Token
.isNot(MIToken::underscore
))
1230 return error("expected '_', register class, or register bank name");
1231 StringRef::iterator Loc
= Token
.location();
1232 StringRef Name
= Token
.stringValue();
1234 // Was it a register class?
1235 const TargetRegisterClass
*RC
= PFS
.Target
.getRegClass(Name
);
1239 switch (RegInfo
.Kind
) {
1240 case VRegInfo::UNKNOWN
:
1241 case VRegInfo::NORMAL
:
1242 RegInfo
.Kind
= VRegInfo::NORMAL
;
1243 if (RegInfo
.Explicit
&& RegInfo
.D
.RC
!= RC
) {
1244 const TargetRegisterInfo
&TRI
= *MF
.getSubtarget().getRegisterInfo();
1245 return error(Loc
, Twine("conflicting register classes, previously: ") +
1246 Twine(TRI
.getRegClassName(RegInfo
.D
.RC
)));
1249 RegInfo
.Explicit
= true;
1252 case VRegInfo::GENERIC
:
1253 case VRegInfo::REGBANK
:
1254 return error(Loc
, "register class specification on generic register");
1256 llvm_unreachable("Unexpected register kind");
1259 // Should be a register bank or a generic register.
1260 const RegisterBank
*RegBank
= nullptr;
1262 RegBank
= PFS
.Target
.getRegBank(Name
);
1264 return error(Loc
, "expected '_', register class, or register bank name");
1269 switch (RegInfo
.Kind
) {
1270 case VRegInfo::UNKNOWN
:
1271 case VRegInfo::GENERIC
:
1272 case VRegInfo::REGBANK
:
1273 RegInfo
.Kind
= RegBank
? VRegInfo::REGBANK
: VRegInfo::GENERIC
;
1274 if (RegInfo
.Explicit
&& RegInfo
.D
.RegBank
!= RegBank
)
1275 return error(Loc
, "conflicting generic register banks");
1276 RegInfo
.D
.RegBank
= RegBank
;
1277 RegInfo
.Explicit
= true;
1280 case VRegInfo::NORMAL
:
1281 return error(Loc
, "register bank specification on normal register");
1283 llvm_unreachable("Unexpected register kind");
1286 bool MIParser::parseRegisterFlag(unsigned &Flags
) {
1287 const unsigned OldFlags
= Flags
;
1288 switch (Token
.kind()) {
1289 case MIToken::kw_implicit
:
1290 Flags
|= RegState::Implicit
;
1292 case MIToken::kw_implicit_define
:
1293 Flags
|= RegState::ImplicitDefine
;
1295 case MIToken::kw_def
:
1296 Flags
|= RegState::Define
;
1298 case MIToken::kw_dead
:
1299 Flags
|= RegState::Dead
;
1301 case MIToken::kw_killed
:
1302 Flags
|= RegState::Kill
;
1304 case MIToken::kw_undef
:
1305 Flags
|= RegState::Undef
;
1307 case MIToken::kw_internal
:
1308 Flags
|= RegState::InternalRead
;
1310 case MIToken::kw_early_clobber
:
1311 Flags
|= RegState::EarlyClobber
;
1313 case MIToken::kw_debug_use
:
1314 Flags
|= RegState::Debug
;
1316 case MIToken::kw_renamable
:
1317 Flags
|= RegState::Renamable
;
1320 llvm_unreachable("The current token should be a register flag");
1322 if (OldFlags
== Flags
)
1323 // We know that the same flag is specified more than once when the flags
1324 // weren't modified.
1325 return error("duplicate '" + Token
.stringValue() + "' register flag");
1330 bool MIParser::parseSubRegisterIndex(unsigned &SubReg
) {
1331 assert(Token
.is(MIToken::dot
));
1333 if (Token
.isNot(MIToken::Identifier
))
1334 return error("expected a subregister index after '.'");
1335 auto Name
= Token
.stringValue();
1336 SubReg
= PFS
.Target
.getSubRegIndex(Name
);
1338 return error(Twine("use of unknown subregister index '") + Name
+ "'");
1343 bool MIParser::parseRegisterTiedDefIndex(unsigned &TiedDefIdx
) {
1344 if (!consumeIfPresent(MIToken::kw_tied_def
))
1346 if (Token
.isNot(MIToken::IntegerLiteral
))
1347 return error("expected an integer literal after 'tied-def'");
1348 if (getUnsigned(TiedDefIdx
))
1351 if (expectAndConsume(MIToken::rparen
))
1356 bool MIParser::assignRegisterTies(MachineInstr
&MI
,
1357 ArrayRef
<ParsedMachineOperand
> Operands
) {
1358 SmallVector
<std::pair
<unsigned, unsigned>, 4> TiedRegisterPairs
;
1359 for (unsigned I
= 0, E
= Operands
.size(); I
!= E
; ++I
) {
1360 if (!Operands
[I
].TiedDefIdx
)
1362 // The parser ensures that this operand is a register use, so we just have
1363 // to check the tied-def operand.
1364 unsigned DefIdx
= Operands
[I
].TiedDefIdx
.getValue();
1366 return error(Operands
[I
].Begin
,
1367 Twine("use of invalid tied-def operand index '" +
1368 Twine(DefIdx
) + "'; instruction has only ") +
1369 Twine(E
) + " operands");
1370 const auto &DefOperand
= Operands
[DefIdx
].Operand
;
1371 if (!DefOperand
.isReg() || !DefOperand
.isDef())
1372 // FIXME: add note with the def operand.
1373 return error(Operands
[I
].Begin
,
1374 Twine("use of invalid tied-def operand index '") +
1375 Twine(DefIdx
) + "'; the operand #" + Twine(DefIdx
) +
1376 " isn't a defined register");
1377 // Check that the tied-def operand wasn't tied elsewhere.
1378 for (const auto &TiedPair
: TiedRegisterPairs
) {
1379 if (TiedPair
.first
== DefIdx
)
1380 return error(Operands
[I
].Begin
,
1381 Twine("the tied-def operand #") + Twine(DefIdx
) +
1382 " is already tied with another register operand");
1384 TiedRegisterPairs
.push_back(std::make_pair(DefIdx
, I
));
1386 // FIXME: Verify that for non INLINEASM instructions, the def and use tied
1387 // indices must be less than tied max.
1388 for (const auto &TiedPair
: TiedRegisterPairs
)
1389 MI
.tieOperands(TiedPair
.first
, TiedPair
.second
);
1393 bool MIParser::parseRegisterOperand(MachineOperand
&Dest
,
1394 Optional
<unsigned> &TiedDefIdx
,
1396 unsigned Flags
= IsDef
? RegState::Define
: 0;
1397 while (Token
.isRegisterFlag()) {
1398 if (parseRegisterFlag(Flags
))
1401 if (!Token
.isRegister())
1402 return error("expected a register after register flags");
1405 if (parseRegister(Reg
, RegInfo
))
1408 unsigned SubReg
= 0;
1409 if (Token
.is(MIToken::dot
)) {
1410 if (parseSubRegisterIndex(SubReg
))
1412 if (!Register::isVirtualRegister(Reg
))
1413 return error("subregister index expects a virtual register");
1415 if (Token
.is(MIToken::colon
)) {
1416 if (!Register::isVirtualRegister(Reg
))
1417 return error("register class specification expects a virtual register");
1419 if (parseRegisterClassOrBank(*RegInfo
))
1422 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
1423 if ((Flags
& RegState::Define
) == 0) {
1424 if (consumeIfPresent(MIToken::lparen
)) {
1426 if (!parseRegisterTiedDefIndex(Idx
))
1429 // Try a redundant low-level type.
1431 if (parseLowLevelType(Token
.location(), Ty
))
1432 return error("expected tied-def or low-level type after '('");
1434 if (expectAndConsume(MIToken::rparen
))
1437 if (MRI
.getType(Reg
).isValid() && MRI
.getType(Reg
) != Ty
)
1438 return error("inconsistent type for generic virtual register");
1440 MRI
.setRegClassOrRegBank(Reg
, static_cast<RegisterBank
*>(nullptr));
1441 MRI
.setType(Reg
, Ty
);
1444 } else if (consumeIfPresent(MIToken::lparen
)) {
1445 // Virtual registers may have a tpe with GlobalISel.
1446 if (!Register::isVirtualRegister(Reg
))
1447 return error("unexpected type on physical register");
1450 if (parseLowLevelType(Token
.location(), Ty
))
1453 if (expectAndConsume(MIToken::rparen
))
1456 if (MRI
.getType(Reg
).isValid() && MRI
.getType(Reg
) != Ty
)
1457 return error("inconsistent type for generic virtual register");
1459 MRI
.setRegClassOrRegBank(Reg
, static_cast<RegisterBank
*>(nullptr));
1460 MRI
.setType(Reg
, Ty
);
1461 } else if (Register::isVirtualRegister(Reg
)) {
1462 // Generic virtual registers must have a type.
1463 // If we end up here this means the type hasn't been specified and
1465 if (RegInfo
->Kind
== VRegInfo::GENERIC
||
1466 RegInfo
->Kind
== VRegInfo::REGBANK
)
1467 return error("generic virtual registers must have a type");
1469 Dest
= MachineOperand::CreateReg(
1470 Reg
, Flags
& RegState::Define
, Flags
& RegState::Implicit
,
1471 Flags
& RegState::Kill
, Flags
& RegState::Dead
, Flags
& RegState::Undef
,
1472 Flags
& RegState::EarlyClobber
, SubReg
, Flags
& RegState::Debug
,
1473 Flags
& RegState::InternalRead
, Flags
& RegState::Renamable
);
1478 bool MIParser::parseImmediateOperand(MachineOperand
&Dest
) {
1479 assert(Token
.is(MIToken::IntegerLiteral
));
1480 const APSInt
&Int
= Token
.integerValue();
1481 if (Int
.getMinSignedBits() > 64)
1482 return error("integer literal is too large to be an immediate operand");
1483 Dest
= MachineOperand::CreateImm(Int
.getExtValue());
1488 bool MIParser::parseIRConstant(StringRef::iterator Loc
, StringRef StringValue
,
1489 const Constant
*&C
) {
1490 auto Source
= StringValue
.str(); // The source has to be null terminated.
1492 C
= parseConstantValue(Source
, Err
, *MF
.getFunction().getParent(),
1495 return error(Loc
+ Err
.getColumnNo(), Err
.getMessage());
1499 bool MIParser::parseIRConstant(StringRef::iterator Loc
, const Constant
*&C
) {
1500 if (parseIRConstant(Loc
, StringRef(Loc
, Token
.range().end() - Loc
), C
))
1506 // See LLT implemntation for bit size limits.
1507 static bool verifyScalarSize(uint64_t Size
) {
1508 return Size
!= 0 && isUInt
<16>(Size
);
1511 static bool verifyVectorElementCount(uint64_t NumElts
) {
1512 return NumElts
!= 0 && isUInt
<16>(NumElts
);
1515 static bool verifyAddrSpace(uint64_t AddrSpace
) {
1516 return isUInt
<24>(AddrSpace
);
1519 bool MIParser::parseLowLevelType(StringRef::iterator Loc
, LLT
&Ty
) {
1520 if (Token
.range().front() == 's' || Token
.range().front() == 'p') {
1521 StringRef SizeStr
= Token
.range().drop_front();
1522 if (SizeStr
.size() == 0 || !llvm::all_of(SizeStr
, isdigit
))
1523 return error("expected integers after 's'/'p' type character");
1526 if (Token
.range().front() == 's') {
1527 auto ScalarSize
= APSInt(Token
.range().drop_front()).getZExtValue();
1528 if (!verifyScalarSize(ScalarSize
))
1529 return error("invalid size for scalar type");
1531 Ty
= LLT::scalar(ScalarSize
);
1534 } else if (Token
.range().front() == 'p') {
1535 const DataLayout
&DL
= MF
.getDataLayout();
1536 uint64_t AS
= APSInt(Token
.range().drop_front()).getZExtValue();
1537 if (!verifyAddrSpace(AS
))
1538 return error("invalid address space number");
1540 Ty
= LLT::pointer(AS
, DL
.getPointerSizeInBits(AS
));
1545 // Now we're looking for a vector.
1546 if (Token
.isNot(MIToken::less
))
1548 "expected sN, pA, <M x sN>, or <M x pA> for GlobalISel type");
1551 if (Token
.isNot(MIToken::IntegerLiteral
))
1552 return error(Loc
, "expected <M x sN> or <M x pA> for vector type");
1553 uint64_t NumElements
= Token
.integerValue().getZExtValue();
1554 if (!verifyVectorElementCount(NumElements
))
1555 return error("invalid number of vector elements");
1559 if (Token
.isNot(MIToken::Identifier
) || Token
.stringValue() != "x")
1560 return error(Loc
, "expected <M x sN> or <M x pA> for vector type");
1563 if (Token
.range().front() != 's' && Token
.range().front() != 'p')
1564 return error(Loc
, "expected <M x sN> or <M x pA> for vector type");
1565 StringRef SizeStr
= Token
.range().drop_front();
1566 if (SizeStr
.size() == 0 || !llvm::all_of(SizeStr
, isdigit
))
1567 return error("expected integers after 's'/'p' type character");
1569 if (Token
.range().front() == 's') {
1570 auto ScalarSize
= APSInt(Token
.range().drop_front()).getZExtValue();
1571 if (!verifyScalarSize(ScalarSize
))
1572 return error("invalid size for scalar type");
1573 Ty
= LLT::scalar(ScalarSize
);
1574 } else if (Token
.range().front() == 'p') {
1575 const DataLayout
&DL
= MF
.getDataLayout();
1576 uint64_t AS
= APSInt(Token
.range().drop_front()).getZExtValue();
1577 if (!verifyAddrSpace(AS
))
1578 return error("invalid address space number");
1580 Ty
= LLT::pointer(AS
, DL
.getPointerSizeInBits(AS
));
1582 return error(Loc
, "expected <M x sN> or <M x pA> for vector type");
1585 if (Token
.isNot(MIToken::greater
))
1586 return error(Loc
, "expected <M x sN> or <M x pA> for vector type");
1589 Ty
= LLT::vector(NumElements
, Ty
);
1593 bool MIParser::parseTypedImmediateOperand(MachineOperand
&Dest
) {
1594 assert(Token
.is(MIToken::Identifier
));
1595 StringRef TypeStr
= Token
.range();
1596 if (TypeStr
.front() != 'i' && TypeStr
.front() != 's' &&
1597 TypeStr
.front() != 'p')
1599 "a typed immediate operand should start with one of 'i', 's', or 'p'");
1600 StringRef SizeStr
= Token
.range().drop_front();
1601 if (SizeStr
.size() == 0 || !llvm::all_of(SizeStr
, isdigit
))
1602 return error("expected integers after 'i'/'s'/'p' type character");
1604 auto Loc
= Token
.location();
1606 if (Token
.isNot(MIToken::IntegerLiteral
)) {
1607 if (Token
.isNot(MIToken::Identifier
) ||
1608 !(Token
.range() == "true" || Token
.range() == "false"))
1609 return error("expected an integer literal");
1611 const Constant
*C
= nullptr;
1612 if (parseIRConstant(Loc
, C
))
1614 Dest
= MachineOperand::CreateCImm(cast
<ConstantInt
>(C
));
1618 bool MIParser::parseFPImmediateOperand(MachineOperand
&Dest
) {
1619 auto Loc
= Token
.location();
1621 if (Token
.isNot(MIToken::FloatingPointLiteral
) &&
1622 Token
.isNot(MIToken::HexLiteral
))
1623 return error("expected a floating point literal");
1624 const Constant
*C
= nullptr;
1625 if (parseIRConstant(Loc
, C
))
1627 Dest
= MachineOperand::CreateFPImm(cast
<ConstantFP
>(C
));
1631 bool MIParser::getUnsigned(unsigned &Result
) {
1632 if (Token
.hasIntegerValue()) {
1633 const uint64_t Limit
= uint64_t(std::numeric_limits
<unsigned>::max()) + 1;
1634 uint64_t Val64
= Token
.integerValue().getLimitedValue(Limit
);
1636 return error("expected 32-bit integer (too large)");
1640 if (Token
.is(MIToken::HexLiteral
)) {
1644 if (A
.getBitWidth() > 32)
1645 return error("expected 32-bit integer (too large)");
1646 Result
= A
.getZExtValue();
1652 bool MIParser::parseMBBReference(MachineBasicBlock
*&MBB
) {
1653 assert(Token
.is(MIToken::MachineBasicBlock
) ||
1654 Token
.is(MIToken::MachineBasicBlockLabel
));
1656 if (getUnsigned(Number
))
1658 auto MBBInfo
= PFS
.MBBSlots
.find(Number
);
1659 if (MBBInfo
== PFS
.MBBSlots
.end())
1660 return error(Twine("use of undefined machine basic block #") +
1662 MBB
= MBBInfo
->second
;
1663 // TODO: Only parse the name if it's a MachineBasicBlockLabel. Deprecate once
1664 // we drop the <irname> from the bb.<id>.<irname> format.
1665 if (!Token
.stringValue().empty() && Token
.stringValue() != MBB
->getName())
1666 return error(Twine("the name of machine basic block #") + Twine(Number
) +
1667 " isn't '" + Token
.stringValue() + "'");
1671 bool MIParser::parseMBBOperand(MachineOperand
&Dest
) {
1672 MachineBasicBlock
*MBB
;
1673 if (parseMBBReference(MBB
))
1675 Dest
= MachineOperand::CreateMBB(MBB
);
1680 bool MIParser::parseStackFrameIndex(int &FI
) {
1681 assert(Token
.is(MIToken::StackObject
));
1683 if (getUnsigned(ID
))
1685 auto ObjectInfo
= PFS
.StackObjectSlots
.find(ID
);
1686 if (ObjectInfo
== PFS
.StackObjectSlots
.end())
1687 return error(Twine("use of undefined stack object '%stack.") + Twine(ID
) +
1690 if (const auto *Alloca
=
1691 MF
.getFrameInfo().getObjectAllocation(ObjectInfo
->second
))
1692 Name
= Alloca
->getName();
1693 if (!Token
.stringValue().empty() && Token
.stringValue() != Name
)
1694 return error(Twine("the name of the stack object '%stack.") + Twine(ID
) +
1695 "' isn't '" + Token
.stringValue() + "'");
1697 FI
= ObjectInfo
->second
;
1701 bool MIParser::parseStackObjectOperand(MachineOperand
&Dest
) {
1703 if (parseStackFrameIndex(FI
))
1705 Dest
= MachineOperand::CreateFI(FI
);
1709 bool MIParser::parseFixedStackFrameIndex(int &FI
) {
1710 assert(Token
.is(MIToken::FixedStackObject
));
1712 if (getUnsigned(ID
))
1714 auto ObjectInfo
= PFS
.FixedStackObjectSlots
.find(ID
);
1715 if (ObjectInfo
== PFS
.FixedStackObjectSlots
.end())
1716 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
1719 FI
= ObjectInfo
->second
;
1723 bool MIParser::parseFixedStackObjectOperand(MachineOperand
&Dest
) {
1725 if (parseFixedStackFrameIndex(FI
))
1727 Dest
= MachineOperand::CreateFI(FI
);
1731 bool MIParser::parseGlobalValue(GlobalValue
*&GV
) {
1732 switch (Token
.kind()) {
1733 case MIToken::NamedGlobalValue
: {
1734 const Module
*M
= MF
.getFunction().getParent();
1735 GV
= M
->getNamedValue(Token
.stringValue());
1737 return error(Twine("use of undefined global value '") + Token
.range() +
1741 case MIToken::GlobalValue
: {
1743 if (getUnsigned(GVIdx
))
1745 if (GVIdx
>= PFS
.IRSlots
.GlobalValues
.size())
1746 return error(Twine("use of undefined global value '@") + Twine(GVIdx
) +
1748 GV
= PFS
.IRSlots
.GlobalValues
[GVIdx
];
1752 llvm_unreachable("The current token should be a global value");
1757 bool MIParser::parseGlobalAddressOperand(MachineOperand
&Dest
) {
1758 GlobalValue
*GV
= nullptr;
1759 if (parseGlobalValue(GV
))
1762 Dest
= MachineOperand::CreateGA(GV
, /*Offset=*/0);
1763 if (parseOperandsOffset(Dest
))
1768 bool MIParser::parseConstantPoolIndexOperand(MachineOperand
&Dest
) {
1769 assert(Token
.is(MIToken::ConstantPoolItem
));
1771 if (getUnsigned(ID
))
1773 auto ConstantInfo
= PFS
.ConstantPoolSlots
.find(ID
);
1774 if (ConstantInfo
== PFS
.ConstantPoolSlots
.end())
1775 return error("use of undefined constant '%const." + Twine(ID
) + "'");
1777 Dest
= MachineOperand::CreateCPI(ID
, /*Offset=*/0);
1778 if (parseOperandsOffset(Dest
))
1783 bool MIParser::parseJumpTableIndexOperand(MachineOperand
&Dest
) {
1784 assert(Token
.is(MIToken::JumpTableIndex
));
1786 if (getUnsigned(ID
))
1788 auto JumpTableEntryInfo
= PFS
.JumpTableSlots
.find(ID
);
1789 if (JumpTableEntryInfo
== PFS
.JumpTableSlots
.end())
1790 return error("use of undefined jump table '%jump-table." + Twine(ID
) + "'");
1792 Dest
= MachineOperand::CreateJTI(JumpTableEntryInfo
->second
);
1796 bool MIParser::parseExternalSymbolOperand(MachineOperand
&Dest
) {
1797 assert(Token
.is(MIToken::ExternalSymbol
));
1798 const char *Symbol
= MF
.createExternalSymbolName(Token
.stringValue());
1800 Dest
= MachineOperand::CreateES(Symbol
);
1801 if (parseOperandsOffset(Dest
))
1806 bool MIParser::parseMCSymbolOperand(MachineOperand
&Dest
) {
1807 assert(Token
.is(MIToken::MCSymbol
));
1808 MCSymbol
*Symbol
= getOrCreateMCSymbol(Token
.stringValue());
1810 Dest
= MachineOperand::CreateMCSymbol(Symbol
);
1811 if (parseOperandsOffset(Dest
))
1816 bool MIParser::parseSubRegisterIndexOperand(MachineOperand
&Dest
) {
1817 assert(Token
.is(MIToken::SubRegisterIndex
));
1818 StringRef Name
= Token
.stringValue();
1819 unsigned SubRegIndex
= PFS
.Target
.getSubRegIndex(Token
.stringValue());
1820 if (SubRegIndex
== 0)
1821 return error(Twine("unknown subregister index '") + Name
+ "'");
1823 Dest
= MachineOperand::CreateImm(SubRegIndex
);
1827 bool MIParser::parseMDNode(MDNode
*&Node
) {
1828 assert(Token
.is(MIToken::exclaim
));
1830 auto Loc
= Token
.location();
1832 if (Token
.isNot(MIToken::IntegerLiteral
) || Token
.integerValue().isSigned())
1833 return error("expected metadata id after '!'");
1835 if (getUnsigned(ID
))
1837 auto NodeInfo
= PFS
.IRSlots
.MetadataNodes
.find(ID
);
1838 if (NodeInfo
== PFS
.IRSlots
.MetadataNodes
.end())
1839 return error(Loc
, "use of undefined metadata '!" + Twine(ID
) + "'");
1841 Node
= NodeInfo
->second
.get();
1845 bool MIParser::parseDIExpression(MDNode
*&Expr
) {
1846 assert(Token
.is(MIToken::md_diexpr
));
1849 // FIXME: Share this parsing with the IL parser.
1850 SmallVector
<uint64_t, 8> Elements
;
1852 if (expectAndConsume(MIToken::lparen
))
1855 if (Token
.isNot(MIToken::rparen
)) {
1857 if (Token
.is(MIToken::Identifier
)) {
1858 if (unsigned Op
= dwarf::getOperationEncoding(Token
.stringValue())) {
1860 Elements
.push_back(Op
);
1863 if (unsigned Enc
= dwarf::getAttributeEncoding(Token
.stringValue())) {
1865 Elements
.push_back(Enc
);
1868 return error(Twine("invalid DWARF op '") + Token
.stringValue() + "'");
1871 if (Token
.isNot(MIToken::IntegerLiteral
) ||
1872 Token
.integerValue().isSigned())
1873 return error("expected unsigned integer");
1875 auto &U
= Token
.integerValue();
1876 if (U
.ugt(UINT64_MAX
))
1877 return error("element too large, limit is " + Twine(UINT64_MAX
));
1878 Elements
.push_back(U
.getZExtValue());
1881 } while (consumeIfPresent(MIToken::comma
));
1884 if (expectAndConsume(MIToken::rparen
))
1887 Expr
= DIExpression::get(MF
.getFunction().getContext(), Elements
);
1891 bool MIParser::parseDILocation(MDNode
*&Loc
) {
1892 assert(Token
.is(MIToken::md_dilocation
));
1895 bool HaveLine
= false;
1897 unsigned Column
= 0;
1898 MDNode
*Scope
= nullptr;
1899 MDNode
*InlinedAt
= nullptr;
1900 bool ImplicitCode
= false;
1902 if (expectAndConsume(MIToken::lparen
))
1905 if (Token
.isNot(MIToken::rparen
)) {
1907 if (Token
.is(MIToken::Identifier
)) {
1908 if (Token
.stringValue() == "line") {
1910 if (expectAndConsume(MIToken::colon
))
1912 if (Token
.isNot(MIToken::IntegerLiteral
) ||
1913 Token
.integerValue().isSigned())
1914 return error("expected unsigned integer");
1915 Line
= Token
.integerValue().getZExtValue();
1920 if (Token
.stringValue() == "column") {
1922 if (expectAndConsume(MIToken::colon
))
1924 if (Token
.isNot(MIToken::IntegerLiteral
) ||
1925 Token
.integerValue().isSigned())
1926 return error("expected unsigned integer");
1927 Column
= Token
.integerValue().getZExtValue();
1931 if (Token
.stringValue() == "scope") {
1933 if (expectAndConsume(MIToken::colon
))
1935 if (parseMDNode(Scope
))
1936 return error("expected metadata node");
1937 if (!isa
<DIScope
>(Scope
))
1938 return error("expected DIScope node");
1941 if (Token
.stringValue() == "inlinedAt") {
1943 if (expectAndConsume(MIToken::colon
))
1945 if (Token
.is(MIToken::exclaim
)) {
1946 if (parseMDNode(InlinedAt
))
1948 } else if (Token
.is(MIToken::md_dilocation
)) {
1949 if (parseDILocation(InlinedAt
))
1952 return error("expected metadata node");
1953 if (!isa
<DILocation
>(InlinedAt
))
1954 return error("expected DILocation node");
1957 if (Token
.stringValue() == "isImplicitCode") {
1959 if (expectAndConsume(MIToken::colon
))
1961 if (!Token
.is(MIToken::Identifier
))
1962 return error("expected true/false");
1963 // As far as I can see, we don't have any existing need for parsing
1964 // true/false in MIR yet. Do it ad-hoc until there's something else
1966 if (Token
.stringValue() == "true")
1967 ImplicitCode
= true;
1968 else if (Token
.stringValue() == "false")
1969 ImplicitCode
= false;
1971 return error("expected true/false");
1976 return error(Twine("invalid DILocation argument '") +
1977 Token
.stringValue() + "'");
1978 } while (consumeIfPresent(MIToken::comma
));
1981 if (expectAndConsume(MIToken::rparen
))
1985 return error("DILocation requires line number");
1987 return error("DILocation requires a scope");
1989 Loc
= DILocation::get(MF
.getFunction().getContext(), Line
, Column
, Scope
,
1990 InlinedAt
, ImplicitCode
);
1994 bool MIParser::parseMetadataOperand(MachineOperand
&Dest
) {
1995 MDNode
*Node
= nullptr;
1996 if (Token
.is(MIToken::exclaim
)) {
1997 if (parseMDNode(Node
))
1999 } else if (Token
.is(MIToken::md_diexpr
)) {
2000 if (parseDIExpression(Node
))
2003 Dest
= MachineOperand::CreateMetadata(Node
);
2007 bool MIParser::parseCFIOffset(int &Offset
) {
2008 if (Token
.isNot(MIToken::IntegerLiteral
))
2009 return error("expected a cfi offset");
2010 if (Token
.integerValue().getMinSignedBits() > 32)
2011 return error("expected a 32 bit integer (the cfi offset is too large)");
2012 Offset
= (int)Token
.integerValue().getExtValue();
2017 bool MIParser::parseCFIRegister(unsigned &Reg
) {
2018 if (Token
.isNot(MIToken::NamedRegister
))
2019 return error("expected a cfi register");
2021 if (parseNamedRegister(LLVMReg
))
2023 const auto *TRI
= MF
.getSubtarget().getRegisterInfo();
2024 assert(TRI
&& "Expected target register info");
2025 int DwarfReg
= TRI
->getDwarfRegNum(LLVMReg
, true);
2027 return error("invalid DWARF register");
2028 Reg
= (unsigned)DwarfReg
;
2033 bool MIParser::parseCFIEscapeValues(std::string
&Values
) {
2035 if (Token
.isNot(MIToken::HexLiteral
))
2036 return error("expected a hexadecimal literal");
2038 if (getUnsigned(Value
))
2040 if (Value
> UINT8_MAX
)
2041 return error("expected a 8-bit integer (too large)");
2042 Values
.push_back(static_cast<uint8_t>(Value
));
2044 } while (consumeIfPresent(MIToken::comma
));
2048 bool MIParser::parseCFIOperand(MachineOperand
&Dest
) {
2049 auto Kind
= Token
.kind();
2055 case MIToken::kw_cfi_same_value
:
2056 if (parseCFIRegister(Reg
))
2058 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createSameValue(nullptr, Reg
));
2060 case MIToken::kw_cfi_offset
:
2061 if (parseCFIRegister(Reg
) || expectAndConsume(MIToken::comma
) ||
2062 parseCFIOffset(Offset
))
2065 MF
.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg
, Offset
));
2067 case MIToken::kw_cfi_rel_offset
:
2068 if (parseCFIRegister(Reg
) || expectAndConsume(MIToken::comma
) ||
2069 parseCFIOffset(Offset
))
2071 CFIIndex
= MF
.addFrameInst(
2072 MCCFIInstruction::createRelOffset(nullptr, Reg
, Offset
));
2074 case MIToken::kw_cfi_def_cfa_register
:
2075 if (parseCFIRegister(Reg
))
2078 MF
.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg
));
2080 case MIToken::kw_cfi_def_cfa_offset
:
2081 if (parseCFIOffset(Offset
))
2083 // NB: MCCFIInstruction::createDefCfaOffset negates the offset.
2084 CFIIndex
= MF
.addFrameInst(
2085 MCCFIInstruction::createDefCfaOffset(nullptr, -Offset
));
2087 case MIToken::kw_cfi_adjust_cfa_offset
:
2088 if (parseCFIOffset(Offset
))
2090 CFIIndex
= MF
.addFrameInst(
2091 MCCFIInstruction::createAdjustCfaOffset(nullptr, Offset
));
2093 case MIToken::kw_cfi_def_cfa
:
2094 if (parseCFIRegister(Reg
) || expectAndConsume(MIToken::comma
) ||
2095 parseCFIOffset(Offset
))
2097 // NB: MCCFIInstruction::createDefCfa negates the offset.
2099 MF
.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg
, -Offset
));
2101 case MIToken::kw_cfi_remember_state
:
2102 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createRememberState(nullptr));
2104 case MIToken::kw_cfi_restore
:
2105 if (parseCFIRegister(Reg
))
2107 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createRestore(nullptr, Reg
));
2109 case MIToken::kw_cfi_restore_state
:
2110 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createRestoreState(nullptr));
2112 case MIToken::kw_cfi_undefined
:
2113 if (parseCFIRegister(Reg
))
2115 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createUndefined(nullptr, Reg
));
2117 case MIToken::kw_cfi_register
: {
2119 if (parseCFIRegister(Reg
) || expectAndConsume(MIToken::comma
) ||
2120 parseCFIRegister(Reg2
))
2124 MF
.addFrameInst(MCCFIInstruction::createRegister(nullptr, Reg
, Reg2
));
2127 case MIToken::kw_cfi_window_save
:
2128 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createWindowSave(nullptr));
2130 case MIToken::kw_cfi_aarch64_negate_ra_sign_state
:
2131 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
2133 case MIToken::kw_cfi_escape
: {
2135 if (parseCFIEscapeValues(Values
))
2137 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createEscape(nullptr, Values
));
2141 // TODO: Parse the other CFI operands.
2142 llvm_unreachable("The current token should be a cfi operand");
2144 Dest
= MachineOperand::CreateCFIIndex(CFIIndex
);
2148 bool MIParser::parseIRBlock(BasicBlock
*&BB
, const Function
&F
) {
2149 switch (Token
.kind()) {
2150 case MIToken::NamedIRBlock
: {
2151 BB
= dyn_cast_or_null
<BasicBlock
>(
2152 F
.getValueSymbolTable()->lookup(Token
.stringValue()));
2154 return error(Twine("use of undefined IR block '") + Token
.range() + "'");
2157 case MIToken::IRBlock
: {
2158 unsigned SlotNumber
= 0;
2159 if (getUnsigned(SlotNumber
))
2161 BB
= const_cast<BasicBlock
*>(getIRBlock(SlotNumber
, F
));
2163 return error(Twine("use of undefined IR block '%ir-block.") +
2164 Twine(SlotNumber
) + "'");
2168 llvm_unreachable("The current token should be an IR block reference");
2173 bool MIParser::parseBlockAddressOperand(MachineOperand
&Dest
) {
2174 assert(Token
.is(MIToken::kw_blockaddress
));
2176 if (expectAndConsume(MIToken::lparen
))
2178 if (Token
.isNot(MIToken::GlobalValue
) &&
2179 Token
.isNot(MIToken::NamedGlobalValue
))
2180 return error("expected a global value");
2181 GlobalValue
*GV
= nullptr;
2182 if (parseGlobalValue(GV
))
2184 auto *F
= dyn_cast
<Function
>(GV
);
2186 return error("expected an IR function reference");
2188 if (expectAndConsume(MIToken::comma
))
2190 BasicBlock
*BB
= nullptr;
2191 if (Token
.isNot(MIToken::IRBlock
) && Token
.isNot(MIToken::NamedIRBlock
))
2192 return error("expected an IR block reference");
2193 if (parseIRBlock(BB
, *F
))
2196 if (expectAndConsume(MIToken::rparen
))
2198 Dest
= MachineOperand::CreateBA(BlockAddress::get(F
, BB
), /*Offset=*/0);
2199 if (parseOperandsOffset(Dest
))
2204 bool MIParser::parseIntrinsicOperand(MachineOperand
&Dest
) {
2205 assert(Token
.is(MIToken::kw_intrinsic
));
2207 if (expectAndConsume(MIToken::lparen
))
2208 return error("expected syntax intrinsic(@llvm.whatever)");
2210 if (Token
.isNot(MIToken::NamedGlobalValue
))
2211 return error("expected syntax intrinsic(@llvm.whatever)");
2213 std::string Name
= Token
.stringValue();
2216 if (expectAndConsume(MIToken::rparen
))
2217 return error("expected ')' to terminate intrinsic name");
2219 // Find out what intrinsic we're dealing with, first try the global namespace
2220 // and then the target's private intrinsics if that fails.
2221 const TargetIntrinsicInfo
*TII
= MF
.getTarget().getIntrinsicInfo();
2222 Intrinsic::ID ID
= Function::lookupIntrinsicID(Name
);
2223 if (ID
== Intrinsic::not_intrinsic
&& TII
)
2224 ID
= static_cast<Intrinsic::ID
>(TII
->lookupName(Name
));
2226 if (ID
== Intrinsic::not_intrinsic
)
2227 return error("unknown intrinsic name");
2228 Dest
= MachineOperand::CreateIntrinsicID(ID
);
2233 bool MIParser::parsePredicateOperand(MachineOperand
&Dest
) {
2234 assert(Token
.is(MIToken::kw_intpred
) || Token
.is(MIToken::kw_floatpred
));
2235 bool IsFloat
= Token
.is(MIToken::kw_floatpred
);
2238 if (expectAndConsume(MIToken::lparen
))
2239 return error("expected syntax intpred(whatever) or floatpred(whatever");
2241 if (Token
.isNot(MIToken::Identifier
))
2242 return error("whatever");
2244 CmpInst::Predicate Pred
;
2246 Pred
= StringSwitch
<CmpInst::Predicate
>(Token
.stringValue())
2247 .Case("false", CmpInst::FCMP_FALSE
)
2248 .Case("oeq", CmpInst::FCMP_OEQ
)
2249 .Case("ogt", CmpInst::FCMP_OGT
)
2250 .Case("oge", CmpInst::FCMP_OGE
)
2251 .Case("olt", CmpInst::FCMP_OLT
)
2252 .Case("ole", CmpInst::FCMP_OLE
)
2253 .Case("one", CmpInst::FCMP_ONE
)
2254 .Case("ord", CmpInst::FCMP_ORD
)
2255 .Case("uno", CmpInst::FCMP_UNO
)
2256 .Case("ueq", CmpInst::FCMP_UEQ
)
2257 .Case("ugt", CmpInst::FCMP_UGT
)
2258 .Case("uge", CmpInst::FCMP_UGE
)
2259 .Case("ult", CmpInst::FCMP_ULT
)
2260 .Case("ule", CmpInst::FCMP_ULE
)
2261 .Case("une", CmpInst::FCMP_UNE
)
2262 .Case("true", CmpInst::FCMP_TRUE
)
2263 .Default(CmpInst::BAD_FCMP_PREDICATE
);
2264 if (!CmpInst::isFPPredicate(Pred
))
2265 return error("invalid floating-point predicate");
2267 Pred
= StringSwitch
<CmpInst::Predicate
>(Token
.stringValue())
2268 .Case("eq", CmpInst::ICMP_EQ
)
2269 .Case("ne", CmpInst::ICMP_NE
)
2270 .Case("sgt", CmpInst::ICMP_SGT
)
2271 .Case("sge", CmpInst::ICMP_SGE
)
2272 .Case("slt", CmpInst::ICMP_SLT
)
2273 .Case("sle", CmpInst::ICMP_SLE
)
2274 .Case("ugt", CmpInst::ICMP_UGT
)
2275 .Case("uge", CmpInst::ICMP_UGE
)
2276 .Case("ult", CmpInst::ICMP_ULT
)
2277 .Case("ule", CmpInst::ICMP_ULE
)
2278 .Default(CmpInst::BAD_ICMP_PREDICATE
);
2279 if (!CmpInst::isIntPredicate(Pred
))
2280 return error("invalid integer predicate");
2284 Dest
= MachineOperand::CreatePredicate(Pred
);
2285 if (expectAndConsume(MIToken::rparen
))
2286 return error("predicate should be terminated by ')'.");
2291 bool MIParser::parseShuffleMaskOperand(MachineOperand
&Dest
) {
2292 assert(Token
.is(MIToken::kw_shufflemask
));
2295 if (expectAndConsume(MIToken::lparen
))
2296 return error("expected syntax shufflemask(<integer or undef>, ...)");
2298 SmallVector
<Constant
*, 32> ShufMask
;
2299 LLVMContext
&Ctx
= MF
.getFunction().getContext();
2300 Type
*I32Ty
= Type::getInt32Ty(Ctx
);
2302 bool AllZero
= true;
2303 bool AllUndef
= true;
2306 if (Token
.is(MIToken::kw_undef
)) {
2307 ShufMask
.push_back(UndefValue::get(I32Ty
));
2309 } else if (Token
.is(MIToken::IntegerLiteral
)) {
2311 const APSInt
&Int
= Token
.integerValue();
2312 if (!Int
.isNullValue())
2314 ShufMask
.push_back(ConstantInt::get(I32Ty
, Int
.getExtValue()));
2316 return error("expected integer constant");
2319 } while (consumeIfPresent(MIToken::comma
));
2321 if (expectAndConsume(MIToken::rparen
))
2322 return error("shufflemask should be terminated by ')'.");
2324 if (AllZero
|| AllUndef
) {
2325 VectorType
*VT
= VectorType::get(I32Ty
, ShufMask
.size());
2326 Constant
*C
= AllZero
? Constant::getNullValue(VT
) : UndefValue::get(VT
);
2327 Dest
= MachineOperand::CreateShuffleMask(C
);
2329 Dest
= MachineOperand::CreateShuffleMask(ConstantVector::get(ShufMask
));
2334 bool MIParser::parseTargetIndexOperand(MachineOperand
&Dest
) {
2335 assert(Token
.is(MIToken::kw_target_index
));
2337 if (expectAndConsume(MIToken::lparen
))
2339 if (Token
.isNot(MIToken::Identifier
))
2340 return error("expected the name of the target index");
2342 if (PFS
.Target
.getTargetIndex(Token
.stringValue(), Index
))
2343 return error("use of undefined target index '" + Token
.stringValue() + "'");
2345 if (expectAndConsume(MIToken::rparen
))
2347 Dest
= MachineOperand::CreateTargetIndex(unsigned(Index
), /*Offset=*/0);
2348 if (parseOperandsOffset(Dest
))
2353 bool MIParser::parseCustomRegisterMaskOperand(MachineOperand
&Dest
) {
2354 assert(Token
.stringValue() == "CustomRegMask" && "Expected a custom RegMask");
2356 if (expectAndConsume(MIToken::lparen
))
2359 uint32_t *Mask
= MF
.allocateRegMask();
2361 if (Token
.isNot(MIToken::NamedRegister
))
2362 return error("expected a named register");
2364 if (parseNamedRegister(Reg
))
2367 Mask
[Reg
/ 32] |= 1U << (Reg
% 32);
2368 // TODO: Report an error if the same register is used more than once.
2369 if (Token
.isNot(MIToken::comma
))
2374 if (expectAndConsume(MIToken::rparen
))
2376 Dest
= MachineOperand::CreateRegMask(Mask
);
2380 bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand
&Dest
) {
2381 assert(Token
.is(MIToken::kw_liveout
));
2382 uint32_t *Mask
= MF
.allocateRegMask();
2384 if (expectAndConsume(MIToken::lparen
))
2387 if (Token
.isNot(MIToken::NamedRegister
))
2388 return error("expected a named register");
2390 if (parseNamedRegister(Reg
))
2393 Mask
[Reg
/ 32] |= 1U << (Reg
% 32);
2394 // TODO: Report an error if the same register is used more than once.
2395 if (Token
.isNot(MIToken::comma
))
2399 if (expectAndConsume(MIToken::rparen
))
2401 Dest
= MachineOperand::CreateRegLiveOut(Mask
);
2405 bool MIParser::parseMachineOperand(MachineOperand
&Dest
,
2406 Optional
<unsigned> &TiedDefIdx
) {
2407 switch (Token
.kind()) {
2408 case MIToken::kw_implicit
:
2409 case MIToken::kw_implicit_define
:
2410 case MIToken::kw_def
:
2411 case MIToken::kw_dead
:
2412 case MIToken::kw_killed
:
2413 case MIToken::kw_undef
:
2414 case MIToken::kw_internal
:
2415 case MIToken::kw_early_clobber
:
2416 case MIToken::kw_debug_use
:
2417 case MIToken::kw_renamable
:
2418 case MIToken::underscore
:
2419 case MIToken::NamedRegister
:
2420 case MIToken::VirtualRegister
:
2421 case MIToken::NamedVirtualRegister
:
2422 return parseRegisterOperand(Dest
, TiedDefIdx
);
2423 case MIToken::IntegerLiteral
:
2424 return parseImmediateOperand(Dest
);
2425 case MIToken::kw_half
:
2426 case MIToken::kw_float
:
2427 case MIToken::kw_double
:
2428 case MIToken::kw_x86_fp80
:
2429 case MIToken::kw_fp128
:
2430 case MIToken::kw_ppc_fp128
:
2431 return parseFPImmediateOperand(Dest
);
2432 case MIToken::MachineBasicBlock
:
2433 return parseMBBOperand(Dest
);
2434 case MIToken::StackObject
:
2435 return parseStackObjectOperand(Dest
);
2436 case MIToken::FixedStackObject
:
2437 return parseFixedStackObjectOperand(Dest
);
2438 case MIToken::GlobalValue
:
2439 case MIToken::NamedGlobalValue
:
2440 return parseGlobalAddressOperand(Dest
);
2441 case MIToken::ConstantPoolItem
:
2442 return parseConstantPoolIndexOperand(Dest
);
2443 case MIToken::JumpTableIndex
:
2444 return parseJumpTableIndexOperand(Dest
);
2445 case MIToken::ExternalSymbol
:
2446 return parseExternalSymbolOperand(Dest
);
2447 case MIToken::MCSymbol
:
2448 return parseMCSymbolOperand(Dest
);
2449 case MIToken::SubRegisterIndex
:
2450 return parseSubRegisterIndexOperand(Dest
);
2451 case MIToken::md_diexpr
:
2452 case MIToken::exclaim
:
2453 return parseMetadataOperand(Dest
);
2454 case MIToken::kw_cfi_same_value
:
2455 case MIToken::kw_cfi_offset
:
2456 case MIToken::kw_cfi_rel_offset
:
2457 case MIToken::kw_cfi_def_cfa_register
:
2458 case MIToken::kw_cfi_def_cfa_offset
:
2459 case MIToken::kw_cfi_adjust_cfa_offset
:
2460 case MIToken::kw_cfi_escape
:
2461 case MIToken::kw_cfi_def_cfa
:
2462 case MIToken::kw_cfi_register
:
2463 case MIToken::kw_cfi_remember_state
:
2464 case MIToken::kw_cfi_restore
:
2465 case MIToken::kw_cfi_restore_state
:
2466 case MIToken::kw_cfi_undefined
:
2467 case MIToken::kw_cfi_window_save
:
2468 case MIToken::kw_cfi_aarch64_negate_ra_sign_state
:
2469 return parseCFIOperand(Dest
);
2470 case MIToken::kw_blockaddress
:
2471 return parseBlockAddressOperand(Dest
);
2472 case MIToken::kw_intrinsic
:
2473 return parseIntrinsicOperand(Dest
);
2474 case MIToken::kw_target_index
:
2475 return parseTargetIndexOperand(Dest
);
2476 case MIToken::kw_liveout
:
2477 return parseLiveoutRegisterMaskOperand(Dest
);
2478 case MIToken::kw_floatpred
:
2479 case MIToken::kw_intpred
:
2480 return parsePredicateOperand(Dest
);
2481 case MIToken::kw_shufflemask
:
2482 return parseShuffleMaskOperand(Dest
);
2483 case MIToken::Error
:
2485 case MIToken::Identifier
:
2486 if (const auto *RegMask
= PFS
.Target
.getRegMask(Token
.stringValue())) {
2487 Dest
= MachineOperand::CreateRegMask(RegMask
);
2490 } else if (Token
.stringValue() == "CustomRegMask") {
2491 return parseCustomRegisterMaskOperand(Dest
);
2493 return parseTypedImmediateOperand(Dest
);
2495 // FIXME: Parse the MCSymbol machine operand.
2496 return error("expected a machine operand");
2501 bool MIParser::parseMachineOperandAndTargetFlags(
2502 MachineOperand
&Dest
, Optional
<unsigned> &TiedDefIdx
) {
2504 bool HasTargetFlags
= false;
2505 if (Token
.is(MIToken::kw_target_flags
)) {
2506 HasTargetFlags
= true;
2508 if (expectAndConsume(MIToken::lparen
))
2510 if (Token
.isNot(MIToken::Identifier
))
2511 return error("expected the name of the target flag");
2512 if (PFS
.Target
.getDirectTargetFlag(Token
.stringValue(), TF
)) {
2513 if (PFS
.Target
.getBitmaskTargetFlag(Token
.stringValue(), TF
))
2514 return error("use of undefined target flag '" + Token
.stringValue() +
2518 while (Token
.is(MIToken::comma
)) {
2520 if (Token
.isNot(MIToken::Identifier
))
2521 return error("expected the name of the target flag");
2522 unsigned BitFlag
= 0;
2523 if (PFS
.Target
.getBitmaskTargetFlag(Token
.stringValue(), BitFlag
))
2524 return error("use of undefined target flag '" + Token
.stringValue() +
2526 // TODO: Report an error when using a duplicate bit target flag.
2530 if (expectAndConsume(MIToken::rparen
))
2533 auto Loc
= Token
.location();
2534 if (parseMachineOperand(Dest
, TiedDefIdx
))
2536 if (!HasTargetFlags
)
2539 return error(Loc
, "register operands can't have target flags");
2540 Dest
.setTargetFlags(TF
);
2544 bool MIParser::parseOffset(int64_t &Offset
) {
2545 if (Token
.isNot(MIToken::plus
) && Token
.isNot(MIToken::minus
))
2547 StringRef Sign
= Token
.range();
2548 bool IsNegative
= Token
.is(MIToken::minus
);
2550 if (Token
.isNot(MIToken::IntegerLiteral
))
2551 return error("expected an integer literal after '" + Sign
+ "'");
2552 if (Token
.integerValue().getMinSignedBits() > 64)
2553 return error("expected 64-bit integer (too large)");
2554 Offset
= Token
.integerValue().getExtValue();
2561 bool MIParser::parseAlignment(unsigned &Alignment
) {
2562 assert(Token
.is(MIToken::kw_align
));
2564 if (Token
.isNot(MIToken::IntegerLiteral
) || Token
.integerValue().isSigned())
2565 return error("expected an integer literal after 'align'");
2566 if (getUnsigned(Alignment
))
2570 if (!isPowerOf2_32(Alignment
))
2571 return error("expected a power-of-2 literal after 'align'");
2576 bool MIParser::parseAddrspace(unsigned &Addrspace
) {
2577 assert(Token
.is(MIToken::kw_addrspace
));
2579 if (Token
.isNot(MIToken::IntegerLiteral
) || Token
.integerValue().isSigned())
2580 return error("expected an integer literal after 'addrspace'");
2581 if (getUnsigned(Addrspace
))
2587 bool MIParser::parseOperandsOffset(MachineOperand
&Op
) {
2589 if (parseOffset(Offset
))
2591 Op
.setOffset(Offset
);
2595 bool MIParser::parseIRValue(const Value
*&V
) {
2596 switch (Token
.kind()) {
2597 case MIToken::NamedIRValue
: {
2598 V
= MF
.getFunction().getValueSymbolTable()->lookup(Token
.stringValue());
2601 case MIToken::IRValue
: {
2602 unsigned SlotNumber
= 0;
2603 if (getUnsigned(SlotNumber
))
2605 V
= getIRValue(SlotNumber
);
2608 case MIToken::NamedGlobalValue
:
2609 case MIToken::GlobalValue
: {
2610 GlobalValue
*GV
= nullptr;
2611 if (parseGlobalValue(GV
))
2616 case MIToken::QuotedIRValue
: {
2617 const Constant
*C
= nullptr;
2618 if (parseIRConstant(Token
.location(), Token
.stringValue(), C
))
2624 llvm_unreachable("The current token should be an IR block reference");
2627 return error(Twine("use of undefined IR value '") + Token
.range() + "'");
2631 bool MIParser::getUint64(uint64_t &Result
) {
2632 if (Token
.hasIntegerValue()) {
2633 if (Token
.integerValue().getActiveBits() > 64)
2634 return error("expected 64-bit integer (too large)");
2635 Result
= Token
.integerValue().getZExtValue();
2638 if (Token
.is(MIToken::HexLiteral
)) {
2642 if (A
.getBitWidth() > 64)
2643 return error("expected 64-bit integer (too large)");
2644 Result
= A
.getZExtValue();
2650 bool MIParser::getHexUint(APInt
&Result
) {
2651 assert(Token
.is(MIToken::HexLiteral
));
2652 StringRef S
= Token
.range();
2653 assert(S
[0] == '0' && tolower(S
[1]) == 'x');
2654 // This could be a floating point literal with a special prefix.
2655 if (!isxdigit(S
[2]))
2657 StringRef V
= S
.substr(2);
2658 APInt
A(V
.size()*4, V
, 16);
2660 // If A is 0, then A.getActiveBits() is 0. This isn't a valid bitwidth. Make
2661 // sure it isn't the case before constructing result.
2662 unsigned NumBits
= (A
== 0) ? 32 : A
.getActiveBits();
2663 Result
= APInt(NumBits
, ArrayRef
<uint64_t>(A
.getRawData(), A
.getNumWords()));
2667 bool MIParser::parseMemoryOperandFlag(MachineMemOperand::Flags
&Flags
) {
2668 const auto OldFlags
= Flags
;
2669 switch (Token
.kind()) {
2670 case MIToken::kw_volatile
:
2671 Flags
|= MachineMemOperand::MOVolatile
;
2673 case MIToken::kw_non_temporal
:
2674 Flags
|= MachineMemOperand::MONonTemporal
;
2676 case MIToken::kw_dereferenceable
:
2677 Flags
|= MachineMemOperand::MODereferenceable
;
2679 case MIToken::kw_invariant
:
2680 Flags
|= MachineMemOperand::MOInvariant
;
2682 case MIToken::StringConstant
: {
2683 MachineMemOperand::Flags TF
;
2684 if (PFS
.Target
.getMMOTargetFlag(Token
.stringValue(), TF
))
2685 return error("use of undefined target MMO flag '" + Token
.stringValue() +
2691 llvm_unreachable("The current token should be a memory operand flag");
2693 if (OldFlags
== Flags
)
2694 // We know that the same flag is specified more than once when the flags
2695 // weren't modified.
2696 return error("duplicate '" + Token
.stringValue() + "' memory operand flag");
2701 bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue
*&PSV
) {
2702 switch (Token
.kind()) {
2703 case MIToken::kw_stack
:
2704 PSV
= MF
.getPSVManager().getStack();
2706 case MIToken::kw_got
:
2707 PSV
= MF
.getPSVManager().getGOT();
2709 case MIToken::kw_jump_table
:
2710 PSV
= MF
.getPSVManager().getJumpTable();
2712 case MIToken::kw_constant_pool
:
2713 PSV
= MF
.getPSVManager().getConstantPool();
2715 case MIToken::FixedStackObject
: {
2717 if (parseFixedStackFrameIndex(FI
))
2719 PSV
= MF
.getPSVManager().getFixedStack(FI
);
2720 // The token was already consumed, so use return here instead of break.
2723 case MIToken::StackObject
: {
2725 if (parseStackFrameIndex(FI
))
2727 PSV
= MF
.getPSVManager().getFixedStack(FI
);
2728 // The token was already consumed, so use return here instead of break.
2731 case MIToken::kw_call_entry
:
2733 switch (Token
.kind()) {
2734 case MIToken::GlobalValue
:
2735 case MIToken::NamedGlobalValue
: {
2736 GlobalValue
*GV
= nullptr;
2737 if (parseGlobalValue(GV
))
2739 PSV
= MF
.getPSVManager().getGlobalValueCallEntry(GV
);
2742 case MIToken::ExternalSymbol
:
2743 PSV
= MF
.getPSVManager().getExternalSymbolCallEntry(
2744 MF
.createExternalSymbolName(Token
.stringValue()));
2748 "expected a global value or an external symbol after 'call-entry'");
2752 llvm_unreachable("The current token should be pseudo source value");
2758 bool MIParser::parseMachinePointerInfo(MachinePointerInfo
&Dest
) {
2759 if (Token
.is(MIToken::kw_constant_pool
) || Token
.is(MIToken::kw_stack
) ||
2760 Token
.is(MIToken::kw_got
) || Token
.is(MIToken::kw_jump_table
) ||
2761 Token
.is(MIToken::FixedStackObject
) || Token
.is(MIToken::StackObject
) ||
2762 Token
.is(MIToken::kw_call_entry
)) {
2763 const PseudoSourceValue
*PSV
= nullptr;
2764 if (parseMemoryPseudoSourceValue(PSV
))
2767 if (parseOffset(Offset
))
2769 Dest
= MachinePointerInfo(PSV
, Offset
);
2772 if (Token
.isNot(MIToken::NamedIRValue
) && Token
.isNot(MIToken::IRValue
) &&
2773 Token
.isNot(MIToken::GlobalValue
) &&
2774 Token
.isNot(MIToken::NamedGlobalValue
) &&
2775 Token
.isNot(MIToken::QuotedIRValue
))
2776 return error("expected an IR value reference");
2777 const Value
*V
= nullptr;
2778 if (parseIRValue(V
))
2780 if (!V
->getType()->isPointerTy())
2781 return error("expected a pointer IR value");
2784 if (parseOffset(Offset
))
2786 Dest
= MachinePointerInfo(V
, Offset
);
2790 bool MIParser::parseOptionalScope(LLVMContext
&Context
,
2791 SyncScope::ID
&SSID
) {
2792 SSID
= SyncScope::System
;
2793 if (Token
.is(MIToken::Identifier
) && Token
.stringValue() == "syncscope") {
2795 if (expectAndConsume(MIToken::lparen
))
2796 return error("expected '(' in syncscope");
2799 if (parseStringConstant(SSN
))
2802 SSID
= Context
.getOrInsertSyncScopeID(SSN
);
2803 if (expectAndConsume(MIToken::rparen
))
2804 return error("expected ')' in syncscope");
2810 bool MIParser::parseOptionalAtomicOrdering(AtomicOrdering
&Order
) {
2811 Order
= AtomicOrdering::NotAtomic
;
2812 if (Token
.isNot(MIToken::Identifier
))
2815 Order
= StringSwitch
<AtomicOrdering
>(Token
.stringValue())
2816 .Case("unordered", AtomicOrdering::Unordered
)
2817 .Case("monotonic", AtomicOrdering::Monotonic
)
2818 .Case("acquire", AtomicOrdering::Acquire
)
2819 .Case("release", AtomicOrdering::Release
)
2820 .Case("acq_rel", AtomicOrdering::AcquireRelease
)
2821 .Case("seq_cst", AtomicOrdering::SequentiallyConsistent
)
2822 .Default(AtomicOrdering::NotAtomic
);
2824 if (Order
!= AtomicOrdering::NotAtomic
) {
2829 return error("expected an atomic scope, ordering or a size specification");
2832 bool MIParser::parseMachineMemoryOperand(MachineMemOperand
*&Dest
) {
2833 if (expectAndConsume(MIToken::lparen
))
2835 MachineMemOperand::Flags Flags
= MachineMemOperand::MONone
;
2836 while (Token
.isMemoryOperandFlag()) {
2837 if (parseMemoryOperandFlag(Flags
))
2840 if (Token
.isNot(MIToken::Identifier
) ||
2841 (Token
.stringValue() != "load" && Token
.stringValue() != "store"))
2842 return error("expected 'load' or 'store' memory operation");
2843 if (Token
.stringValue() == "load")
2844 Flags
|= MachineMemOperand::MOLoad
;
2846 Flags
|= MachineMemOperand::MOStore
;
2849 // Optional 'store' for operands that both load and store.
2850 if (Token
.is(MIToken::Identifier
) && Token
.stringValue() == "store") {
2851 Flags
|= MachineMemOperand::MOStore
;
2855 // Optional synchronization scope.
2857 if (parseOptionalScope(MF
.getFunction().getContext(), SSID
))
2860 // Up to two atomic orderings (cmpxchg provides guarantees on failure).
2861 AtomicOrdering Order
, FailureOrder
;
2862 if (parseOptionalAtomicOrdering(Order
))
2865 if (parseOptionalAtomicOrdering(FailureOrder
))
2868 if (Token
.isNot(MIToken::IntegerLiteral
) &&
2869 Token
.isNot(MIToken::kw_unknown_size
))
2870 return error("expected the size integer literal or 'unknown-size' after "
2871 "memory operation");
2873 if (Token
.is(MIToken::IntegerLiteral
)) {
2874 if (getUint64(Size
))
2876 } else if (Token
.is(MIToken::kw_unknown_size
)) {
2877 Size
= MemoryLocation::UnknownSize
;
2881 MachinePointerInfo Ptr
= MachinePointerInfo();
2882 if (Token
.is(MIToken::Identifier
)) {
2884 ((Flags
& MachineMemOperand::MOLoad
) &&
2885 (Flags
& MachineMemOperand::MOStore
))
2887 : Flags
& MachineMemOperand::MOLoad
? "from" : "into";
2888 if (Token
.stringValue() != Word
)
2889 return error(Twine("expected '") + Word
+ "'");
2892 if (parseMachinePointerInfo(Ptr
))
2895 unsigned BaseAlignment
= (Size
!= MemoryLocation::UnknownSize
? Size
: 1);
2897 MDNode
*Range
= nullptr;
2898 while (consumeIfPresent(MIToken::comma
)) {
2899 switch (Token
.kind()) {
2900 case MIToken::kw_align
:
2901 if (parseAlignment(BaseAlignment
))
2904 case MIToken::kw_addrspace
:
2905 if (parseAddrspace(Ptr
.AddrSpace
))
2908 case MIToken::md_tbaa
:
2910 if (parseMDNode(AAInfo
.TBAA
))
2913 case MIToken::md_alias_scope
:
2915 if (parseMDNode(AAInfo
.Scope
))
2918 case MIToken::md_noalias
:
2920 if (parseMDNode(AAInfo
.NoAlias
))
2923 case MIToken::md_range
:
2925 if (parseMDNode(Range
))
2928 // TODO: Report an error on duplicate metadata nodes.
2930 return error("expected 'align' or '!tbaa' or '!alias.scope' or "
2931 "'!noalias' or '!range'");
2934 if (expectAndConsume(MIToken::rparen
))
2936 Dest
= MF
.getMachineMemOperand(Ptr
, Flags
, Size
, BaseAlignment
, AAInfo
, Range
,
2937 SSID
, Order
, FailureOrder
);
2941 bool MIParser::parsePreOrPostInstrSymbol(MCSymbol
*&Symbol
) {
2942 assert((Token
.is(MIToken::kw_pre_instr_symbol
) ||
2943 Token
.is(MIToken::kw_post_instr_symbol
)) &&
2944 "Invalid token for a pre- post-instruction symbol!");
2946 if (Token
.isNot(MIToken::MCSymbol
))
2947 return error("expected a symbol after 'pre-instr-symbol'");
2948 Symbol
= getOrCreateMCSymbol(Token
.stringValue());
2950 if (Token
.isNewlineOrEOF() || Token
.is(MIToken::coloncolon
) ||
2951 Token
.is(MIToken::lbrace
))
2953 if (Token
.isNot(MIToken::comma
))
2954 return error("expected ',' before the next machine operand");
2959 static void initSlots2BasicBlocks(
2961 DenseMap
<unsigned, const BasicBlock
*> &Slots2BasicBlocks
) {
2962 ModuleSlotTracker
MST(F
.getParent(), /*ShouldInitializeAllMetadata=*/false);
2963 MST
.incorporateFunction(F
);
2964 for (auto &BB
: F
) {
2967 int Slot
= MST
.getLocalSlot(&BB
);
2970 Slots2BasicBlocks
.insert(std::make_pair(unsigned(Slot
), &BB
));
2974 static const BasicBlock
*getIRBlockFromSlot(
2976 const DenseMap
<unsigned, const BasicBlock
*> &Slots2BasicBlocks
) {
2977 auto BlockInfo
= Slots2BasicBlocks
.find(Slot
);
2978 if (BlockInfo
== Slots2BasicBlocks
.end())
2980 return BlockInfo
->second
;
2983 const BasicBlock
*MIParser::getIRBlock(unsigned Slot
) {
2984 if (Slots2BasicBlocks
.empty())
2985 initSlots2BasicBlocks(MF
.getFunction(), Slots2BasicBlocks
);
2986 return getIRBlockFromSlot(Slot
, Slots2BasicBlocks
);
2989 const BasicBlock
*MIParser::getIRBlock(unsigned Slot
, const Function
&F
) {
2990 if (&F
== &MF
.getFunction())
2991 return getIRBlock(Slot
);
2992 DenseMap
<unsigned, const BasicBlock
*> CustomSlots2BasicBlocks
;
2993 initSlots2BasicBlocks(F
, CustomSlots2BasicBlocks
);
2994 return getIRBlockFromSlot(Slot
, CustomSlots2BasicBlocks
);
2997 static void mapValueToSlot(const Value
*V
, ModuleSlotTracker
&MST
,
2998 DenseMap
<unsigned, const Value
*> &Slots2Values
) {
2999 int Slot
= MST
.getLocalSlot(V
);
3002 Slots2Values
.insert(std::make_pair(unsigned(Slot
), V
));
3005 /// Creates the mapping from slot numbers to function's unnamed IR values.
3006 static void initSlots2Values(const Function
&F
,
3007 DenseMap
<unsigned, const Value
*> &Slots2Values
) {
3008 ModuleSlotTracker
MST(F
.getParent(), /*ShouldInitializeAllMetadata=*/false);
3009 MST
.incorporateFunction(F
);
3010 for (const auto &Arg
: F
.args())
3011 mapValueToSlot(&Arg
, MST
, Slots2Values
);
3012 for (const auto &BB
: F
) {
3013 mapValueToSlot(&BB
, MST
, Slots2Values
);
3014 for (const auto &I
: BB
)
3015 mapValueToSlot(&I
, MST
, Slots2Values
);
3019 const Value
*MIParser::getIRValue(unsigned Slot
) {
3020 if (Slots2Values
.empty())
3021 initSlots2Values(MF
.getFunction(), Slots2Values
);
3022 auto ValueInfo
= Slots2Values
.find(Slot
);
3023 if (ValueInfo
== Slots2Values
.end())
3025 return ValueInfo
->second
;
3028 MCSymbol
*MIParser::getOrCreateMCSymbol(StringRef Name
) {
3029 // FIXME: Currently we can't recognize temporary or local symbols and call all
3030 // of the appropriate forms to create them. However, this handles basic cases
3031 // well as most of the special aspects are recognized by a prefix on their
3032 // name, and the input names should already be unique. For test cases, keeping
3033 // the symbol name out of the symbol table isn't terribly important.
3034 return MF
.getContext().getOrCreateSymbol(Name
);
3037 bool MIParser::parseStringConstant(std::string
&Result
) {
3038 if (Token
.isNot(MIToken::StringConstant
))
3039 return error("expected string constant");
3040 Result
= Token
.stringValue();
3045 bool llvm::parseMachineBasicBlockDefinitions(PerFunctionMIParsingState
&PFS
,
3047 SMDiagnostic
&Error
) {
3048 return MIParser(PFS
, Error
, Src
).parseBasicBlockDefinitions(PFS
.MBBSlots
);
3051 bool llvm::parseMachineInstructions(PerFunctionMIParsingState
&PFS
,
3052 StringRef Src
, SMDiagnostic
&Error
) {
3053 return MIParser(PFS
, Error
, Src
).parseBasicBlocks();
3056 bool llvm::parseMBBReference(PerFunctionMIParsingState
&PFS
,
3057 MachineBasicBlock
*&MBB
, StringRef Src
,
3058 SMDiagnostic
&Error
) {
3059 return MIParser(PFS
, Error
, Src
).parseStandaloneMBB(MBB
);
3062 bool llvm::parseRegisterReference(PerFunctionMIParsingState
&PFS
,
3063 unsigned &Reg
, StringRef Src
,
3064 SMDiagnostic
&Error
) {
3065 return MIParser(PFS
, Error
, Src
).parseStandaloneRegister(Reg
);
3068 bool llvm::parseNamedRegisterReference(PerFunctionMIParsingState
&PFS
,
3069 unsigned &Reg
, StringRef Src
,
3070 SMDiagnostic
&Error
) {
3071 return MIParser(PFS
, Error
, Src
).parseStandaloneNamedRegister(Reg
);
3074 bool llvm::parseVirtualRegisterReference(PerFunctionMIParsingState
&PFS
,
3075 VRegInfo
*&Info
, StringRef Src
,
3076 SMDiagnostic
&Error
) {
3077 return MIParser(PFS
, Error
, Src
).parseStandaloneVirtualRegister(Info
);
3080 bool llvm::parseStackObjectReference(PerFunctionMIParsingState
&PFS
,
3081 int &FI
, StringRef Src
,
3082 SMDiagnostic
&Error
) {
3083 return MIParser(PFS
, Error
, Src
).parseStandaloneStackObject(FI
);
3086 bool llvm::parseMDNode(PerFunctionMIParsingState
&PFS
,
3087 MDNode
*&Node
, StringRef Src
, SMDiagnostic
&Error
) {
3088 return MIParser(PFS
, Error
, Src
).parseStandaloneMDNode(Node
);