1 //===- CodeGenMapTable.cpp - Instruction Mapping Table Generator ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
9 // CodeGenMapTable provides functionality for the TabelGen to create
10 // relation mapping between instructions. Relation models are defined using
11 // InstrMapping as a base class. This file implements the functionality which
12 // parses these definitions and generates relation maps using the information
13 // specified there. These maps are emitted as tables in the XXXGenInstrInfo.inc
14 // file along with the functions to query them.
16 // A relationship model to relate non-predicate instructions with their
17 // predicated true/false forms can be defined as follows:
19 // def getPredOpcode : InstrMapping {
20 // let FilterClass = "PredRel";
21 // let RowFields = ["BaseOpcode"];
22 // let ColFields = ["PredSense"];
23 // let KeyCol = ["none"];
24 // let ValueCols = [["true"], ["false"]]; }
26 // CodeGenMapTable parses this map and generates a table in XXXGenInstrInfo.inc
27 // file that contains the instructions modeling this relationship. This table
28 // is defined in the function
29 // "int getPredOpcode(uint16_t Opcode, enum PredSense inPredSense)"
30 // that can be used to retrieve the predicated form of the instruction by
31 // passing its opcode value and the predicate sense (true/false) of the desired
32 // instruction as arguments.
34 // Short description of the algorithm:
36 // 1) Iterate through all the records that derive from "InstrMapping" class.
37 // 2) For each record, filter out instructions based on the FilterClass value.
38 // 3) Iterate through this set of instructions and insert them into
39 // RowInstrMap map based on their RowFields values. RowInstrMap is keyed by the
40 // vector of RowFields values and contains vectors of Records (instructions) as
41 // values. RowFields is a list of fields that are required to have the same
42 // values for all the instructions appearing in the same row of the relation
43 // table. All the instructions in a given row of the relation table have some
44 // sort of relationship with the key instruction defined by the corresponding
45 // relationship model.
47 // Ex: RowInstrMap(RowVal1, RowVal2, ...) -> [Instr1, Instr2, Instr3, ... ]
48 // Here Instr1, Instr2, Instr3 have same values (RowVal1, RowVal2) for
49 // RowFields. These groups of instructions are later matched against ValueCols
50 // to determine the column they belong to, if any.
52 // While building the RowInstrMap map, collect all the key instructions in
53 // KeyInstrVec. These are the instructions having the same values as KeyCol
54 // for all the fields listed in ColFields.
58 // Relate non-predicate instructions with their predicated true/false forms.
60 // def getPredOpcode : InstrMapping {
61 // let FilterClass = "PredRel";
62 // let RowFields = ["BaseOpcode"];
63 // let ColFields = ["PredSense"];
64 // let KeyCol = ["none"];
65 // let ValueCols = [["true"], ["false"]]; }
67 // Here, only instructions that have "none" as PredSense will be selected as key
70 // 4) For each key instruction, get the group of instructions that share the
71 // same key-value as the key instruction from RowInstrMap. Iterate over the list
72 // of columns in ValueCols (it is defined as a list<list<string> >. Therefore,
73 // it can specify multi-column relationships). For each column, find the
74 // instruction from the group that matches all the values for the column.
75 // Multiple matches are not allowed.
77 //===----------------------------------------------------------------------===//
79 #include "CodeGenTarget.h"
80 #include "llvm/Support/Format.h"
81 #include "llvm/TableGen/Error.h"
83 typedef std::map<std::string, std::vector<Record*> > InstrRelMapTy;
85 typedef std::map<std::vector<Init*>, std::vector<Record*> > RowInstrMapTy;
89 //===----------------------------------------------------------------------===//
90 // This class is used to represent InstrMapping class defined in Target.td file.
94 std::string FilterClass;
98 std::vector<ListInit*> ValueCols;
101 InstrMap(Record* MapRec) {
102 Name = MapRec->getName();
104 // FilterClass - It's used to reduce the search space only to the
105 // instructions that define the kind of relationship modeled by
106 // this InstrMapping object/record.
107 const RecordVal *Filter = MapRec->getValue("FilterClass");
108 FilterClass = Filter->getValue()->getAsUnquotedString();
110 // List of fields/attributes that need to be same across all the
111 // instructions in a row of the relation table.
112 RowFields = MapRec->getValueAsListInit("RowFields");
114 // List of fields/attributes that are constant across all the instruction
115 // in a column of the relation table. Ex: ColFields = 'predSense'
116 ColFields = MapRec->getValueAsListInit("ColFields");
118 // Values for the fields/attributes listed in 'ColFields'.
119 // Ex: KeyCol = 'noPred' -- key instruction is non-predicated
120 KeyCol = MapRec->getValueAsListInit("KeyCol");
122 // List of values for the fields/attributes listed in 'ColFields', one for
123 // each column in the relation table.
125 // Ex: ValueCols = [['true'],['false']] -- it results two columns in the
126 // table. First column requires all the instructions to have predSense
127 // set to 'true' and second column requires it to be 'false'.
128 ListInit *ColValList = MapRec->getValueAsListInit("ValueCols");
130 // Each instruction map must specify at least one column for it to be valid.
131 if (ColValList->getSize() == 0)
132 PrintFatalError(MapRec->getLoc(), "InstrMapping record `" +
133 MapRec->getName() + "' has empty " + "`ValueCols' field!");
135 for (unsigned i = 0, e = ColValList->getSize(); i < e; i++) {
136 ListInit *ColI = dyn_cast<ListInit>(ColValList->getElement(i));
138 // Make sure that all the sub-lists in 'ValueCols' have same number of
139 // elements as the fields in 'ColFields'.
140 if (ColI->getSize() != ColFields->getSize())
141 PrintFatalError(MapRec->getLoc(), "Record `" + MapRec->getName() +
142 "', field `ValueCols' entries don't match with " +
143 " the entries in 'ColFields'!");
144 ValueCols.push_back(ColI);
148 std::string getName() const {
152 std::string getFilterClass() {
156 ListInit *getRowFields() const {
160 ListInit *getColFields() const {
164 ListInit *getKeyCol() const {
168 const std::vector<ListInit*> &getValueCols() const {
172 } // End anonymous namespace.
175 //===----------------------------------------------------------------------===//
176 // class MapTableEmitter : It builds the instruction relation maps using
177 // the information provided in InstrMapping records. It outputs these
178 // relationship maps as tables into XXXGenInstrInfo.inc file along with the
179 // functions to query them.
182 class MapTableEmitter {
184 // std::string TargetName;
185 const CodeGenTarget &Target;
186 // InstrMapDesc - InstrMapping record to be processed.
187 InstrMap InstrMapDesc;
189 // InstrDefs - list of instructions filtered using FilterClass defined
191 std::vector<Record*> InstrDefs;
193 // RowInstrMap - maps RowFields values to the instructions. It's keyed by the
194 // values of the row fields and contains vector of records as values.
195 RowInstrMapTy RowInstrMap;
197 // KeyInstrVec - list of key instructions.
198 std::vector<Record*> KeyInstrVec;
199 DenseMap<Record*, std::vector<Record*> > MapTable;
202 MapTableEmitter(CodeGenTarget &Target, RecordKeeper &Records, Record *IMRec):
203 Target(Target), InstrMapDesc(IMRec) {
204 const std::string FilterClass = InstrMapDesc.getFilterClass();
205 InstrDefs = Records.getAllDerivedDefinitions(FilterClass);
208 void buildRowInstrMap();
210 // Returns true if an instruction is a key instruction, i.e., its ColFields
211 // have same values as KeyCol.
212 bool isKeyColInstr(Record* CurInstr);
214 // Find column instruction corresponding to a key instruction based on the
215 // constraints for that column.
216 Record *getInstrForColumn(Record *KeyInstr, ListInit *CurValueCol);
218 // Find column instructions for each key instruction based
219 // on ValueCols and store them into MapTable.
220 void buildMapTable();
222 void emitBinSearch(raw_ostream &OS, unsigned TableSize);
223 void emitTablesWithFunc(raw_ostream &OS);
224 unsigned emitBinSearchTable(raw_ostream &OS);
226 // Lookup functions to query binary search tables.
227 void emitMapFuncBody(raw_ostream &OS, unsigned TableSize);
230 } // End anonymous namespace.
233 //===----------------------------------------------------------------------===//
234 // Process all the instructions that model this relation (alreday present in
235 // InstrDefs) and insert them into RowInstrMap which is keyed by the values of
236 // the fields listed as RowFields. It stores vectors of records as values.
237 // All the related instructions have the same values for the RowFields thus are
238 // part of the same key-value pair.
239 //===----------------------------------------------------------------------===//
241 void MapTableEmitter::buildRowInstrMap() {
242 for (unsigned i = 0, e = InstrDefs.size(); i < e; i++) {
243 Record *CurInstr = InstrDefs[i];
244 std::vector<Init*> KeyValue;
245 ListInit *RowFields = InstrMapDesc.getRowFields();
246 for (unsigned j = 0, endRF = RowFields->getSize(); j < endRF; j++) {
247 Init *RowFieldsJ = RowFields->getElement(j);
248 Init *CurInstrVal = CurInstr->getValue(RowFieldsJ)->getValue();
249 KeyValue.push_back(CurInstrVal);
252 // Collect key instructions into KeyInstrVec. Later, these instructions are
253 // processed to assign column position to the instructions sharing
254 // their KeyValue in RowInstrMap.
255 if (isKeyColInstr(CurInstr))
256 KeyInstrVec.push_back(CurInstr);
258 RowInstrMap[KeyValue].push_back(CurInstr);
262 //===----------------------------------------------------------------------===//
263 // Return true if an instruction is a KeyCol instruction.
264 //===----------------------------------------------------------------------===//
266 bool MapTableEmitter::isKeyColInstr(Record* CurInstr) {
267 ListInit *ColFields = InstrMapDesc.getColFields();
268 ListInit *KeyCol = InstrMapDesc.getKeyCol();
270 // Check if the instruction is a KeyCol instruction.
271 bool MatchFound = true;
272 for (unsigned j = 0, endCF = ColFields->getSize();
273 (j < endCF) && MatchFound; j++) {
274 RecordVal *ColFieldName = CurInstr->getValue(ColFields->getElement(j));
275 std::string CurInstrVal = ColFieldName->getValue()->getAsUnquotedString();
276 std::string KeyColValue = KeyCol->getElement(j)->getAsUnquotedString();
277 MatchFound = (CurInstrVal == KeyColValue);
282 //===----------------------------------------------------------------------===//
283 // Build a map to link key instructions with the column instructions arranged
284 // according to their column positions.
285 //===----------------------------------------------------------------------===//
287 void MapTableEmitter::buildMapTable() {
288 // Find column instructions for a given key based on the ColField
290 const std::vector<ListInit*> &ValueCols = InstrMapDesc.getValueCols();
291 unsigned NumOfCols = ValueCols.size();
292 for (unsigned j = 0, endKI = KeyInstrVec.size(); j < endKI; j++) {
293 Record *CurKeyInstr = KeyInstrVec[j];
294 std::vector<Record*> ColInstrVec(NumOfCols);
296 // Find the column instruction based on the constraints for the column.
297 for (unsigned ColIdx = 0; ColIdx < NumOfCols; ColIdx++) {
298 ListInit *CurValueCol = ValueCols[ColIdx];
299 Record *ColInstr = getInstrForColumn(CurKeyInstr, CurValueCol);
300 ColInstrVec[ColIdx] = ColInstr;
302 MapTable[CurKeyInstr] = ColInstrVec;
306 //===----------------------------------------------------------------------===//
307 // Find column instruction based on the constraints for that column.
308 //===----------------------------------------------------------------------===//
310 Record *MapTableEmitter::getInstrForColumn(Record *KeyInstr,
311 ListInit *CurValueCol) {
312 ListInit *RowFields = InstrMapDesc.getRowFields();
313 std::vector<Init*> KeyValue;
315 // Construct KeyValue using KeyInstr's values for RowFields.
316 for (unsigned j = 0, endRF = RowFields->getSize(); j < endRF; j++) {
317 Init *RowFieldsJ = RowFields->getElement(j);
318 Init *KeyInstrVal = KeyInstr->getValue(RowFieldsJ)->getValue();
319 KeyValue.push_back(KeyInstrVal);
322 // Get all the instructions that share the same KeyValue as the KeyInstr
323 // in RowInstrMap. We search through these instructions to find a match
324 // for the current column, i.e., the instruction which has the same values
325 // as CurValueCol for all the fields in ColFields.
326 const std::vector<Record*> &RelatedInstrVec = RowInstrMap[KeyValue];
328 ListInit *ColFields = InstrMapDesc.getColFields();
329 Record *MatchInstr = nullptr;
331 for (unsigned i = 0, e = RelatedInstrVec.size(); i < e; i++) {
332 bool MatchFound = true;
333 Record *CurInstr = RelatedInstrVec[i];
334 for (unsigned j = 0, endCF = ColFields->getSize();
335 (j < endCF) && MatchFound; j++) {
336 Init *ColFieldJ = ColFields->getElement(j);
337 Init *CurInstrInit = CurInstr->getValue(ColFieldJ)->getValue();
338 std::string CurInstrVal = CurInstrInit->getAsUnquotedString();
339 Init *ColFieldJVallue = CurValueCol->getElement(j);
340 MatchFound = (CurInstrVal == ColFieldJVallue->getAsUnquotedString());
344 if (MatchInstr) // Already had a match
345 // Error if multiple matches are found for a column.
346 PrintFatalError("Multiple matches found for `" + KeyInstr->getName() +
347 "', for the relation `" + InstrMapDesc.getName());
348 MatchInstr = CurInstr;
354 //===----------------------------------------------------------------------===//
355 // Emit one table per relation. Only instructions with a valid relation of a
356 // given type are included in the table sorted by their enum values (opcodes).
357 // Binary search is used for locating instructions in the table.
358 //===----------------------------------------------------------------------===//
360 unsigned MapTableEmitter::emitBinSearchTable(raw_ostream &OS) {
362 const std::vector<const CodeGenInstruction*> &NumberedInstructions =
363 Target.getInstructionsByEnumValue();
364 std::string TargetName = Target.getName();
365 const std::vector<ListInit*> &ValueCols = InstrMapDesc.getValueCols();
366 unsigned NumCol = ValueCols.size();
367 unsigned TotalNumInstr = NumberedInstructions.size();
368 unsigned TableSize = 0;
370 OS << "static const uint16_t "<<InstrMapDesc.getName();
371 // Number of columns in the table are NumCol+1 because key instructions are
372 // emitted as first column.
373 OS << "Table[]["<< NumCol+1 << "] = {\n";
374 for (unsigned i = 0; i < TotalNumInstr; i++) {
375 Record *CurInstr = NumberedInstructions[i]->TheDef;
376 std::vector<Record*> ColInstrs = MapTable[CurInstr];
377 std::string OutStr("");
378 unsigned RelExists = 0;
379 if (!ColInstrs.empty()) {
380 for (unsigned j = 0; j < NumCol; j++) {
381 if (ColInstrs[j] != nullptr) {
384 OutStr += TargetName;
386 OutStr += ColInstrs[j]->getName();
387 } else { OutStr += ", (uint16_t)-1U";}
391 OS << " { " << TargetName << "::" << CurInstr->getName();
392 OS << OutStr <<" },\n";
398 OS << " { " << TargetName << "::" << "INSTRUCTION_LIST_END, ";
399 OS << TargetName << "::" << "INSTRUCTION_LIST_END }";
401 OS << "}; // End of " << InstrMapDesc.getName() << "Table\n\n";
405 //===----------------------------------------------------------------------===//
406 // Emit binary search algorithm as part of the functions used to query
408 //===----------------------------------------------------------------------===//
410 void MapTableEmitter::emitBinSearch(raw_ostream &OS, unsigned TableSize) {
411 OS << " unsigned mid;\n";
412 OS << " unsigned start = 0;\n";
413 OS << " unsigned end = " << TableSize << ";\n";
414 OS << " while (start < end) {\n";
415 OS << " mid = start + (end - start)/2;\n";
416 OS << " if (Opcode == " << InstrMapDesc.getName() << "Table[mid][0]) {\n";
419 OS << " if (Opcode < " << InstrMapDesc.getName() << "Table[mid][0])\n";
420 OS << " end = mid;\n";
422 OS << " start = mid + 1;\n";
424 OS << " if (start == end)\n";
425 OS << " return -1; // Instruction doesn't exist in this table.\n\n";
428 //===----------------------------------------------------------------------===//
429 // Emit functions to query relation tables.
430 //===----------------------------------------------------------------------===//
432 void MapTableEmitter::emitMapFuncBody(raw_ostream &OS,
433 unsigned TableSize) {
435 ListInit *ColFields = InstrMapDesc.getColFields();
436 const std::vector<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 ListInit *ColumnI = ValueCols[i];
446 for (unsigned j = 0, ColSize = ColumnI->getSize(); j < ColSize; j++) {
447 std::string ColName = ColFields->getElement(j)->getAsUnquotedString();
448 OS << " if (in" << ColName;
450 OS << ColName << "_" << ColumnI->getElement(j)->getAsUnquotedString();
451 if (j < ColumnI->getSize() - 1) OS << " && ";
454 OS << " return " << InstrMapDesc.getName();
455 OS << "Table[mid]["<<i+1<<"];\n";
460 OS << " return " << InstrMapDesc.getName() << "Table[mid][1];\n";
465 //===----------------------------------------------------------------------===//
466 // Emit relation tables and the functions to query them.
467 //===----------------------------------------------------------------------===//
469 void MapTableEmitter::emitTablesWithFunc(raw_ostream &OS) {
471 // Emit function name and the input parameters : mostly opcode value of the
472 // current instruction. However, if a table has multiple columns (more than 2
473 // since first column is used for the key instructions), then we also need
474 // to pass another input to indicate the column to be selected.
476 ListInit *ColFields = InstrMapDesc.getColFields();
477 const std::vector<ListInit*> &ValueCols = InstrMapDesc.getValueCols();
478 OS << "// "<< InstrMapDesc.getName() << "\n";
479 OS << "int "<< InstrMapDesc.getName() << "(uint16_t Opcode";
480 if (ValueCols.size() > 1) {
481 for (unsigned i = 0, e = ColFields->getSize(); i < e; i++) {
482 std::string ColName = ColFields->getElement(i)->getAsUnquotedString();
483 OS << ", enum " << ColName << " in" << ColName << ") {\n";
485 } else { OS << ") {\n"; }
488 unsigned TableSize = emitBinSearchTable(OS);
490 // Emit rest of the function body.
491 emitMapFuncBody(OS, TableSize);
494 //===----------------------------------------------------------------------===//
495 // Emit enums for the column fields across all the instruction maps.
496 //===----------------------------------------------------------------------===//
498 static void emitEnums(raw_ostream &OS, RecordKeeper &Records) {
500 std::vector<Record*> InstrMapVec;
501 InstrMapVec = Records.getAllDerivedDefinitions("InstrMapping");
502 std::map<std::string, std::vector<Init*> > ColFieldValueMap;
504 // Iterate over all InstrMapping records and create a map between column
505 // fields and their possible values across all records.
506 for (unsigned i = 0, e = InstrMapVec.size(); i < e; i++) {
507 Record *CurMap = InstrMapVec[i];
509 ColFields = CurMap->getValueAsListInit("ColFields");
510 ListInit *List = CurMap->getValueAsListInit("ValueCols");
511 std::vector<ListInit*> ValueCols;
512 unsigned ListSize = List->getSize();
514 for (unsigned j = 0; j < ListSize; j++) {
515 ListInit *ListJ = dyn_cast<ListInit>(List->getElement(j));
517 if (ListJ->getSize() != ColFields->getSize())
518 PrintFatalError("Record `" + CurMap->getName() + "', field "
519 "`ValueCols' entries don't match with the entries in 'ColFields' !");
520 ValueCols.push_back(ListJ);
523 for (unsigned j = 0, endCF = ColFields->getSize(); 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 (std::map<std::string, std::vector<Init*> >::iterator
532 II = ColFieldValueMap.begin(), IE = ColFieldValueMap.end();
534 std::vector<Init*> FieldValues = (*II).second;
536 // Delete duplicate entries from ColFieldValueMap
537 for (unsigned i = 0; i < FieldValues.size() - 1; i++) {
538 Init *CurVal = FieldValues[i];
539 for (unsigned j = i+1; j < FieldValues.size(); j++) {
540 if (CurVal == FieldValues[j]) {
541 FieldValues.erase(FieldValues.begin()+j);
546 // Emit enumerated values for the column fields.
547 OS << "enum " << (*II).first << " {\n";
548 for (unsigned i = 0, endFV = FieldValues.size(); i < endFV; i++) {
549 OS << "\t" << (*II).first << "_" << FieldValues[i]->getAsUnquotedString();
559 //===----------------------------------------------------------------------===//
560 // Parse 'InstrMapping' records and use the information to form relationship
561 // between instructions. These relations are emitted as a tables along with the
562 // functions to query them.
563 //===----------------------------------------------------------------------===//
564 void EmitMapTable(RecordKeeper &Records, raw_ostream &OS) {
565 CodeGenTarget Target(Records);
566 std::string TargetName = Target.getName();
567 std::vector<Record*> InstrMapVec;
568 InstrMapVec = Records.getAllDerivedDefinitions("InstrMapping");
570 if (InstrMapVec.empty())
573 OS << "#ifdef GET_INSTRMAP_INFO\n";
574 OS << "#undef GET_INSTRMAP_INFO\n";
575 OS << "namespace llvm {\n\n";
576 OS << "namespace " << TargetName << " {\n\n";
578 // Emit coulumn field names and their values as enums.
579 emitEnums(OS, Records);
581 // Iterate over all instruction mapping records and construct relationship
582 // maps based on the information specified there.
584 for (unsigned i = 0, e = InstrMapVec.size(); i < e; i++) {
585 MapTableEmitter IMap(Target, Records, InstrMapVec[i]);
587 // Build RowInstrMap to group instructions based on their values for
588 // RowFields. In the process, also collect key instructions into
590 IMap.buildRowInstrMap();
592 // Build MapTable to map key instructions with the corresponding column
594 IMap.buildMapTable();
596 // Emit map tables and the functions to query them.
597 IMap.emitTablesWithFunc(OS);
599 OS << "} // End " << TargetName << " namespace\n";
600 OS << "} // End llvm namespace\n";
601 OS << "#endif // GET_INSTRMAP_INFO\n\n";
604 } // End llvm namespace