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