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