[llvm-exegesis] [NFC] Fixing typo.
[llvm-complete.git] / utils / TableGen / RISCVCompressInstEmitter.cpp
blobf95b3bf9cb48b59f705bdd855718b28904d982fb
1 //===- RISCVCompressInstEmitter.cpp - Generator for RISCV Compression -===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 // RISCVCompressInstEmitter implements a tablegen-driven CompressPat based
8 // RISCV Instruction Compression mechanism.
9 //
10 //===--------------------------------------------------------------===//
12 // RISCVCompressInstEmitter implements a tablegen-driven CompressPat Instruction
13 // Compression mechanism for generating RISCV compressed instructions
14 // (C ISA Extension) from the expanded instruction form.
16 // This tablegen backend processes CompressPat declarations in a
17 // td file and generates all the required checks to validate the pattern
18 // declarations; validate the input and output operands to generate the correct
19 // compressed instructions. The checks include validating different types of
20 // operands; register operands, immediate operands, fixed register and fixed
21 // immediate inputs.
23 // Example:
24 // class CompressPat<dag input, dag output> {
25 // dag Input = input;
26 // dag Output = output;
27 // list<Predicate> Predicates = [];
28 // }
30 // let Predicates = [HasStdExtC] in {
31 // def : CompressPat<(ADD GPRNoX0:$rs1, GPRNoX0:$rs1, GPRNoX0:$rs2),
32 // (C_ADD GPRNoX0:$rs1, GPRNoX0:$rs2)>;
33 // }
35 // The result is an auto-generated header file
36 // 'RISCVGenCompressInstEmitter.inc' which exports two functions for
37 // compressing/uncompressing MCInst instructions, plus
38 // some helper functions:
40 // bool compressInst(MCInst& OutInst, const MCInst &MI,
41 // const MCSubtargetInfo &STI,
42 // MCContext &Context);
44 // bool uncompressInst(MCInst& OutInst, const MCInst &MI,
45 // const MCRegisterInfo &MRI,
46 // const MCSubtargetInfo &STI);
48 // The clients that include this auto-generated header file and
49 // invoke these functions can compress an instruction before emitting
50 // it in the target-specific ASM or ELF streamer or can uncompress
51 // an instruction before printing it when the expanded instruction
52 // format aliases is favored.
54 //===----------------------------------------------------------------------===//
56 #include "CodeGenInstruction.h"
57 #include "CodeGenTarget.h"
58 #include "llvm/ADT/IndexedMap.h"
59 #include "llvm/ADT/SmallVector.h"
60 #include "llvm/ADT/StringExtras.h"
61 #include "llvm/ADT/StringMap.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/TableGen/Error.h"
65 #include "llvm/TableGen/Record.h"
66 #include "llvm/TableGen/TableGenBackend.h"
67 #include <vector>
68 using namespace llvm;
70 #define DEBUG_TYPE "compress-inst-emitter"
72 namespace {
73 class RISCVCompressInstEmitter {
74 struct OpData {
75 enum MapKind { Operand, Imm, Reg };
76 MapKind Kind;
77 union {
78 unsigned Operand; // Operand number mapped to.
79 uint64_t Imm; // Integer immediate value.
80 Record *Reg; // Physical register.
81 } Data;
82 int TiedOpIdx = -1; // Tied operand index within the instruction.
84 struct CompressPat {
85 CodeGenInstruction Source; // The source instruction definition.
86 CodeGenInstruction Dest; // The destination instruction to transform to.
87 std::vector<Record *>
88 PatReqFeatures; // Required target features to enable pattern.
89 IndexedMap<OpData>
90 SourceOperandMap; // Maps operands in the Source Instruction to
91 // the corresponding Dest instruction operand.
92 IndexedMap<OpData>
93 DestOperandMap; // Maps operands in the Dest Instruction
94 // to the corresponding Source instruction operand.
95 CompressPat(CodeGenInstruction &S, CodeGenInstruction &D,
96 std::vector<Record *> RF, IndexedMap<OpData> &SourceMap,
97 IndexedMap<OpData> &DestMap)
98 : Source(S), Dest(D), PatReqFeatures(RF), SourceOperandMap(SourceMap),
99 DestOperandMap(DestMap) {}
102 RecordKeeper &Records;
103 CodeGenTarget Target;
104 SmallVector<CompressPat, 4> CompressPatterns;
106 void addDagOperandMapping(Record *Rec, DagInit *Dag, CodeGenInstruction &Inst,
107 IndexedMap<OpData> &OperandMap, bool IsSourceInst);
108 void evaluateCompressPat(Record *Compress);
109 void emitCompressInstEmitter(raw_ostream &o, bool Compress);
110 bool validateTypes(Record *SubType, Record *Type, bool IsSourceInst);
111 bool validateRegister(Record *Reg, Record *RegClass);
112 void createDagOperandMapping(Record *Rec, StringMap<unsigned> &SourceOperands,
113 StringMap<unsigned> &DestOperands,
114 DagInit *SourceDag, DagInit *DestDag,
115 IndexedMap<OpData> &SourceOperandMap);
117 void createInstOperandMapping(Record *Rec, DagInit *SourceDag,
118 DagInit *DestDag,
119 IndexedMap<OpData> &SourceOperandMap,
120 IndexedMap<OpData> &DestOperandMap,
121 StringMap<unsigned> &SourceOperands,
122 CodeGenInstruction &DestInst);
124 public:
125 RISCVCompressInstEmitter(RecordKeeper &R) : Records(R), Target(R) {}
127 void run(raw_ostream &o);
129 } // End anonymous namespace.
131 bool RISCVCompressInstEmitter::validateRegister(Record *Reg, Record *RegClass) {
132 assert(Reg->isSubClassOf("Register") && "Reg record should be a Register\n");
133 assert(RegClass->isSubClassOf("RegisterClass") && "RegClass record should be"
134 " a RegisterClass\n");
135 CodeGenRegisterClass RC = Target.getRegisterClass(RegClass);
136 const CodeGenRegister *R = Target.getRegisterByName(Reg->getName().lower());
137 assert((R != nullptr) &&
138 ("Register" + Reg->getName().str() + " not defined!!\n").c_str());
139 return RC.contains(R);
142 bool RISCVCompressInstEmitter::validateTypes(Record *DagOpType,
143 Record *InstOpType,
144 bool IsSourceInst) {
145 if (DagOpType == InstOpType)
146 return true;
147 // Only source instruction operands are allowed to not match Input Dag
148 // operands.
149 if (!IsSourceInst)
150 return false;
152 if (DagOpType->isSubClassOf("RegisterClass") &&
153 InstOpType->isSubClassOf("RegisterClass")) {
154 CodeGenRegisterClass RC = Target.getRegisterClass(InstOpType);
155 CodeGenRegisterClass SubRC = Target.getRegisterClass(DagOpType);
156 return RC.hasSubClass(&SubRC);
159 // At this point either or both types are not registers, reject the pattern.
160 if (DagOpType->isSubClassOf("RegisterClass") ||
161 InstOpType->isSubClassOf("RegisterClass"))
162 return false;
164 // Let further validation happen when compress()/uncompress() functions are
165 // invoked.
166 LLVM_DEBUG(dbgs() << (IsSourceInst ? "Input" : "Output")
167 << " Dag Operand Type: '" << DagOpType->getName()
168 << "' and "
169 << "Instruction Operand Type: '" << InstOpType->getName()
170 << "' can't be checked at pattern validation time!\n");
171 return true;
174 /// The patterns in the Dag contain different types of operands:
175 /// Register operands, e.g.: GPRC:$rs1; Fixed registers, e.g: X1; Immediate
176 /// operands, e.g.: simm6:$imm; Fixed immediate operands, e.g.: 0. This function
177 /// maps Dag operands to its corresponding instruction operands. For register
178 /// operands and fixed registers it expects the Dag operand type to be contained
179 /// in the instantiated instruction operand type. For immediate operands and
180 /// immediates no validation checks are enforced at pattern validation time.
181 void RISCVCompressInstEmitter::addDagOperandMapping(
182 Record *Rec, DagInit *Dag, CodeGenInstruction &Inst,
183 IndexedMap<OpData> &OperandMap, bool IsSourceInst) {
184 // TiedCount keeps track of the number of operands skipped in Inst
185 // operands list to get to the corresponding Dag operand. This is
186 // necessary because the number of operands in Inst might be greater
187 // than number of operands in the Dag due to how tied operands
188 // are represented.
189 unsigned TiedCount = 0;
190 for (unsigned i = 0, e = Inst.Operands.size(); i != e; ++i) {
191 int TiedOpIdx = Inst.Operands[i].getTiedRegister();
192 if (-1 != TiedOpIdx) {
193 // Set the entry in OperandMap for the tied operand we're skipping.
194 OperandMap[i].Kind = OperandMap[TiedOpIdx].Kind;
195 OperandMap[i].Data = OperandMap[TiedOpIdx].Data;
196 TiedCount++;
197 continue;
199 if (DefInit *DI = dyn_cast<DefInit>(Dag->getArg(i - TiedCount))) {
200 if (DI->getDef()->isSubClassOf("Register")) {
201 // Check if the fixed register belongs to the Register class.
202 if (!validateRegister(DI->getDef(), Inst.Operands[i].Rec))
203 PrintFatalError(Rec->getLoc(),
204 "Error in Dag '" + Dag->getAsString() +
205 "'Register: '" + DI->getDef()->getName() +
206 "' is not in register class '" +
207 Inst.Operands[i].Rec->getName() + "'");
208 OperandMap[i].Kind = OpData::Reg;
209 OperandMap[i].Data.Reg = DI->getDef();
210 continue;
212 // Validate that Dag operand type matches the type defined in the
213 // corresponding instruction. Operands in the input Dag pattern are
214 // allowed to be a subclass of the type specified in corresponding
215 // instruction operand instead of being an exact match.
216 if (!validateTypes(DI->getDef(), Inst.Operands[i].Rec, IsSourceInst))
217 PrintFatalError(Rec->getLoc(),
218 "Error in Dag '" + Dag->getAsString() + "'. Operand '" +
219 Dag->getArgNameStr(i - TiedCount) + "' has type '" +
220 DI->getDef()->getName() +
221 "' which does not match the type '" +
222 Inst.Operands[i].Rec->getName() +
223 "' in the corresponding instruction operand!");
225 OperandMap[i].Kind = OpData::Operand;
226 } else if (IntInit *II = dyn_cast<IntInit>(Dag->getArg(i - TiedCount))) {
227 // Validate that corresponding instruction operand expects an immediate.
228 if (Inst.Operands[i].Rec->isSubClassOf("RegisterClass"))
229 PrintFatalError(
230 Rec->getLoc(),
231 ("Error in Dag '" + Dag->getAsString() + "' Found immediate: '" +
232 II->getAsString() +
233 "' but corresponding instruction operand expected a register!"));
234 // No pattern validation check possible for values of fixed immediate.
235 OperandMap[i].Kind = OpData::Imm;
236 OperandMap[i].Data.Imm = II->getValue();
237 LLVM_DEBUG(
238 dbgs() << " Found immediate '" << II->getValue() << "' at "
239 << (IsSourceInst ? "input " : "output ")
240 << "Dag. No validation time check possible for values of "
241 "fixed immediate.\n");
242 } else
243 llvm_unreachable("Unhandled CompressPat argument type!");
247 // Verify the Dag operand count is enough to build an instruction.
248 static bool verifyDagOpCount(CodeGenInstruction &Inst, DagInit *Dag,
249 bool IsSource) {
250 if (Dag->getNumArgs() == Inst.Operands.size())
251 return true;
252 // Source instructions are non compressed instructions and don't have tied
253 // operands.
254 if (IsSource)
255 PrintFatalError(Inst.TheDef->getLoc(),
256 "Input operands for Inst '" + Inst.TheDef->getName() +
257 "' and input Dag operand count mismatch");
258 // The Dag can't have more arguments than the Instruction.
259 if (Dag->getNumArgs() > Inst.Operands.size())
260 PrintFatalError(Inst.TheDef->getLoc(),
261 "Inst '" + Inst.TheDef->getName() +
262 "' and Dag operand count mismatch");
264 // The Instruction might have tied operands so the Dag might have
265 // a fewer operand count.
266 unsigned RealCount = Inst.Operands.size();
267 for (unsigned i = 0; i < Inst.Operands.size(); i++)
268 if (Inst.Operands[i].getTiedRegister() != -1)
269 --RealCount;
271 if (Dag->getNumArgs() != RealCount)
272 PrintFatalError(Inst.TheDef->getLoc(),
273 "Inst '" + Inst.TheDef->getName() +
274 "' and Dag operand count mismatch");
275 return true;
278 static bool validateArgsTypes(Init *Arg1, Init *Arg2) {
279 DefInit *Type1 = dyn_cast<DefInit>(Arg1);
280 DefInit *Type2 = dyn_cast<DefInit>(Arg2);
281 assert(Type1 && ("Arg1 type not found\n"));
282 assert(Type2 && ("Arg2 type not found\n"));
283 return Type1->getDef() == Type2->getDef();
286 // Creates a mapping between the operand name in the Dag (e.g. $rs1) and
287 // its index in the list of Dag operands and checks that operands with the same
288 // name have the same types. For example in 'C_ADD $rs1, $rs2' we generate the
289 // mapping $rs1 --> 0, $rs2 ---> 1. If the operand appears twice in the (tied)
290 // same Dag we use the last occurrence for indexing.
291 void RISCVCompressInstEmitter::createDagOperandMapping(
292 Record *Rec, StringMap<unsigned> &SourceOperands,
293 StringMap<unsigned> &DestOperands, DagInit *SourceDag, DagInit *DestDag,
294 IndexedMap<OpData> &SourceOperandMap) {
295 for (unsigned i = 0; i < DestDag->getNumArgs(); ++i) {
296 // Skip fixed immediates and registers, they were handled in
297 // addDagOperandMapping.
298 if ("" == DestDag->getArgNameStr(i))
299 continue;
300 DestOperands[DestDag->getArgNameStr(i)] = i;
303 for (unsigned i = 0; i < SourceDag->getNumArgs(); ++i) {
304 // Skip fixed immediates and registers, they were handled in
305 // addDagOperandMapping.
306 if ("" == SourceDag->getArgNameStr(i))
307 continue;
309 StringMap<unsigned>::iterator it =
310 SourceOperands.find(SourceDag->getArgNameStr(i));
311 if (it != SourceOperands.end()) {
312 // Operand sharing the same name in the Dag should be mapped as tied.
313 SourceOperandMap[i].TiedOpIdx = it->getValue();
314 if (!validateArgsTypes(SourceDag->getArg(it->getValue()),
315 SourceDag->getArg(i)))
316 PrintFatalError(Rec->getLoc(),
317 "Input Operand '" + SourceDag->getArgNameStr(i) +
318 "' has a mismatched tied operand!\n");
320 it = DestOperands.find(SourceDag->getArgNameStr(i));
321 if (it == DestOperands.end())
322 PrintFatalError(Rec->getLoc(), "Operand " + SourceDag->getArgNameStr(i) +
323 " defined in Input Dag but not used in"
324 " Output Dag!\n");
325 // Input Dag operand types must match output Dag operand type.
326 if (!validateArgsTypes(DestDag->getArg(it->getValue()),
327 SourceDag->getArg(i)))
328 PrintFatalError(Rec->getLoc(), "Type mismatch between Input and "
329 "Output Dag operand '" +
330 SourceDag->getArgNameStr(i) + "'!");
331 SourceOperands[SourceDag->getArgNameStr(i)] = i;
335 /// Map operand names in the Dag to their index in both corresponding input and
336 /// output instructions. Validate that operands defined in the input are
337 /// used in the output pattern while populating the maps.
338 void RISCVCompressInstEmitter::createInstOperandMapping(
339 Record *Rec, DagInit *SourceDag, DagInit *DestDag,
340 IndexedMap<OpData> &SourceOperandMap, IndexedMap<OpData> &DestOperandMap,
341 StringMap<unsigned> &SourceOperands, CodeGenInstruction &DestInst) {
342 // TiedCount keeps track of the number of operands skipped in Inst
343 // operands list to get to the corresponding Dag operand.
344 unsigned TiedCount = 0;
345 LLVM_DEBUG(dbgs() << " Operand mapping:\n Source Dest\n");
346 for (unsigned i = 0, e = DestInst.Operands.size(); i != e; ++i) {
347 int TiedInstOpIdx = DestInst.Operands[i].getTiedRegister();
348 if (TiedInstOpIdx != -1) {
349 ++TiedCount;
350 DestOperandMap[i].Data = DestOperandMap[TiedInstOpIdx].Data;
351 DestOperandMap[i].Kind = DestOperandMap[TiedInstOpIdx].Kind;
352 if (DestOperandMap[i].Kind == OpData::Operand)
353 // No need to fill the SourceOperandMap here since it was mapped to
354 // destination operand 'TiedInstOpIdx' in a previous iteration.
355 LLVM_DEBUG(dbgs() << " " << DestOperandMap[i].Data.Operand
356 << " ====> " << i
357 << " Dest operand tied with operand '"
358 << TiedInstOpIdx << "'\n");
359 continue;
361 // Skip fixed immediates and registers, they were handled in
362 // addDagOperandMapping.
363 if (DestOperandMap[i].Kind != OpData::Operand)
364 continue;
366 unsigned DagArgIdx = i - TiedCount;
367 StringMap<unsigned>::iterator SourceOp =
368 SourceOperands.find(DestDag->getArgNameStr(DagArgIdx));
369 if (SourceOp == SourceOperands.end())
370 PrintFatalError(Rec->getLoc(),
371 "Output Dag operand '" +
372 DestDag->getArgNameStr(DagArgIdx) +
373 "' has no matching input Dag operand.");
375 assert(DestDag->getArgNameStr(DagArgIdx) ==
376 SourceDag->getArgNameStr(SourceOp->getValue()) &&
377 "Incorrect operand mapping detected!\n");
378 DestOperandMap[i].Data.Operand = SourceOp->getValue();
379 SourceOperandMap[SourceOp->getValue()].Data.Operand = i;
380 LLVM_DEBUG(dbgs() << " " << SourceOp->getValue() << " ====> " << i
381 << "\n");
385 /// Validates the CompressPattern and create operand mapping.
386 /// These are the checks to validate a CompressPat pattern declarations.
387 /// Error out with message under these conditions:
388 /// - Dag Input opcode is an expanded instruction and Dag Output opcode is a
389 /// compressed instruction.
390 /// - Operands in Dag Input must be all used in Dag Output.
391 /// Register Operand type in Dag Input Type must be contained in the
392 /// corresponding Source Instruction type.
393 /// - Register Operand type in Dag Input must be the same as in Dag Ouput.
394 /// - Register Operand type in Dag Output must be the same as the
395 /// corresponding Destination Inst type.
396 /// - Immediate Operand type in Dag Input must be the same as in Dag Ouput.
397 /// - Immediate Operand type in Dag Ouput must be the same as the corresponding
398 /// Destination Instruction type.
399 /// - Fixed register must be contained in the corresponding Source Instruction
400 /// type.
401 /// - Fixed register must be contained in the corresponding Destination
402 /// Instruction type. Warning message printed under these conditions:
403 /// - Fixed immediate in Dag Input or Dag Ouput cannot be checked at this time
404 /// and generate warning.
405 /// - Immediate operand type in Dag Input differs from the corresponding Source
406 /// Instruction type and generate a warning.
407 void RISCVCompressInstEmitter::evaluateCompressPat(Record *Rec) {
408 // Validate input Dag operands.
409 DagInit *SourceDag = Rec->getValueAsDag("Input");
410 assert(SourceDag && "Missing 'Input' in compress pattern!");
411 LLVM_DEBUG(dbgs() << "Input: " << *SourceDag << "\n");
413 DefInit *OpDef = dyn_cast<DefInit>(SourceDag->getOperator());
414 if (!OpDef)
415 PrintFatalError(Rec->getLoc(),
416 Rec->getName() + " has unexpected operator type!");
417 // Checking we are transforming from compressed to uncompressed instructions.
418 Record *Operator = OpDef->getDef();
419 if (!Operator->isSubClassOf("RVInst"))
420 PrintFatalError(Rec->getLoc(), "Input instruction '" + Operator->getName() +
421 "' is not a 32 bit wide instruction!");
422 CodeGenInstruction SourceInst(Operator);
423 verifyDagOpCount(SourceInst, SourceDag, true);
425 // Validate output Dag operands.
426 DagInit *DestDag = Rec->getValueAsDag("Output");
427 assert(DestDag && "Missing 'Output' in compress pattern!");
428 LLVM_DEBUG(dbgs() << "Output: " << *DestDag << "\n");
430 DefInit *DestOpDef = dyn_cast<DefInit>(DestDag->getOperator());
431 if (!DestOpDef)
432 PrintFatalError(Rec->getLoc(),
433 Rec->getName() + " has unexpected operator type!");
435 Record *DestOperator = DestOpDef->getDef();
436 if (!DestOperator->isSubClassOf("RVInst16"))
437 PrintFatalError(Rec->getLoc(), "Output instruction '" +
438 DestOperator->getName() +
439 "' is not a 16 bit wide instruction!");
440 CodeGenInstruction DestInst(DestOperator);
441 verifyDagOpCount(DestInst, DestDag, false);
443 // Fill the mapping from the source to destination instructions.
445 IndexedMap<OpData> SourceOperandMap;
446 SourceOperandMap.grow(SourceInst.Operands.size());
447 // Create a mapping between source Dag operands and source Inst operands.
448 addDagOperandMapping(Rec, SourceDag, SourceInst, SourceOperandMap,
449 /*IsSourceInst*/ true);
451 IndexedMap<OpData> DestOperandMap;
452 DestOperandMap.grow(DestInst.Operands.size());
453 // Create a mapping between destination Dag operands and destination Inst
454 // operands.
455 addDagOperandMapping(Rec, DestDag, DestInst, DestOperandMap,
456 /*IsSourceInst*/ false);
458 StringMap<unsigned> SourceOperands;
459 StringMap<unsigned> DestOperands;
460 createDagOperandMapping(Rec, SourceOperands, DestOperands, SourceDag, DestDag,
461 SourceOperandMap);
462 // Create operand mapping between the source and destination instructions.
463 createInstOperandMapping(Rec, SourceDag, DestDag, SourceOperandMap,
464 DestOperandMap, SourceOperands, DestInst);
466 // Get the target features for the CompressPat.
467 std::vector<Record *> PatReqFeatures;
468 std::vector<Record *> RF = Rec->getValueAsListOfDefs("Predicates");
469 copy_if(RF, std::back_inserter(PatReqFeatures), [](Record *R) {
470 return R->getValueAsBit("AssemblerMatcherPredicate");
473 CompressPatterns.push_back(CompressPat(SourceInst, DestInst, PatReqFeatures,
474 SourceOperandMap, DestOperandMap));
477 static void getReqFeatures(std::map<StringRef, int> &FeaturesMap,
478 const std::vector<Record *> &ReqFeatures) {
479 for (auto &R : ReqFeatures) {
480 StringRef AsmCondString = R->getValueAsString("AssemblerCondString");
482 // AsmCondString has syntax [!]F(,[!]F)*
483 SmallVector<StringRef, 4> Ops;
484 SplitString(AsmCondString, Ops, ",");
485 assert(!Ops.empty() && "AssemblerCondString cannot be empty");
487 for (auto &Op : Ops) {
488 assert(!Op.empty() && "Empty operator");
489 if (FeaturesMap.find(Op) == FeaturesMap.end())
490 FeaturesMap[Op] = FeaturesMap.size();
495 unsigned getMCOpPredicate(DenseMap<const Record *, unsigned> &MCOpPredicateMap,
496 std::vector<const Record *> &MCOpPredicates,
497 Record *Rec) {
498 unsigned Entry = MCOpPredicateMap[Rec];
499 if (Entry)
500 return Entry;
502 if (!Rec->isValueUnset("MCOperandPredicate")) {
503 MCOpPredicates.push_back(Rec);
504 Entry = MCOpPredicates.size();
505 MCOpPredicateMap[Rec] = Entry;
506 return Entry;
509 PrintFatalError(Rec->getLoc(),
510 "No MCOperandPredicate on this operand at all: " +
511 Rec->getName().str() + "'");
512 return 0;
515 static std::string mergeCondAndCode(raw_string_ostream &CondStream,
516 raw_string_ostream &CodeStream) {
517 std::string S;
518 raw_string_ostream CombinedStream(S);
519 CombinedStream.indent(4)
520 << "if ("
521 << CondStream.str().substr(
522 6, CondStream.str().length() -
523 10) // remove first indentation and last '&&'.
524 << ") {\n";
525 CombinedStream << CodeStream.str();
526 CombinedStream.indent(4) << " return true;\n";
527 CombinedStream.indent(4) << "} // if\n";
528 return CombinedStream.str();
531 void RISCVCompressInstEmitter::emitCompressInstEmitter(raw_ostream &o,
532 bool Compress) {
533 Record *AsmWriter = Target.getAsmWriter();
534 if (!AsmWriter->getValueAsInt("PassSubtarget"))
535 PrintFatalError(AsmWriter->getLoc(),
536 "'PassSubtarget' is false. SubTargetInfo object is needed "
537 "for target features.\n");
539 std::string Namespace = Target.getName();
541 // Sort entries in CompressPatterns to handle instructions that can have more
542 // than one candidate for compression\uncompression, e.g ADD can be
543 // transformed to a C_ADD or a C_MV. When emitting 'uncompress()' function the
544 // source and destination are flipped and the sort key needs to change
545 // accordingly.
546 std::stable_sort(CompressPatterns.begin(), CompressPatterns.end(),
547 [Compress](const CompressPat &LHS, const CompressPat &RHS) {
548 if (Compress)
549 return (LHS.Source.TheDef->getName().str() <
550 RHS.Source.TheDef->getName().str());
551 else
552 return (LHS.Dest.TheDef->getName().str() <
553 RHS.Dest.TheDef->getName().str());
556 // A list of MCOperandPredicates for all operands in use, and the reverse map.
557 std::vector<const Record *> MCOpPredicates;
558 DenseMap<const Record *, unsigned> MCOpPredicateMap;
560 std::string F;
561 std::string FH;
562 raw_string_ostream Func(F);
563 raw_string_ostream FuncH(FH);
564 bool NeedMRI = false;
566 if (Compress)
567 o << "\n#ifdef GEN_COMPRESS_INSTR\n"
568 << "#undef GEN_COMPRESS_INSTR\n\n";
569 else
570 o << "\n#ifdef GEN_UNCOMPRESS_INSTR\n"
571 << "#undef GEN_UNCOMPRESS_INSTR\n\n";
573 if (Compress) {
574 FuncH << "static bool compressInst(MCInst& OutInst,\n";
575 FuncH.indent(25) << "const MCInst &MI,\n";
576 FuncH.indent(25) << "const MCSubtargetInfo &STI,\n";
577 FuncH.indent(25) << "MCContext &Context) {\n";
578 } else {
579 FuncH << "static bool uncompressInst(MCInst& OutInst,\n";
580 FuncH.indent(27) << "const MCInst &MI,\n";
581 FuncH.indent(27) << "const MCRegisterInfo &MRI,\n";
582 FuncH.indent(27) << "const MCSubtargetInfo &STI) {\n";
585 if (CompressPatterns.empty()) {
586 o << FuncH.str();
587 o.indent(2) << "return false;\n}\n";
588 if (Compress)
589 o << "\n#endif //GEN_COMPRESS_INSTR\n";
590 else
591 o << "\n#endif //GEN_UNCOMPRESS_INSTR\n\n";
592 return;
595 std::string CaseString("");
596 raw_string_ostream CaseStream(CaseString);
597 std::string PrevOp("");
598 std::string CurOp("");
599 CaseStream << " switch (MI.getOpcode()) {\n";
600 CaseStream << " default: return false;\n";
602 for (auto &CompressPat : CompressPatterns) {
603 std::string CondString;
604 std::string CodeString;
605 raw_string_ostream CondStream(CondString);
606 raw_string_ostream CodeStream(CodeString);
607 CodeGenInstruction &Source =
608 Compress ? CompressPat.Source : CompressPat.Dest;
609 CodeGenInstruction &Dest = Compress ? CompressPat.Dest : CompressPat.Source;
610 IndexedMap<OpData> SourceOperandMap =
611 Compress ? CompressPat.SourceOperandMap : CompressPat.DestOperandMap;
612 IndexedMap<OpData> &DestOperandMap =
613 Compress ? CompressPat.DestOperandMap : CompressPat.SourceOperandMap;
615 CurOp = Source.TheDef->getName().str();
616 // Check current and previous opcode to decide to continue or end a case.
617 if (CurOp != PrevOp) {
618 if (PrevOp != "")
619 CaseStream.indent(6) << "break;\n } // case " + PrevOp + "\n";
620 CaseStream.indent(4) << "case " + Namespace + "::" + CurOp + ": {\n";
623 std::map<StringRef, int> FeaturesMap;
624 // Add CompressPat required features.
625 getReqFeatures(FeaturesMap, CompressPat.PatReqFeatures);
627 // Add Dest instruction required features.
628 std::vector<Record *> ReqFeatures;
629 std::vector<Record *> RF = Dest.TheDef->getValueAsListOfDefs("Predicates");
630 copy_if(RF, std::back_inserter(ReqFeatures), [](Record *R) {
631 return R->getValueAsBit("AssemblerMatcherPredicate");
633 getReqFeatures(FeaturesMap, ReqFeatures);
635 // Emit checks for all required features.
636 for (auto &F : FeaturesMap) {
637 StringRef Op = F.first;
638 if (Op[0] == '!')
639 CondStream.indent(6) << ("!STI.getFeatureBits()[" + Namespace +
640 "::" + Op.substr(1) + "]")
641 .str() +
642 " &&\n";
643 else
644 CondStream.indent(6)
645 << ("STI.getFeatureBits()[" + Namespace + "::" + Op + "]").str() +
646 " &&\n";
649 // Start Source Inst operands validation.
650 unsigned OpNo = 0;
651 for (OpNo = 0; OpNo < Source.Operands.size(); ++OpNo) {
652 if (SourceOperandMap[OpNo].TiedOpIdx != -1) {
653 if (Source.Operands[OpNo].Rec->isSubClassOf("RegisterClass"))
654 CondStream.indent(6)
655 << "(MI.getOperand("
656 << std::to_string(OpNo) + ").getReg() == MI.getOperand("
657 << std::to_string(SourceOperandMap[OpNo].TiedOpIdx)
658 << ").getReg()) &&\n";
659 else
660 PrintFatalError("Unexpected tied operand types!\n");
662 // Check for fixed immediates\registers in the source instruction.
663 switch (SourceOperandMap[OpNo].Kind) {
664 case OpData::Operand:
665 // We don't need to do anything for source instruction operand checks.
666 break;
667 case OpData::Imm:
668 CondStream.indent(6)
669 << "(MI.getOperand(" + std::to_string(OpNo) + ").isImm()) &&\n" +
670 " (MI.getOperand(" + std::to_string(OpNo) +
671 ").getImm() == " +
672 std::to_string(SourceOperandMap[OpNo].Data.Imm) + ") &&\n";
673 break;
674 case OpData::Reg: {
675 Record *Reg = SourceOperandMap[OpNo].Data.Reg;
676 CondStream.indent(6) << "(MI.getOperand(" + std::to_string(OpNo) +
677 ").getReg() == " + Namespace +
678 "::" + Reg->getName().str() + ") &&\n";
679 break;
683 CodeStream.indent(6) << "// " + Dest.AsmString + "\n";
684 CodeStream.indent(6) << "OutInst.setOpcode(" + Namespace +
685 "::" + Dest.TheDef->getName().str() + ");\n";
686 OpNo = 0;
687 for (const auto &DestOperand : Dest.Operands) {
688 CodeStream.indent(6) << "// Operand: " + DestOperand.Name + "\n";
689 switch (DestOperandMap[OpNo].Kind) {
690 case OpData::Operand: {
691 unsigned OpIdx = DestOperandMap[OpNo].Data.Operand;
692 // Check that the operand in the Source instruction fits
693 // the type for the Dest instruction.
694 if (DestOperand.Rec->isSubClassOf("RegisterClass")) {
695 NeedMRI = true;
696 // This is a register operand. Check the register class.
697 // Don't check register class if this is a tied operand, it was done
698 // for the operand its tied to.
699 if (DestOperand.getTiedRegister() == -1)
700 CondStream.indent(6)
701 << "(MRI.getRegClass(" + Namespace +
702 "::" + DestOperand.Rec->getName().str() +
703 "RegClassID).contains(" + "MI.getOperand(" +
704 std::to_string(OpIdx) + ").getReg())) &&\n";
706 CodeStream.indent(6) << "OutInst.addOperand(MI.getOperand(" +
707 std::to_string(OpIdx) + "));\n";
708 } else {
709 // Handling immediate operands.
710 unsigned Entry = getMCOpPredicate(MCOpPredicateMap, MCOpPredicates,
711 DestOperand.Rec);
712 CondStream.indent(6) << Namespace + "ValidateMCOperand(" +
713 "MI.getOperand(" + std::to_string(OpIdx) +
714 "), STI, " + std::to_string(Entry) +
715 ") &&\n";
716 CodeStream.indent(6) << "OutInst.addOperand(MI.getOperand(" +
717 std::to_string(OpIdx) + "));\n";
719 break;
721 case OpData::Imm: {
722 unsigned Entry =
723 getMCOpPredicate(MCOpPredicateMap, MCOpPredicates, DestOperand.Rec);
724 CondStream.indent(6)
725 << Namespace + "ValidateMCOperand(" + "MCOperand::createImm(" +
726 std::to_string(DestOperandMap[OpNo].Data.Imm) + "), STI, " +
727 std::to_string(Entry) + ") &&\n";
728 CodeStream.indent(6)
729 << "OutInst.addOperand(MCOperand::createImm(" +
730 std::to_string(DestOperandMap[OpNo].Data.Imm) + "));\n";
731 } break;
732 case OpData::Reg: {
733 // Fixed register has been validated at pattern validation time.
734 Record *Reg = DestOperandMap[OpNo].Data.Reg;
735 CodeStream.indent(6) << "OutInst.addOperand(MCOperand::createReg(" +
736 Namespace + "::" + Reg->getName().str() +
737 "));\n";
738 } break;
740 ++OpNo;
742 CaseStream << mergeCondAndCode(CondStream, CodeStream);
743 PrevOp = CurOp;
745 Func << CaseStream.str() << "\n";
746 // Close brace for the last case.
747 Func.indent(4) << "} // case " + CurOp + "\n";
748 Func.indent(2) << "} // switch\n";
749 Func.indent(2) << "return false;\n}\n";
751 if (!MCOpPredicates.empty()) {
752 o << "static bool " << Namespace
753 << "ValidateMCOperand(const MCOperand &MCOp,\n"
754 << " const MCSubtargetInfo &STI,\n"
755 << " unsigned PredicateIndex) {\n"
756 << " switch (PredicateIndex) {\n"
757 << " default:\n"
758 << " llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n"
759 << " break;\n";
761 for (unsigned i = 0; i < MCOpPredicates.size(); ++i) {
762 Init *MCOpPred = MCOpPredicates[i]->getValueInit("MCOperandPredicate");
763 if (CodeInit *SI = dyn_cast<CodeInit>(MCOpPred))
764 o << " case " << i + 1 << ": {\n"
765 << " // " << MCOpPredicates[i]->getName().str() << SI->getValue()
766 << "\n"
767 << " }\n";
768 else
769 llvm_unreachable("Unexpected MCOperandPredicate field!");
771 o << " }\n"
772 << "}\n\n";
775 o << FuncH.str();
776 if (NeedMRI && Compress)
777 o.indent(2) << "const MCRegisterInfo &MRI = *Context.getRegisterInfo();\n";
778 o << Func.str();
780 if (Compress)
781 o << "\n#endif //GEN_COMPRESS_INSTR\n";
782 else
783 o << "\n#endif //GEN_UNCOMPRESS_INSTR\n\n";
786 void RISCVCompressInstEmitter::run(raw_ostream &o) {
787 Record *CompressClass = Records.getClass("CompressPat");
788 assert(CompressClass && "Compress class definition missing!");
789 std::vector<Record *> Insts;
790 for (const auto &D : Records.getDefs()) {
791 if (D.second->isSubClassOf(CompressClass))
792 Insts.push_back(D.second.get());
795 // Process the CompressPat definitions, validating them as we do so.
796 for (unsigned i = 0, e = Insts.size(); i != e; ++i)
797 evaluateCompressPat(Insts[i]);
799 // Emit file header.
800 emitSourceFileHeader("Compress instruction Source Fragment", o);
801 // Generate compressInst() function.
802 emitCompressInstEmitter(o, true);
803 // Generate uncompressInst() function.
804 emitCompressInstEmitter(o, false);
807 namespace llvm {
809 void EmitCompressInst(RecordKeeper &RK, raw_ostream &OS) {
810 RISCVCompressInstEmitter(RK).run(OS);
813 } // namespace llvm