1. Simplfy bit operations.
[oota-llvm.git] / utils / TableGen / CodeEmitterGen.cpp
1 //===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Debug.h"
21 using namespace llvm;
22
23 void CodeEmitterGen::reverseBits(std::vector<Record*> &Insts) {
24   for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end();
25        I != E; ++I) {
26     Record *R = *I;
27     if (R->getName() == "PHI" || R->getName() == "INLINEASM") continue;
28     
29     BitsInit *BI = R->getValueAsBitsInit("Inst");
30
31     unsigned numBits = BI->getNumBits();
32     BitsInit *NewBI = new BitsInit(numBits);
33     for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
34       unsigned bitSwapIdx = numBits - bit - 1;
35       Init *OrigBit = BI->getBit(bit);
36       Init *BitSwap = BI->getBit(bitSwapIdx);
37       NewBI->setBit(bit, BitSwap);
38       NewBI->setBit(bitSwapIdx, OrigBit);
39     }
40     if (numBits % 2) {
41       unsigned middle = (numBits + 1) / 2;
42       NewBI->setBit(middle, BI->getBit(middle));
43     }
44     
45     // Update the bits in reversed order so that emitInstrOpBits will get the
46     // correct endianness.
47     R->getValue("Inst")->setValue(NewBI);
48   }
49 }
50
51
52 int CodeEmitterGen::getVariableBit(const std::string &VarName, BitsInit *BI, int bit){
53   if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(BI->getBit(bit))) {
54     TypedInit *TI = VBI->getVariable();
55     
56     if (VarInit *VI = dynamic_cast<VarInit*>(TI)) {
57       if (VI->getName() == VarName) return VBI->getBitNum();
58     }
59   }
60   
61   return -1;
62
63
64
65 void CodeEmitterGen::run(std::ostream &o) {
66   CodeGenTarget Target;
67   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
68   
69   // For little-endian instruction bit encodings, reverse the bit order
70   if (Target.isLittleEndianEncoding()) reverseBits(Insts);
71
72   EmitSourceFileHeader("Machine Code Emitter", o);
73   std::string Namespace = Insts[0]->getValueAsString("Namespace") + "::";
74   
75   std::vector<const CodeGenInstruction*> NumberedInstructions;
76   Target.getInstructionsByEnumValue(NumberedInstructions);
77
78   // Emit function declaration
79   o << "unsigned " << Target.getName() << "CodeEmitter::"
80     << "getBinaryCodeForInstr(MachineInstr &MI) {\n";
81
82   // Emit instruction base values
83   o << "  static const unsigned InstBits[] = {\n";
84   for (std::vector<const CodeGenInstruction*>::iterator
85           IN = NumberedInstructions.begin(),
86           EN = NumberedInstructions.end();
87        IN != EN; ++IN) {
88     const CodeGenInstruction *CGI = *IN;
89     Record *R = CGI->TheDef;
90     
91     if (IN != NumberedInstructions.begin()) o << ",\n";
92     
93     if (R->getName() == "PHI" || R->getName() == "INLINEASM") {
94       o << "    0U";
95       continue;
96     }
97     
98     BitsInit *BI = R->getValueAsBitsInit("Inst");
99
100     unsigned Value = 0;
101     const std::vector<RecordVal> &Vals = R->getValues();
102
103     // Start by filling in fixed values...
104     for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
105       if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) {
106         Value |= B->getValue() << (e-i-1);
107       }
108     }
109     o << "    " << Value << "U";
110   }
111   o << "\n  };\n";
112   
113   // Map to accumulate all the cases.
114   std::map<std::string, std::vector<std::string> > CaseMap;
115   
116   // Construct all cases statement for each opcode
117   for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
118         IC != EC; ++IC) {
119     Record *R = *IC;
120     const std::string &InstName = R->getName();
121     std::string Case("");
122     
123     if (InstName == "PHI" || InstName == "INLINEASM") continue;
124     
125     BitsInit *BI = R->getValueAsBitsInit("Inst");
126     const std::vector<RecordVal> &Vals = R->getValues();
127
128     // Loop over all of the fields in the instruction, determining which are the
129     // operands to the instruction.
130     unsigned op = 0;
131     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
132       if (!Vals[i].getPrefix() && !Vals[i].getValue()->isComplete()) {
133         // Is the operand continuous? If so, we can just mask and OR it in
134         // instead of doing it bit-by-bit, saving a lot in runtime cost.
135         const std::string &VarName = Vals[i].getName();
136         bool gotOp = false;
137         
138         for (int bit = BI->getNumBits()-1; bit >= 0; ) {
139           int varBit = getVariableBit(VarName, BI, bit);
140           
141           if (varBit == -1) {
142             --bit;
143           } else {
144             int beginInstBit = bit;
145             int beginVarBit = varBit;
146             int N = 1;
147             
148             for (--bit; bit >= 0;) {
149               varBit = getVariableBit(VarName, BI, bit);
150               if (varBit == -1 || varBit != (beginVarBit - N)) break;
151               ++N;
152               --bit;
153             }
154
155             if (!gotOp) {
156               Case += "      // op: " + VarName + "\n"
157                    +  "      op = getMachineOpValue(MI, MI.getOperand("
158                    +  utostr(op++)
159                    +  "));\n";
160               gotOp = true;
161             }
162             
163             unsigned opMask = (1 << N) - 1;
164             int opShift = beginVarBit - N + 1;
165             opMask <<= opShift;
166             opShift = beginInstBit - beginVarBit;
167             
168             if (opShift > 0) {
169               Case += "      Value |= (op & " + utostr(opMask) + "U) << "
170                    +  itostr(opShift) + ";\n";
171             } else if (opShift < 0) {
172               Case += "      Value |= (op & " + utostr(opMask) + "U) >> "
173                    +  itostr(-opShift) + ";\n";
174             } else {
175               Case += "      Value |= op & " + utostr(opMask) + "U;\n";
176             }
177           }
178         }
179       }
180     }
181
182     std::vector<std::string> &InstList =  CaseMap[Case];
183     InstList.push_back(InstName);
184   }
185
186
187   // Emit initial function code
188   o << "  const unsigned opcode = MI.getOpcode();\n"
189     << "  unsigned Value = InstBits[opcode];\n"
190     << "  unsigned op;\n"
191     << "  switch (opcode) {\n";
192
193   // Emit each case statement
194   std::map<std::string, std::vector<std::string> >::iterator IE, EE;
195   for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
196     const std::string &Case = IE->first;
197     std::vector<std::string> &InstList = IE->second;
198
199     for (int i = 0, N = InstList.size(); i < N; i++) {
200       if (i) o << "\n";
201       o << "    case " << Namespace << InstList[i]  << ":";
202     }
203     o << " {\n";
204     o << Case;
205     o << "      break;\n"
206       << "    }\n";
207   }
208
209   // Default case: unhandled opcode
210   o << "  default:\n"
211     << "    std::cerr << \"Not supported instr: \" << MI << \"\\n\";\n"
212     << "    abort();\n"
213     << "  }\n"
214     << "  return Value;\n"
215     << "}\n\n";
216 }