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