1 //===- CodeGenMapTable.cpp - Instruction Mapping Table Generator ----------===//
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
7 //===----------------------------------------------------------------------===//
8 // CodeGenMapTable provides functionality for the TableGen to create
9 // relation mapping between instructions. Relation models are defined using
10 // InstrMapping as a base class. This file implements the functionality which
11 // parses these definitions and generates relation maps using the information
12 // specified there. These maps are emitted as tables in the XXXGenInstrInfo.inc
13 // file along with the functions to query them.
15 // A relationship model to relate non-predicate instructions with their
16 // predicated true/false forms can be defined as follows:
18 // def getPredOpcode : InstrMapping {
19 // let FilterClass = "PredRel";
20 // let RowFields = ["BaseOpcode"];
21 // let ColFields = ["PredSense"];
22 // let KeyCol = ["none"];
23 // let ValueCols = [["true"], ["false"]]; }
25 // CodeGenMapTable parses this map and generates a table in XXXGenInstrInfo.inc
26 // file that contains the instructions modeling this relationship. This table
27 // is defined in the function
28 // "int getPredOpcode(uint16_t Opcode, enum PredSense inPredSense)"
29 // that can be used to retrieve the predicated form of the instruction by
30 // passing its opcode value and the predicate sense (true/false) of the desired
31 // instruction as arguments.
33 // Short description of the algorithm:
35 // 1) Iterate through all the records that derive from "InstrMapping" class.
36 // 2) For each record, filter out instructions based on the FilterClass value.
37 // 3) Iterate through this set of instructions and insert them into
38 // RowInstrMap map based on their RowFields values. RowInstrMap is keyed by the
39 // vector of RowFields values and contains vectors of Records (instructions) as
40 // values. RowFields is a list of fields that are required to have the same
41 // values for all the instructions appearing in the same row of the relation
42 // table. All the instructions in a given row of the relation table have some
43 // sort of relationship with the key instruction defined by the corresponding
44 // relationship model.
46 // Ex: RowInstrMap(RowVal1, RowVal2, ...) -> [Instr1, Instr2, Instr3, ... ]
47 // Here Instr1, Instr2, Instr3 have same values (RowVal1, RowVal2) for
48 // RowFields. These groups of instructions are later matched against ValueCols
49 // to determine the column they belong to, if any.
51 // While building the RowInstrMap map, collect all the key instructions in
52 // KeyInstrVec. These are the instructions having the same values as KeyCol
53 // for all the fields listed in ColFields.
57 // Relate non-predicate instructions with their predicated true/false forms.
59 // def getPredOpcode : InstrMapping {
60 // let FilterClass = "PredRel";
61 // let RowFields = ["BaseOpcode"];
62 // let ColFields = ["PredSense"];
63 // let KeyCol = ["none"];
64 // let ValueCols = [["true"], ["false"]]; }
66 // Here, only instructions that have "none" as PredSense will be selected as key
69 // 4) For each key instruction, get the group of instructions that share the
70 // same key-value as the key instruction from RowInstrMap. Iterate over the list
71 // of columns in ValueCols (it is defined as a list<list<string> >. Therefore,
72 // it can specify multi-column relationships). For each column, find the
73 // instruction from the group that matches all the values for the column.
74 // Multiple matches are not allowed.
76 //===----------------------------------------------------------------------===//
78 #include "Common/CodeGenInstruction.h"
79 #include "Common/CodeGenTarget.h"
80 #include "TableGenBackends.h"
81 #include "llvm/ADT/StringExtras.h"
82 #include "llvm/TableGen/Error.h"
83 #include "llvm/TableGen/Record.h"
86 typedef std::map
<std::string
, std::vector
<const Record
*>> InstrRelMapTy
;
87 typedef std::map
<std::vector
<const Init
*>, std::vector
<const Record
*>>
92 //===----------------------------------------------------------------------===//
93 // This class is used to represent InstrMapping class defined in Target.td file.
97 std::string FilterClass
;
98 const ListInit
*RowFields
;
99 const ListInit
*ColFields
;
100 const ListInit
*KeyCol
;
101 std::vector
<const ListInit
*> ValueCols
;
104 InstrMap(const Record
*MapRec
) {
105 Name
= std::string(MapRec
->getName());
107 // FilterClass - It's used to reduce the search space only to the
108 // instructions that define the kind of relationship modeled by
109 // this InstrMapping object/record.
110 const RecordVal
*Filter
= MapRec
->getValue("FilterClass");
111 FilterClass
= Filter
->getValue()->getAsUnquotedString();
113 // List of fields/attributes that need to be same across all the
114 // instructions in a row of the relation table.
115 RowFields
= MapRec
->getValueAsListInit("RowFields");
117 // List of fields/attributes that are constant across all the instruction
118 // in a column of the relation table. Ex: ColFields = 'predSense'
119 ColFields
= MapRec
->getValueAsListInit("ColFields");
121 // Values for the fields/attributes listed in 'ColFields'.
122 // Ex: KeyCol = 'noPred' -- key instruction is non-predicated
123 KeyCol
= MapRec
->getValueAsListInit("KeyCol");
125 // List of values for the fields/attributes listed in 'ColFields', one for
126 // each column in the relation table.
128 // Ex: ValueCols = [['true'],['false']] -- it results two columns in the
129 // table. First column requires all the instructions to have predSense
130 // set to 'true' and second column requires it to be 'false'.
131 const ListInit
*ColValList
= MapRec
->getValueAsListInit("ValueCols");
133 // Each instruction map must specify at least one column for it to be valid.
134 if (ColValList
->empty())
135 PrintFatalError(MapRec
->getLoc(), "InstrMapping record `" +
136 MapRec
->getName() + "' has empty " +
137 "`ValueCols' field!");
139 for (const Init
*I
: ColValList
->getValues()) {
140 const auto *ColI
= cast
<ListInit
>(I
);
142 // Make sure that all the sub-lists in 'ValueCols' have same number of
143 // elements as the fields in 'ColFields'.
144 if (ColI
->size() != ColFields
->size())
145 PrintFatalError(MapRec
->getLoc(),
146 "Record `" + MapRec
->getName() +
147 "', field `ValueCols' entries don't match with " +
148 " the entries in 'ColFields'!");
149 ValueCols
.push_back(ColI
);
153 const std::string
&getName() const { return Name
; }
154 const std::string
&getFilterClass() const { return FilterClass
; }
155 const ListInit
*getRowFields() const { return RowFields
; }
156 const ListInit
*getColFields() const { return ColFields
; }
157 const ListInit
*getKeyCol() const { return KeyCol
; }
158 ArrayRef
<const ListInit
*> getValueCols() const { return ValueCols
; }
161 //===----------------------------------------------------------------------===//
162 // class MapTableEmitter : It builds the instruction relation maps using
163 // the information provided in InstrMapping records. It outputs these
164 // relationship maps as tables into XXXGenInstrInfo.inc file along with the
165 // functions to query them.
167 class MapTableEmitter
{
169 // std::string TargetName;
170 const CodeGenTarget
&Target
;
171 // InstrMapDesc - InstrMapping record to be processed.
172 InstrMap InstrMapDesc
;
174 // InstrDefs - list of instructions filtered using FilterClass defined
176 ArrayRef
<const Record
*> InstrDefs
;
178 // RowInstrMap - maps RowFields values to the instructions. It's keyed by the
179 // values of the row fields and contains vector of records as values.
180 RowInstrMapTy RowInstrMap
;
182 // KeyInstrVec - list of key instructions.
183 std::vector
<const Record
*> KeyInstrVec
;
184 DenseMap
<const Record
*, std::vector
<const Record
*>> MapTable
;
187 MapTableEmitter(const CodeGenTarget
&Target
, const RecordKeeper
&Records
,
189 : Target(Target
), InstrMapDesc(IMRec
) {
190 const std::string
&FilterClass
= InstrMapDesc
.getFilterClass();
191 InstrDefs
= Records
.getAllDerivedDefinitions(FilterClass
);
194 void buildRowInstrMap();
196 // Returns true if an instruction is a key instruction, i.e., its ColFields
197 // have same values as KeyCol.
198 bool isKeyColInstr(const Record
*CurInstr
);
200 // Find column instruction corresponding to a key instruction based on the
201 // constraints for that column.
202 const Record
*getInstrForColumn(const Record
*KeyInstr
,
203 const ListInit
*CurValueCol
);
205 // Find column instructions for each key instruction based
206 // on ValueCols and store them into MapTable.
207 void buildMapTable();
209 void emitBinSearch(raw_ostream
&OS
, unsigned TableSize
);
210 void emitTablesWithFunc(raw_ostream
&OS
);
211 unsigned emitBinSearchTable(raw_ostream
&OS
);
213 // Lookup functions to query binary search tables.
214 void emitMapFuncBody(raw_ostream
&OS
, unsigned TableSize
);
216 } // end anonymous namespace
218 //===----------------------------------------------------------------------===//
219 // Process all the instructions that model this relation (alreday present in
220 // InstrDefs) and insert them into RowInstrMap which is keyed by the values of
221 // the fields listed as RowFields. It stores vectors of records as values.
222 // All the related instructions have the same values for the RowFields thus are
223 // part of the same key-value pair.
224 //===----------------------------------------------------------------------===//
226 void MapTableEmitter::buildRowInstrMap() {
227 for (const Record
*CurInstr
: InstrDefs
) {
228 std::vector
<const Init
*> KeyValue
;
229 const ListInit
*RowFields
= InstrMapDesc
.getRowFields();
230 for (const Init
*RowField
: RowFields
->getValues()) {
231 const RecordVal
*RecVal
= CurInstr
->getValue(RowField
);
232 if (RecVal
== nullptr)
233 PrintFatalError(CurInstr
->getLoc(),
234 "No value " + RowField
->getAsString() + " found in \"" +
235 CurInstr
->getName() +
236 "\" instruction description.");
237 const Init
*CurInstrVal
= RecVal
->getValue();
238 KeyValue
.push_back(CurInstrVal
);
241 // Collect key instructions into KeyInstrVec. Later, these instructions are
242 // processed to assign column position to the instructions sharing
243 // their KeyValue in RowInstrMap.
244 if (isKeyColInstr(CurInstr
))
245 KeyInstrVec
.push_back(CurInstr
);
247 RowInstrMap
[KeyValue
].push_back(CurInstr
);
251 //===----------------------------------------------------------------------===//
252 // Return true if an instruction is a KeyCol instruction.
253 //===----------------------------------------------------------------------===//
255 bool MapTableEmitter::isKeyColInstr(const Record
*CurInstr
) {
256 const ListInit
*ColFields
= InstrMapDesc
.getColFields();
257 const ListInit
*KeyCol
= InstrMapDesc
.getKeyCol();
259 // Check if the instruction is a KeyCol instruction.
260 bool MatchFound
= true;
261 for (unsigned J
= 0, EndCf
= ColFields
->size(); (J
< EndCf
) && MatchFound
;
263 const RecordVal
*ColFieldName
=
264 CurInstr
->getValue(ColFields
->getElement(J
));
265 std::string CurInstrVal
= ColFieldName
->getValue()->getAsUnquotedString();
266 std::string KeyColValue
= KeyCol
->getElement(J
)->getAsUnquotedString();
267 MatchFound
= CurInstrVal
== KeyColValue
;
272 //===----------------------------------------------------------------------===//
273 // Build a map to link key instructions with the column instructions arranged
274 // according to their column positions.
275 //===----------------------------------------------------------------------===//
277 void MapTableEmitter::buildMapTable() {
278 // Find column instructions for a given key based on the ColField
280 ArrayRef
<const ListInit
*> ValueCols
= InstrMapDesc
.getValueCols();
281 unsigned NumOfCols
= ValueCols
.size();
282 for (const Record
*CurKeyInstr
: KeyInstrVec
) {
283 std::vector
<const Record
*> ColInstrVec(NumOfCols
);
285 // Find the column instruction based on the constraints for the column.
286 for (unsigned ColIdx
= 0; ColIdx
< NumOfCols
; ColIdx
++) {
287 const ListInit
*CurValueCol
= ValueCols
[ColIdx
];
288 const Record
*ColInstr
= getInstrForColumn(CurKeyInstr
, CurValueCol
);
289 ColInstrVec
[ColIdx
] = ColInstr
;
291 MapTable
[CurKeyInstr
] = ColInstrVec
;
295 //===----------------------------------------------------------------------===//
296 // Find column instruction based on the constraints for that column.
297 //===----------------------------------------------------------------------===//
299 const Record
*MapTableEmitter::getInstrForColumn(const Record
*KeyInstr
,
300 const ListInit
*CurValueCol
) {
301 const ListInit
*RowFields
= InstrMapDesc
.getRowFields();
302 std::vector
<const Init
*> KeyValue
;
304 // Construct KeyValue using KeyInstr's values for RowFields.
305 for (const Init
*RowField
: RowFields
->getValues()) {
306 const Init
*KeyInstrVal
= KeyInstr
->getValue(RowField
)->getValue();
307 KeyValue
.push_back(KeyInstrVal
);
310 // Get all the instructions that share the same KeyValue as the KeyInstr
311 // in RowInstrMap. We search through these instructions to find a match
312 // for the current column, i.e., the instruction which has the same values
313 // as CurValueCol for all the fields in ColFields.
314 ArrayRef
<const Record
*> RelatedInstrVec
= RowInstrMap
[KeyValue
];
316 const ListInit
*ColFields
= InstrMapDesc
.getColFields();
317 const Record
*MatchInstr
= nullptr;
319 for (const Record
*CurInstr
: RelatedInstrVec
) {
320 bool MatchFound
= true;
321 for (unsigned J
= 0, EndCf
= ColFields
->size(); (J
< EndCf
) && MatchFound
;
323 const Init
*ColFieldJ
= ColFields
->getElement(J
);
324 const Init
*CurInstrInit
= CurInstr
->getValue(ColFieldJ
)->getValue();
325 std::string CurInstrVal
= CurInstrInit
->getAsUnquotedString();
326 const Init
*ColFieldJVallue
= CurValueCol
->getElement(J
);
327 MatchFound
= CurInstrVal
== ColFieldJVallue
->getAsUnquotedString();
332 // Already had a match
333 // Error if multiple matches are found for a column.
334 std::string KeyValueStr
;
335 for (const Init
*Value
: KeyValue
) {
336 if (!KeyValueStr
.empty())
338 KeyValueStr
+= Value
->getAsString();
341 PrintFatalError("Multiple matches found for `" + KeyInstr
->getName() +
342 "', for the relation `" + InstrMapDesc
.getName() +
343 "', row fields [" + KeyValueStr
+ "], column `" +
344 CurValueCol
->getAsString() + "'");
346 MatchInstr
= CurInstr
;
352 //===----------------------------------------------------------------------===//
353 // Emit one table per relation. Only instructions with a valid relation of a
354 // given type are included in the table sorted by their enum values (opcodes).
355 // Binary search is used for locating instructions in the table.
356 //===----------------------------------------------------------------------===//
358 unsigned MapTableEmitter::emitBinSearchTable(raw_ostream
&OS
) {
359 ArrayRef
<const CodeGenInstruction
*> NumberedInstructions
=
360 Target
.getInstructionsByEnumValue();
361 StringRef Namespace
= Target
.getInstNamespace();
362 ArrayRef
<const ListInit
*> ValueCols
= InstrMapDesc
.getValueCols();
363 unsigned NumCol
= ValueCols
.size();
364 unsigned TotalNumInstr
= NumberedInstructions
.size();
365 unsigned TableSize
= 0;
367 OS
<< "static const uint16_t " << InstrMapDesc
.getName();
368 // Number of columns in the table are NumCol+1 because key instructions are
369 // emitted as first column.
370 OS
<< "Table[][" << NumCol
+ 1 << "] = {\n";
371 for (unsigned I
= 0; I
< TotalNumInstr
; I
++) {
372 const Record
*CurInstr
= NumberedInstructions
[I
]->TheDef
;
373 ArrayRef
<const Record
*> ColInstrs
= MapTable
[CurInstr
];
375 unsigned RelExists
= 0;
376 if (!ColInstrs
.empty()) {
377 for (unsigned J
= 0; J
< NumCol
; J
++) {
378 if (ColInstrs
[J
] != nullptr) {
383 OutStr
+= ColInstrs
[J
]->getName();
385 OutStr
+= ", (uint16_t)-1U";
390 OS
<< " { " << Namespace
<< "::" << CurInstr
->getName();
391 OS
<< OutStr
<< " },\n";
397 OS
<< " { " << Namespace
<< "::"
398 << "INSTRUCTION_LIST_END, ";
399 OS
<< Namespace
<< "::"
400 << "INSTRUCTION_LIST_END }";
402 OS
<< "}; // End of " << InstrMapDesc
.getName() << "Table\n\n";
406 //===----------------------------------------------------------------------===//
407 // Emit binary search algorithm as part of the functions used to query
409 //===----------------------------------------------------------------------===//
411 void MapTableEmitter::emitBinSearch(raw_ostream
&OS
, unsigned TableSize
) {
412 OS
<< " unsigned mid;\n";
413 OS
<< " unsigned start = 0;\n";
414 OS
<< " unsigned end = " << TableSize
<< ";\n";
415 OS
<< " while (start < end) {\n";
416 OS
<< " mid = start + (end - start) / 2;\n";
417 OS
<< " if (Opcode == " << InstrMapDesc
.getName() << "Table[mid][0]) {\n";
420 OS
<< " if (Opcode < " << InstrMapDesc
.getName() << "Table[mid][0])\n";
421 OS
<< " end = mid;\n";
423 OS
<< " start = mid + 1;\n";
425 OS
<< " if (start == end)\n";
426 OS
<< " return -1; // Instruction doesn't exist in this table.\n\n";
429 //===----------------------------------------------------------------------===//
430 // Emit functions to query relation tables.
431 //===----------------------------------------------------------------------===//
433 void MapTableEmitter::emitMapFuncBody(raw_ostream
&OS
, unsigned TableSize
) {
435 const ListInit
*ColFields
= InstrMapDesc
.getColFields();
436 ArrayRef
<const ListInit
*> ValueCols
= InstrMapDesc
.getValueCols();
438 // Emit binary search algorithm to locate instructions in the
439 // relation table. If found, return opcode value from the appropriate column
441 emitBinSearch(OS
, TableSize
);
443 if (ValueCols
.size() > 1) {
444 for (unsigned I
= 0, E
= ValueCols
.size(); I
< E
; I
++) {
445 const ListInit
*ColumnI
= ValueCols
[I
];
447 for (unsigned J
= 0, ColSize
= ColumnI
->size(); J
< ColSize
; ++J
) {
448 std::string ColName
= ColFields
->getElement(J
)->getAsUnquotedString();
449 OS
<< "in" << ColName
;
451 OS
<< ColName
<< "_" << ColumnI
->getElement(J
)->getAsUnquotedString();
452 if (J
< ColumnI
->size() - 1)
456 OS
<< " return " << InstrMapDesc
.getName();
457 OS
<< "Table[mid][" << I
+ 1 << "];\n";
461 OS
<< " return " << InstrMapDesc
.getName() << "Table[mid][1];\n";
466 //===----------------------------------------------------------------------===//
467 // Emit relation tables and the functions to query them.
468 //===----------------------------------------------------------------------===//
470 void MapTableEmitter::emitTablesWithFunc(raw_ostream
&OS
) {
472 // Emit function name and the input parameters : mostly opcode value of the
473 // current instruction. However, if a table has multiple columns (more than 2
474 // since first column is used for the key instructions), then we also need
475 // to pass another input to indicate the column to be selected.
477 const ListInit
*ColFields
= InstrMapDesc
.getColFields();
478 ArrayRef
<const ListInit
*> ValueCols
= InstrMapDesc
.getValueCols();
479 OS
<< "// " << InstrMapDesc
.getName() << "\nLLVM_READONLY\n";
480 OS
<< "int " << InstrMapDesc
.getName() << "(uint16_t Opcode";
481 if (ValueCols
.size() > 1) {
482 for (const Init
*CF
: ColFields
->getValues()) {
483 std::string ColName
= CF
->getAsUnquotedString();
484 OS
<< ", enum " << ColName
<< " in" << ColName
;
490 unsigned TableSize
= emitBinSearchTable(OS
);
492 // Emit rest of the function body.
493 emitMapFuncBody(OS
, TableSize
);
496 //===----------------------------------------------------------------------===//
497 // Emit enums for the column fields across all the instruction maps.
498 //===----------------------------------------------------------------------===//
500 static void emitEnums(raw_ostream
&OS
, const RecordKeeper
&Records
) {
501 std::map
<std::string
, std::vector
<const Init
*>> ColFieldValueMap
;
503 // Iterate over all InstrMapping records and create a map between column
504 // fields and their possible values across all records.
505 for (const Record
*CurMap
:
506 Records
.getAllDerivedDefinitions("InstrMapping")) {
507 const ListInit
*ColFields
= CurMap
->getValueAsListInit("ColFields");
508 const ListInit
*List
= CurMap
->getValueAsListInit("ValueCols");
509 std::vector
<const ListInit
*> ValueCols
;
510 unsigned ListSize
= List
->size();
512 for (unsigned J
= 0; J
< ListSize
; J
++) {
513 const auto *ListJ
= cast
<ListInit
>(List
->getElement(J
));
515 if (ListJ
->size() != ColFields
->size())
516 PrintFatalError("Record `" + CurMap
->getName() +
518 "`ValueCols' entries don't match with the entries in "
520 ValueCols
.push_back(ListJ
);
523 for (unsigned J
= 0, EndCf
= ColFields
->size(); J
< EndCf
; J
++) {
524 for (unsigned K
= 0; K
< ListSize
; K
++) {
525 std::string ColName
= ColFields
->getElement(J
)->getAsUnquotedString();
526 ColFieldValueMap
[ColName
].push_back((ValueCols
[K
])->getElement(J
));
531 for (auto &[EnumName
, FieldValues
] : ColFieldValueMap
) {
532 // Delete duplicate entries from ColFieldValueMap
533 for (unsigned i
= 0; i
< FieldValues
.size() - 1; i
++) {
534 const Init
*CurVal
= FieldValues
[i
];
535 for (unsigned j
= i
+ 1; j
< FieldValues
.size(); j
++) {
536 if (CurVal
== FieldValues
[j
]) {
537 FieldValues
.erase(FieldValues
.begin() + j
);
543 // Emit enumerated values for the column fields.
544 OS
<< "enum " << EnumName
<< " {\n";
545 ListSeparator
LS(",\n");
546 for (const Init
*Field
: FieldValues
)
547 OS
<< LS
<< "\t" << EnumName
<< "_" << Field
->getAsUnquotedString();
552 //===----------------------------------------------------------------------===//
553 // Parse 'InstrMapping' records and use the information to form relationship
554 // between instructions. These relations are emitted as a tables along with the
555 // functions to query them.
556 //===----------------------------------------------------------------------===//
557 void llvm::EmitMapTable(const RecordKeeper
&Records
, raw_ostream
&OS
) {
558 CodeGenTarget
Target(Records
);
559 StringRef NameSpace
= Target
.getInstNamespace();
560 ArrayRef
<const Record
*> InstrMapVec
=
561 Records
.getAllDerivedDefinitions("InstrMapping");
563 if (InstrMapVec
.empty())
566 OS
<< "#ifdef GET_INSTRMAP_INFO\n";
567 OS
<< "#undef GET_INSTRMAP_INFO\n";
568 OS
<< "namespace llvm {\n\n";
569 OS
<< "namespace " << NameSpace
<< " {\n\n";
571 // Emit coulumn field names and their values as enums.
572 emitEnums(OS
, Records
);
574 // Iterate over all instruction mapping records and construct relationship
575 // maps based on the information specified there.
577 for (const Record
*CurMap
: InstrMapVec
) {
578 MapTableEmitter
IMap(Target
, Records
, CurMap
);
580 // Build RowInstrMap to group instructions based on their values for
581 // RowFields. In the process, also collect key instructions into
583 IMap
.buildRowInstrMap();
585 // Build MapTable to map key instructions with the corresponding column
587 IMap
.buildMapTable();
589 // Emit map tables and the functions to query them.
590 IMap
.emitTablesWithFunc(OS
);
592 OS
<< "} // end namespace " << NameSpace
<< "\n";
593 OS
<< "} // end namespace llvm\n";
594 OS
<< "#endif // GET_INSTRMAP_INFO\n\n";