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 "CodeGenTarget.h" 17 #include "llvm/ADT/StringExtras.h" 18 #include "llvm/Support/CommandLine.h" 19 #include "llvm/Support/Debug.h" 20 #include "llvm/TableGen/Record.h" 21 #include "llvm/TableGen/TableGenBackend.h" 22 #include <map> 23 #include <string> 24 #include <vector> 25 using namespace llvm; 26 27 // FIXME: Somewhat hackish to use a command line option for this. There should 28 // be a CodeEmitter class in the Target.td that controls this sort of thing 29 // instead. 30 static cl::opt<bool> 31 MCEmitter("mc-emitter", 32 cl::desc("Generate CodeEmitter for use with the MC library."), 33 cl::init(false)); 34 35 namespace { 36 37 class CodeEmitterGen { 38 RecordKeeper &Records; 39 public: 40 CodeEmitterGen(RecordKeeper &R) : Records(R) {} 41 42 void run(raw_ostream &o); 43 private: 44 void emitMachineOpEmitter(raw_ostream &o, const std::string &Namespace); 45 void emitGetValueBit(raw_ostream &o, const std::string &Namespace); 46 int getVariableBit(const std::string &VarName, BitsInit *BI, int bit); 47 std::string getInstructionCase(Record *R, CodeGenTarget &Target); 48 void AddCodeToMergeInOperand(Record *R, BitsInit *BI, 49 const std::string &VarName, 50 unsigned &NumberedOp, 51 std::string &Case, CodeGenTarget &Target); 52 53 }; 54 55 // If the VarBitInit at position 'bit' matches the specified variable then 56 // return the variable bit position. Otherwise return -1. 57 int CodeEmitterGen::getVariableBit(const std::string &VarName, 58 BitsInit *BI, int bit) { 59 if (VarBitInit *VBI = dyn_cast<VarBitInit>(BI->getBit(bit))) { 60 if (VarInit *VI = dyn_cast<VarInit>(VBI->getBitVar())) 61 if (VI->getName() == VarName) 62 return VBI->getBitNum(); 63 } else if (VarInit *VI = dyn_cast<VarInit>(BI->getBit(bit))) { 64 if (VI->getName() == VarName) 65 return 0; 66 } 67 68 return -1; 69 } 70 71 void CodeEmitterGen:: 72 AddCodeToMergeInOperand(Record *R, BitsInit *BI, const std::string &VarName, 73 unsigned &NumberedOp, 74 std::string &Case, CodeGenTarget &Target) { 75 CodeGenInstruction &CGI = Target.getInstruction(R); 76 77 // Determine if VarName actually contributes to the Inst encoding. 78 int bit = BI->getNumBits()-1; 79 80 // Scan for a bit that this contributed to. 81 for (; bit >= 0; ) { 82 if (getVariableBit(VarName, BI, bit) != -1) 83 break; 84 85 --bit; 86 } 87 88 // If we found no bits, ignore this value, otherwise emit the call to get the 89 // operand encoding. 90 if (bit < 0) return; 91 92 // If the operand matches by name, reference according to that 93 // operand number. Non-matching operands are assumed to be in 94 // order. 95 unsigned OpIdx; 96 if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) { 97 // Get the machine operand number for the indicated operand. 98 OpIdx = CGI.Operands[OpIdx].MIOperandNo; 99 assert(!CGI.Operands.isFlatOperandNotEmitted(OpIdx) && 100 "Explicitly used operand also marked as not emitted!"); 101 } else { 102 unsigned NumberOps = CGI.Operands.size(); 103 /// If this operand is not supposed to be emitted by the 104 /// generated emitter, skip it. 105 while (NumberedOp < NumberOps && 106 CGI.Operands.isFlatOperandNotEmitted(NumberedOp)) 107 ++NumberedOp; 108 109 OpIdx = NumberedOp++; 110 } 111 112 std::pair<unsigned, unsigned> SO = CGI.Operands.getSubOperandNumber(OpIdx); 113 std::string &EncoderMethodName = CGI.Operands[SO.first].EncoderMethodName; 114 115 // If the source operand has a custom encoder, use it. This will 116 // get the encoding for all of the suboperands. 117 if (!EncoderMethodName.empty()) { 118 // A custom encoder has all of the information for the 119 // sub-operands, if there are more than one, so only 120 // query the encoder once per source operand. 121 if (SO.second == 0) { 122 Case += " // op: " + VarName + "\n" + 123 " op = " + EncoderMethodName + "(MI, " + utostr(OpIdx); 124 if (MCEmitter) 125 Case += ", Fixups, STI"; 126 Case += ");\n"; 127 } 128 } else { 129 Case += " // op: " + VarName + "\n" + 130 " op = getMachineOpValue(MI, MI.getOperand(" + utostr(OpIdx) + ")"; 131 if (MCEmitter) 132 Case += ", Fixups, STI"; 133 Case += ");\n"; 134 } 135 136 for (; bit >= 0; ) { 137 int varBit = getVariableBit(VarName, BI, bit); 138 139 // If this bit isn't from a variable, skip it. 140 if (varBit == -1) { 141 --bit; 142 continue; 143 } 144 145 // Figure out the consecutive range of bits covered by this operand, in 146 // order to generate better encoding code. 147 int beginInstBit = bit; 148 int beginVarBit = varBit; 149 int N = 1; 150 for (--bit; bit >= 0;) { 151 varBit = getVariableBit(VarName, BI, bit); 152 if (varBit == -1 || varBit != (beginVarBit - N)) break; 153 ++N; 154 --bit; 155 } 156 157 uint64_t opMask = ~(uint64_t)0 >> (64-N); 158 int opShift = beginVarBit - N + 1; 159 opMask <<= opShift; 160 opShift = beginInstBit - beginVarBit; 161 162 if (opShift > 0) { 163 Case += " Value |= (op & UINT64_C(" + utostr(opMask) + ")) << " + 164 itostr(opShift) + ";\n"; 165 } else if (opShift < 0) { 166 Case += " Value |= (op & UINT64_C(" + utostr(opMask) + ")) >> " + 167 itostr(-opShift) + ";\n"; 168 } else { 169 Case += " Value |= op & UINT64_C(" + utostr(opMask) + ");\n"; 170 } 171 } 172 } 173 174 175 std::string CodeEmitterGen::getInstructionCase(Record *R, 176 CodeGenTarget &Target) { 177 std::string Case; 178 179 BitsInit *BI = R->getValueAsBitsInit("Inst"); 180 const std::vector<RecordVal> &Vals = R->getValues(); 181 unsigned NumberedOp = 0; 182 183 // Loop over all of the fields in the instruction, determining which are the 184 // operands to the instruction. 185 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 186 // Ignore fixed fields in the record, we're looking for values like: 187 // bits<5> RST = { ?, ?, ?, ?, ? }; 188 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete()) 189 continue; 190 191 AddCodeToMergeInOperand(R, BI, Vals[i].getName(), NumberedOp, Case, Target); 192 } 193 194 std::string PostEmitter = R->getValueAsString("PostEncoderMethod"); 195 if (!PostEmitter.empty()) { 196 Case += " Value = " + PostEmitter + "(MI, Value"; 197 if (MCEmitter) 198 Case += ", STI"; 199 Case += ");\n"; 200 } 201 202 return Case; 203 } 204 205 void CodeEmitterGen::run(raw_ostream &o) { 206 CodeGenTarget Target(Records); 207 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction"); 208 209 // For little-endian instruction bit encodings, reverse the bit order 210 Target.reverseBitsForLittleEndianEncoding(); 211 212 const std::vector<const CodeGenInstruction*> &NumberedInstructions = 213 Target.getInstructionsByEnumValue(); 214 215 // Emit function declaration 216 o << "uint64_t " << Target.getName(); 217 if (MCEmitter) 218 o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n" 219 << " SmallVectorImpl<MCFixup> &Fixups,\n" 220 << " const MCSubtargetInfo &STI) const {\n"; 221 else 222 o << "CodeEmitter::getBinaryCodeForInstr(const MachineInstr &MI) const {\n"; 223 224 // Emit instruction base values 225 o << " static const uint64_t InstBits[] = {\n"; 226 for (std::vector<const CodeGenInstruction*>::const_iterator 227 IN = NumberedInstructions.begin(), 228 EN = NumberedInstructions.end(); 229 IN != EN; ++IN) { 230 const CodeGenInstruction *CGI = *IN; 231 Record *R = CGI->TheDef; 232 233 if (R->getValueAsString("Namespace") == "TargetOpcode" || 234 R->getValueAsBit("isPseudo")) { 235 o << " UINT64_C(0),\n"; 236 continue; 237 } 238 239 BitsInit *BI = R->getValueAsBitsInit("Inst"); 240 241 // Start by filling in fixed values. 242 uint64_t Value = 0; 243 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) { 244 if (BitInit *B = dyn_cast<BitInit>(BI->getBit(e-i-1))) 245 Value |= (uint64_t)B->getValue() << (e-i-1); 246 } 247 o << " UINT64_C(" << Value << ")," << '\t' << "// " << R->getName() << "\n"; 248 } 249 o << " UINT64_C(0)\n };\n"; 250 251 // Map to accumulate all the cases. 252 std::map<std::string, std::vector<std::string> > CaseMap; 253 254 // Construct all cases statement for each opcode 255 for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end(); 256 IC != EC; ++IC) { 257 Record *R = *IC; 258 if (R->getValueAsString("Namespace") == "TargetOpcode" || 259 R->getValueAsBit("isPseudo")) 260 continue; 261 const std::string &InstName = R->getValueAsString("Namespace") + "::" 262 + R->getName(); 263 std::string Case = getInstructionCase(R, Target); 264 265 CaseMap[Case].push_back(InstName); 266 } 267 268 // Emit initial function code 269 o << " const unsigned opcode = MI.getOpcode();\n" 270 << " uint64_t Value = InstBits[opcode];\n" 271 << " uint64_t op = 0;\n" 272 << " (void)op; // suppress warning\n" 273 << " switch (opcode) {\n"; 274 275 // Emit each case statement 276 std::map<std::string, std::vector<std::string> >::iterator IE, EE; 277 for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) { 278 const std::string &Case = IE->first; 279 std::vector<std::string> &InstList = IE->second; 280 281 for (int i = 0, N = InstList.size(); i < N; i++) { 282 if (i) o << "\n"; 283 o << " case " << InstList[i] << ":"; 284 } 285 o << " {\n"; 286 o << Case; 287 o << " break;\n" 288 << " }\n"; 289 } 290 291 // Default case: unhandled opcode 292 o << " default:\n" 293 << " std::string msg;\n" 294 << " raw_string_ostream Msg(msg);\n" 295 << " Msg << \"Not supported instr: \" << MI;\n" 296 << " report_fatal_error(Msg.str());\n" 297 << " }\n" 298 << " return Value;\n" 299 << "}\n\n"; 300 } 301 302 } // End anonymous namespace 303 304 namespace llvm { 305 306 void EmitCodeEmitter(RecordKeeper &RK, raw_ostream &OS) { 307 emitSourceFileHeader("Machine Code Emitter", OS); 308 CodeEmitterGen(RK).run(OS); 309 } 310 311 } // End llvm namespace 312