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