pull the code to get the operand value out of the loop.
[oota-llvm.git] / utils / TableGen / CodeEmitterGen.cpp
1 //===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===//
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 // CodeEmitterGen uses the descriptions of instructions and their fields to
11 // construct an automated code emitter: a function that, given a MachineInstr,
12 // returns the (currently, 32-bit unsigned) value of the instruction.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "CodeEmitterGen.h"
17 #include "CodeGenTarget.h"
18 #include "Record.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/Debug.h"
22 using namespace llvm;
23
24 // FIXME: Somewhat hackish to use a command line option for this. There should
25 // be a CodeEmitter class in the Target.td that controls this sort of thing
26 // instead.
27 static cl::opt<bool>
28 MCEmitter("mc-emitter",
29           cl::desc("Generate CodeEmitter for use with the MC library."),
30           cl::init(false));
31
32 void CodeEmitterGen::reverseBits(std::vector<Record*> &Insts) {
33   for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end();
34        I != E; ++I) {
35     Record *R = *I;
36     if (R->getValueAsString("Namespace") == "TargetOpcode")
37       continue;
38
39     BitsInit *BI = R->getValueAsBitsInit("Inst");
40
41     unsigned numBits = BI->getNumBits();
42     BitsInit *NewBI = new BitsInit(numBits);
43     for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
44       unsigned bitSwapIdx = numBits - bit - 1;
45       Init *OrigBit = BI->getBit(bit);
46       Init *BitSwap = BI->getBit(bitSwapIdx);
47       NewBI->setBit(bit, BitSwap);
48       NewBI->setBit(bitSwapIdx, OrigBit);
49     }
50     if (numBits % 2) {
51       unsigned middle = (numBits + 1) / 2;
52       NewBI->setBit(middle, BI->getBit(middle));
53     }
54
55     // Update the bits in reversed order so that emitInstrOpBits will get the
56     // correct endianness.
57     R->getValue("Inst")->setValue(NewBI);
58   }
59 }
60
61 // If the VarBitInit at position 'bit' matches the specified variable then
62 // return the variable bit position.  Otherwise return -1.
63 int CodeEmitterGen::getVariableBit(const std::string &VarName,
64                                    BitsInit *BI, int bit) {
65   if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(BI->getBit(bit)))
66     if (VarInit *VI = dynamic_cast<VarInit*>(VBI->getVariable()))
67       if (VI->getName() == VarName)
68         return VBI->getBitNum();
69
70   return -1;
71 }
72
73 void CodeEmitterGen::
74 AddCodeToMergeInOperand(Record *R, BitsInit *BI, const std::string &VarName,
75                         unsigned &NumberedOp,
76                         std::string &Case, CodeGenTarget &Target) {
77   CodeGenInstruction &CGI = Target.getInstruction(R);
78
79   // Determine if VarName actually contributes to the Inst encoding.
80   int bit = BI->getNumBits()-1;
81
82   // Scan for a bit that this contributed to.
83   for (; bit >= 0; ) {
84     if (getVariableBit(VarName, BI, bit) != -1)
85       break;
86     
87     --bit;
88   }
89   
90   // If we found no bits, ignore this value, otherwise emit the call to get the
91   // operand encoding.
92   if (bit < 0) return;
93   
94   // If the operand matches by name, reference according to that
95   // operand number. Non-matching operands are assumed to be in
96   // order.
97   unsigned OpIdx;
98   if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {
99     // Get the machine operand number for the indicated operand.
100     OpIdx = CGI.Operands[OpIdx].MIOperandNo;
101     assert(!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&
102            "Explicitly used operand also marked as not emitted!");
103   } else {
104     /// If this operand is not supposed to be emitted by the
105     /// generated emitter, skip it.
106     while (CGI.Operands.isFlatOperandNotEmitted(NumberedOp))
107       ++NumberedOp;
108     OpIdx = NumberedOp++;
109   }
110   
111   std::pair<unsigned, unsigned> SO = CGI.Operands.getSubOperandNumber(OpIdx);
112   std::string &EncoderMethodName = CGI.Operands[SO.first].EncoderMethodName;
113   
114   // If the source operand has a custom encoder, use it. This will
115   // get the encoding for all of the suboperands.
116   if (!EncoderMethodName.empty()) {
117     // A custom encoder has all of the information for the
118     // sub-operands, if there are more than one, so only
119     // query the encoder once per source operand.
120     if (SO.second == 0) {
121       Case += "      // op: " + VarName + "\n" +
122               "      op = " + EncoderMethodName + "(MI, " + utostr(OpIdx);
123       if (MCEmitter)
124         Case += ", Fixups";
125       Case += ");\n";
126     }
127   } else {
128     Case += "      // op: " + VarName + "\n" +
129       "      op = getMachineOpValue(MI, MI.getOperand(" + utostr(OpIdx) + ")";
130     if (MCEmitter)
131       Case += ", Fixups";
132     Case += ");\n";
133   }
134   
135   for (; bit >= 0; ) {
136     int varBit = getVariableBit(VarName, BI, bit);
137     
138     // If this bit isn't from a variable, skip it.
139     if (varBit == -1) {
140       --bit;
141       continue;
142     }
143     
144     // Figure out the consequtive range of bits covered by this operand, in
145     // order to generate better encoding code.
146     int beginInstBit = bit;
147     int beginVarBit = varBit;
148     int N = 1;
149     for (--bit; bit >= 0;) {
150       varBit = getVariableBit(VarName, BI, bit);
151       if (varBit == -1 || varBit != (beginVarBit - N)) break;
152       ++N;
153       --bit;
154     }
155      
156     unsigned opMask = ~0U >> (32-N);
157     int opShift = beginVarBit - N + 1;
158     opMask <<= opShift;
159     opShift = beginInstBit - beginVarBit;
160     
161     if (opShift > 0) {
162       Case += "      Value |= (op & " + utostr(opMask) + "U) << " +
163               itostr(opShift) + ";\n";
164     } else if (opShift < 0) {
165       Case += "      Value |= (op & " + utostr(opMask) + "U) >> " + 
166               itostr(-opShift) + ";\n";
167     } else {
168       Case += "      Value |= op & " + utostr(opMask) + "U;\n";
169     }
170   }
171 }
172
173
174 std::string CodeEmitterGen::getInstructionCase(Record *R,
175                                                CodeGenTarget &Target) {
176   std::string Case;
177   
178   BitsInit *BI = R->getValueAsBitsInit("Inst");
179   const std::vector<RecordVal> &Vals = R->getValues();
180   unsigned NumberedOp = 0;
181
182   // Loop over all of the fields in the instruction, determining which are the
183   // operands to the instruction.
184   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
185     // Ignore fixed fields in the record, we're looking for values like:
186     //    bits<5> RST = { ?, ?, ?, ?, ? };
187     if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
188       continue;
189     
190     AddCodeToMergeInOperand(R, BI, Vals[i].getName(), NumberedOp, Case, Target);
191   }
192   
193   std::string PostEmitter = R->getValueAsString("PostEncoderMethod");
194   if (!PostEmitter.empty())
195     Case += "      Value = " + PostEmitter + "(MI, Value);\n";
196   
197   return Case;
198 }
199
200 void CodeEmitterGen::run(raw_ostream &o) {
201   CodeGenTarget Target;
202   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
203
204   // For little-endian instruction bit encodings, reverse the bit order
205   if (Target.isLittleEndianEncoding()) reverseBits(Insts);
206
207   EmitSourceFileHeader("Machine Code Emitter", o);
208   std::string Namespace = Insts[0]->getValueAsString("Namespace") + "::";
209
210   const std::vector<const CodeGenInstruction*> &NumberedInstructions =
211     Target.getInstructionsByEnumValue();
212
213   // Emit function declaration
214   o << "unsigned " << Target.getName();
215   if (MCEmitter)
216     o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
217       << "    SmallVectorImpl<MCFixup> &Fixups) const {\n";
218   else
219     o << "CodeEmitter::getBinaryCodeForInstr(const MachineInstr &MI) const {\n";
220
221   // Emit instruction base values
222   o << "  static const unsigned InstBits[] = {\n";
223   for (std::vector<const CodeGenInstruction*>::const_iterator
224           IN = NumberedInstructions.begin(),
225           EN = NumberedInstructions.end();
226        IN != EN; ++IN) {
227     const CodeGenInstruction *CGI = *IN;
228     Record *R = CGI->TheDef;
229
230     if (R->getValueAsString("Namespace") == "TargetOpcode") {
231       o << "    0U,\n";
232       continue;
233     }
234
235     BitsInit *BI = R->getValueAsBitsInit("Inst");
236
237     // Start by filling in fixed values.
238     unsigned Value = 0;
239     for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
240       if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1)))
241         Value |= B->getValue() << (e-i-1);
242     }
243     o << "    " << Value << "U," << '\t' << "// " << R->getName() << "\n";
244   }
245   o << "    0U\n  };\n";
246
247   // Map to accumulate all the cases.
248   std::map<std::string, std::vector<std::string> > CaseMap;
249
250   // Construct all cases statement for each opcode
251   for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
252         IC != EC; ++IC) {
253     Record *R = *IC;
254     if (R->getValueAsString("Namespace") == "TargetOpcode")
255       continue;
256     const std::string &InstName = R->getName();
257     std::string Case = getInstructionCase(R, Target);
258
259     CaseMap[Case].push_back(InstName);
260   }
261
262   // Emit initial function code
263   o << "  const unsigned opcode = MI.getOpcode();\n"
264     << "  unsigned Value = InstBits[opcode];\n"
265     << "  unsigned op = 0;\n"
266     << "  op = op;  // suppress warning\n"
267     << "  switch (opcode) {\n";
268
269   // Emit each case statement
270   std::map<std::string, std::vector<std::string> >::iterator IE, EE;
271   for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
272     const std::string &Case = IE->first;
273     std::vector<std::string> &InstList = IE->second;
274
275     for (int i = 0, N = InstList.size(); i < N; i++) {
276       if (i) o << "\n";
277       o << "    case " << Namespace << InstList[i]  << ":";
278     }
279     o << " {\n";
280     o << Case;
281     o << "      break;\n"
282       << "    }\n";
283   }
284
285   // Default case: unhandled opcode
286   o << "  default:\n"
287     << "    std::string msg;\n"
288     << "    raw_string_ostream Msg(msg);\n"
289     << "    Msg << \"Not supported instr: \" << MI;\n"
290     << "    report_fatal_error(Msg.str());\n"
291     << "  }\n"
292     << "  return Value;\n"
293     << "}\n\n";
294 }