6b90d904efcf27cdf37d23aec992088842203f5d
[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/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Target/TargetSubtargetInfo.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27
28 using namespace llvm;
29
30 namespace {
31
32 /// A wrapper struct around the 'MachineOperand' struct that includes a source
33 /// range.
34 struct MachineOperandWithLocation {
35   MachineOperand Operand;
36   StringRef::iterator Begin;
37   StringRef::iterator End;
38
39   MachineOperandWithLocation(const MachineOperand &Operand,
40                              StringRef::iterator Begin, StringRef::iterator End)
41       : Operand(Operand), Begin(Begin), End(End) {}
42 };
43
44 class MIParser {
45   SourceMgr &SM;
46   MachineFunction &MF;
47   SMDiagnostic &Error;
48   StringRef Source, CurrentSource;
49   MIToken Token;
50   /// Maps from basic block numbers to MBBs.
51   const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots;
52   /// Maps from indices to unnamed global values and metadata nodes.
53   const SlotMapping &IRSlots;
54   /// Maps from instruction names to op codes.
55   StringMap<unsigned> Names2InstrOpCodes;
56   /// Maps from register names to registers.
57   StringMap<unsigned> Names2Regs;
58   /// Maps from register mask names to register masks.
59   StringMap<const uint32_t *> Names2RegMasks;
60
61 public:
62   MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
63            StringRef Source,
64            const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
65            const SlotMapping &IRSlots);
66
67   void lex();
68
69   /// Report an error at the current location with the given message.
70   ///
71   /// This function always return true.
72   bool error(const Twine &Msg);
73
74   /// Report an error at the given location with the given message.
75   ///
76   /// This function always return true.
77   bool error(StringRef::iterator Loc, const Twine &Msg);
78
79   bool parse(MachineInstr *&MI);
80   bool parseMBB(MachineBasicBlock *&MBB);
81
82   bool parseRegister(unsigned &Reg);
83   bool parseRegisterFlag(unsigned &Flags);
84   bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
85   bool parseImmediateOperand(MachineOperand &Dest);
86   bool parseMBBReference(MachineBasicBlock *&MBB);
87   bool parseMBBOperand(MachineOperand &Dest);
88   bool parseGlobalAddressOperand(MachineOperand &Dest);
89   bool parseMachineOperand(MachineOperand &Dest);
90
91 private:
92   /// Convert the integer literal in the current token into an unsigned integer.
93   ///
94   /// Return true if an error occurred.
95   bool getUnsigned(unsigned &Result);
96
97   void initNames2InstrOpCodes();
98
99   /// Try to convert an instruction name to an opcode. Return true if the
100   /// instruction name is invalid.
101   bool parseInstrName(StringRef InstrName, unsigned &OpCode);
102
103   bool parseInstruction(unsigned &OpCode);
104
105   bool verifyImplicitOperands(ArrayRef<MachineOperandWithLocation> Operands,
106                               const MCInstrDesc &MCID);
107
108   void initNames2Regs();
109
110   /// Try to convert a register name to a register number. Return true if the
111   /// register name is invalid.
112   bool getRegisterByName(StringRef RegName, unsigned &Reg);
113
114   void initNames2RegMasks();
115
116   /// Check if the given identifier is a name of a register mask.
117   ///
118   /// Return null if the identifier isn't a register mask.
119   const uint32_t *getRegMask(StringRef Identifier);
120 };
121
122 } // end anonymous namespace
123
124 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
125                    StringRef Source,
126                    const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
127                    const SlotMapping &IRSlots)
128     : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
129       Token(MIToken::Error, StringRef()), MBBSlots(MBBSlots), IRSlots(IRSlots) {
130 }
131
132 void MIParser::lex() {
133   CurrentSource = lexMIToken(
134       CurrentSource, Token,
135       [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
136 }
137
138 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
139
140 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
141   // TODO: Get the proper location in the MIR file, not just a location inside
142   // the string.
143   assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
144   Error = SMDiagnostic(
145       SM, SMLoc(),
146       SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
147       Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
148   return true;
149 }
150
151 bool MIParser::parse(MachineInstr *&MI) {
152   lex();
153
154   // Parse any register operands before '='
155   // TODO: Allow parsing of multiple operands before '='
156   MachineOperand MO = MachineOperand::CreateImm(0);
157   SmallVector<MachineOperandWithLocation, 8> Operands;
158   if (Token.isRegister() || Token.isRegisterFlag()) {
159     auto Loc = Token.location();
160     if (parseRegisterOperand(MO, /*IsDef=*/true))
161       return true;
162     Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
163     if (Token.isNot(MIToken::equal))
164       return error("expected '='");
165     lex();
166   }
167
168   unsigned OpCode;
169   if (Token.isError() || parseInstruction(OpCode))
170     return true;
171
172   // TODO: Parse the instruction flags and memory operands.
173
174   // Parse the remaining machine operands.
175   while (Token.isNot(MIToken::Eof)) {
176     auto Loc = Token.location();
177     if (parseMachineOperand(MO))
178       return true;
179     Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
180     if (Token.is(MIToken::Eof))
181       break;
182     if (Token.isNot(MIToken::comma))
183       return error("expected ',' before the next machine operand");
184     lex();
185   }
186
187   const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
188   if (!MCID.isVariadic()) {
189     // FIXME: Move the implicit operand verification to the machine verifier.
190     if (verifyImplicitOperands(Operands, MCID))
191       return true;
192   }
193
194   // TODO: Check for extraneous machine operands.
195   MI = MF.CreateMachineInstr(MCID, DebugLoc(), /*NoImplicit=*/true);
196   for (const auto &Operand : Operands)
197     MI->addOperand(MF, Operand.Operand);
198   return false;
199 }
200
201 bool MIParser::parseMBB(MachineBasicBlock *&MBB) {
202   lex();
203   if (Token.isNot(MIToken::MachineBasicBlock))
204     return error("expected a machine basic block reference");
205   if (parseMBBReference(MBB))
206     return true;
207   lex();
208   if (Token.isNot(MIToken::Eof))
209     return error(
210         "expected end of string after the machine basic block reference");
211   return false;
212 }
213
214 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
215   assert(MO.isImplicit());
216   return MO.isDef() ? "implicit-def" : "implicit";
217 }
218
219 static std::string getRegisterName(const TargetRegisterInfo *TRI,
220                                    unsigned Reg) {
221   assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
222   return StringRef(TRI->getName(Reg)).lower();
223 }
224
225 bool MIParser::verifyImplicitOperands(
226     ArrayRef<MachineOperandWithLocation> Operands, const MCInstrDesc &MCID) {
227   if (MCID.isCall())
228     // We can't verify call instructions as they can contain arbitrary implicit
229     // register and register mask operands.
230     return false;
231
232   // Gather all the expected implicit operands.
233   SmallVector<MachineOperand, 4> ImplicitOperands;
234   if (MCID.ImplicitDefs)
235     for (const uint16_t *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
236       ImplicitOperands.push_back(
237           MachineOperand::CreateReg(*ImpDefs, true, true));
238   if (MCID.ImplicitUses)
239     for (const uint16_t *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
240       ImplicitOperands.push_back(
241           MachineOperand::CreateReg(*ImpUses, false, true));
242
243   const auto *TRI = MF.getSubtarget().getRegisterInfo();
244   assert(TRI && "Expected target register info");
245   size_t I = ImplicitOperands.size(), J = Operands.size();
246   while (I) {
247     --I;
248     if (J) {
249       --J;
250       const auto &ImplicitOperand = ImplicitOperands[I];
251       const auto &Operand = Operands[J].Operand;
252       if (ImplicitOperand.isIdenticalTo(Operand))
253         continue;
254       if (Operand.isReg() && Operand.isImplicit()) {
255         return error(Operands[J].Begin,
256                      Twine("expected an implicit register operand '") +
257                          printImplicitRegisterFlag(ImplicitOperand) + " %" +
258                          getRegisterName(TRI, ImplicitOperand.getReg()) + "'");
259       }
260     }
261     // TODO: Fix source location when Operands[J].end is right before '=', i.e:
262     // insead of reporting an error at this location:
263     //            %eax = MOV32r0
264     //                 ^
265     // report the error at the following location:
266     //            %eax = MOV32r0
267     //                          ^
268     return error(J < Operands.size() ? Operands[J].End : Token.location(),
269                  Twine("missing implicit register operand '") +
270                      printImplicitRegisterFlag(ImplicitOperands[I]) + " %" +
271                      getRegisterName(TRI, ImplicitOperands[I].getReg()) + "'");
272   }
273   return false;
274 }
275
276 bool MIParser::parseInstruction(unsigned &OpCode) {
277   if (Token.isNot(MIToken::Identifier))
278     return error("expected a machine instruction");
279   StringRef InstrName = Token.stringValue();
280   if (parseInstrName(InstrName, OpCode))
281     return error(Twine("unknown machine instruction name '") + InstrName + "'");
282   lex();
283   return false;
284 }
285
286 bool MIParser::parseRegister(unsigned &Reg) {
287   switch (Token.kind()) {
288   case MIToken::underscore:
289     Reg = 0;
290     break;
291   case MIToken::NamedRegister: {
292     StringRef Name = Token.stringValue();
293     if (getRegisterByName(Name, Reg))
294       return error(Twine("unknown register name '") + Name + "'");
295     break;
296   }
297   // TODO: Parse other register kinds.
298   default:
299     llvm_unreachable("The current token should be a register");
300   }
301   return false;
302 }
303
304 bool MIParser::parseRegisterFlag(unsigned &Flags) {
305   switch (Token.kind()) {
306   case MIToken::kw_implicit:
307     Flags |= RegState::Implicit;
308     break;
309   case MIToken::kw_implicit_define:
310     Flags |= RegState::ImplicitDefine;
311     break;
312   // TODO: report an error when we specify the same flag more than once.
313   // TODO: parse the other register flags.
314   default:
315     llvm_unreachable("The current token should be a register flag");
316   }
317   lex();
318   return false;
319 }
320
321 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
322   unsigned Reg;
323   unsigned Flags = IsDef ? RegState::Define : 0;
324   while (Token.isRegisterFlag()) {
325     if (parseRegisterFlag(Flags))
326       return true;
327   }
328   if (!Token.isRegister())
329     return error("expected a register after register flags");
330   if (parseRegister(Reg))
331     return true;
332   lex();
333   // TODO: Parse subregister.
334   Dest = MachineOperand::CreateReg(Reg, Flags & RegState::Define,
335                                    Flags & RegState::Implicit);
336   return false;
337 }
338
339 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
340   assert(Token.is(MIToken::IntegerLiteral));
341   const APSInt &Int = Token.integerValue();
342   if (Int.getMinSignedBits() > 64)
343     // TODO: Replace this with an error when we can parse CIMM Machine Operands.
344     llvm_unreachable("Can't parse large integer literals yet!");
345   Dest = MachineOperand::CreateImm(Int.getExtValue());
346   lex();
347   return false;
348 }
349
350 bool MIParser::getUnsigned(unsigned &Result) {
351   assert(Token.hasIntegerValue() && "Expected a token with an integer value");
352   const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
353   uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
354   if (Val64 == Limit)
355     return error("expected 32-bit integer (too large)");
356   Result = Val64;
357   return false;
358 }
359
360 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
361   assert(Token.is(MIToken::MachineBasicBlock));
362   unsigned Number;
363   if (getUnsigned(Number))
364     return true;
365   auto MBBInfo = MBBSlots.find(Number);
366   if (MBBInfo == MBBSlots.end())
367     return error(Twine("use of undefined machine basic block #") +
368                  Twine(Number));
369   MBB = MBBInfo->second;
370   if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
371     return error(Twine("the name of machine basic block #") + Twine(Number) +
372                  " isn't '" + Token.stringValue() + "'");
373   return false;
374 }
375
376 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
377   MachineBasicBlock *MBB;
378   if (parseMBBReference(MBB))
379     return true;
380   Dest = MachineOperand::CreateMBB(MBB);
381   lex();
382   return false;
383 }
384
385 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
386   switch (Token.kind()) {
387   case MIToken::NamedGlobalValue: {
388     auto Name = Token.stringValue();
389     const Module *M = MF.getFunction()->getParent();
390     if (const auto *GV = M->getNamedValue(Name)) {
391       Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
392       break;
393     }
394     return error(Twine("use of undefined global value '@") + Name + "'");
395   }
396   case MIToken::GlobalValue: {
397     unsigned GVIdx;
398     if (getUnsigned(GVIdx))
399       return true;
400     if (GVIdx >= IRSlots.GlobalValues.size())
401       return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
402                    "'");
403     Dest = MachineOperand::CreateGA(IRSlots.GlobalValues[GVIdx],
404                                     /*Offset=*/0);
405     break;
406   }
407   default:
408     llvm_unreachable("The current token should be a global value");
409   }
410   // TODO: Parse offset and target flags.
411   lex();
412   return false;
413 }
414
415 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
416   switch (Token.kind()) {
417   case MIToken::kw_implicit:
418   case MIToken::kw_implicit_define:
419   case MIToken::underscore:
420   case MIToken::NamedRegister:
421     return parseRegisterOperand(Dest);
422   case MIToken::IntegerLiteral:
423     return parseImmediateOperand(Dest);
424   case MIToken::MachineBasicBlock:
425     return parseMBBOperand(Dest);
426   case MIToken::GlobalValue:
427   case MIToken::NamedGlobalValue:
428     return parseGlobalAddressOperand(Dest);
429   case MIToken::Error:
430     return true;
431   case MIToken::Identifier:
432     if (const auto *RegMask = getRegMask(Token.stringValue())) {
433       Dest = MachineOperand::CreateRegMask(RegMask);
434       lex();
435       break;
436     }
437   // fallthrough
438   default:
439     // TODO: parse the other machine operands.
440     return error("expected a machine operand");
441   }
442   return false;
443 }
444
445 void MIParser::initNames2InstrOpCodes() {
446   if (!Names2InstrOpCodes.empty())
447     return;
448   const auto *TII = MF.getSubtarget().getInstrInfo();
449   assert(TII && "Expected target instruction info");
450   for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
451     Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
452 }
453
454 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
455   initNames2InstrOpCodes();
456   auto InstrInfo = Names2InstrOpCodes.find(InstrName);
457   if (InstrInfo == Names2InstrOpCodes.end())
458     return true;
459   OpCode = InstrInfo->getValue();
460   return false;
461 }
462
463 void MIParser::initNames2Regs() {
464   if (!Names2Regs.empty())
465     return;
466   // The '%noreg' register is the register 0.
467   Names2Regs.insert(std::make_pair("noreg", 0));
468   const auto *TRI = MF.getSubtarget().getRegisterInfo();
469   assert(TRI && "Expected target register info");
470   for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
471     bool WasInserted =
472         Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
473             .second;
474     (void)WasInserted;
475     assert(WasInserted && "Expected registers to be unique case-insensitively");
476   }
477 }
478
479 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
480   initNames2Regs();
481   auto RegInfo = Names2Regs.find(RegName);
482   if (RegInfo == Names2Regs.end())
483     return true;
484   Reg = RegInfo->getValue();
485   return false;
486 }
487
488 void MIParser::initNames2RegMasks() {
489   if (!Names2RegMasks.empty())
490     return;
491   const auto *TRI = MF.getSubtarget().getRegisterInfo();
492   assert(TRI && "Expected target register info");
493   ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
494   ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
495   assert(RegMasks.size() == RegMaskNames.size());
496   for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
497     Names2RegMasks.insert(
498         std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
499 }
500
501 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
502   initNames2RegMasks();
503   auto RegMaskInfo = Names2RegMasks.find(Identifier);
504   if (RegMaskInfo == Names2RegMasks.end())
505     return nullptr;
506   return RegMaskInfo->getValue();
507 }
508
509 bool llvm::parseMachineInstr(
510     MachineInstr *&MI, SourceMgr &SM, MachineFunction &MF, StringRef Src,
511     const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
512     const SlotMapping &IRSlots, SMDiagnostic &Error) {
513   return MIParser(SM, MF, Error, Src, MBBSlots, IRSlots).parse(MI);
514 }
515
516 bool llvm::parseMBBReference(
517     MachineBasicBlock *&MBB, SourceMgr &SM, MachineFunction &MF, StringRef Src,
518     const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
519     const SlotMapping &IRSlots, SMDiagnostic &Error) {
520   return MIParser(SM, MF, Error, Src, MBBSlots, IRSlots).parseMBB(MBB);
521 }