MIR Serialization: Serialize the register mask 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/AsmParser/SlotMapping.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Support/SourceMgr.h"
24 #include "llvm/Target/TargetSubtargetInfo.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26
27 using namespace llvm;
28
29 namespace {
30
31 class MIParser {
32   SourceMgr &SM;
33   MachineFunction &MF;
34   SMDiagnostic &Error;
35   StringRef Source, CurrentSource;
36   MIToken Token;
37   /// Maps from basic block numbers to MBBs.
38   const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots;
39   /// Maps from indices to unnamed global values and metadata nodes.
40   const SlotMapping &IRSlots;
41   /// Maps from instruction names to op codes.
42   StringMap<unsigned> Names2InstrOpCodes;
43   /// Maps from register names to registers.
44   StringMap<unsigned> Names2Regs;
45   /// Maps from register mask names to register masks.
46   StringMap<const uint32_t *> Names2RegMasks;
47
48 public:
49   MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
50            StringRef Source,
51            const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
52            const SlotMapping &IRSlots);
53
54   void lex();
55
56   /// Report an error at the current location with the given message.
57   ///
58   /// This function always return true.
59   bool error(const Twine &Msg);
60
61   /// Report an error at the given location with the given message.
62   ///
63   /// This function always return true.
64   bool error(StringRef::iterator Loc, const Twine &Msg);
65
66   MachineInstr *parse();
67
68   bool parseRegister(unsigned &Reg);
69   bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
70   bool parseImmediateOperand(MachineOperand &Dest);
71   bool parseMBBOperand(MachineOperand &Dest);
72   bool parseGlobalAddressOperand(MachineOperand &Dest);
73   bool parseMachineOperand(MachineOperand &Dest);
74
75 private:
76   /// Convert the integer literal in the current token into an unsigned integer.
77   ///
78   /// Return true if an error occurred.
79   bool getUnsigned(unsigned &Result);
80
81   void initNames2InstrOpCodes();
82
83   /// Try to convert an instruction name to an opcode. Return true if the
84   /// instruction name is invalid.
85   bool parseInstrName(StringRef InstrName, unsigned &OpCode);
86
87   bool parseInstruction(unsigned &OpCode);
88
89   void initNames2Regs();
90
91   /// Try to convert a register name to a register number. Return true if the
92   /// register name is invalid.
93   bool getRegisterByName(StringRef RegName, unsigned &Reg);
94
95   void initNames2RegMasks();
96
97   /// Check if the given identifier is a name of a register mask.
98   ///
99   /// Return null if the identifier isn't a register mask.
100   const uint32_t *getRegMask(StringRef Identifier);
101 };
102
103 } // end anonymous namespace
104
105 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
106                    StringRef Source,
107                    const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
108                    const SlotMapping &IRSlots)
109     : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
110       Token(MIToken::Error, StringRef()), MBBSlots(MBBSlots), IRSlots(IRSlots) {
111 }
112
113 void MIParser::lex() {
114   CurrentSource = lexMIToken(
115       CurrentSource, Token,
116       [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
117 }
118
119 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
120
121 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
122   // TODO: Get the proper location in the MIR file, not just a location inside
123   // the string.
124   assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
125   Error = SMDiagnostic(
126       SM, SMLoc(),
127       SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
128       Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
129   return true;
130 }
131
132 MachineInstr *MIParser::parse() {
133   lex();
134
135   // Parse any register operands before '='
136   // TODO: Allow parsing of multiple operands before '='
137   MachineOperand MO = MachineOperand::CreateImm(0);
138   SmallVector<MachineOperand, 8> Operands;
139   if (Token.isRegister()) {
140     if (parseRegisterOperand(MO, /*IsDef=*/true))
141       return nullptr;
142     Operands.push_back(MO);
143     if (Token.isNot(MIToken::equal)) {
144       error("expected '='");
145       return nullptr;
146     }
147     lex();
148   }
149
150   unsigned OpCode;
151   if (Token.isError() || parseInstruction(OpCode))
152     return nullptr;
153
154   // TODO: Parse the instruction flags and memory operands.
155
156   // Parse the remaining machine operands.
157   while (Token.isNot(MIToken::Eof)) {
158     if (parseMachineOperand(MO))
159       return nullptr;
160     Operands.push_back(MO);
161     if (Token.is(MIToken::Eof))
162       break;
163     if (Token.isNot(MIToken::comma)) {
164       error("expected ',' before the next machine operand");
165       return nullptr;
166     }
167     lex();
168   }
169
170   const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
171
172   // Verify machine operands.
173   if (!MCID.isVariadic()) {
174     for (size_t I = 0, E = Operands.size(); I < E; ++I) {
175       if (I < MCID.getNumOperands())
176         continue;
177       // Mark this register as implicit to prevent an assertion when it's added
178       // to an instruction. This is a temporary workaround until the implicit
179       // register flag can be parsed.
180       if (Operands[I].isReg())
181         Operands[I].setImplicit();
182     }
183   }
184
185   // TODO: Determine the implicit behaviour when implicit register flags are
186   // parsed.
187   auto *MI = MF.CreateMachineInstr(MCID, DebugLoc(), /*NoImplicit=*/true);
188   for (const auto &Operand : Operands)
189     MI->addOperand(MF, Operand);
190   return MI;
191 }
192
193 bool MIParser::parseInstruction(unsigned &OpCode) {
194   if (Token.isNot(MIToken::Identifier))
195     return error("expected a machine instruction");
196   StringRef InstrName = Token.stringValue();
197   if (parseInstrName(InstrName, OpCode))
198     return error(Twine("unknown machine instruction name '") + InstrName + "'");
199   lex();
200   return false;
201 }
202
203 bool MIParser::parseRegister(unsigned &Reg) {
204   switch (Token.kind()) {
205   case MIToken::underscore:
206     Reg = 0;
207     break;
208   case MIToken::NamedRegister: {
209     StringRef Name = Token.stringValue();
210     if (getRegisterByName(Name, Reg))
211       return error(Twine("unknown register name '") + Name + "'");
212     break;
213   }
214   // TODO: Parse other register kinds.
215   default:
216     llvm_unreachable("The current token should be a register");
217   }
218   return false;
219 }
220
221 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
222   unsigned Reg;
223   // TODO: Parse register flags.
224   if (parseRegister(Reg))
225     return true;
226   lex();
227   // TODO: Parse subregister.
228   Dest = MachineOperand::CreateReg(Reg, IsDef);
229   return false;
230 }
231
232 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
233   assert(Token.is(MIToken::IntegerLiteral));
234   const APSInt &Int = Token.integerValue();
235   if (Int.getMinSignedBits() > 64)
236     // TODO: Replace this with an error when we can parse CIMM Machine Operands.
237     llvm_unreachable("Can't parse large integer literals yet!");
238   Dest = MachineOperand::CreateImm(Int.getExtValue());
239   lex();
240   return false;
241 }
242
243 bool MIParser::getUnsigned(unsigned &Result) {
244   assert(Token.hasIntegerValue() && "Expected a token with an integer value");
245   const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
246   uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
247   if (Val64 == Limit)
248     return error("expected 32-bit integer (too large)");
249   Result = Val64;
250   return false;
251 }
252
253 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
254   assert(Token.is(MIToken::MachineBasicBlock));
255   unsigned Number;
256   if (getUnsigned(Number))
257     return true;
258   auto MBBInfo = MBBSlots.find(Number);
259   if (MBBInfo == MBBSlots.end())
260     return error(Twine("use of undefined machine basic block #") +
261                  Twine(Number));
262   MachineBasicBlock *MBB = MBBInfo->second;
263   if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
264     return error(Twine("the name of machine basic block #") + Twine(Number) +
265                  " isn't '" + Token.stringValue() + "'");
266   Dest = MachineOperand::CreateMBB(MBB);
267   lex();
268   return false;
269 }
270
271 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
272   switch (Token.kind()) {
273   case MIToken::NamedGlobalValue: {
274     auto Name = Token.stringValue();
275     const Module *M = MF.getFunction()->getParent();
276     if (const auto *GV = M->getNamedValue(Name)) {
277       Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
278       break;
279     }
280     return error(Twine("use of undefined global value '@") + Name + "'");
281   }
282   case MIToken::GlobalValue: {
283     unsigned GVIdx;
284     if (getUnsigned(GVIdx))
285       return true;
286     if (GVIdx >= IRSlots.GlobalValues.size())
287       return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
288                    "'");
289     Dest = MachineOperand::CreateGA(IRSlots.GlobalValues[GVIdx],
290                                     /*Offset=*/0);
291     break;
292   }
293   default:
294     llvm_unreachable("The current token should be a global value");
295   }
296   // TODO: Parse offset and target flags.
297   lex();
298   return false;
299 }
300
301 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
302   switch (Token.kind()) {
303   case MIToken::underscore:
304   case MIToken::NamedRegister:
305     return parseRegisterOperand(Dest);
306   case MIToken::IntegerLiteral:
307     return parseImmediateOperand(Dest);
308   case MIToken::MachineBasicBlock:
309     return parseMBBOperand(Dest);
310   case MIToken::GlobalValue:
311   case MIToken::NamedGlobalValue:
312     return parseGlobalAddressOperand(Dest);
313   case MIToken::Error:
314     return true;
315   case MIToken::Identifier:
316     if (const auto *RegMask = getRegMask(Token.stringValue())) {
317       Dest = MachineOperand::CreateRegMask(RegMask);
318       lex();
319       break;
320     }
321   // fallthrough
322   default:
323     // TODO: parse the other machine operands.
324     return error("expected a machine operand");
325   }
326   return false;
327 }
328
329 void MIParser::initNames2InstrOpCodes() {
330   if (!Names2InstrOpCodes.empty())
331     return;
332   const auto *TII = MF.getSubtarget().getInstrInfo();
333   assert(TII && "Expected target instruction info");
334   for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
335     Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
336 }
337
338 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
339   initNames2InstrOpCodes();
340   auto InstrInfo = Names2InstrOpCodes.find(InstrName);
341   if (InstrInfo == Names2InstrOpCodes.end())
342     return true;
343   OpCode = InstrInfo->getValue();
344   return false;
345 }
346
347 void MIParser::initNames2Regs() {
348   if (!Names2Regs.empty())
349     return;
350   // The '%noreg' register is the register 0.
351   Names2Regs.insert(std::make_pair("noreg", 0));
352   const auto *TRI = MF.getSubtarget().getRegisterInfo();
353   assert(TRI && "Expected target register info");
354   for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
355     bool WasInserted =
356         Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
357             .second;
358     (void)WasInserted;
359     assert(WasInserted && "Expected registers to be unique case-insensitively");
360   }
361 }
362
363 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
364   initNames2Regs();
365   auto RegInfo = Names2Regs.find(RegName);
366   if (RegInfo == Names2Regs.end())
367     return true;
368   Reg = RegInfo->getValue();
369   return false;
370 }
371
372 void MIParser::initNames2RegMasks() {
373   if (!Names2RegMasks.empty())
374     return;
375   const auto *TRI = MF.getSubtarget().getRegisterInfo();
376   assert(TRI && "Expected target register info");
377   ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
378   ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
379   assert(RegMasks.size() == RegMaskNames.size());
380   for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
381     Names2RegMasks.insert(
382         std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
383 }
384
385 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
386   initNames2RegMasks();
387   auto RegMaskInfo = Names2RegMasks.find(Identifier);
388   if (RegMaskInfo == Names2RegMasks.end())
389     return nullptr;
390   return RegMaskInfo->getValue();
391 }
392
393 MachineInstr *
394 llvm::parseMachineInstr(SourceMgr &SM, MachineFunction &MF, StringRef Src,
395                         const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
396                         const SlotMapping &IRSlots, SMDiagnostic &Error) {
397   return MIParser(SM, MF, Error, Src, MBBSlots, IRSlots).parse();
398 }