MIR Serialization: Serialize the null register operands.
[oota-llvm.git] / lib / CodeGen / MIRParser / MIParser.cpp
1 //===- MIParser.cpp - Machine instructions parser implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the parsing of machine instructions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "MIParser.h"
15 #include "MILexer.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/CodeGen/MachineBasicBlock.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include "llvm/Support/SourceMgr.h"
22 #include "llvm/Target/TargetSubtargetInfo.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24
25 using namespace llvm;
26
27 namespace {
28
29 class MIParser {
30   SourceMgr &SM;
31   MachineFunction &MF;
32   SMDiagnostic &Error;
33   StringRef Source, CurrentSource;
34   MIToken Token;
35   /// Maps from instruction names to op codes.
36   StringMap<unsigned> Names2InstrOpCodes;
37   /// Maps from register names to registers.
38   StringMap<unsigned> Names2Regs;
39
40 public:
41   MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
42            StringRef Source);
43
44   void lex();
45
46   /// Report an error at the current location with the given message.
47   ///
48   /// This function always return true.
49   bool error(const Twine &Msg);
50
51   /// Report an error at the given location with the given message.
52   ///
53   /// This function always return true.
54   bool error(StringRef::iterator Loc, const Twine &Msg);
55
56   MachineInstr *parse();
57
58   bool parseRegister(unsigned &Reg);
59   bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
60   bool parseImmediateOperand(MachineOperand &Dest);
61   bool parseMachineOperand(MachineOperand &Dest);
62
63 private:
64   void initNames2InstrOpCodes();
65
66   /// Try to convert an instruction name to an opcode. Return true if the
67   /// instruction name is invalid.
68   bool parseInstrName(StringRef InstrName, unsigned &OpCode);
69
70   bool parseInstruction(unsigned &OpCode);
71
72   void initNames2Regs();
73
74   /// Try to convert a register name to a register number. Return true if the
75   /// register name is invalid.
76   bool getRegisterByName(StringRef RegName, unsigned &Reg);
77 };
78
79 } // end anonymous namespace
80
81 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
82                    StringRef Source)
83     : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
84       Token(MIToken::Error, StringRef()) {}
85
86 void MIParser::lex() {
87   CurrentSource = lexMIToken(
88       CurrentSource, Token,
89       [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
90 }
91
92 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
93
94 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
95   // TODO: Get the proper location in the MIR file, not just a location inside
96   // the string.
97   assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
98   Error = SMDiagnostic(
99       SM, SMLoc(),
100       SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
101       Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
102   return true;
103 }
104
105 MachineInstr *MIParser::parse() {
106   lex();
107
108   // Parse any register operands before '='
109   // TODO: Allow parsing of multiple operands before '='
110   MachineOperand MO = MachineOperand::CreateImm(0);
111   SmallVector<MachineOperand, 8> Operands;
112   if (Token.isRegister()) {
113     if (parseRegisterOperand(MO, /*IsDef=*/true))
114       return nullptr;
115     Operands.push_back(MO);
116     if (Token.isNot(MIToken::equal)) {
117       error("expected '='");
118       return nullptr;
119     }
120     lex();
121   }
122
123   unsigned OpCode;
124   if (Token.isError() || parseInstruction(OpCode))
125     return nullptr;
126
127   // TODO: Parse the instruction flags and memory operands.
128
129   // Parse the remaining machine operands.
130   while (Token.isNot(MIToken::Eof)) {
131     if (parseMachineOperand(MO))
132       return nullptr;
133     Operands.push_back(MO);
134     if (Token.is(MIToken::Eof))
135       break;
136     if (Token.isNot(MIToken::comma)) {
137       error("expected ',' before the next machine operand");
138       return nullptr;
139     }
140     lex();
141   }
142
143   const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
144
145   // Verify machine operands.
146   if (!MCID.isVariadic()) {
147     for (size_t I = 0, E = Operands.size(); I < E; ++I) {
148       if (I < MCID.getNumOperands())
149         continue;
150       // Mark this register as implicit to prevent an assertion when it's added
151       // to an instruction. This is a temporary workaround until the implicit
152       // register flag can be parsed.
153       Operands[I].setImplicit();
154     }
155   }
156
157   // TODO: Determine the implicit behaviour when implicit register flags are
158   // parsed.
159   auto *MI = MF.CreateMachineInstr(MCID, DebugLoc(), /*NoImplicit=*/true);
160   for (const auto &Operand : Operands)
161     MI->addOperand(MF, Operand);
162   return MI;
163 }
164
165 bool MIParser::parseInstruction(unsigned &OpCode) {
166   if (Token.isNot(MIToken::Identifier))
167     return error("expected a machine instruction");
168   StringRef InstrName = Token.stringValue();
169   if (parseInstrName(InstrName, OpCode))
170     return error(Twine("unknown machine instruction name '") + InstrName + "'");
171   lex();
172   return false;
173 }
174
175 bool MIParser::parseRegister(unsigned &Reg) {
176   switch (Token.kind()) {
177   case MIToken::underscore:
178     Reg = 0;
179     break;
180   case MIToken::NamedRegister: {
181     StringRef Name = Token.stringValue().drop_front(1); // Drop the '%'
182     if (getRegisterByName(Name, Reg))
183       return error(Twine("unknown register name '") + Name + "'");
184     break;
185   }
186   // TODO: Parse other register kinds.
187   default:
188     llvm_unreachable("The current token should be a register");
189   }
190   return false;
191 }
192
193 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
194   unsigned Reg;
195   // TODO: Parse register flags.
196   if (parseRegister(Reg))
197     return true;
198   lex();
199   // TODO: Parse subregister.
200   Dest = MachineOperand::CreateReg(Reg, IsDef);
201   return false;
202 }
203
204 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
205   assert(Token.is(MIToken::IntegerLiteral));
206   const APSInt &Int = Token.integerValue();
207   if (Int.getMinSignedBits() > 64)
208     // TODO: Replace this with an error when we can parse CIMM Machine Operands.
209     llvm_unreachable("Can't parse large integer literals yet!");
210   Dest = MachineOperand::CreateImm(Int.getExtValue());
211   lex();
212   return false;
213 }
214
215 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
216   switch (Token.kind()) {
217   case MIToken::underscore:
218   case MIToken::NamedRegister:
219     return parseRegisterOperand(Dest);
220   case MIToken::IntegerLiteral:
221     return parseImmediateOperand(Dest);
222   case MIToken::Error:
223     return true;
224   default:
225     // TODO: parse the other machine operands.
226     return error("expected a machine operand");
227   }
228   return false;
229 }
230
231 void MIParser::initNames2InstrOpCodes() {
232   if (!Names2InstrOpCodes.empty())
233     return;
234   const auto *TII = MF.getSubtarget().getInstrInfo();
235   assert(TII && "Expected target instruction info");
236   for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
237     Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
238 }
239
240 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
241   initNames2InstrOpCodes();
242   auto InstrInfo = Names2InstrOpCodes.find(InstrName);
243   if (InstrInfo == Names2InstrOpCodes.end())
244     return true;
245   OpCode = InstrInfo->getValue();
246   return false;
247 }
248
249 void MIParser::initNames2Regs() {
250   if (!Names2Regs.empty())
251     return;
252   // The '%noreg' register is the register 0.
253   Names2Regs.insert(std::make_pair("noreg", 0));
254   const auto *TRI = MF.getSubtarget().getRegisterInfo();
255   assert(TRI && "Expected target register info");
256   for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
257     bool WasInserted =
258         Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
259             .second;
260     (void)WasInserted;
261     assert(WasInserted && "Expected registers to be unique case-insensitively");
262   }
263 }
264
265 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
266   initNames2Regs();
267   auto RegInfo = Names2Regs.find(RegName);
268   if (RegInfo == Names2Regs.end())
269     return true;
270   Reg = RegInfo->getValue();
271   return false;
272 }
273
274 MachineInstr *llvm::parseMachineInstr(SourceMgr &SM, MachineFunction &MF,
275                                       StringRef Src, SMDiagnostic &Error) {
276   return MIParser(SM, MF, Error, Src).parse();
277 }