[llvm-objcopy] [COFF] Clear the unwritten tail of coff_section::Header::Name
[llvm-complete.git] / utils / TableGen / RISCVCompressInstEmitter.cpp
blob87c825b3422f12eabbe3a6f55b6803c933db5102
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("Input operands for Inst '" + Inst.TheDef->getName() +
256 "' and input Dag operand count mismatch");
257 // The Dag can't have more arguments than the Instruction.
258 if (Dag->getNumArgs() > Inst.Operands.size())
259 PrintFatalError("Inst '" + Inst.TheDef->getName() +
260 "' and Dag operand count mismatch");
262 // The Instruction might have tied operands so the Dag might have
263 // a fewer operand count.
264 unsigned RealCount = Inst.Operands.size();
265 for (unsigned i = 0; i < Inst.Operands.size(); i++)
266 if (Inst.Operands[i].getTiedRegister() != -1)
267 --RealCount;
269 if (Dag->getNumArgs() != RealCount)
270 PrintFatalError("Inst '" + Inst.TheDef->getName() +
271 "' and Dag operand count mismatch");
272 return true;
275 static bool validateArgsTypes(Init *Arg1, Init *Arg2) {
276 DefInit *Type1 = dyn_cast<DefInit>(Arg1);
277 DefInit *Type2 = dyn_cast<DefInit>(Arg2);
278 assert(Type1 && ("Arg1 type not found\n"));
279 assert(Type2 && ("Arg2 type not found\n"));
280 return Type1->getDef() == Type2->getDef();
283 // Creates a mapping between the operand name in the Dag (e.g. $rs1) and
284 // its index in the list of Dag operands and checks that operands with the same
285 // name have the same types. For example in 'C_ADD $rs1, $rs2' we generate the
286 // mapping $rs1 --> 0, $rs2 ---> 1. If the operand appears twice in the (tied)
287 // same Dag we use the last occurrence for indexing.
288 void RISCVCompressInstEmitter::createDagOperandMapping(
289 Record *Rec, StringMap<unsigned> &SourceOperands,
290 StringMap<unsigned> &DestOperands, DagInit *SourceDag, DagInit *DestDag,
291 IndexedMap<OpData> &SourceOperandMap) {
292 for (unsigned i = 0; i < DestDag->getNumArgs(); ++i) {
293 // Skip fixed immediates and registers, they were handled in
294 // addDagOperandMapping.
295 if ("" == DestDag->getArgNameStr(i))
296 continue;
297 DestOperands[DestDag->getArgNameStr(i)] = i;
300 for (unsigned i = 0; i < SourceDag->getNumArgs(); ++i) {
301 // Skip fixed immediates and registers, they were handled in
302 // addDagOperandMapping.
303 if ("" == SourceDag->getArgNameStr(i))
304 continue;
306 StringMap<unsigned>::iterator it =
307 SourceOperands.find(SourceDag->getArgNameStr(i));
308 if (it != SourceOperands.end()) {
309 // Operand sharing the same name in the Dag should be mapped as tied.
310 SourceOperandMap[i].TiedOpIdx = it->getValue();
311 if (!validateArgsTypes(SourceDag->getArg(it->getValue()),
312 SourceDag->getArg(i)))
313 PrintFatalError(Rec->getLoc(),
314 "Input Operand '" + SourceDag->getArgNameStr(i) +
315 "' has a mismatched tied operand!\n");
317 it = DestOperands.find(SourceDag->getArgNameStr(i));
318 if (it == DestOperands.end())
319 PrintFatalError(Rec->getLoc(), "Operand " + SourceDag->getArgNameStr(i) +
320 " defined in Input Dag but not used in"
321 " Output Dag!\n");
322 // Input Dag operand types must match output Dag operand type.
323 if (!validateArgsTypes(DestDag->getArg(it->getValue()),
324 SourceDag->getArg(i)))
325 PrintFatalError(Rec->getLoc(), "Type mismatch between Input and "
326 "Output Dag operand '" +
327 SourceDag->getArgNameStr(i) + "'!");
328 SourceOperands[SourceDag->getArgNameStr(i)] = i;
332 /// Map operand names in the Dag to their index in both corresponding input and
333 /// output instructions. Validate that operands defined in the input are
334 /// used in the output pattern while populating the maps.
335 void RISCVCompressInstEmitter::createInstOperandMapping(
336 Record *Rec, DagInit *SourceDag, DagInit *DestDag,
337 IndexedMap<OpData> &SourceOperandMap, IndexedMap<OpData> &DestOperandMap,
338 StringMap<unsigned> &SourceOperands, CodeGenInstruction &DestInst) {
339 // TiedCount keeps track of the number of operands skipped in Inst
340 // operands list to get to the corresponding Dag operand.
341 unsigned TiedCount = 0;
342 LLVM_DEBUG(dbgs() << " Operand mapping:\n Source Dest\n");
343 for (unsigned i = 0, e = DestInst.Operands.size(); i != e; ++i) {
344 int TiedInstOpIdx = DestInst.Operands[i].getTiedRegister();
345 if (TiedInstOpIdx != -1) {
346 ++TiedCount;
347 DestOperandMap[i].Data = DestOperandMap[TiedInstOpIdx].Data;
348 DestOperandMap[i].Kind = DestOperandMap[TiedInstOpIdx].Kind;
349 if (DestOperandMap[i].Kind == OpData::Operand)
350 // No need to fill the SourceOperandMap here since it was mapped to
351 // destination operand 'TiedInstOpIdx' in a previous iteration.
352 LLVM_DEBUG(dbgs() << " " << DestOperandMap[i].Data.Operand
353 << " ====> " << i
354 << " Dest operand tied with operand '"
355 << TiedInstOpIdx << "'\n");
356 continue;
358 // Skip fixed immediates and registers, they were handled in
359 // addDagOperandMapping.
360 if (DestOperandMap[i].Kind != OpData::Operand)
361 continue;
363 unsigned DagArgIdx = i - TiedCount;
364 StringMap<unsigned>::iterator SourceOp =
365 SourceOperands.find(DestDag->getArgNameStr(DagArgIdx));
366 if (SourceOp == SourceOperands.end())
367 PrintFatalError(Rec->getLoc(),
368 "Output Dag operand '" +
369 DestDag->getArgNameStr(DagArgIdx) +
370 "' has no matching input Dag operand.");
372 assert(DestDag->getArgNameStr(DagArgIdx) ==
373 SourceDag->getArgNameStr(SourceOp->getValue()) &&
374 "Incorrect operand mapping detected!\n");
375 DestOperandMap[i].Data.Operand = SourceOp->getValue();
376 SourceOperandMap[SourceOp->getValue()].Data.Operand = i;
377 LLVM_DEBUG(dbgs() << " " << SourceOp->getValue() << " ====> " << i
378 << "\n");
382 /// Validates the CompressPattern and create operand mapping.
383 /// These are the checks to validate a CompressPat pattern declarations.
384 /// Error out with message under these conditions:
385 /// - Dag Input opcode is an expanded instruction and Dag Output opcode is a
386 /// compressed instruction.
387 /// - Operands in Dag Input must be all used in Dag Output.
388 /// Register Operand type in Dag Input Type must be contained in the
389 /// corresponding Source Instruction type.
390 /// - Register Operand type in Dag Input must be the same as in Dag Ouput.
391 /// - Register Operand type in Dag Output must be the same as the
392 /// corresponding Destination Inst type.
393 /// - Immediate Operand type in Dag Input must be the same as in Dag Ouput.
394 /// - Immediate Operand type in Dag Ouput must be the same as the corresponding
395 /// Destination Instruction type.
396 /// - Fixed register must be contained in the corresponding Source Instruction
397 /// type.
398 /// - Fixed register must be contained in the corresponding Destination
399 /// Instruction type. Warning message printed under these conditions:
400 /// - Fixed immediate in Dag Input or Dag Ouput cannot be checked at this time
401 /// and generate warning.
402 /// - Immediate operand type in Dag Input differs from the corresponding Source
403 /// Instruction type and generate a warning.
404 void RISCVCompressInstEmitter::evaluateCompressPat(Record *Rec) {
405 // Validate input Dag operands.
406 DagInit *SourceDag = Rec->getValueAsDag("Input");
407 assert(SourceDag && "Missing 'Input' in compress pattern!");
408 LLVM_DEBUG(dbgs() << "Input: " << *SourceDag << "\n");
410 DefInit *OpDef = dyn_cast<DefInit>(SourceDag->getOperator());
411 if (!OpDef)
412 PrintFatalError(Rec->getLoc(),
413 Rec->getName() + " has unexpected operator type!");
414 // Checking we are transforming from compressed to uncompressed instructions.
415 Record *Operator = OpDef->getDef();
416 if (!Operator->isSubClassOf("RVInst"))
417 PrintFatalError(Rec->getLoc(), "Input instruction '" + Operator->getName() +
418 "' is not a 32 bit wide instruction!");
419 CodeGenInstruction SourceInst(Operator);
420 verifyDagOpCount(SourceInst, SourceDag, true);
422 // Validate output Dag operands.
423 DagInit *DestDag = Rec->getValueAsDag("Output");
424 assert(DestDag && "Missing 'Output' in compress pattern!");
425 LLVM_DEBUG(dbgs() << "Output: " << *DestDag << "\n");
427 DefInit *DestOpDef = dyn_cast<DefInit>(DestDag->getOperator());
428 if (!DestOpDef)
429 PrintFatalError(Rec->getLoc(),
430 Rec->getName() + " has unexpected operator type!");
432 Record *DestOperator = DestOpDef->getDef();
433 if (!DestOperator->isSubClassOf("RVInst16"))
434 PrintFatalError(Rec->getLoc(), "Output instruction '" +
435 DestOperator->getName() +
436 "' is not a 16 bit wide instruction!");
437 CodeGenInstruction DestInst(DestOperator);
438 verifyDagOpCount(DestInst, DestDag, false);
440 // Fill the mapping from the source to destination instructions.
442 IndexedMap<OpData> SourceOperandMap;
443 SourceOperandMap.grow(SourceInst.Operands.size());
444 // Create a mapping between source Dag operands and source Inst operands.
445 addDagOperandMapping(Rec, SourceDag, SourceInst, SourceOperandMap,
446 /*IsSourceInst*/ true);
448 IndexedMap<OpData> DestOperandMap;
449 DestOperandMap.grow(DestInst.Operands.size());
450 // Create a mapping between destination Dag operands and destination Inst
451 // operands.
452 addDagOperandMapping(Rec, DestDag, DestInst, DestOperandMap,
453 /*IsSourceInst*/ false);
455 StringMap<unsigned> SourceOperands;
456 StringMap<unsigned> DestOperands;
457 createDagOperandMapping(Rec, SourceOperands, DestOperands, SourceDag, DestDag,
458 SourceOperandMap);
459 // Create operand mapping between the source and destination instructions.
460 createInstOperandMapping(Rec, SourceDag, DestDag, SourceOperandMap,
461 DestOperandMap, SourceOperands, DestInst);
463 // Get the target features for the CompressPat.
464 std::vector<Record *> PatReqFeatures;
465 std::vector<Record *> RF = Rec->getValueAsListOfDefs("Predicates");
466 copy_if(RF, std::back_inserter(PatReqFeatures), [](Record *R) {
467 return R->getValueAsBit("AssemblerMatcherPredicate");
470 CompressPatterns.push_back(CompressPat(SourceInst, DestInst, PatReqFeatures,
471 SourceOperandMap, DestOperandMap));
474 static void getReqFeatures(std::map<StringRef, int> &FeaturesMap,
475 const std::vector<Record *> &ReqFeatures) {
476 for (auto &R : ReqFeatures) {
477 StringRef AsmCondString = R->getValueAsString("AssemblerCondString");
479 // AsmCondString has syntax [!]F(,[!]F)*
480 SmallVector<StringRef, 4> Ops;
481 SplitString(AsmCondString, Ops, ",");
482 assert(!Ops.empty() && "AssemblerCondString cannot be empty");
484 for (auto &Op : Ops) {
485 assert(!Op.empty() && "Empty operator");
486 if (FeaturesMap.find(Op) == FeaturesMap.end())
487 FeaturesMap[Op] = FeaturesMap.size();
492 unsigned getMCOpPredicate(DenseMap<const Record *, unsigned> &MCOpPredicateMap,
493 std::vector<const Record *> &MCOpPredicates,
494 Record *Rec) {
495 unsigned Entry = MCOpPredicateMap[Rec];
496 if (Entry)
497 return Entry;
499 if (!Rec->isValueUnset("MCOperandPredicate")) {
500 MCOpPredicates.push_back(Rec);
501 Entry = MCOpPredicates.size();
502 MCOpPredicateMap[Rec] = Entry;
503 return Entry;
506 PrintFatalError(Rec->getLoc(),
507 "No MCOperandPredicate on this operand at all: " +
508 Rec->getName().str() + "'");
509 return 0;
512 static std::string mergeCondAndCode(raw_string_ostream &CondStream,
513 raw_string_ostream &CodeStream) {
514 std::string S;
515 raw_string_ostream CombinedStream(S);
516 CombinedStream.indent(4)
517 << "if ("
518 << CondStream.str().substr(
519 6, CondStream.str().length() -
520 10) // remove first indentation and last '&&'.
521 << ") {\n";
522 CombinedStream << CodeStream.str();
523 CombinedStream.indent(4) << " return true;\n";
524 CombinedStream.indent(4) << "} // if\n";
525 return CombinedStream.str();
528 void RISCVCompressInstEmitter::emitCompressInstEmitter(raw_ostream &o,
529 bool Compress) {
530 Record *AsmWriter = Target.getAsmWriter();
531 if (!AsmWriter->getValueAsInt("PassSubtarget"))
532 PrintFatalError("'PassSubtarget' is false. SubTargetInfo object is needed "
533 "for target features.\n");
535 std::string Namespace = Target.getName();
537 // Sort entries in CompressPatterns to handle instructions that can have more
538 // than one candidate for compression\uncompression, e.g ADD can be
539 // transformed to a C_ADD or a C_MV. When emitting 'uncompress()' function the
540 // source and destination are flipped and the sort key needs to change
541 // accordingly.
542 std::stable_sort(CompressPatterns.begin(), CompressPatterns.end(),
543 [Compress](const CompressPat &LHS, const CompressPat &RHS) {
544 if (Compress)
545 return (LHS.Source.TheDef->getName().str() <
546 RHS.Source.TheDef->getName().str());
547 else
548 return (LHS.Dest.TheDef->getName().str() <
549 RHS.Dest.TheDef->getName().str());
552 // A list of MCOperandPredicates for all operands in use, and the reverse map.
553 std::vector<const Record *> MCOpPredicates;
554 DenseMap<const Record *, unsigned> MCOpPredicateMap;
556 std::string F;
557 std::string FH;
558 raw_string_ostream Func(F);
559 raw_string_ostream FuncH(FH);
560 bool NeedMRI = false;
562 if (Compress)
563 o << "\n#ifdef GEN_COMPRESS_INSTR\n"
564 << "#undef GEN_COMPRESS_INSTR\n\n";
565 else
566 o << "\n#ifdef GEN_UNCOMPRESS_INSTR\n"
567 << "#undef GEN_UNCOMPRESS_INSTR\n\n";
569 if (Compress) {
570 FuncH << "static bool compressInst(MCInst& OutInst,\n";
571 FuncH.indent(25) << "const MCInst &MI,\n";
572 FuncH.indent(25) << "const MCSubtargetInfo &STI,\n";
573 FuncH.indent(25) << "MCContext &Context) {\n";
574 } else {
575 FuncH << "static bool uncompressInst(MCInst& OutInst,\n";
576 FuncH.indent(27) << "const MCInst &MI,\n";
577 FuncH.indent(27) << "const MCRegisterInfo &MRI,\n";
578 FuncH.indent(27) << "const MCSubtargetInfo &STI) {\n";
581 if (CompressPatterns.empty()) {
582 o << FuncH.str();
583 o.indent(2) << "return false;\n}\n";
584 if (Compress)
585 o << "\n#endif //GEN_COMPRESS_INSTR\n";
586 else
587 o << "\n#endif //GEN_UNCOMPRESS_INSTR\n\n";
588 return;
591 std::string CaseString("");
592 raw_string_ostream CaseStream(CaseString);
593 std::string PrevOp("");
594 std::string CurOp("");
595 CaseStream << " switch (MI.getOpcode()) {\n";
596 CaseStream << " default: return false;\n";
598 for (auto &CompressPat : CompressPatterns) {
599 std::string CondString;
600 std::string CodeString;
601 raw_string_ostream CondStream(CondString);
602 raw_string_ostream CodeStream(CodeString);
603 CodeGenInstruction &Source =
604 Compress ? CompressPat.Source : CompressPat.Dest;
605 CodeGenInstruction &Dest = Compress ? CompressPat.Dest : CompressPat.Source;
606 IndexedMap<OpData> SourceOperandMap =
607 Compress ? CompressPat.SourceOperandMap : CompressPat.DestOperandMap;
608 IndexedMap<OpData> &DestOperandMap =
609 Compress ? CompressPat.DestOperandMap : CompressPat.SourceOperandMap;
611 CurOp = Source.TheDef->getName().str();
612 // Check current and previous opcode to decide to continue or end a case.
613 if (CurOp != PrevOp) {
614 if (PrevOp != "")
615 CaseStream.indent(6) << "break;\n } // case " + PrevOp + "\n";
616 CaseStream.indent(4) << "case " + Namespace + "::" + CurOp + ": {\n";
619 std::map<StringRef, int> FeaturesMap;
620 // Add CompressPat required features.
621 getReqFeatures(FeaturesMap, CompressPat.PatReqFeatures);
623 // Add Dest instruction required features.
624 std::vector<Record *> ReqFeatures;
625 std::vector<Record *> RF = Dest.TheDef->getValueAsListOfDefs("Predicates");
626 copy_if(RF, std::back_inserter(ReqFeatures), [](Record *R) {
627 return R->getValueAsBit("AssemblerMatcherPredicate");
629 getReqFeatures(FeaturesMap, ReqFeatures);
631 // Emit checks for all required features.
632 for (auto &F : FeaturesMap) {
633 StringRef Op = F.first;
634 if (Op[0] == '!')
635 CondStream.indent(6) << ("!STI.getFeatureBits()[" + Namespace +
636 "::" + Op.substr(1) + "]")
637 .str() +
638 " &&\n";
639 else
640 CondStream.indent(6)
641 << ("STI.getFeatureBits()[" + Namespace + "::" + Op + "]").str() +
642 " &&\n";
645 // Start Source Inst operands validation.
646 unsigned OpNo = 0;
647 for (OpNo = 0; OpNo < Source.Operands.size(); ++OpNo) {
648 if (SourceOperandMap[OpNo].TiedOpIdx != -1) {
649 if (Source.Operands[OpNo].Rec->isSubClassOf("RegisterClass"))
650 CondStream.indent(6)
651 << "(MI.getOperand("
652 << std::to_string(OpNo) + ").getReg() == MI.getOperand("
653 << std::to_string(SourceOperandMap[OpNo].TiedOpIdx)
654 << ").getReg()) &&\n";
655 else
656 PrintFatalError("Unexpected tied operand types!\n");
658 // Check for fixed immediates\registers in the source instruction.
659 switch (SourceOperandMap[OpNo].Kind) {
660 case OpData::Operand:
661 // We don't need to do anything for source instruction operand checks.
662 break;
663 case OpData::Imm:
664 CondStream.indent(6)
665 << "(MI.getOperand(" + std::to_string(OpNo) + ").isImm()) &&\n" +
666 " (MI.getOperand(" + std::to_string(OpNo) +
667 ").getImm() == " +
668 std::to_string(SourceOperandMap[OpNo].Data.Imm) + ") &&\n";
669 break;
670 case OpData::Reg: {
671 Record *Reg = SourceOperandMap[OpNo].Data.Reg;
672 CondStream.indent(6) << "(MI.getOperand(" + std::to_string(OpNo) +
673 ").getReg() == " + Namespace +
674 "::" + Reg->getName().str() + ") &&\n";
675 break;
679 CodeStream.indent(6) << "// " + Dest.AsmString + "\n";
680 CodeStream.indent(6) << "OutInst.setOpcode(" + Namespace +
681 "::" + Dest.TheDef->getName().str() + ");\n";
682 OpNo = 0;
683 for (const auto &DestOperand : Dest.Operands) {
684 CodeStream.indent(6) << "// Operand: " + DestOperand.Name + "\n";
685 switch (DestOperandMap[OpNo].Kind) {
686 case OpData::Operand: {
687 unsigned OpIdx = DestOperandMap[OpNo].Data.Operand;
688 // Check that the operand in the Source instruction fits
689 // the type for the Dest instruction.
690 if (DestOperand.Rec->isSubClassOf("RegisterClass")) {
691 NeedMRI = true;
692 // This is a register operand. Check the register class.
693 // Don't check register class if this is a tied operand, it was done
694 // for the operand its tied to.
695 if (DestOperand.getTiedRegister() == -1)
696 CondStream.indent(6)
697 << "(MRI.getRegClass(" + Namespace +
698 "::" + DestOperand.Rec->getName().str() +
699 "RegClassID).contains(" + "MI.getOperand(" +
700 std::to_string(OpIdx) + ").getReg())) &&\n";
702 CodeStream.indent(6) << "OutInst.addOperand(MI.getOperand(" +
703 std::to_string(OpIdx) + "));\n";
704 } else {
705 // Handling immediate operands.
706 unsigned Entry = getMCOpPredicate(MCOpPredicateMap, MCOpPredicates,
707 DestOperand.Rec);
708 CondStream.indent(6) << Namespace + "ValidateMCOperand(" +
709 "MI.getOperand(" + std::to_string(OpIdx) +
710 "), STI, " + std::to_string(Entry) +
711 ") &&\n";
712 CodeStream.indent(6) << "OutInst.addOperand(MI.getOperand(" +
713 std::to_string(OpIdx) + "));\n";
715 break;
717 case OpData::Imm: {
718 unsigned Entry =
719 getMCOpPredicate(MCOpPredicateMap, MCOpPredicates, DestOperand.Rec);
720 CondStream.indent(6)
721 << Namespace + "ValidateMCOperand(" + "MCOperand::createImm(" +
722 std::to_string(DestOperandMap[OpNo].Data.Imm) + "), STI, " +
723 std::to_string(Entry) + ") &&\n";
724 CodeStream.indent(6)
725 << "OutInst.addOperand(MCOperand::createImm(" +
726 std::to_string(DestOperandMap[OpNo].Data.Imm) + "));\n";
727 } break;
728 case OpData::Reg: {
729 // Fixed register has been validated at pattern validation time.
730 Record *Reg = DestOperandMap[OpNo].Data.Reg;
731 CodeStream.indent(6) << "OutInst.addOperand(MCOperand::createReg(" +
732 Namespace + "::" + Reg->getName().str() +
733 "));\n";
734 } break;
736 ++OpNo;
738 CaseStream << mergeCondAndCode(CondStream, CodeStream);
739 PrevOp = CurOp;
741 Func << CaseStream.str() << "\n";
742 // Close brace for the last case.
743 Func.indent(4) << "} // case " + CurOp + "\n";
744 Func.indent(2) << "} // switch\n";
745 Func.indent(2) << "return false;\n}\n";
747 if (!MCOpPredicates.empty()) {
748 o << "static bool " << Namespace
749 << "ValidateMCOperand(const MCOperand &MCOp,\n"
750 << " const MCSubtargetInfo &STI,\n"
751 << " unsigned PredicateIndex) {\n"
752 << " switch (PredicateIndex) {\n"
753 << " default:\n"
754 << " llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n"
755 << " break;\n";
757 for (unsigned i = 0; i < MCOpPredicates.size(); ++i) {
758 Init *MCOpPred = MCOpPredicates[i]->getValueInit("MCOperandPredicate");
759 if (CodeInit *SI = dyn_cast<CodeInit>(MCOpPred))
760 o << " case " << i + 1 << ": {\n"
761 << " // " << MCOpPredicates[i]->getName().str() << SI->getValue()
762 << "\n"
763 << " }\n";
764 else
765 llvm_unreachable("Unexpected MCOperandPredicate field!");
767 o << " }\n"
768 << "}\n\n";
771 o << FuncH.str();
772 if (NeedMRI && Compress)
773 o.indent(2) << "const MCRegisterInfo &MRI = *Context.getRegisterInfo();\n";
774 o << Func.str();
776 if (Compress)
777 o << "\n#endif //GEN_COMPRESS_INSTR\n";
778 else
779 o << "\n#endif //GEN_UNCOMPRESS_INSTR\n\n";
782 void RISCVCompressInstEmitter::run(raw_ostream &o) {
783 Record *CompressClass = Records.getClass("CompressPat");
784 assert(CompressClass && "Compress class definition missing!");
785 std::vector<Record *> Insts;
786 for (const auto &D : Records.getDefs()) {
787 if (D.second->isSubClassOf(CompressClass))
788 Insts.push_back(D.second.get());
791 // Process the CompressPat definitions, validating them as we do so.
792 for (unsigned i = 0, e = Insts.size(); i != e; ++i)
793 evaluateCompressPat(Insts[i]);
795 // Emit file header.
796 emitSourceFileHeader("Compress instruction Source Fragment", o);
797 // Generate compressInst() function.
798 emitCompressInstEmitter(o, true);
799 // Generate uncompressInst() function.
800 emitCompressInstEmitter(o, false);
803 namespace llvm {
805 void EmitCompressInst(RecordKeeper &RK, raw_ostream &OS) {
806 RISCVCompressInstEmitter(RK).run(OS);
809 } // namespace llvm