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 "CodeGenInstruction.h" 17 #include "CodeGenTarget.h" 18 #include "SubtargetFeatureInfo.h" 19 #include "llvm/ADT/ArrayRef.h" 20 #include "llvm/ADT/StringExtras.h" 21 #include "llvm/Support/Casting.h" 22 #include "llvm/Support/raw_ostream.h" 23 #include "llvm/TableGen/Record.h" 24 #include "llvm/TableGen/TableGenBackend.h" 25 #include <cassert> 26 #include <cstdint> 27 #include <map> 28 #include <set> 29 #include <string> 30 #include <utility> 31 #include <vector> 32 33 using namespace llvm; 34 35 namespace { 36 37 class CodeEmitterGen { 38 RecordKeeper &Records; 39 40 public: 41 CodeEmitterGen(RecordKeeper &R) : Records(R) {} 42 43 void run(raw_ostream &o); 44 45 private: 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::set<unsigned> &NamedOpIndices, 52 std::string &Case, CodeGenTarget &Target); 53 54 }; 55 56 // If the VarBitInit at position 'bit' matches the specified variable then 57 // return the variable bit position. Otherwise return -1. 58 int CodeEmitterGen::getVariableBit(const std::string &VarName, 59 BitsInit *BI, int bit) { 60 if (VarBitInit *VBI = dyn_cast<VarBitInit>(BI->getBit(bit))) { 61 if (VarInit *VI = dyn_cast<VarInit>(VBI->getBitVar())) 62 if (VI->getName() == VarName) 63 return VBI->getBitNum(); 64 } else if (VarInit *VI = dyn_cast<VarInit>(BI->getBit(bit))) { 65 if (VI->getName() == VarName) 66 return 0; 67 } 68 69 return -1; 70 } 71 72 void CodeEmitterGen:: 73 AddCodeToMergeInOperand(Record *R, BitsInit *BI, const std::string &VarName, 74 unsigned &NumberedOp, 75 std::set<unsigned> &NamedOpIndices, 76 std::string &Case, CodeGenTarget &Target) { 77 CodeGenInstruction &CGI = Target.getInstruction(R); 78 79 // Determine if VarName actually contributes to the Inst encoding. 80 int bit = BI->getNumBits()-1; 81 82 // Scan for a bit that this contributed to. 83 for (; bit >= 0; ) { 84 if (getVariableBit(VarName, BI, bit) != -1) 85 break; 86 87 --bit; 88 } 89 90 // If we found no bits, ignore this value, otherwise emit the call to get the 91 // operand encoding. 92 if (bit < 0) return; 93 94 // If the operand matches by name, reference according to that 95 // operand number. Non-matching operands are assumed to be in 96 // order. 97 unsigned OpIdx; 98 if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) { 99 // Get the machine operand number for the indicated operand. 100 OpIdx = CGI.Operands[OpIdx].MIOperandNo; 101 assert(!CGI.Operands.isFlatOperandNotEmitted(OpIdx) && 102 "Explicitly used operand also marked as not emitted!"); 103 } else { 104 unsigned NumberOps = CGI.Operands.size(); 105 /// If this operand is not supposed to be emitted by the 106 /// generated emitter, skip it. 107 while (NumberedOp < NumberOps && 108 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) || 109 (!NamedOpIndices.empty() && NamedOpIndices.count( 110 CGI.Operands.getSubOperandNumber(NumberedOp).first)))) { 111 ++NumberedOp; 112 113 if (NumberedOp >= CGI.Operands.back().MIOperandNo + 114 CGI.Operands.back().MINumOperands) { 115 errs() << "Too few operands in record " << R->getName() << 116 " (no match for variable " << VarName << "):\n"; 117 errs() << *R; 118 errs() << '\n'; 119 120 return; 121 } 122 } 123 124 OpIdx = NumberedOp++; 125 } 126 127 std::pair<unsigned, unsigned> SO = CGI.Operands.getSubOperandNumber(OpIdx); 128 std::string &EncoderMethodName = CGI.Operands[SO.first].EncoderMethodName; 129 130 // If the source operand has a custom encoder, use it. This will 131 // get the encoding for all of the suboperands. 132 if (!EncoderMethodName.empty()) { 133 // A custom encoder has all of the information for the 134 // sub-operands, if there are more than one, so only 135 // query the encoder once per source operand. 136 if (SO.second == 0) { 137 Case += " // op: " + VarName + "\n" + 138 " op = " + EncoderMethodName + "(MI, " + utostr(OpIdx); 139 Case += ", Fixups, STI"; 140 Case += ");\n"; 141 } 142 } else { 143 Case += " // op: " + VarName + "\n" + 144 " op = getMachineOpValue(MI, MI.getOperand(" + utostr(OpIdx) + ")"; 145 Case += ", Fixups, STI"; 146 Case += ");\n"; 147 } 148 149 for (; bit >= 0; ) { 150 int varBit = getVariableBit(VarName, BI, bit); 151 152 // If this bit isn't from a variable, skip it. 153 if (varBit == -1) { 154 --bit; 155 continue; 156 } 157 158 // Figure out the consecutive range of bits covered by this operand, in 159 // order to generate better encoding code. 160 int beginInstBit = bit; 161 int beginVarBit = varBit; 162 int N = 1; 163 for (--bit; bit >= 0;) { 164 varBit = getVariableBit(VarName, BI, bit); 165 if (varBit == -1 || varBit != (beginVarBit - N)) break; 166 ++N; 167 --bit; 168 } 169 170 uint64_t opMask = ~(uint64_t)0 >> (64-N); 171 int opShift = beginVarBit - N + 1; 172 opMask <<= opShift; 173 opShift = beginInstBit - beginVarBit; 174 175 if (opShift > 0) { 176 Case += " Value |= (op & UINT64_C(" + utostr(opMask) + ")) << " + 177 itostr(opShift) + ";\n"; 178 } else if (opShift < 0) { 179 Case += " Value |= (op & UINT64_C(" + utostr(opMask) + ")) >> " + 180 itostr(-opShift) + ";\n"; 181 } else { 182 Case += " Value |= op & UINT64_C(" + utostr(opMask) + ");\n"; 183 } 184 } 185 } 186 187 std::string CodeEmitterGen::getInstructionCase(Record *R, 188 CodeGenTarget &Target) { 189 std::string Case; 190 191 BitsInit *BI = R->getValueAsBitsInit("Inst"); 192 const std::vector<RecordVal> &Vals = R->getValues(); 193 unsigned NumberedOp = 0; 194 195 std::set<unsigned> NamedOpIndices; 196 // Collect the set of operand indices that might correspond to named 197 // operand, and skip these when assigning operands based on position. 198 if (Target.getInstructionSet()-> 199 getValueAsBit("noNamedPositionallyEncodedOperands")) { 200 CodeGenInstruction &CGI = Target.getInstruction(R); 201 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 202 unsigned OpIdx; 203 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx)) 204 continue; 205 206 NamedOpIndices.insert(OpIdx); 207 } 208 } 209 210 // Loop over all of the fields in the instruction, determining which are the 211 // operands to the instruction. 212 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 213 // Ignore fixed fields in the record, we're looking for values like: 214 // bits<5> RST = { ?, ?, ?, ?, ? }; 215 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete()) 216 continue; 217 218 AddCodeToMergeInOperand(R, BI, Vals[i].getName(), NumberedOp, 219 NamedOpIndices, Case, Target); 220 } 221 222 StringRef PostEmitter = R->getValueAsString("PostEncoderMethod"); 223 if (!PostEmitter.empty()) { 224 Case += " Value = "; 225 Case += PostEmitter; 226 Case += "(MI, Value"; 227 Case += ", STI"; 228 Case += ");\n"; 229 } 230 231 return Case; 232 } 233 234 void CodeEmitterGen::run(raw_ostream &o) { 235 CodeGenTarget Target(Records); 236 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction"); 237 238 // For little-endian instruction bit encodings, reverse the bit order 239 Target.reverseBitsForLittleEndianEncoding(); 240 241 ArrayRef<const CodeGenInstruction*> NumberedInstructions = 242 Target.getInstructionsByEnumValue(); 243 244 // Emit function declaration 245 o << "uint64_t " << Target.getName(); 246 o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n" 247 << " SmallVectorImpl<MCFixup> &Fixups,\n" 248 << " const MCSubtargetInfo &STI) const {\n"; 249 250 // Emit instruction base values 251 o << " static const uint64_t InstBits[] = {\n"; 252 for (const CodeGenInstruction *CGI : NumberedInstructions) { 253 Record *R = CGI->TheDef; 254 255 if (R->getValueAsString("Namespace") == "TargetOpcode" || 256 R->getValueAsBit("isPseudo")) { 257 o << " UINT64_C(0),\n"; 258 continue; 259 } 260 261 BitsInit *BI = R->getValueAsBitsInit("Inst"); 262 263 // Start by filling in fixed values. 264 uint64_t Value = 0; 265 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) { 266 if (BitInit *B = dyn_cast<BitInit>(BI->getBit(e-i-1))) 267 Value |= (uint64_t)B->getValue() << (e-i-1); 268 } 269 o << " UINT64_C(" << Value << ")," << '\t' << "// " << R->getName() << "\n"; 270 } 271 o << " UINT64_C(0)\n };\n"; 272 273 // Map to accumulate all the cases. 274 std::map<std::string, std::vector<std::string>> CaseMap; 275 276 // Construct all cases statement for each opcode 277 for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end(); 278 IC != EC; ++IC) { 279 Record *R = *IC; 280 if (R->getValueAsString("Namespace") == "TargetOpcode" || 281 R->getValueAsBit("isPseudo")) 282 continue; 283 std::string InstName = 284 (R->getValueAsString("Namespace") + "::" + R->getName()).str(); 285 std::string Case = getInstructionCase(R, Target); 286 287 CaseMap[Case].push_back(std::move(InstName)); 288 } 289 290 // Emit initial function code 291 o << " const unsigned opcode = MI.getOpcode();\n" 292 << " uint64_t Value = InstBits[opcode];\n" 293 << " uint64_t op = 0;\n" 294 << " (void)op; // suppress warning\n" 295 << " switch (opcode) {\n"; 296 297 // Emit each case statement 298 std::map<std::string, std::vector<std::string>>::iterator IE, EE; 299 for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) { 300 const std::string &Case = IE->first; 301 std::vector<std::string> &InstList = IE->second; 302 303 for (int i = 0, N = InstList.size(); i < N; i++) { 304 if (i) o << "\n"; 305 o << " case " << InstList[i] << ":"; 306 } 307 o << " {\n"; 308 o << Case; 309 o << " break;\n" 310 << " }\n"; 311 } 312 313 // Default case: unhandled opcode 314 o << " default:\n" 315 << " std::string msg;\n" 316 << " raw_string_ostream Msg(msg);\n" 317 << " Msg << \"Not supported instr: \" << MI;\n" 318 << " report_fatal_error(Msg.str());\n" 319 << " }\n" 320 << " return Value;\n" 321 << "}\n\n"; 322 323 const auto &All = SubtargetFeatureInfo::getAll(Records); 324 std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures; 325 SubtargetFeatures.insert(All.begin(), All.end()); 326 327 o << "#ifdef ENABLE_INSTR_PREDICATE_VERIFIER\n" 328 << "#undef ENABLE_INSTR_PREDICATE_VERIFIER\n" 329 << "#include <sstream>\n\n"; 330 331 // Emit the subtarget feature enumeration. 332 SubtargetFeatureInfo::emitSubtargetFeatureFlagEnumeration(SubtargetFeatures, 333 o); 334 335 // Emit the name table for error messages. 336 o << "#ifndef NDEBUG\n"; 337 SubtargetFeatureInfo::emitNameTable(SubtargetFeatures, o); 338 o << "#endif // NDEBUG\n"; 339 340 // Emit the available features compute function. 341 SubtargetFeatureInfo::emitComputeAssemblerAvailableFeatures( 342 Target.getName(), "MCCodeEmitter", "computeAvailableFeatures", 343 SubtargetFeatures, o); 344 345 // Emit the predicate verifier. 346 o << "void " << Target.getName() 347 << "MCCodeEmitter::verifyInstructionPredicates(\n" 348 << " const MCInst &Inst, uint64_t AvailableFeatures) const {\n" 349 << "#ifndef NDEBUG\n" 350 << " static uint64_t RequiredFeatures[] = {\n"; 351 unsigned InstIdx = 0; 352 for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) { 353 o << " "; 354 for (Record *Predicate : Inst->TheDef->getValueAsListOfDefs("Predicates")) { 355 const auto &I = SubtargetFeatures.find(Predicate); 356 if (I != SubtargetFeatures.end()) 357 o << I->second.getEnumName() << " | "; 358 } 359 o << "0, // " << Inst->TheDef->getName() << " = " << InstIdx << "\n"; 360 InstIdx++; 361 } 362 o << " };\n\n"; 363 o << " assert(Inst.getOpcode() < " << InstIdx << ");\n"; 364 o << " uint64_t MissingFeatures =\n" 365 << " (AvailableFeatures & RequiredFeatures[Inst.getOpcode()]) ^\n" 366 << " RequiredFeatures[Inst.getOpcode()];\n" 367 << " if (MissingFeatures) {\n" 368 << " std::ostringstream Msg;\n" 369 << " Msg << \"Attempting to emit \" << " 370 "MCII.getName(Inst.getOpcode()).str()\n" 371 << " << \" instruction but the \";\n" 372 << " for (unsigned i = 0; i < 8 * sizeof(MissingFeatures); ++i)\n" 373 << " if (MissingFeatures & (1ULL << i))\n" 374 << " Msg << SubtargetFeatureNames[i] << \" \";\n" 375 << " Msg << \"predicate(s) are not met\";\n" 376 << " report_fatal_error(Msg.str());\n" 377 << " }\n" 378 << "#else\n" 379 << "// Silence unused variable warning on targets that don't use MCII for " 380 "other purposes (e.g. BPF).\n" 381 << "(void)MCII;\n" 382 << "#endif // NDEBUG\n"; 383 o << "}\n"; 384 o << "#endif\n"; 385 } 386 387 } // end anonymous namespace 388 389 namespace llvm { 390 391 void EmitCodeEmitter(RecordKeeper &RK, raw_ostream &OS) { 392 emitSourceFileHeader("Machine Code Emitter", OS); 393 CodeEmitterGen(RK).run(OS); 394 } 395 396 } // end namespace llvm 397