1 //===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
16 #include "CodeEmitterGen.h"
17 #include "CodeGenTarget.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/Debug.h"
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
28 MCEmitter("mc-emitter",
29 cl::desc("Generate CodeEmitter for use with the MC library."),
32 void CodeEmitterGen::reverseBits(std::vector<Record*> &Insts) {
33 for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end();
36 if (R->getValueAsString("Namespace") == "TargetOpcode")
39 BitsInit *BI = R->getValueAsBitsInit("Inst");
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);
51 unsigned middle = (numBits + 1) / 2;
52 NewBI->setBit(middle, BI->getBit(middle));
55 // Update the bits in reversed order so that emitInstrOpBits will get the
56 // correct endianness.
57 R->getValue("Inst")->setValue(NewBI);
61 // If the VarBitInit at position 'bit' matches the specified variable then
62 // return the variable bit position. Otherwise return -1.
63 int CodeEmitterGen::getVariableBit(const std::string &VarName,
64 BitsInit *BI, int bit) {
65 if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(BI->getBit(bit)))
66 if (VarInit *VI = dynamic_cast<VarInit*>(VBI->getVariable()))
67 if (VI->getName() == VarName)
68 return VBI->getBitNum();
73 void CodeEmitterGen::run(raw_ostream &o) {
75 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
77 // For little-endian instruction bit encodings, reverse the bit order
78 if (Target.isLittleEndianEncoding()) reverseBits(Insts);
80 EmitSourceFileHeader("Machine Code Emitter", o);
81 std::string Namespace = Insts[0]->getValueAsString("Namespace") + "::";
83 const std::vector<const CodeGenInstruction*> &NumberedInstructions =
84 Target.getInstructionsByEnumValue();
86 // Emit function declaration
87 o << "unsigned " << Target.getName();
89 o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
90 << " SmallVectorImpl<MCFixup> &Fixups) const {\n";
92 o << "CodeEmitter::getBinaryCodeForInstr(const MachineInstr &MI) const {\n";
94 // Emit instruction base values
95 o << " static const unsigned InstBits[] = {\n";
96 for (std::vector<const CodeGenInstruction*>::const_iterator
97 IN = NumberedInstructions.begin(),
98 EN = NumberedInstructions.end();
100 const CodeGenInstruction *CGI = *IN;
101 Record *R = CGI->TheDef;
103 if (R->getValueAsString("Namespace") == "TargetOpcode") {
108 BitsInit *BI = R->getValueAsBitsInit("Inst");
110 // Start by filling in fixed values...
112 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
113 if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) {
114 Value |= B->getValue() << (e-i-1);
117 o << " " << Value << "U," << '\t' << "// " << R->getName() << "\n";
121 // Map to accumulate all the cases.
122 std::map<std::string, std::vector<std::string> > CaseMap;
124 // Construct all cases statement for each opcode
125 for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
128 if (R->getValueAsString("Namespace") == "TargetOpcode")
130 const std::string &InstName = R->getName();
131 std::string Case("");
133 BitsInit *BI = R->getValueAsBitsInit("Inst");
134 const std::vector<RecordVal> &Vals = R->getValues();
135 CodeGenInstruction &CGI = Target.getInstruction(R);
137 // Loop over all of the fields in the instruction, determining which are the
138 // operands to the instruction.
139 unsigned NumberedOp = 0;
140 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
141 // Ignore fixed fields.
142 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();
150 for (int bit = BI->getNumBits()-1; bit >= 0; ) {
151 int varBit = getVariableBit(VarName, BI, bit);
153 // If this bit isn't from a variable, skip it.
159 int beginInstBit = bit;
160 int beginVarBit = varBit;
163 for (--bit; bit >= 0;) {
164 varBit = getVariableBit(VarName, BI, bit);
165 if (varBit == -1 || varBit != (beginVarBit - N)) break;
171 // If the operand matches by name, reference according to that
172 // operand number. Non-matching operands are assumed to be in
175 if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {
176 // Get the machine operand number for the indicated operand.
177 OpIdx = CGI.Operands[OpIdx].MIOperandNo;
178 assert (!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&
179 "Explicitly used operand also marked as not emitted!");
181 /// If this operand is not supposed to be emitted by the
182 /// generated emitter, skip it.
183 while (CGI.Operands.isFlatOperandNotEmitted(NumberedOp))
185 OpIdx = NumberedOp++;
187 std::pair<unsigned, unsigned> SO =
188 CGI.Operands.getSubOperandNumber(OpIdx);
189 std::string &EncoderMethodName =
190 CGI.Operands[SO.first].EncoderMethodName;
192 // If the source operand has a custom encoder, use it. This will
193 // get the encoding for all of the suboperands.
194 if (!EncoderMethodName.empty()) {
195 // A custom encoder has all of the information for the
196 // sub-operands, if there are more than one, so only
197 // query the encoder once per source operand.
198 if (SO.second == 0) {
199 Case += " // op: " + VarName + "\n"
200 + " op = " + EncoderMethodName + "(MI, "
207 Case += " // op: " + VarName + "\n"
208 + " op = getMachineOpValue(MI, MI.getOperand("
209 + utostr(OpIdx) + ")";
217 unsigned opMask = ~0U >> (32-N);
218 int opShift = beginVarBit - N + 1;
220 opShift = beginInstBit - beginVarBit;
223 Case += " Value |= (op & " + utostr(opMask) + "U) << "
224 + itostr(opShift) + ";\n";
225 } else if (opShift < 0) {
226 Case += " Value |= (op & " + utostr(opMask) + "U) >> "
227 + itostr(-opShift) + ";\n";
229 Case += " Value |= op & " + utostr(opMask) + "U;\n";
234 std::string PostEmitter = R->getValueAsString("PostEncoderMethod");
235 if (!PostEmitter.empty())
236 Case += " Value = " + PostEmitter + "(MI, Value);\n";
238 std::vector<std::string> &InstList = CaseMap[Case];
239 InstList.push_back(InstName);
242 // Emit initial function code
243 o << " const unsigned opcode = MI.getOpcode();\n"
244 << " unsigned Value = InstBits[opcode];\n"
245 << " unsigned op = 0;\n"
246 << " op = op; // suppress warning\n"
247 << " switch (opcode) {\n";
249 // Emit each case statement
250 std::map<std::string, std::vector<std::string> >::iterator IE, EE;
251 for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
252 const std::string &Case = IE->first;
253 std::vector<std::string> &InstList = IE->second;
255 for (int i = 0, N = InstList.size(); i < N; i++) {
257 o << " case " << Namespace << InstList[i] << ":";
265 // Default case: unhandled opcode
267 << " std::string msg;\n"
268 << " raw_string_ostream Msg(msg);\n"
269 << " Msg << \"Not supported instr: \" << MI;\n"
270 << " report_fatal_error(Msg.str());\n"
272 << " return Value;\n"