[AVX] Make Inits Foldable
[oota-llvm.git] / utils / TableGen / PseudoLoweringEmitter.cpp
1 //===- PseudoLoweringEmitter.cpp - PseudoLowering Generator -----*- C++ -*-===//
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 #define DEBUG_TYPE "pseudo-lowering"
11 #include "Error.h"
12 #include "CodeGenInstruction.h"
13 #include "PseudoLoweringEmitter.h"
14 #include "Record.h"
15 #include "llvm/ADT/IndexedMap.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/Support/ErrorHandling.h"
18 #include "llvm/Support/Debug.h"
19 #include <vector>
20 using namespace llvm;
21
22 // FIXME: This pass currently can only expand a pseudo to a single instruction.
23 //        The pseudo expansion really should take a list of dags, not just
24 //        a single dag, so we can do fancier things.
25
26 unsigned PseudoLoweringEmitter::
27 addDagOperandMapping(Record *Rec, const DagInit *Dag, CodeGenInstruction &Insn,
28                      IndexedMap<OpData> &OperandMap, unsigned BaseIdx) {
29   unsigned OpsAdded = 0;
30   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
31     if (const DefInit *DI = dynamic_cast<const DefInit*>(Dag->getArg(i))) {
32       // Physical register reference. Explicit check for the special case
33       // "zero_reg" definition.
34       if (DI->getDef()->isSubClassOf("Register") ||
35           DI->getDef()->getName() == "zero_reg") {
36         OperandMap[BaseIdx + i].Kind = OpData::Reg;
37         OperandMap[BaseIdx + i].Data.Reg = DI->getDef();
38         ++OpsAdded;
39         continue;
40       }
41
42       // Normal operands should always have the same type, or we have a
43       // problem.
44       // FIXME: We probably shouldn't ever get a non-zero BaseIdx here.
45       assert(BaseIdx == 0 && "Named subargument in pseudo expansion?!");
46       if (DI->getDef() != Insn.Operands[BaseIdx + i].Rec)
47         throw TGError(Rec->getLoc(),
48                       "Pseudo operand type '" + DI->getDef()->getName() +
49                       "' does not match expansion operand type '" +
50                       Insn.Operands[BaseIdx + i].Rec->getName() + "'");
51       // Source operand maps to destination operand. The Data element
52       // will be filled in later, just set the Kind for now. Do it
53       // for each corresponding MachineInstr operand, not just the first.
54       for (unsigned I = 0, E = Insn.Operands[i].MINumOperands; I != E; ++I)
55         OperandMap[BaseIdx + i + I].Kind = OpData::Operand;
56       OpsAdded += Insn.Operands[i].MINumOperands;
57     } else if (const IntInit *II =
58                dynamic_cast<const IntInit*>(Dag->getArg(i))) {
59       OperandMap[BaseIdx + i].Kind = OpData::Imm;
60       OperandMap[BaseIdx + i].Data.Imm = II->getValue();
61       ++OpsAdded;
62     } else if (const DagInit *SubDag =
63                dynamic_cast<const DagInit*>(Dag->getArg(i))) {
64       // Just add the operands recursively. This is almost certainly
65       // a constant value for a complex operand (> 1 MI operand).
66       unsigned NewOps =
67         addDagOperandMapping(Rec, SubDag, Insn, OperandMap, BaseIdx + i);
68       OpsAdded += NewOps;
69       // Since we added more than one, we also need to adjust the base.
70       BaseIdx += NewOps - 1;
71     } else
72       assert(0 && "Unhandled pseudo-expansion argument type!");
73   }
74   return OpsAdded;
75 }
76
77 void PseudoLoweringEmitter::evaluateExpansion(Record *Rec) {
78   DEBUG(dbgs() << "Pseudo definition: " << Rec->getName() << "\n");
79
80   // Validate that the result pattern has the corrent number and types
81   // of arguments for the instruction it references.
82   const DagInit *Dag = Rec->getValueAsDag("ResultInst");
83   assert(Dag && "Missing result instruction in pseudo expansion!");
84   DEBUG(dbgs() << "  Result: " << *Dag << "\n");
85
86   const DefInit *OpDef = dynamic_cast<const DefInit*>(Dag->getOperator());
87   if (!OpDef)
88     throw TGError(Rec->getLoc(), Rec->getName() +
89                   " has unexpected operator type!");
90   Record *Operator = OpDef->getDef();
91   if (!Operator->isSubClassOf("Instruction"))
92     throw TGError(Rec->getLoc(), "Pseudo result '" + Operator->getName() +
93                                  "' is not an instruction!");
94
95   CodeGenInstruction Insn(Operator);
96
97   if (Insn.isCodeGenOnly || Insn.isPseudo)
98     throw TGError(Rec->getLoc(), "Pseudo result '" + Operator->getName() +
99                                  "' cannot be another pseudo instruction!");
100
101   if (Insn.Operands.size() != Dag->getNumArgs())
102     throw TGError(Rec->getLoc(), "Pseudo result '" + Operator->getName() +
103                                  "' operand count mismatch");
104
105   IndexedMap<OpData> OperandMap;
106   OperandMap.grow(Insn.Operands.size());
107
108   addDagOperandMapping(Rec, Dag, Insn, OperandMap, 0);
109
110   // If there are more operands that weren't in the DAG, they have to
111   // be operands that have default values, or we have an error. Currently,
112   // PredicateOperand and OptionalDefOperand both have default values.
113
114
115   // Validate that each result pattern argument has a matching (by name)
116   // argument in the source instruction, in either the (outs) or (ins) list.
117   // Also check that the type of the arguments match.
118   //
119   // Record the mapping of the source to result arguments for use by
120   // the lowering emitter.
121   CodeGenInstruction SourceInsn(Rec);
122   StringMap<unsigned> SourceOperands;
123   for (unsigned i = 0, e = SourceInsn.Operands.size(); i != e; ++i)
124     SourceOperands[SourceInsn.Operands[i].Name] = i;
125
126   DEBUG(dbgs() << "  Operand mapping:\n");
127   for (unsigned i = 0, e = Insn.Operands.size(); i != e; ++i) {
128     // We've already handled constant values. Just map instruction operands
129     // here.
130     if (OperandMap[Insn.Operands[i].MIOperandNo].Kind != OpData::Operand)
131       continue;
132     StringMap<unsigned>::iterator SourceOp =
133       SourceOperands.find(Dag->getArgName(i));
134     if (SourceOp == SourceOperands.end())
135       throw TGError(Rec->getLoc(),
136                     "Pseudo output operand '" + Dag->getArgName(i) +
137                     "' has no matching source operand.");
138     // Map the source operand to the destination operand index for each
139     // MachineInstr operand.
140     for (unsigned I = 0, E = Insn.Operands[i].MINumOperands; I != E; ++I)
141       OperandMap[Insn.Operands[i].MIOperandNo + I].Data.Operand =
142         SourceOp->getValue();
143
144     DEBUG(dbgs() << "    " << SourceOp->getValue() << " ==> " << i << "\n");
145   }
146
147   Expansions.push_back(PseudoExpansion(SourceInsn, Insn, OperandMap));
148 }
149
150 void PseudoLoweringEmitter::emitLoweringEmitter(raw_ostream &o) {
151   // Emit file header.
152   EmitSourceFileHeader("Pseudo-instruction MC lowering Source Fragment", o);
153
154   o << "bool " << Target.getName() + "AsmPrinter" << "::\n"
155     << "emitPseudoExpansionLowering(MCStreamer &OutStreamer,\n"
156     << "                            const MachineInstr *MI) {\n"
157     << "  switch (MI->getOpcode()) {\n"
158     << "    default: return false;\n";
159   for (unsigned i = 0, e = Expansions.size(); i != e; ++i) {
160     PseudoExpansion &Expansion = Expansions[i];
161     CodeGenInstruction &Source = Expansion.Source;
162     CodeGenInstruction &Dest = Expansion.Dest;
163     o << "    case " << Source.Namespace << "::"
164       << Source.TheDef->getName() << ": {\n"
165       << "      MCInst TmpInst;\n"
166       << "      MCOperand MCOp;\n"
167       << "      TmpInst.setOpcode(" << Dest.Namespace << "::"
168       << Dest.TheDef->getName() << ");\n";
169
170     // Copy the operands from the source instruction.
171     // FIXME: Instruction operands with defaults values (predicates and cc_out
172     //        in ARM, for example shouldn't need explicit values in the
173     //        expansion DAG.
174     unsigned MIOpNo = 0;
175     for (unsigned OpNo = 0, E = Dest.Operands.size(); OpNo != E;
176          ++OpNo) {
177       o << "      // Operand: " << Dest.Operands[OpNo].Name << "\n";
178       for (unsigned i = 0, e = Dest.Operands[OpNo].MINumOperands;
179            i != e; ++i) {
180         switch (Expansion.OperandMap[MIOpNo + i].Kind) {
181         default:
182           llvm_unreachable("Unknown operand type?!");
183         case OpData::Operand:
184           o << "      lowerOperand(MI->getOperand("
185             << Source.Operands[Expansion.OperandMap[MIOpNo].Data
186                 .Operand].MIOperandNo + i
187             << "), MCOp);\n"
188             << "      TmpInst.addOperand(MCOp);\n";
189           break;
190         case OpData::Imm:
191           o << "      TmpInst.addOperand(MCOperand::CreateImm("
192             << Expansion.OperandMap[MIOpNo + i].Data.Imm << "));\n";
193           break;
194         case OpData::Reg: {
195           Record *Reg = Expansion.OperandMap[MIOpNo + i].Data.Reg;
196           o << "      TmpInst.addOperand(MCOperand::CreateReg(";
197           // "zero_reg" is special.
198           if (Reg->getName() == "zero_reg")
199             o << "0";
200           else
201             o << Reg->getValueAsString("Namespace") << "::" << Reg->getName();
202           o << "));\n";
203           break;
204         }
205         }
206       }
207       MIOpNo += Dest.Operands[OpNo].MINumOperands;
208     }
209     if (Dest.Operands.isVariadic) {
210       o << "      // variable_ops\n";
211       o << "      for (unsigned i = " << MIOpNo
212         << ", e = MI->getNumOperands(); i != e; ++i)\n"
213         << "        if (lowerOperand(MI->getOperand(i), MCOp))\n"
214         << "          TmpInst.addOperand(MCOp);\n";
215     }
216     o << "      OutStreamer.EmitInstruction(TmpInst);\n"
217       << "      break;\n"
218       << "    }\n";
219   }
220   o << "  }\n  return true;\n}\n\n";
221 }
222
223 void PseudoLoweringEmitter::run(raw_ostream &o) {
224   Record *ExpansionClass = Records.getClass("PseudoInstExpansion");
225   Record *InstructionClass = Records.getClass("PseudoInstExpansion");
226   assert(ExpansionClass && "PseudoInstExpansion class definition missing!");
227   assert(InstructionClass && "Instruction class definition missing!");
228
229   std::vector<Record*> Insts;
230   for (std::map<std::string, Record*>::const_iterator I =
231          Records.getDefs().begin(), E = Records.getDefs().end(); I != E; ++I) {
232     if (I->second->isSubClassOf(ExpansionClass) &&
233         I->second->isSubClassOf(InstructionClass))
234       Insts.push_back(I->second);
235   }
236
237   // Process the pseudo expansion definitions, validating them as we do so.
238   for (unsigned i = 0, e = Insts.size(); i != e; ++i)
239     evaluateExpansion(Insts[i]);
240
241   // Generate expansion code to lower the pseudo to an MCInst of the real
242   // instruction.
243   emitLoweringEmitter(o);
244 }
245