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();
74 AddCodeToMergeInOperand(Record *R, BitsInit *BI, const std::string &VarName,
76 std::string &Case, CodeGenTarget &Target) {
78 CodeGenInstruction &CGI = Target.getInstruction(R);
80 for (int bit = BI->getNumBits()-1; bit >= 0; ) {
81 int varBit = getVariableBit(VarName, BI, bit);
83 // If this bit isn't from a variable, skip it.
89 // Figure out the consequtive range of bits covered by this operand, in
90 // order to generate better encoding code.
91 int beginInstBit = bit;
92 int beginVarBit = varBit;
94 for (--bit; bit >= 0;) {
95 varBit = getVariableBit(VarName, BI, bit);
96 if (varBit == -1 || varBit != (beginVarBit - N)) break;
102 // If the operand matches by name, reference according to that
103 // operand number. Non-matching operands are assumed to be in
106 if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {
107 // Get the machine operand number for the indicated operand.
108 OpIdx = CGI.Operands[OpIdx].MIOperandNo;
109 assert(!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&
110 "Explicitly used operand also marked as not emitted!");
112 /// If this operand is not supposed to be emitted by the
113 /// generated emitter, skip it.
114 while (CGI.Operands.isFlatOperandNotEmitted(NumberedOp))
116 OpIdx = NumberedOp++;
118 std::pair<unsigned, unsigned> SO =CGI.Operands.getSubOperandNumber(OpIdx);
119 std::string &EncoderMethodName = CGI.Operands[SO.first].EncoderMethodName;
121 // If the source operand has a custom encoder, use it. This will
122 // get the encoding for all of the suboperands.
123 if (!EncoderMethodName.empty()) {
124 // A custom encoder has all of the information for the
125 // sub-operands, if there are more than one, so only
126 // query the encoder once per source operand.
127 if (SO.second == 0) {
128 Case += " // op: " + VarName + "\n"
129 + " op = " + EncoderMethodName + "(MI, "
136 Case += " // op: " + VarName + "\n" +
137 " op = getMachineOpValue(MI, MI.getOperand(" +
146 unsigned opMask = ~0U >> (32-N);
147 int opShift = beginVarBit - N + 1;
149 opShift = beginInstBit - beginVarBit;
152 Case += " Value |= (op & " + utostr(opMask) + "U) << " +
153 itostr(opShift) + ";\n";
154 } else if (opShift < 0) {
155 Case += " Value |= (op & " + utostr(opMask) + "U) >> " +
156 itostr(-opShift) + ";\n";
158 Case += " Value |= op & " + utostr(opMask) + "U;\n";
164 std::string CodeEmitterGen::getInstructionCase(Record *R,
165 CodeGenTarget &Target) {
168 BitsInit *BI = R->getValueAsBitsInit("Inst");
169 const std::vector<RecordVal> &Vals = R->getValues();
170 unsigned NumberedOp = 0;
172 // Loop over all of the fields in the instruction, determining which are the
173 // operands to the instruction.
174 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
175 // Ignore fixed fields in the record, we're looking for values like:
176 // bits<5> RST = { ?, ?, ?, ?, ? };
177 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
180 AddCodeToMergeInOperand(R, BI, Vals[i].getName(), NumberedOp, Case, Target);
183 std::string PostEmitter = R->getValueAsString("PostEncoderMethod");
184 if (!PostEmitter.empty())
185 Case += " Value = " + PostEmitter + "(MI, Value);\n";
190 void CodeEmitterGen::run(raw_ostream &o) {
191 CodeGenTarget Target;
192 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
194 // For little-endian instruction bit encodings, reverse the bit order
195 if (Target.isLittleEndianEncoding()) reverseBits(Insts);
197 EmitSourceFileHeader("Machine Code Emitter", o);
198 std::string Namespace = Insts[0]->getValueAsString("Namespace") + "::";
200 const std::vector<const CodeGenInstruction*> &NumberedInstructions =
201 Target.getInstructionsByEnumValue();
203 // Emit function declaration
204 o << "unsigned " << Target.getName();
206 o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
207 << " SmallVectorImpl<MCFixup> &Fixups) const {\n";
209 o << "CodeEmitter::getBinaryCodeForInstr(const MachineInstr &MI) const {\n";
211 // Emit instruction base values
212 o << " static const unsigned InstBits[] = {\n";
213 for (std::vector<const CodeGenInstruction*>::const_iterator
214 IN = NumberedInstructions.begin(),
215 EN = NumberedInstructions.end();
217 const CodeGenInstruction *CGI = *IN;
218 Record *R = CGI->TheDef;
220 if (R->getValueAsString("Namespace") == "TargetOpcode") {
225 BitsInit *BI = R->getValueAsBitsInit("Inst");
227 // Start by filling in fixed values.
229 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
230 if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1)))
231 Value |= B->getValue() << (e-i-1);
233 o << " " << Value << "U," << '\t' << "// " << R->getName() << "\n";
237 // Map to accumulate all the cases.
238 std::map<std::string, std::vector<std::string> > CaseMap;
240 // Construct all cases statement for each opcode
241 for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
244 if (R->getValueAsString("Namespace") == "TargetOpcode")
246 const std::string &InstName = R->getName();
247 std::string Case = getInstructionCase(R, Target);
249 CaseMap[Case].push_back(InstName);
252 // Emit initial function code
253 o << " const unsigned opcode = MI.getOpcode();\n"
254 << " unsigned Value = InstBits[opcode];\n"
255 << " unsigned op = 0;\n"
256 << " op = op; // suppress warning\n"
257 << " switch (opcode) {\n";
259 // Emit each case statement
260 std::map<std::string, std::vector<std::string> >::iterator IE, EE;
261 for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
262 const std::string &Case = IE->first;
263 std::vector<std::string> &InstList = IE->second;
265 for (int i = 0, N = InstList.size(); i < N; i++) {
267 o << " case " << Namespace << InstList[i] << ":";
275 // Default case: unhandled opcode
277 << " std::string msg;\n"
278 << " raw_string_ostream Msg(msg);\n"
279 << " Msg << \"Not supported instr: \" << MI;\n"
280 << " report_fatal_error(Msg.str());\n"
282 << " return Value;\n"