MIR Serialization: Serialize immediate machine 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::NamedRegister: {
178     StringRef Name = Token.stringValue().drop_front(1); // Drop the '%'
179     if (getRegisterByName(Name, Reg))
180       return error(Twine("unknown register name '") + Name + "'");
181     break;
182   }
183   // TODO: Parse other register kinds.
184   default:
185     llvm_unreachable("The current token should be a register");
186   }
187   return false;
188 }
189
190 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
191   unsigned Reg;
192   // TODO: Parse register flags.
193   if (parseRegister(Reg))
194     return true;
195   lex();
196   // TODO: Parse subregister.
197   Dest = MachineOperand::CreateReg(Reg, IsDef);
198   return false;
199 }
200
201 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
202   assert(Token.is(MIToken::IntegerLiteral));
203   const APSInt &Int = Token.integerValue();
204   if (Int.getMinSignedBits() > 64)
205     // TODO: Replace this with an error when we can parse CIMM Machine Operands.
206     llvm_unreachable("Can't parse large integer literals yet!");
207   Dest = MachineOperand::CreateImm(Int.getExtValue());
208   lex();
209   return false;
210 }
211
212 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
213   switch (Token.kind()) {
214   case MIToken::NamedRegister:
215     return parseRegisterOperand(Dest);
216   case MIToken::IntegerLiteral:
217     return parseImmediateOperand(Dest);
218   case MIToken::Error:
219     return true;
220   default:
221     // TODO: parse the other machine operands.
222     return error("expected a machine operand");
223   }
224   return false;
225 }
226
227 void MIParser::initNames2InstrOpCodes() {
228   if (!Names2InstrOpCodes.empty())
229     return;
230   const auto *TII = MF.getSubtarget().getInstrInfo();
231   assert(TII && "Expected target instruction info");
232   for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
233     Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
234 }
235
236 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
237   initNames2InstrOpCodes();
238   auto InstrInfo = Names2InstrOpCodes.find(InstrName);
239   if (InstrInfo == Names2InstrOpCodes.end())
240     return true;
241   OpCode = InstrInfo->getValue();
242   return false;
243 }
244
245 void MIParser::initNames2Regs() {
246   if (!Names2Regs.empty())
247     return;
248   const auto *TRI = MF.getSubtarget().getRegisterInfo();
249   assert(TRI && "Expected target register info");
250   for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
251     bool WasInserted =
252         Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
253             .second;
254     (void)WasInserted;
255     assert(WasInserted && "Expected registers to be unique case-insensitively");
256   }
257 }
258
259 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
260   initNames2Regs();
261   auto RegInfo = Names2Regs.find(RegName);
262   if (RegInfo == Names2Regs.end())
263     return true;
264   Reg = RegInfo->getValue();
265   return false;
266 }
267
268 MachineInstr *llvm::parseMachineInstr(SourceMgr &SM, MachineFunction &MF,
269                                       StringRef Src, SMDiagnostic &Error) {
270   return MIParser(SM, MF, Error, Src).parse();
271 }