CodeEmitterGen.cpp revision 336b8b42445920a3f59e42c61f2ccd9fbdfc497e
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"
22using 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.
27static cl::opt<bool>
28MCEmitter("mc-emitter",
29          cl::desc("Generate CodeEmitter for use with the MC library."),
30          cl::init(false));
31
32void 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.
63int CodeEmitterGen::getVariableBit(const std::string &VarName,
64            BitsInit *BI, int bit) {
65  if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(BI->getBit(bit))) {
66    TypedInit *TI = VBI->getVariable();
67
68    if (VarInit *VI = dynamic_cast<VarInit*>(TI)) {
69      if (VI->getName() == VarName) return VBI->getBitNum();
70    }
71  }
72
73  return -1;
74}
75
76void CodeEmitterGen::run(raw_ostream &o) {
77  CodeGenTarget Target;
78  std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
79
80  // For little-endian instruction bit encodings, reverse the bit order
81  if (Target.isLittleEndianEncoding()) reverseBits(Insts);
82
83  EmitSourceFileHeader("Machine Code Emitter", o);
84  std::string Namespace = Insts[0]->getValueAsString("Namespace") + "::";
85
86  const std::vector<const CodeGenInstruction*> &NumberedInstructions =
87    Target.getInstructionsByEnumValue();
88
89  // Emit function declaration
90  o << "unsigned " << Target.getName();
91  if (MCEmitter)
92    o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
93      << "    SmallVectorImpl<MCFixup> &Fixups) const {\n";
94  else
95    o << "CodeEmitter::getBinaryCodeForInstr(const MachineInstr &MI) const {\n";
96
97  // Emit instruction base values
98  o << "  static const unsigned InstBits[] = {\n";
99  for (std::vector<const CodeGenInstruction*>::const_iterator
100          IN = NumberedInstructions.begin(),
101          EN = NumberedInstructions.end();
102       IN != EN; ++IN) {
103    const CodeGenInstruction *CGI = *IN;
104    Record *R = CGI->TheDef;
105
106    if (R->getValueAsString("Namespace") == "TargetOpcode") {
107      o << "    0U,\n";
108      continue;
109    }
110
111    BitsInit *BI = R->getValueAsBitsInit("Inst");
112
113    // Start by filling in fixed values...
114    unsigned Value = 0;
115    for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
116      if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) {
117        Value |= B->getValue() << (e-i-1);
118      }
119    }
120    o << "    " << Value << "U," << '\t' << "// " << R->getName() << "\n";
121  }
122  o << "    0U\n  };\n";
123
124  // Map to accumulate all the cases.
125  std::map<std::string, std::vector<std::string> > CaseMap;
126
127  // Construct all cases statement for each opcode
128  for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
129        IC != EC; ++IC) {
130    Record *R = *IC;
131    if (R->getValueAsString("Namespace") == "TargetOpcode")
132      continue;
133    const std::string &InstName = R->getName();
134    std::string Case("");
135
136    BitsInit *BI = R->getValueAsBitsInit("Inst");
137    const std::vector<RecordVal> &Vals = R->getValues();
138    CodeGenInstruction &CGI = Target.getInstruction(R);
139
140    // Loop over all of the fields in the instruction, determining which are the
141    // operands to the instruction.
142    unsigned NumberedOp = 0;
143    for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
144      if (!Vals[i].getPrefix() && !Vals[i].getValue()->isComplete()) {
145        // Is the operand continuous? If so, we can just mask and OR it in
146        // instead of doing it bit-by-bit, saving a lot in runtime cost.
147        const std::string &VarName = Vals[i].getName();
148        bool gotOp = false;
149
150        for (int bit = BI->getNumBits()-1; bit >= 0; ) {
151          int varBit = getVariableBit(VarName, BI, bit);
152
153          if (varBit == -1) {
154            --bit;
155          } else {
156            int beginInstBit = bit;
157            int beginVarBit = varBit;
158            int N = 1;
159
160            for (--bit; bit >= 0;) {
161              varBit = getVariableBit(VarName, BI, bit);
162              if (varBit == -1 || varBit != (beginVarBit - N)) break;
163              ++N;
164              --bit;
165            }
166
167            if (!gotOp) {
168              // If the operand matches by name, reference according to that
169              // operand number. Non-matching operands are assumed to be in
170              // order.
171              unsigned OpIdx;
172              if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {
173                // Get the machine operand number for the indicated operand.
174                OpIdx = CGI.Operands[OpIdx].MIOperandNo;
175                assert (!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&
176                        "Explicitly used operand also marked as not emitted!");
177              } else {
178                /// If this operand is not supposed to be emitted by the
179                /// generated emitter, skip it.
180                while (CGI.Operands.isFlatOperandNotEmitted(NumberedOp))
181                  ++NumberedOp;
182                OpIdx = NumberedOp++;
183              }
184              std::pair<unsigned, unsigned> SO =
185                CGI.Operands.getSubOperandNumber(OpIdx);
186              std::string &EncoderMethodName =
187                CGI.Operands[SO.first].EncoderMethodName;
188
189              // If the source operand has a custom encoder, use it. This will
190              // get the encoding for all of the suboperands.
191              if (!EncoderMethodName.empty()) {
192                // A custom encoder has all of the information for the
193                // sub-operands, if there are more than one, so only
194                // query the encoder once per source operand.
195                if (SO.second == 0) {
196                  Case += "      // op: " + VarName + "\n"
197                       + "      op = " + EncoderMethodName + "(MI, "
198                       + utostr(OpIdx);
199                  if (MCEmitter)
200                    Case += ", Fixups";
201                  Case += ");\n";
202                }
203              } else {
204                Case += "      // op: " + VarName + "\n"
205                     +  "      op = getMachineOpValue(MI, MI.getOperand("
206                     +  utostr(OpIdx) + ")";
207                if (MCEmitter)
208                  Case += ", Fixups";
209                Case += ");\n";
210              }
211              gotOp = true;
212            }
213
214            unsigned opMask = ~0U >> (32-N);
215            int opShift = beginVarBit - N + 1;
216            opMask <<= opShift;
217            opShift = beginInstBit - beginVarBit;
218
219            if (opShift > 0) {
220              Case += "      Value |= (op & " + utostr(opMask) + "U) << "
221                   +  itostr(opShift) + ";\n";
222            } else if (opShift < 0) {
223              Case += "      Value |= (op & " + utostr(opMask) + "U) >> "
224                   +  itostr(-opShift) + ";\n";
225            } else {
226              Case += "      Value |= op & " + utostr(opMask) + "U;\n";
227            }
228          }
229        }
230      }
231    }
232
233    if (R->getValue("PostEncoderMethod"))
234      Case += "      Value = " +
235              R->getValueAsString("PostEncoderMethod") + "(MI, Value);\n";
236
237    std::vector<std::string> &InstList = CaseMap[Case];
238    InstList.push_back(InstName);
239  }
240
241  // Emit initial function code
242  o << "  const unsigned opcode = MI.getOpcode();\n"
243    << "  unsigned Value = InstBits[opcode];\n"
244    << "  unsigned op = 0;\n"
245    << "  op = op;  // suppress warning\n"
246    << "  switch (opcode) {\n";
247
248  // Emit each case statement
249  std::map<std::string, std::vector<std::string> >::iterator IE, EE;
250  for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
251    const std::string &Case = IE->first;
252    std::vector<std::string> &InstList = IE->second;
253
254    for (int i = 0, N = InstList.size(); i < N; i++) {
255      if (i) o << "\n";
256      o << "    case " << Namespace << InstList[i]  << ":";
257    }
258    o << " {\n";
259    o << Case;
260    o << "      break;\n"
261      << "    }\n";
262  }
263
264  // Default case: unhandled opcode
265  o << "  default:\n"
266    << "    std::string msg;\n"
267    << "    raw_string_ostream Msg(msg);\n"
268    << "    Msg << \"Not supported instr: \" << MI;\n"
269    << "    report_fatal_error(Msg.str());\n"
270    << "  }\n"
271    << "  return Value;\n"
272    << "}\n\n";
273}
274