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