MIR Serialization: Serialize physical register 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 parseMachineOperand(MachineOperand &Dest);
61
62 private:
63   void initNames2InstrOpCodes();
64
65   /// Try to convert an instruction name to an opcode. Return true if the
66   /// instruction name is invalid.
67   bool parseInstrName(StringRef InstrName, unsigned &OpCode);
68
69   bool parseInstruction(unsigned &OpCode);
70
71   void initNames2Regs();
72
73   /// Try to convert a register name to a register number. Return true if the
74   /// register name is invalid.
75   bool getRegisterByName(StringRef RegName, unsigned &Reg);
76 };
77
78 } // end anonymous namespace
79
80 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
81                    StringRef Source)
82     : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
83       Token(MIToken::Error, StringRef()) {}
84
85 void MIParser::lex() {
86   CurrentSource = lexMIToken(
87       CurrentSource, Token,
88       [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
89 }
90
91 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
92
93 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
94   // TODO: Get the proper location in the MIR file, not just a location inside
95   // the string.
96   assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
97   Error = SMDiagnostic(
98       SM, SMLoc(),
99       SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
100       Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
101   return true;
102 }
103
104 MachineInstr *MIParser::parse() {
105   lex();
106
107   // Parse any register operands before '='
108   // TODO: Allow parsing of multiple operands before '='
109   MachineOperand MO = MachineOperand::CreateImm(0);
110   SmallVector<MachineOperand, 8> Operands;
111   if (Token.isRegister()) {
112     if (parseRegisterOperand(MO, /*IsDef=*/true))
113       return nullptr;
114     Operands.push_back(MO);
115     if (Token.isNot(MIToken::equal)) {
116       error("expected '='");
117       return nullptr;
118     }
119     lex();
120   }
121
122   unsigned OpCode;
123   if (Token.isError() || parseInstruction(OpCode))
124     return nullptr;
125
126   // TODO: Parse the instruction flags and memory operands.
127
128   // Parse the remaining machine operands.
129   while (Token.isNot(MIToken::Eof)) {
130     if (parseMachineOperand(MO))
131       return nullptr;
132     Operands.push_back(MO);
133     if (Token.is(MIToken::Eof))
134       break;
135     if (Token.isNot(MIToken::comma)) {
136       error("expected ',' before the next machine operand");
137       return nullptr;
138     }
139     lex();
140   }
141
142   const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
143
144   // Verify machine operands.
145   if (!MCID.isVariadic()) {
146     for (size_t I = 0, E = Operands.size(); I < E; ++I) {
147       if (I < MCID.getNumOperands())
148         continue;
149       // Mark this register as implicit to prevent an assertion when it's added
150       // to an instruction. This is a temporary workaround until the implicit
151       // register flag can be parsed.
152       Operands[I].setImplicit();
153     }
154   }
155
156   // TODO: Determine the implicit behaviour when implicit register flags are
157   // parsed.
158   auto *MI = MF.CreateMachineInstr(MCID, DebugLoc(), /*NoImplicit=*/true);
159   for (const auto &Operand : Operands)
160     MI->addOperand(MF, Operand);
161   return MI;
162 }
163
164 bool MIParser::parseInstruction(unsigned &OpCode) {
165   if (Token.isNot(MIToken::Identifier))
166     return error("expected a machine instruction");
167   StringRef InstrName = Token.stringValue();
168   if (parseInstrName(InstrName, OpCode))
169     return error(Twine("unknown machine instruction name '") + InstrName + "'");
170   lex();
171   return false;
172 }
173
174 bool MIParser::parseRegister(unsigned &Reg) {
175   switch (Token.kind()) {
176   case MIToken::NamedRegister: {
177     StringRef Name = Token.stringValue().drop_front(1); // Drop the '%'
178     if (getRegisterByName(Name, Reg))
179       return error(Twine("unknown register name '") + Name + "'");
180     break;
181   }
182   // TODO: Parse other register kinds.
183   default:
184     llvm_unreachable("The current token should be a register");
185   }
186   return false;
187 }
188
189 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
190   unsigned Reg;
191   // TODO: Parse register flags.
192   if (parseRegister(Reg))
193     return true;
194   lex();
195   // TODO: Parse subregister.
196   Dest = MachineOperand::CreateReg(Reg, IsDef);
197   return false;
198 }
199
200 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
201   switch (Token.kind()) {
202   case MIToken::NamedRegister:
203     return parseRegisterOperand(Dest);
204   case MIToken::Error:
205     return true;
206   default:
207     // TODO: parse the other machine operands.
208     return error("expected a machine operand");
209   }
210   return false;
211 }
212
213 void MIParser::initNames2InstrOpCodes() {
214   if (!Names2InstrOpCodes.empty())
215     return;
216   const auto *TII = MF.getSubtarget().getInstrInfo();
217   assert(TII && "Expected target instruction info");
218   for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
219     Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
220 }
221
222 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
223   initNames2InstrOpCodes();
224   auto InstrInfo = Names2InstrOpCodes.find(InstrName);
225   if (InstrInfo == Names2InstrOpCodes.end())
226     return true;
227   OpCode = InstrInfo->getValue();
228   return false;
229 }
230
231 void MIParser::initNames2Regs() {
232   if (!Names2Regs.empty())
233     return;
234   const auto *TRI = MF.getSubtarget().getRegisterInfo();
235   assert(TRI && "Expected target register info");
236   for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
237     bool WasInserted =
238         Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
239             .second;
240     (void)WasInserted;
241     assert(WasInserted && "Expected registers to be unique case-insensitively");
242   }
243 }
244
245 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
246   initNames2Regs();
247   auto RegInfo = Names2Regs.find(RegName);
248   if (RegInfo == Names2Regs.end())
249     return true;
250   Reg = RegInfo->getValue();
251   return false;
252 }
253
254 MachineInstr *llvm::parseMachineInstr(SourceMgr &SM, MachineFunction &MF,
255                                       StringRef Src, SMDiagnostic &Error) {
256   return MIParser(SM, MF, Error, Src).parse();
257 }