blob: 084bef2dc72998f7e8a8b786d512facd3dd7cb2a [file] [log] [blame]
Owen Anderson4e818902011-02-18 21:51:29 +00001//===------------ FixedLenDecoderEmitter.cpp - Decoder Generator ----------===//
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//===----------------------------------------------------------------------===//
9//
10// It contains the tablegen backend that emits the decoder functions for
11// targets with fixed length instruction set.
12//
13//===----------------------------------------------------------------------===//
14
Owen Anderson4e818902011-02-18 21:51:29 +000015#include "CodeGenTarget.h"
James Molloyd9ba4fd2012-02-09 10:56:31 +000016#include "llvm/ADT/APInt.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000017#include "llvm/ADT/SmallString.h"
Owen Anderson4e818902011-02-18 21:51:29 +000018#include "llvm/ADT/StringExtras.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000019#include "llvm/ADT/StringRef.h"
20#include "llvm/ADT/Twine.h"
21#include "llvm/MC/MCFixedLenDisassembler.h"
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000022#include "llvm/Support/DataTypes.h"
Owen Anderson4e818902011-02-18 21:51:29 +000023#include "llvm/Support/Debug.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000024#include "llvm/Support/FormattedStream.h"
25#include "llvm/Support/LEB128.h"
Owen Anderson4e818902011-02-18 21:51:29 +000026#include "llvm/Support/raw_ostream.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000027#include "llvm/TableGen/Error.h"
28#include "llvm/TableGen/Record.h"
Owen Anderson4e818902011-02-18 21:51:29 +000029#include <map>
30#include <string>
Chandler Carruth91d19d82012-12-04 10:37:14 +000031#include <vector>
Owen Anderson4e818902011-02-18 21:51:29 +000032
33using namespace llvm;
34
Chandler Carruth97acce22014-04-22 03:06:00 +000035#define DEBUG_TYPE "decoder-emitter"
36
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000037namespace {
38struct EncodingField {
39 unsigned Base, Width, Offset;
40 EncodingField(unsigned B, unsigned W, unsigned O)
41 : Base(B), Width(W), Offset(O) { }
42};
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000043
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000044struct OperandInfo {
45 std::vector<EncodingField> Fields;
46 std::string Decoder;
47
48 OperandInfo(std::string D)
49 : Decoder(D) { }
50
51 void addField(unsigned Base, unsigned Width, unsigned Offset) {
52 Fields.push_back(EncodingField(Base, Width, Offset));
53 }
54
55 unsigned numFields() const { return Fields.size(); }
56
57 typedef std::vector<EncodingField>::const_iterator const_iterator;
58
59 const_iterator begin() const { return Fields.begin(); }
60 const_iterator end() const { return Fields.end(); }
61};
Jim Grosbachecaef492012-08-14 19:06:05 +000062
63typedef std::vector<uint8_t> DecoderTable;
64typedef uint32_t DecoderFixup;
65typedef std::vector<DecoderFixup> FixupList;
66typedef std::vector<FixupList> FixupScopeList;
67typedef SetVector<std::string> PredicateSet;
68typedef SetVector<std::string> DecoderSet;
69struct DecoderTableInfo {
70 DecoderTable Table;
71 FixupScopeList FixupStack;
72 PredicateSet Predicates;
73 DecoderSet Decoders;
74};
75
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000076} // End anonymous namespace
77
78namespace {
79class FixedLenDecoderEmitter {
Jim Grosbachecaef492012-08-14 19:06:05 +000080 const std::vector<const CodeGenInstruction*> *NumberedInstructions;
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000081public:
82
83 // Defaults preserved here for documentation, even though they aren't
84 // strictly necessary given the way that this is currently being called.
85 FixedLenDecoderEmitter(RecordKeeper &R,
86 std::string PredicateNamespace,
87 std::string GPrefix = "if (",
88 std::string GPostfix = " == MCDisassembler::Fail)"
89 " return MCDisassembler::Fail;",
90 std::string ROK = "MCDisassembler::Success",
91 std::string RFail = "MCDisassembler::Fail",
92 std::string L = "") :
93 Target(R),
94 PredicateNamespace(PredicateNamespace),
95 GuardPrefix(GPrefix), GuardPostfix(GPostfix),
96 ReturnOK(ROK), ReturnFail(RFail), Locals(L) {}
97
Jim Grosbachecaef492012-08-14 19:06:05 +000098 // Emit the decoder state machine table.
99 void emitTable(formatted_raw_ostream &o, DecoderTable &Table,
100 unsigned Indentation, unsigned BitWidth,
101 StringRef Namespace) const;
102 void emitPredicateFunction(formatted_raw_ostream &OS,
103 PredicateSet &Predicates,
104 unsigned Indentation) const;
105 void emitDecoderFunction(formatted_raw_ostream &OS,
106 DecoderSet &Decoders,
107 unsigned Indentation) const;
108
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000109 // run - Output the code emitter
110 void run(raw_ostream &o);
111
112private:
113 CodeGenTarget Target;
114public:
115 std::string PredicateNamespace;
116 std::string GuardPrefix, GuardPostfix;
117 std::string ReturnOK, ReturnFail;
118 std::string Locals;
119};
120} // End anonymous namespace
121
Owen Anderson4e818902011-02-18 21:51:29 +0000122// The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
123// for a bit value.
124//
125// BIT_UNFILTERED is used as the init value for a filter position. It is used
126// only for filter processings.
127typedef enum {
128 BIT_TRUE, // '1'
129 BIT_FALSE, // '0'
130 BIT_UNSET, // '?'
131 BIT_UNFILTERED // unfiltered
132} bit_value_t;
133
134static bool ValueSet(bit_value_t V) {
135 return (V == BIT_TRUE || V == BIT_FALSE);
136}
137static bool ValueNotSet(bit_value_t V) {
138 return (V == BIT_UNSET);
139}
140static int Value(bit_value_t V) {
141 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
142}
Craig Topper48c112b2012-03-16 05:58:09 +0000143static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
Sean Silvafb509ed2012-10-10 20:24:43 +0000144 if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index)))
Owen Anderson4e818902011-02-18 21:51:29 +0000145 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
146
147 // The bit is uninitialized.
148 return BIT_UNSET;
149}
150// Prints the bit value for each position.
Craig Topper48c112b2012-03-16 05:58:09 +0000151static void dumpBits(raw_ostream &o, const BitsInit &bits) {
Craig Topper29688ab2012-08-17 05:42:16 +0000152 for (unsigned index = bits.getNumBits(); index > 0; --index) {
Owen Anderson4e818902011-02-18 21:51:29 +0000153 switch (bitFromBits(bits, index - 1)) {
154 case BIT_TRUE:
155 o << "1";
156 break;
157 case BIT_FALSE:
158 o << "0";
159 break;
160 case BIT_UNSET:
161 o << "_";
162 break;
163 default:
Craig Topperc4965bc2012-02-05 07:21:30 +0000164 llvm_unreachable("unexpected return value from bitFromBits");
Owen Anderson4e818902011-02-18 21:51:29 +0000165 }
166 }
167}
168
David Greeneaf8ee2c2011-07-29 22:43:06 +0000169static BitsInit &getBitsField(const Record &def, const char *str) {
170 BitsInit *bits = def.getValueAsBitsInit(str);
Owen Anderson4e818902011-02-18 21:51:29 +0000171 return *bits;
172}
173
174// Forward declaration.
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000175namespace {
Owen Anderson4e818902011-02-18 21:51:29 +0000176class FilterChooser;
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000177} // End anonymous namespace
Owen Anderson4e818902011-02-18 21:51:29 +0000178
Owen Anderson4e818902011-02-18 21:51:29 +0000179// Representation of the instruction to work on.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000180typedef std::vector<bit_value_t> insn_t;
Owen Anderson4e818902011-02-18 21:51:29 +0000181
182/// Filter - Filter works with FilterChooser to produce the decoding tree for
183/// the ISA.
184///
185/// It is useful to think of a Filter as governing the switch stmts of the
186/// decoding tree in a certain level. Each case stmt delegates to an inferior
187/// FilterChooser to decide what further decoding logic to employ, or in another
188/// words, what other remaining bits to look at. The FilterChooser eventually
189/// chooses a best Filter to do its job.
190///
191/// This recursive scheme ends when the number of Opcodes assigned to the
192/// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
193/// the Filter/FilterChooser combo does not know how to distinguish among the
194/// Opcodes assigned.
195///
196/// An example of a conflict is
197///
198/// Conflict:
199/// 111101000.00........00010000....
200/// 111101000.00........0001........
201/// 1111010...00........0001........
202/// 1111010...00....................
203/// 1111010.........................
204/// 1111............................
205/// ................................
206/// VST4q8a 111101000_00________00010000____
207/// VST4q8b 111101000_00________00010000____
208///
209/// The Debug output shows the path that the decoding tree follows to reach the
210/// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
211/// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
212///
213/// The encoding info in the .td files does not specify this meta information,
214/// which could have been used by the decoder to resolve the conflict. The
215/// decoder could try to decode the even/odd register numbering and assign to
216/// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
217/// version and return the Opcode since the two have the same Asm format string.
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000218namespace {
Owen Anderson4e818902011-02-18 21:51:29 +0000219class Filter {
220protected:
Craig Topper501d95c2012-03-16 06:52:56 +0000221 const FilterChooser *Owner;// points to the FilterChooser who owns this filter
Owen Anderson4e818902011-02-18 21:51:29 +0000222 unsigned StartBit; // the starting bit position
223 unsigned NumBits; // number of bits to filter
224 bool Mixed; // a mixed region contains both set and unset bits
225
226 // Map of well-known segment value to the set of uid's with that value.
227 std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
228
229 // Set of uid's with non-constant segment values.
230 std::vector<unsigned> VariableInstructions;
231
232 // Map of well-known segment value to its delegate.
Craig Toppercf05f912014-09-03 06:07:54 +0000233 std::map<unsigned, std::unique_ptr<const FilterChooser>> FilterChooserMap;
Owen Anderson4e818902011-02-18 21:51:29 +0000234
235 // Number of instructions which fall under FilteredInstructions category.
236 unsigned NumFiltered;
237
238 // Keeps track of the last opcode in the filtered bucket.
239 unsigned LastOpcFiltered;
240
Owen Anderson4e818902011-02-18 21:51:29 +0000241public:
Craig Topper48c112b2012-03-16 05:58:09 +0000242 unsigned getNumFiltered() const { return NumFiltered; }
243 unsigned getSingletonOpc() const {
Owen Anderson4e818902011-02-18 21:51:29 +0000244 assert(NumFiltered == 1);
245 return LastOpcFiltered;
246 }
247 // Return the filter chooser for the group of instructions without constant
248 // segment values.
Craig Topper48c112b2012-03-16 05:58:09 +0000249 const FilterChooser &getVariableFC() const {
Owen Anderson4e818902011-02-18 21:51:29 +0000250 assert(NumFiltered == 1);
251 assert(FilterChooserMap.size() == 1);
252 return *(FilterChooserMap.find((unsigned)-1)->second);
253 }
254
Craig Topper5c2b4ac2014-09-03 05:49:07 +0000255 Filter(Filter &&f);
Owen Anderson4e818902011-02-18 21:51:29 +0000256 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
257
258 ~Filter();
259
260 // Divides the decoding task into sub tasks and delegates them to the
261 // inferior FilterChooser's.
262 //
263 // A special case arises when there's only one entry in the filtered
264 // instructions. In order to unambiguously decode the singleton, we need to
265 // match the remaining undecoded encoding bits against the singleton.
266 void recurse();
267
Jim Grosbachecaef492012-08-14 19:06:05 +0000268 // Emit table entries to decode instructions given a segment or segments of
269 // bits.
270 void emitTableEntry(DecoderTableInfo &TableInfo) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000271
272 // Returns the number of fanout produced by the filter. More fanout implies
273 // the filter distinguishes more categories of instructions.
274 unsigned usefulness() const;
275}; // End of class Filter
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000276} // End anonymous namespace
Owen Anderson4e818902011-02-18 21:51:29 +0000277
278// These are states of our finite state machines used in FilterChooser's
279// filterProcessor() which produces the filter candidates to use.
280typedef enum {
281 ATTR_NONE,
282 ATTR_FILTERED,
283 ATTR_ALL_SET,
284 ATTR_ALL_UNSET,
285 ATTR_MIXED
286} bitAttr_t;
287
288/// FilterChooser - FilterChooser chooses the best filter among a set of Filters
289/// in order to perform the decoding of instructions at the current level.
290///
291/// Decoding proceeds from the top down. Based on the well-known encoding bits
292/// of instructions available, FilterChooser builds up the possible Filters that
293/// can further the task of decoding by distinguishing among the remaining
294/// candidate instructions.
295///
296/// Once a filter has been chosen, it is called upon to divide the decoding task
297/// into sub-tasks and delegates them to its inferior FilterChoosers for further
298/// processings.
299///
300/// It is useful to think of a Filter as governing the switch stmts of the
301/// decoding tree. And each case is delegated to an inferior FilterChooser to
302/// decide what further remaining bits to look at.
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000303namespace {
Owen Anderson4e818902011-02-18 21:51:29 +0000304class FilterChooser {
305protected:
306 friend class Filter;
307
308 // Vector of codegen instructions to choose our filter.
309 const std::vector<const CodeGenInstruction*> &AllInstructions;
310
311 // Vector of uid's for this filter chooser to work on.
Craig Topper501d95c2012-03-16 06:52:56 +0000312 const std::vector<unsigned> &Opcodes;
Owen Anderson4e818902011-02-18 21:51:29 +0000313
314 // Lookup table for the operand decoding of instructions.
Craig Topper501d95c2012-03-16 06:52:56 +0000315 const std::map<unsigned, std::vector<OperandInfo> > &Operands;
Owen Anderson4e818902011-02-18 21:51:29 +0000316
317 // Vector of candidate filters.
318 std::vector<Filter> Filters;
319
320 // Array of bit values passed down from our parent.
321 // Set to all BIT_UNFILTERED's for Parent == NULL.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000322 std::vector<bit_value_t> FilterBitValues;
Owen Anderson4e818902011-02-18 21:51:29 +0000323
324 // Links to the FilterChooser above us in the decoding tree.
Craig Topper501d95c2012-03-16 06:52:56 +0000325 const FilterChooser *Parent;
Owen Anderson4e818902011-02-18 21:51:29 +0000326
327 // Index of the best filter from Filters.
328 int BestIndex;
329
Owen Andersonc78e03c2011-07-19 21:06:00 +0000330 // Width of instructions
331 unsigned BitWidth;
332
Owen Andersona4043c42011-08-17 17:44:15 +0000333 // Parent emitter
334 const FixedLenDecoderEmitter *Emitter;
335
Craig Topper5c2b4ac2014-09-03 05:49:07 +0000336 FilterChooser(const FilterChooser &) LLVM_DELETED_FUNCTION;
337 void operator=(const FilterChooser &) LLVM_DELETED_FUNCTION;
Owen Anderson4e818902011-02-18 21:51:29 +0000338public:
Owen Anderson4e818902011-02-18 21:51:29 +0000339
340 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
341 const std::vector<unsigned> &IDs,
Craig Topper501d95c2012-03-16 06:52:56 +0000342 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
Owen Andersona4043c42011-08-17 17:44:15 +0000343 unsigned BW,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000344 const FixedLenDecoderEmitter *E)
345 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
Craig Topper1ddc2882014-09-04 04:49:03 +0000346 FilterBitValues(BW, BIT_UNFILTERED), Parent(nullptr), BestIndex(-1),
347 BitWidth(BW), Emitter(E) {
Owen Anderson4e818902011-02-18 21:51:29 +0000348 doFilter();
349 }
350
351 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
352 const std::vector<unsigned> &IDs,
Craig Topper501d95c2012-03-16 06:52:56 +0000353 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
354 const std::vector<bit_value_t> &ParentFilterBitValues,
355 const FilterChooser &parent)
Craig Topper82d0d5f2012-03-16 01:19:24 +0000356 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
Owen Andersonc78e03c2011-07-19 21:06:00 +0000357 Filters(), FilterBitValues(ParentFilterBitValues),
Owen Andersona4043c42011-08-17 17:44:15 +0000358 Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
359 Emitter(parent.Emitter) {
Owen Anderson4e818902011-02-18 21:51:29 +0000360 doFilter();
361 }
362
Jim Grosbachecaef492012-08-14 19:06:05 +0000363 unsigned getBitWidth() const { return BitWidth; }
Owen Anderson4e818902011-02-18 21:51:29 +0000364
365protected:
366 // Populates the insn given the uid.
367 void insnWithID(insn_t &Insn, unsigned Opcode) const {
David Greeneaf8ee2c2011-07-29 22:43:06 +0000368 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
Owen Anderson4e818902011-02-18 21:51:29 +0000369
James Molloyd9ba4fd2012-02-09 10:56:31 +0000370 // We may have a SoftFail bitmask, which specifies a mask where an encoding
371 // may differ from the value in "Inst" and yet still be valid, but the
372 // disassembler should return SoftFail instead of Success.
373 //
374 // This is used for marking UNPREDICTABLE instructions in the ARM world.
Jim Grosbach3f4b2392012-02-29 22:07:56 +0000375 BitsInit *SFBits =
376 AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
James Molloyd9ba4fd2012-02-09 10:56:31 +0000377
378 for (unsigned i = 0; i < BitWidth; ++i) {
379 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
380 Insn.push_back(BIT_UNSET);
381 else
382 Insn.push_back(bitFromBits(Bits, i));
383 }
Owen Anderson4e818902011-02-18 21:51:29 +0000384 }
385
386 // Returns the record name.
387 const std::string &nameWithID(unsigned Opcode) const {
388 return AllInstructions[Opcode]->TheDef->getName();
389 }
390
391 // Populates the field of the insn given the start position and the number of
392 // consecutive bits to scan for.
393 //
394 // Returns false if there exists any uninitialized bit value in the range.
395 // Returns true, otherwise.
396 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000397 unsigned NumBits) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000398
399 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
400 /// filter array as a series of chars.
Craig Topper48c112b2012-03-16 05:58:09 +0000401 void dumpFilterArray(raw_ostream &o,
402 const std::vector<bit_value_t> & filter) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000403
404 /// dumpStack - dumpStack traverses the filter chooser chain and calls
405 /// dumpFilterArray on each filter chooser up to the top level one.
Craig Topper48c112b2012-03-16 05:58:09 +0000406 void dumpStack(raw_ostream &o, const char *prefix) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000407
408 Filter &bestFilter() {
409 assert(BestIndex != -1 && "BestIndex not set");
410 return Filters[BestIndex];
411 }
412
413 // Called from Filter::recurse() when singleton exists. For debug purpose.
Craig Topper48c112b2012-03-16 05:58:09 +0000414 void SingletonExists(unsigned Opc) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000415
Craig Topper48c112b2012-03-16 05:58:09 +0000416 bool PositionFiltered(unsigned i) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000417 return ValueSet(FilterBitValues[i]);
418 }
419
420 // Calculates the island(s) needed to decode the instruction.
421 // This returns a lit of undecoded bits of an instructions, for example,
422 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
423 // decoded bits in order to verify that the instruction matches the Opcode.
424 unsigned getIslands(std::vector<unsigned> &StartBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000425 std::vector<unsigned> &EndBits,
Craig Topper48c112b2012-03-16 05:58:09 +0000426 std::vector<uint64_t> &FieldVals,
427 const insn_t &Insn) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000428
James Molloy8067df92011-09-07 19:42:28 +0000429 // Emits code to check the Predicates member of an instruction are true.
430 // Returns true if predicate matches were emitted, false otherwise.
Craig Topper48c112b2012-03-16 05:58:09 +0000431 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
432 unsigned Opc) const;
James Molloy8067df92011-09-07 19:42:28 +0000433
Jim Grosbachecaef492012-08-14 19:06:05 +0000434 bool doesOpcodeNeedPredicate(unsigned Opc) const;
435 unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
436 void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
437 unsigned Opc) const;
James Molloyd9ba4fd2012-02-09 10:56:31 +0000438
Jim Grosbachecaef492012-08-14 19:06:05 +0000439 void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
440 unsigned Opc) const;
441
442 // Emits table entries to decode the singleton.
443 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
444 unsigned Opc) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000445
446 // Emits code to decode the singleton, and then to decode the rest.
Jim Grosbachecaef492012-08-14 19:06:05 +0000447 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
448 const Filter &Best) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000449
Jim Grosbachecaef492012-08-14 19:06:05 +0000450 void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
Craig Topper48c112b2012-03-16 05:58:09 +0000451 const OperandInfo &OpInfo) const;
Owen Andersone3591652011-07-28 21:54:31 +0000452
Jim Grosbachecaef492012-08-14 19:06:05 +0000453 void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc) const;
454 unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc) const;
455
Owen Anderson4e818902011-02-18 21:51:29 +0000456 // Assign a single filter and run with it.
Craig Topper48c112b2012-03-16 05:58:09 +0000457 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
Owen Anderson4e818902011-02-18 21:51:29 +0000458
459 // reportRegion is a helper function for filterProcessor to mark a region as
460 // eligible for use as a filter region.
461 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000462 bool AllowMixed);
Owen Anderson4e818902011-02-18 21:51:29 +0000463
464 // FilterProcessor scans the well-known encoding bits of the instructions and
465 // builds up a list of candidate filters. It chooses the best filter and
466 // recursively descends down the decoding tree.
467 bool filterProcessor(bool AllowMixed, bool Greedy = true);
468
469 // Decides on the best configuration of filter(s) to use in order to decode
470 // the instructions. A conflict of instructions may occur, in which case we
471 // dump the conflict set to the standard error.
472 void doFilter();
473
Jim Grosbachecaef492012-08-14 19:06:05 +0000474public:
475 // emitTableEntries - Emit state machine entries to decode our share of
476 // instructions.
477 void emitTableEntries(DecoderTableInfo &TableInfo) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000478};
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000479} // End anonymous namespace
Owen Anderson4e818902011-02-18 21:51:29 +0000480
481///////////////////////////
482// //
Craig Topper93e64342012-03-16 00:56:01 +0000483// Filter Implementation //
Owen Anderson4e818902011-02-18 21:51:29 +0000484// //
485///////////////////////////
486
Craig Topper5c2b4ac2014-09-03 05:49:07 +0000487Filter::Filter(Filter &&f)
Craig Topper82d0d5f2012-03-16 01:19:24 +0000488 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
Craig Topper5c2b4ac2014-09-03 05:49:07 +0000489 FilteredInstructions(std::move(f.FilteredInstructions)),
490 VariableInstructions(std::move(f.VariableInstructions)),
491 FilterChooserMap(std::move(f.FilterChooserMap)), NumFiltered(f.NumFiltered),
Craig Topper82d0d5f2012-03-16 01:19:24 +0000492 LastOpcFiltered(f.LastOpcFiltered) {
Owen Anderson4e818902011-02-18 21:51:29 +0000493}
494
495Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000496 bool mixed)
497 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
Owen Andersonc78e03c2011-07-19 21:06:00 +0000498 assert(StartBit + NumBits - 1 < Owner->BitWidth);
Owen Anderson4e818902011-02-18 21:51:29 +0000499
500 NumFiltered = 0;
501 LastOpcFiltered = 0;
Owen Anderson4e818902011-02-18 21:51:29 +0000502
503 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
504 insn_t Insn;
505
506 // Populates the insn given the uid.
507 Owner->insnWithID(Insn, Owner->Opcodes[i]);
508
509 uint64_t Field;
510 // Scans the segment for possibly well-specified encoding bits.
511 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
512
513 if (ok) {
514 // The encoding bits are well-known. Lets add the uid of the
515 // instruction into the bucket keyed off the constant field value.
516 LastOpcFiltered = Owner->Opcodes[i];
517 FilteredInstructions[Field].push_back(LastOpcFiltered);
518 ++NumFiltered;
519 } else {
Craig Topper93e64342012-03-16 00:56:01 +0000520 // Some of the encoding bit(s) are unspecified. This contributes to
Owen Anderson4e818902011-02-18 21:51:29 +0000521 // one additional member of "Variable" instructions.
522 VariableInstructions.push_back(Owner->Opcodes[i]);
Owen Anderson4e818902011-02-18 21:51:29 +0000523 }
524 }
525
526 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
527 && "Filter returns no instruction categories");
528}
529
530Filter::~Filter() {
Owen Anderson4e818902011-02-18 21:51:29 +0000531}
532
533// Divides the decoding task into sub tasks and delegates them to the
534// inferior FilterChooser's.
535//
536// A special case arises when there's only one entry in the filtered
537// instructions. In order to unambiguously decode the singleton, we need to
538// match the remaining undecoded encoding bits against the singleton.
539void Filter::recurse() {
540 std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
541
Owen Anderson4e818902011-02-18 21:51:29 +0000542 // Starts by inheriting our parent filter chooser's filter bit values.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000543 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
Owen Anderson4e818902011-02-18 21:51:29 +0000544
Owen Anderson4e818902011-02-18 21:51:29 +0000545 if (VariableInstructions.size()) {
546 // Conservatively marks each segment position as BIT_UNSET.
Craig Topper29688ab2012-08-17 05:42:16 +0000547 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
Owen Anderson4e818902011-02-18 21:51:29 +0000548 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
549
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000550 // Delegates to an inferior filter chooser for further processing on this
Owen Anderson4e818902011-02-18 21:51:29 +0000551 // group of instructions whose segment values are variable.
Yaron Kerene499db02014-09-03 08:22:30 +0000552 FilterChooserMap.insert(
553 std::make_pair(-1U, llvm::make_unique<FilterChooser>(
554 Owner->AllInstructions, VariableInstructions,
555 Owner->Operands, BitValueArray, *Owner)));
Owen Anderson4e818902011-02-18 21:51:29 +0000556 }
557
558 // No need to recurse for a singleton filtered instruction.
Jim Grosbachecaef492012-08-14 19:06:05 +0000559 // See also Filter::emit*().
Owen Anderson4e818902011-02-18 21:51:29 +0000560 if (getNumFiltered() == 1) {
561 //Owner->SingletonExists(LastOpcFiltered);
562 assert(FilterChooserMap.size() == 1);
563 return;
564 }
565
566 // Otherwise, create sub choosers.
567 for (mapIterator = FilteredInstructions.begin();
568 mapIterator != FilteredInstructions.end();
569 mapIterator++) {
570
571 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
Craig Topper29688ab2012-08-17 05:42:16 +0000572 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +0000573 if (mapIterator->first & (1ULL << bitIndex))
574 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
575 else
576 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
577 }
578
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000579 // Delegates to an inferior filter chooser for further processing on this
Owen Anderson4e818902011-02-18 21:51:29 +0000580 // category of instructions.
Craig Toppercf05f912014-09-03 06:07:54 +0000581 FilterChooserMap.insert(std::make_pair(
Yaron Kerene499db02014-09-03 08:22:30 +0000582 mapIterator->first, llvm::make_unique<FilterChooser>(
583 Owner->AllInstructions, mapIterator->second,
584 Owner->Operands, BitValueArray, *Owner)));
Owen Anderson4e818902011-02-18 21:51:29 +0000585 }
586}
587
Jim Grosbachecaef492012-08-14 19:06:05 +0000588static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
589 uint32_t DestIdx) {
590 // Any NumToSkip fixups in the current scope can resolve to the
591 // current location.
592 for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
593 E = Fixups.rend();
594 I != E; ++I) {
595 // Calculate the distance from the byte following the fixup entry byte
596 // to the destination. The Target is calculated from after the 16-bit
597 // NumToSkip entry itself, so subtract two from the displacement here
598 // to account for that.
599 uint32_t FixupIdx = *I;
600 uint32_t Delta = DestIdx - FixupIdx - 2;
601 // Our NumToSkip entries are 16-bits. Make sure our table isn't too
602 // big.
603 assert(Delta < 65536U && "disassembler decoding table too large!");
604 Table[FixupIdx] = (uint8_t)Delta;
605 Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
606 }
607}
Owen Anderson4e818902011-02-18 21:51:29 +0000608
Jim Grosbachecaef492012-08-14 19:06:05 +0000609// Emit table entries to decode instructions given a segment or segments
610// of bits.
611void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
612 TableInfo.Table.push_back(MCD::OPC_ExtractField);
613 TableInfo.Table.push_back(StartBit);
614 TableInfo.Table.push_back(NumBits);
Owen Anderson4e818902011-02-18 21:51:29 +0000615
Jim Grosbachecaef492012-08-14 19:06:05 +0000616 // A new filter entry begins a new scope for fixup resolution.
617 TableInfo.FixupStack.push_back(FixupList());
Owen Anderson4e818902011-02-18 21:51:29 +0000618
Craig Toppercf05f912014-09-03 06:07:54 +0000619 std::map<unsigned,
620 std::unique_ptr<const FilterChooser>>::const_iterator filterIterator;
Owen Anderson4e818902011-02-18 21:51:29 +0000621
Jim Grosbachecaef492012-08-14 19:06:05 +0000622 DecoderTable &Table = TableInfo.Table;
623
624 size_t PrevFilter = 0;
625 bool HasFallthrough = false;
Owen Anderson4e818902011-02-18 21:51:29 +0000626 for (filterIterator = FilterChooserMap.begin();
627 filterIterator != FilterChooserMap.end();
628 filterIterator++) {
Owen Anderson4e818902011-02-18 21:51:29 +0000629 // Field value -1 implies a non-empty set of variable instructions.
630 // See also recurse().
631 if (filterIterator->first == (unsigned)-1) {
Jim Grosbachecaef492012-08-14 19:06:05 +0000632 HasFallthrough = true;
Owen Anderson4e818902011-02-18 21:51:29 +0000633
Jim Grosbachecaef492012-08-14 19:06:05 +0000634 // Each scope should always have at least one filter value to check
635 // for.
636 assert(PrevFilter != 0 && "empty filter set!");
637 FixupList &CurScope = TableInfo.FixupStack.back();
638 // Resolve any NumToSkip fixups in the current scope.
639 resolveTableFixups(Table, CurScope, Table.size());
640 CurScope.clear();
641 PrevFilter = 0; // Don't re-process the filter's fallthrough.
642 } else {
643 Table.push_back(MCD::OPC_FilterValue);
644 // Encode and emit the value to filter against.
645 uint8_t Buffer[8];
646 unsigned Len = encodeULEB128(filterIterator->first, Buffer);
647 Table.insert(Table.end(), Buffer, Buffer + Len);
648 // Reserve space for the NumToSkip entry. We'll backpatch the value
649 // later.
650 PrevFilter = Table.size();
651 Table.push_back(0);
652 Table.push_back(0);
653 }
Owen Anderson4e818902011-02-18 21:51:29 +0000654
655 // We arrive at a category of instructions with the same segment value.
656 // Now delegate to the sub filter chooser for further decodings.
657 // The case may fallthrough, which happens if the remaining well-known
658 // encoding bits do not match exactly.
Jim Grosbachecaef492012-08-14 19:06:05 +0000659 filterIterator->second->emitTableEntries(TableInfo);
Owen Anderson4e818902011-02-18 21:51:29 +0000660
Jim Grosbachecaef492012-08-14 19:06:05 +0000661 // Now that we've emitted the body of the handler, update the NumToSkip
662 // of the filter itself to be able to skip forward when false. Subtract
663 // two as to account for the width of the NumToSkip field itself.
664 if (PrevFilter) {
665 uint32_t NumToSkip = Table.size() - PrevFilter - 2;
666 assert(NumToSkip < 65536U && "disassembler decoding table too large!");
667 Table[PrevFilter] = (uint8_t)NumToSkip;
668 Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
669 }
Owen Anderson4e818902011-02-18 21:51:29 +0000670 }
671
Jim Grosbachecaef492012-08-14 19:06:05 +0000672 // Any remaining unresolved fixups bubble up to the parent fixup scope.
673 assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
674 FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
675 FixupScopeList::iterator Dest = Source - 1;
676 Dest->insert(Dest->end(), Source->begin(), Source->end());
677 TableInfo.FixupStack.pop_back();
678
679 // If there is no fallthrough, then the final filter should get fixed
680 // up according to the enclosing scope rather than the current position.
681 if (!HasFallthrough)
682 TableInfo.FixupStack.back().push_back(PrevFilter);
Owen Anderson4e818902011-02-18 21:51:29 +0000683}
684
685// Returns the number of fanout produced by the filter. More fanout implies
686// the filter distinguishes more categories of instructions.
687unsigned Filter::usefulness() const {
688 if (VariableInstructions.size())
689 return FilteredInstructions.size();
690 else
691 return FilteredInstructions.size() + 1;
692}
693
694//////////////////////////////////
695// //
696// Filterchooser Implementation //
697// //
698//////////////////////////////////
699
Jim Grosbachecaef492012-08-14 19:06:05 +0000700// Emit the decoder state machine table.
701void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
702 DecoderTable &Table,
703 unsigned Indentation,
704 unsigned BitWidth,
705 StringRef Namespace) const {
706 OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
707 << BitWidth << "[] = {\n";
Owen Anderson4e818902011-02-18 21:51:29 +0000708
Jim Grosbachecaef492012-08-14 19:06:05 +0000709 Indentation += 2;
Owen Anderson4e818902011-02-18 21:51:29 +0000710
Jim Grosbachecaef492012-08-14 19:06:05 +0000711 // FIXME: We may be able to use the NumToSkip values to recover
712 // appropriate indentation levels.
713 DecoderTable::const_iterator I = Table.begin();
714 DecoderTable::const_iterator E = Table.end();
715 while (I != E) {
716 assert (I < E && "incomplete decode table entry!");
Owen Anderson4e818902011-02-18 21:51:29 +0000717
Jim Grosbachecaef492012-08-14 19:06:05 +0000718 uint64_t Pos = I - Table.begin();
719 OS << "/* " << Pos << " */";
720 OS.PadToColumn(12);
Owen Anderson4e818902011-02-18 21:51:29 +0000721
Jim Grosbachecaef492012-08-14 19:06:05 +0000722 switch (*I) {
723 default:
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000724 PrintFatalError("invalid decode table opcode");
Jim Grosbachecaef492012-08-14 19:06:05 +0000725 case MCD::OPC_ExtractField: {
726 ++I;
727 unsigned Start = *I++;
728 unsigned Len = *I++;
729 OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
730 << Len << ", // Inst{";
731 if (Len > 1)
732 OS << (Start + Len - 1) << "-";
733 OS << Start << "} ...\n";
734 break;
735 }
736 case MCD::OPC_FilterValue: {
737 ++I;
738 OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
739 // The filter value is ULEB128 encoded.
740 while (*I >= 128)
741 OS << utostr(*I++) << ", ";
742 OS << utostr(*I++) << ", ";
743
744 // 16-bit numtoskip value.
745 uint8_t Byte = *I++;
746 uint32_t NumToSkip = Byte;
747 OS << utostr(Byte) << ", ";
748 Byte = *I++;
749 OS << utostr(Byte) << ", ";
750 NumToSkip |= Byte << 8;
751 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
752 break;
753 }
754 case MCD::OPC_CheckField: {
755 ++I;
756 unsigned Start = *I++;
757 unsigned Len = *I++;
758 OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
759 << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
760 // ULEB128 encoded field value.
761 for (; *I >= 128; ++I)
762 OS << utostr(*I) << ", ";
763 OS << utostr(*I++) << ", ";
764 // 16-bit numtoskip value.
765 uint8_t Byte = *I++;
766 uint32_t NumToSkip = Byte;
767 OS << utostr(Byte) << ", ";
768 Byte = *I++;
769 OS << utostr(Byte) << ", ";
770 NumToSkip |= Byte << 8;
771 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
772 break;
773 }
774 case MCD::OPC_CheckPredicate: {
775 ++I;
776 OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
777 for (; *I >= 128; ++I)
778 OS << utostr(*I) << ", ";
779 OS << utostr(*I++) << ", ";
780
781 // 16-bit numtoskip value.
782 uint8_t Byte = *I++;
783 uint32_t NumToSkip = Byte;
784 OS << utostr(Byte) << ", ";
785 Byte = *I++;
786 OS << utostr(Byte) << ", ";
787 NumToSkip |= Byte << 8;
788 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
789 break;
790 }
791 case MCD::OPC_Decode: {
792 ++I;
793 // Extract the ULEB128 encoded Opcode to a buffer.
794 uint8_t Buffer[8], *p = Buffer;
795 while ((*p++ = *I++) >= 128)
796 assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
797 && "ULEB128 value too large!");
798 // Decode the Opcode value.
799 unsigned Opc = decodeULEB128(Buffer);
800 OS.indent(Indentation) << "MCD::OPC_Decode, ";
801 for (p = Buffer; *p >= 128; ++p)
802 OS << utostr(*p) << ", ";
803 OS << utostr(*p) << ", ";
804
805 // Decoder index.
806 for (; *I >= 128; ++I)
807 OS << utostr(*I) << ", ";
808 OS << utostr(*I++) << ", ";
809
810 OS << "// Opcode: "
811 << NumberedInstructions->at(Opc)->TheDef->getName() << "\n";
812 break;
813 }
814 case MCD::OPC_SoftFail: {
815 ++I;
816 OS.indent(Indentation) << "MCD::OPC_SoftFail";
817 // Positive mask
818 uint64_t Value = 0;
819 unsigned Shift = 0;
820 do {
821 OS << ", " << utostr(*I);
822 Value += (*I & 0x7f) << Shift;
823 Shift += 7;
824 } while (*I++ >= 128);
825 if (Value > 127)
826 OS << " /* 0x" << utohexstr(Value) << " */";
827 // Negative mask
828 Value = 0;
829 Shift = 0;
830 do {
831 OS << ", " << utostr(*I);
832 Value += (*I & 0x7f) << Shift;
833 Shift += 7;
834 } while (*I++ >= 128);
835 if (Value > 127)
836 OS << " /* 0x" << utohexstr(Value) << " */";
837 OS << ",\n";
838 break;
839 }
840 case MCD::OPC_Fail: {
841 ++I;
842 OS.indent(Indentation) << "MCD::OPC_Fail,\n";
843 break;
844 }
845 }
846 }
847 OS.indent(Indentation) << "0\n";
848
849 Indentation -= 2;
850
851 OS.indent(Indentation) << "};\n\n";
852}
853
854void FixedLenDecoderEmitter::
855emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
856 unsigned Indentation) const {
857 // The predicate function is just a big switch statement based on the
858 // input predicate index.
859 OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
860 << "uint64_t Bits) {\n";
861 Indentation += 2;
Aaron Ballmane59e3582013-07-15 16:53:32 +0000862 if (!Predicates.empty()) {
863 OS.indent(Indentation) << "switch (Idx) {\n";
864 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
865 unsigned Index = 0;
866 for (PredicateSet::const_iterator I = Predicates.begin(), E = Predicates.end();
867 I != E; ++I, ++Index) {
868 OS.indent(Indentation) << "case " << Index << ":\n";
869 OS.indent(Indentation+2) << "return (" << *I << ");\n";
870 }
871 OS.indent(Indentation) << "}\n";
872 } else {
873 // No case statement to emit
874 OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000875 }
Jim Grosbachecaef492012-08-14 19:06:05 +0000876 Indentation -= 2;
877 OS.indent(Indentation) << "}\n\n";
878}
879
880void FixedLenDecoderEmitter::
881emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
882 unsigned Indentation) const {
883 // The decoder function is just a big switch statement based on the
884 // input decoder index.
885 OS.indent(Indentation) << "template<typename InsnType>\n";
886 OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
887 << " unsigned Idx, InsnType insn, MCInst &MI,\n";
888 OS.indent(Indentation) << " uint64_t "
Benjamin Kramer26b568d2012-08-15 10:26:44 +0000889 << "Address, const void *Decoder) {\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000890 Indentation += 2;
891 OS.indent(Indentation) << "InsnType tmp;\n";
892 OS.indent(Indentation) << "switch (Idx) {\n";
893 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
894 unsigned Index = 0;
895 for (DecoderSet::const_iterator I = Decoders.begin(), E = Decoders.end();
896 I != E; ++I, ++Index) {
897 OS.indent(Indentation) << "case " << Index << ":\n";
Craig Topperebc3aa22012-08-17 05:16:15 +0000898 OS << *I;
Jim Grosbachecaef492012-08-14 19:06:05 +0000899 OS.indent(Indentation+2) << "return S;\n";
900 }
901 OS.indent(Indentation) << "}\n";
902 Indentation -= 2;
903 OS.indent(Indentation) << "}\n\n";
Owen Anderson4e818902011-02-18 21:51:29 +0000904}
905
906// Populates the field of the insn given the start position and the number of
907// consecutive bits to scan for.
908//
909// Returns false if and on the first uninitialized bit value encountered.
910// Returns true, otherwise.
911bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
Craig Topper48c112b2012-03-16 05:58:09 +0000912 unsigned StartBit, unsigned NumBits) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000913 Field = 0;
914
915 for (unsigned i = 0; i < NumBits; ++i) {
916 if (Insn[StartBit + i] == BIT_UNSET)
917 return false;
918
919 if (Insn[StartBit + i] == BIT_TRUE)
920 Field = Field | (1ULL << i);
921 }
922
923 return true;
924}
925
926/// dumpFilterArray - dumpFilterArray prints out debugging info for the given
927/// filter array as a series of chars.
928void FilterChooser::dumpFilterArray(raw_ostream &o,
Craig Topper48c112b2012-03-16 05:58:09 +0000929 const std::vector<bit_value_t> &filter) const {
Craig Topper29688ab2012-08-17 05:42:16 +0000930 for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
Owen Anderson4e818902011-02-18 21:51:29 +0000931 switch (filter[bitIndex - 1]) {
932 case BIT_UNFILTERED:
933 o << ".";
934 break;
935 case BIT_UNSET:
936 o << "_";
937 break;
938 case BIT_TRUE:
939 o << "1";
940 break;
941 case BIT_FALSE:
942 o << "0";
943 break;
944 }
945 }
946}
947
948/// dumpStack - dumpStack traverses the filter chooser chain and calls
949/// dumpFilterArray on each filter chooser up to the top level one.
Craig Topper48c112b2012-03-16 05:58:09 +0000950void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
951 const FilterChooser *current = this;
Owen Anderson4e818902011-02-18 21:51:29 +0000952
953 while (current) {
954 o << prefix;
955 dumpFilterArray(o, current->FilterBitValues);
956 o << '\n';
957 current = current->Parent;
958 }
959}
960
961// Called from Filter::recurse() when singleton exists. For debug purpose.
Craig Topper48c112b2012-03-16 05:58:09 +0000962void FilterChooser::SingletonExists(unsigned Opc) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000963 insn_t Insn0;
964 insnWithID(Insn0, Opc);
965
966 errs() << "Singleton exists: " << nameWithID(Opc)
967 << " with its decoding dominating ";
968 for (unsigned i = 0; i < Opcodes.size(); ++i) {
969 if (Opcodes[i] == Opc) continue;
970 errs() << nameWithID(Opcodes[i]) << ' ';
971 }
972 errs() << '\n';
973
974 dumpStack(errs(), "\t\t");
Craig Topper82d0d5f2012-03-16 01:19:24 +0000975 for (unsigned i = 0; i < Opcodes.size(); ++i) {
Owen Anderson4e818902011-02-18 21:51:29 +0000976 const std::string &Name = nameWithID(Opcodes[i]);
977
978 errs() << '\t' << Name << " ";
979 dumpBits(errs(),
980 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
981 errs() << '\n';
982 }
983}
984
985// Calculates the island(s) needed to decode the instruction.
986// This returns a list of undecoded bits of an instructions, for example,
987// Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
988// decoded bits in order to verify that the instruction matches the Opcode.
989unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000990 std::vector<unsigned> &EndBits,
991 std::vector<uint64_t> &FieldVals,
Craig Topper48c112b2012-03-16 05:58:09 +0000992 const insn_t &Insn) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000993 unsigned Num, BitNo;
994 Num = BitNo = 0;
995
996 uint64_t FieldVal = 0;
997
998 // 0: Init
999 // 1: Water (the bit value does not affect decoding)
1000 // 2: Island (well-known bit value needed for decoding)
1001 int State = 0;
1002 int Val = -1;
1003
Owen Andersonc78e03c2011-07-19 21:06:00 +00001004 for (unsigned i = 0; i < BitWidth; ++i) {
Owen Anderson4e818902011-02-18 21:51:29 +00001005 Val = Value(Insn[i]);
1006 bool Filtered = PositionFiltered(i);
1007 switch (State) {
Craig Topperc4965bc2012-02-05 07:21:30 +00001008 default: llvm_unreachable("Unreachable code!");
Owen Anderson4e818902011-02-18 21:51:29 +00001009 case 0:
1010 case 1:
1011 if (Filtered || Val == -1)
1012 State = 1; // Still in Water
1013 else {
1014 State = 2; // Into the Island
1015 BitNo = 0;
1016 StartBits.push_back(i);
1017 FieldVal = Val;
1018 }
1019 break;
1020 case 2:
1021 if (Filtered || Val == -1) {
1022 State = 1; // Into the Water
1023 EndBits.push_back(i - 1);
1024 FieldVals.push_back(FieldVal);
1025 ++Num;
1026 } else {
1027 State = 2; // Still in Island
1028 ++BitNo;
1029 FieldVal = FieldVal | Val << BitNo;
1030 }
1031 break;
1032 }
1033 }
1034 // If we are still in Island after the loop, do some housekeeping.
1035 if (State == 2) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00001036 EndBits.push_back(BitWidth - 1);
Owen Anderson4e818902011-02-18 21:51:29 +00001037 FieldVals.push_back(FieldVal);
1038 ++Num;
1039 }
1040
1041 assert(StartBits.size() == Num && EndBits.size() == Num &&
1042 FieldVals.size() == Num);
1043 return Num;
1044}
1045
Owen Andersone3591652011-07-28 21:54:31 +00001046void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
Craig Topper48c112b2012-03-16 05:58:09 +00001047 const OperandInfo &OpInfo) const {
1048 const std::string &Decoder = OpInfo.Decoder;
Owen Andersone3591652011-07-28 21:54:31 +00001049
1050 if (OpInfo.numFields() == 1) {
Craig Topper48c112b2012-03-16 05:58:09 +00001051 OperandInfo::const_iterator OI = OpInfo.begin();
Craig Topperebc3aa22012-08-17 05:16:15 +00001052 o.indent(Indentation) << "tmp = fieldFromInstruction"
Jim Grosbachecaef492012-08-14 19:06:05 +00001053 << "(insn, " << OI->Base << ", " << OI->Width
1054 << ");\n";
Owen Andersone3591652011-07-28 21:54:31 +00001055 } else {
Craig Topperebc3aa22012-08-17 05:16:15 +00001056 o.indent(Indentation) << "tmp = 0;\n";
Craig Topper48c112b2012-03-16 05:58:09 +00001057 for (OperandInfo::const_iterator OI = OpInfo.begin(), OE = OpInfo.end();
Owen Andersone3591652011-07-28 21:54:31 +00001058 OI != OE; ++OI) {
Craig Topperebc3aa22012-08-17 05:16:15 +00001059 o.indent(Indentation) << "tmp |= (fieldFromInstruction"
Andrew Trick61abca62011-09-08 05:23:14 +00001060 << "(insn, " << OI->Base << ", " << OI->Width
Owen Andersone3591652011-07-28 21:54:31 +00001061 << ") << " << OI->Offset << ");\n";
1062 }
1063 }
1064
1065 if (Decoder != "")
Craig Topperebc3aa22012-08-17 05:16:15 +00001066 o.indent(Indentation) << Emitter->GuardPrefix << Decoder
Jim Grosbach3f4b2392012-02-29 22:07:56 +00001067 << "(MI, tmp, Address, Decoder)"
1068 << Emitter->GuardPostfix << "\n";
Owen Andersone3591652011-07-28 21:54:31 +00001069 else
Craig Topperebc3aa22012-08-17 05:16:15 +00001070 o.indent(Indentation) << "MI.addOperand(MCOperand::CreateImm(tmp));\n";
Owen Andersone3591652011-07-28 21:54:31 +00001071
1072}
1073
Jim Grosbachecaef492012-08-14 19:06:05 +00001074void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
1075 unsigned Opc) const {
1076 std::map<unsigned, std::vector<OperandInfo> >::const_iterator OpIter =
1077 Operands.find(Opc);
1078 const std::vector<OperandInfo>& InsnOperands = OpIter->second;
1079 for (std::vector<OperandInfo>::const_iterator
1080 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
1081 // If a custom instruction decoder was specified, use that.
1082 if (I->numFields() == 0 && I->Decoder.size()) {
Craig Topperebc3aa22012-08-17 05:16:15 +00001083 OS.indent(Indentation) << Emitter->GuardPrefix << I->Decoder
Jim Grosbachecaef492012-08-14 19:06:05 +00001084 << "(MI, insn, Address, Decoder)"
1085 << Emitter->GuardPostfix << "\n";
1086 break;
1087 }
1088
1089 emitBinaryParser(OS, Indentation, *I);
1090 }
1091}
1092
1093unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
1094 unsigned Opc) const {
1095 // Build up the predicate string.
1096 SmallString<256> Decoder;
1097 // FIXME: emitDecoder() function can take a buffer directly rather than
1098 // a stream.
1099 raw_svector_ostream S(Decoder);
Craig Topperebc3aa22012-08-17 05:16:15 +00001100 unsigned I = 4;
Jim Grosbachecaef492012-08-14 19:06:05 +00001101 emitDecoder(S, I, Opc);
1102 S.flush();
1103
1104 // Using the full decoder string as the key value here is a bit
1105 // heavyweight, but is effective. If the string comparisons become a
1106 // performance concern, we can implement a mangling of the predicate
1107 // data easilly enough with a map back to the actual string. That's
1108 // overkill for now, though.
1109
1110 // Make sure the predicate is in the table.
1111 Decoders.insert(Decoder.str());
1112 // Now figure out the index for when we write out the table.
1113 DecoderSet::const_iterator P = std::find(Decoders.begin(),
1114 Decoders.end(),
1115 Decoder.str());
1116 return (unsigned)(P - Decoders.begin());
1117}
1118
James Molloy8067df92011-09-07 19:42:28 +00001119static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
Craig Topper48c112b2012-03-16 05:58:09 +00001120 const std::string &PredicateNamespace) {
Andrew Trick43674ad2011-09-08 05:25:49 +00001121 if (str[0] == '!')
1122 o << "!(Bits & " << PredicateNamespace << "::"
1123 << str.slice(1,str.size()) << ")";
James Molloy8067df92011-09-07 19:42:28 +00001124 else
Andrew Trick43674ad2011-09-08 05:25:49 +00001125 o << "(Bits & " << PredicateNamespace << "::" << str << ")";
James Molloy8067df92011-09-07 19:42:28 +00001126}
1127
1128bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
Craig Topper48c112b2012-03-16 05:58:09 +00001129 unsigned Opc) const {
Jim Grosbach3f4b2392012-02-29 22:07:56 +00001130 ListInit *Predicates =
1131 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
James Molloy8067df92011-09-07 19:42:28 +00001132 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1133 Record *Pred = Predicates->getElementAsRecord(i);
1134 if (!Pred->getValue("AssemblerMatcherPredicate"))
1135 continue;
1136
1137 std::string P = Pred->getValueAsString("AssemblerCondString");
1138
1139 if (!P.length())
1140 continue;
1141
1142 if (i != 0)
1143 o << " && ";
1144
1145 StringRef SR(P);
1146 std::pair<StringRef, StringRef> pairs = SR.split(',');
1147 while (pairs.second.size()) {
1148 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1149 o << " && ";
1150 pairs = pairs.second.split(',');
1151 }
1152 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1153 }
1154 return Predicates->getSize() > 0;
Andrew Trick61abca62011-09-08 05:23:14 +00001155}
James Molloy8067df92011-09-07 19:42:28 +00001156
Jim Grosbachecaef492012-08-14 19:06:05 +00001157bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1158 ListInit *Predicates =
1159 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1160 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1161 Record *Pred = Predicates->getElementAsRecord(i);
1162 if (!Pred->getValue("AssemblerMatcherPredicate"))
1163 continue;
1164
1165 std::string P = Pred->getValueAsString("AssemblerCondString");
1166
1167 if (!P.length())
1168 continue;
1169
1170 return true;
1171 }
1172 return false;
1173}
1174
1175unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1176 StringRef Predicate) const {
1177 // Using the full predicate string as the key value here is a bit
1178 // heavyweight, but is effective. If the string comparisons become a
1179 // performance concern, we can implement a mangling of the predicate
1180 // data easilly enough with a map back to the actual string. That's
1181 // overkill for now, though.
1182
1183 // Make sure the predicate is in the table.
1184 TableInfo.Predicates.insert(Predicate.str());
1185 // Now figure out the index for when we write out the table.
1186 PredicateSet::const_iterator P = std::find(TableInfo.Predicates.begin(),
1187 TableInfo.Predicates.end(),
1188 Predicate.str());
1189 return (unsigned)(P - TableInfo.Predicates.begin());
1190}
1191
1192void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1193 unsigned Opc) const {
1194 if (!doesOpcodeNeedPredicate(Opc))
1195 return;
1196
1197 // Build up the predicate string.
1198 SmallString<256> Predicate;
1199 // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1200 // than a stream.
1201 raw_svector_ostream PS(Predicate);
1202 unsigned I = 0;
1203 emitPredicateMatch(PS, I, Opc);
1204
1205 // Figure out the index into the predicate table for the predicate just
1206 // computed.
1207 unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1208 SmallString<16> PBytes;
1209 raw_svector_ostream S(PBytes);
1210 encodeULEB128(PIdx, S);
1211 S.flush();
1212
1213 TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1214 // Predicate index
Craig Topper29688ab2012-08-17 05:42:16 +00001215 for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001216 TableInfo.Table.push_back(PBytes[i]);
1217 // Push location for NumToSkip backpatching.
1218 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1219 TableInfo.Table.push_back(0);
1220 TableInfo.Table.push_back(0);
1221}
1222
1223void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1224 unsigned Opc) const {
Jim Grosbach3f4b2392012-02-29 22:07:56 +00001225 BitsInit *SFBits =
1226 AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
James Molloyd9ba4fd2012-02-09 10:56:31 +00001227 if (!SFBits) return;
1228 BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
1229
1230 APInt PositiveMask(BitWidth, 0ULL);
1231 APInt NegativeMask(BitWidth, 0ULL);
1232 for (unsigned i = 0; i < BitWidth; ++i) {
1233 bit_value_t B = bitFromBits(*SFBits, i);
1234 bit_value_t IB = bitFromBits(*InstBits, i);
1235
1236 if (B != BIT_TRUE) continue;
1237
1238 switch (IB) {
1239 case BIT_FALSE:
1240 // The bit is meant to be false, so emit a check to see if it is true.
1241 PositiveMask.setBit(i);
1242 break;
1243 case BIT_TRUE:
1244 // The bit is meant to be true, so emit a check to see if it is false.
1245 NegativeMask.setBit(i);
1246 break;
1247 default:
1248 // The bit is not set; this must be an error!
1249 StringRef Name = AllInstructions[Opc]->TheDef->getName();
Jim Grosbachecaef492012-08-14 19:06:05 +00001250 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
1251 << " is set but Inst{" << i << "} is unset!\n"
James Molloyd9ba4fd2012-02-09 10:56:31 +00001252 << " - You can only mark a bit as SoftFail if it is fully defined"
1253 << " (1/0 - not '?') in Inst\n";
Jim Grosbachecaef492012-08-14 19:06:05 +00001254 return;
James Molloyd9ba4fd2012-02-09 10:56:31 +00001255 }
1256 }
1257
1258 bool NeedPositiveMask = PositiveMask.getBoolValue();
1259 bool NeedNegativeMask = NegativeMask.getBoolValue();
1260
1261 if (!NeedPositiveMask && !NeedNegativeMask)
1262 return;
1263
Jim Grosbachecaef492012-08-14 19:06:05 +00001264 TableInfo.Table.push_back(MCD::OPC_SoftFail);
James Molloyd9ba4fd2012-02-09 10:56:31 +00001265
Jim Grosbachecaef492012-08-14 19:06:05 +00001266 SmallString<16> MaskBytes;
1267 raw_svector_ostream S(MaskBytes);
1268 if (NeedPositiveMask) {
1269 encodeULEB128(PositiveMask.getZExtValue(), S);
1270 S.flush();
Craig Topper29688ab2012-08-17 05:42:16 +00001271 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001272 TableInfo.Table.push_back(MaskBytes[i]);
1273 } else
1274 TableInfo.Table.push_back(0);
1275 if (NeedNegativeMask) {
1276 MaskBytes.clear();
1277 S.resync();
1278 encodeULEB128(NegativeMask.getZExtValue(), S);
1279 S.flush();
Craig Topper29688ab2012-08-17 05:42:16 +00001280 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001281 TableInfo.Table.push_back(MaskBytes[i]);
1282 } else
1283 TableInfo.Table.push_back(0);
James Molloyd9ba4fd2012-02-09 10:56:31 +00001284}
1285
Jim Grosbachecaef492012-08-14 19:06:05 +00001286// Emits table entries to decode the singleton.
1287void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1288 unsigned Opc) const {
Owen Anderson4e818902011-02-18 21:51:29 +00001289 std::vector<unsigned> StartBits;
1290 std::vector<unsigned> EndBits;
1291 std::vector<uint64_t> FieldVals;
1292 insn_t Insn;
1293 insnWithID(Insn, Opc);
1294
1295 // Look for islands of undecoded bits of the singleton.
1296 getIslands(StartBits, EndBits, FieldVals, Insn);
1297
1298 unsigned Size = StartBits.size();
Owen Anderson4e818902011-02-18 21:51:29 +00001299
Jim Grosbachecaef492012-08-14 19:06:05 +00001300 // Emit the predicate table entry if one is needed.
1301 emitPredicateTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001302
Jim Grosbachecaef492012-08-14 19:06:05 +00001303 // Check any additional encoding fields needed.
Craig Topper29688ab2012-08-17 05:42:16 +00001304 for (unsigned I = Size; I != 0; --I) {
1305 unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
Jim Grosbachecaef492012-08-14 19:06:05 +00001306 TableInfo.Table.push_back(MCD::OPC_CheckField);
1307 TableInfo.Table.push_back(StartBits[I-1]);
1308 TableInfo.Table.push_back(NumBits);
1309 uint8_t Buffer[8], *p;
1310 encodeULEB128(FieldVals[I-1], Buffer);
1311 for (p = Buffer; *p >= 128 ; ++p)
1312 TableInfo.Table.push_back(*p);
1313 TableInfo.Table.push_back(*p);
1314 // Push location for NumToSkip backpatching.
1315 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1316 // The fixup is always 16-bits, so go ahead and allocate the space
1317 // in the table so all our relative position calculations work OK even
1318 // before we fully resolve the real value here.
1319 TableInfo.Table.push_back(0);
1320 TableInfo.Table.push_back(0);
Owen Anderson4e818902011-02-18 21:51:29 +00001321 }
Owen Anderson4e818902011-02-18 21:51:29 +00001322
Jim Grosbachecaef492012-08-14 19:06:05 +00001323 // Check for soft failure of the match.
1324 emitSoftFailTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001325
Jim Grosbachecaef492012-08-14 19:06:05 +00001326 TableInfo.Table.push_back(MCD::OPC_Decode);
1327 uint8_t Buffer[8], *p;
1328 encodeULEB128(Opc, Buffer);
1329 for (p = Buffer; *p >= 128 ; ++p)
1330 TableInfo.Table.push_back(*p);
1331 TableInfo.Table.push_back(*p);
1332
1333 unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc);
1334 SmallString<16> Bytes;
1335 raw_svector_ostream S(Bytes);
1336 encodeULEB128(DIdx, S);
1337 S.flush();
1338
1339 // Decoder index
Craig Topper29688ab2012-08-17 05:42:16 +00001340 for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001341 TableInfo.Table.push_back(Bytes[i]);
Owen Anderson4e818902011-02-18 21:51:29 +00001342}
1343
Jim Grosbachecaef492012-08-14 19:06:05 +00001344// Emits table entries to decode the singleton, and then to decode the rest.
1345void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1346 const Filter &Best) const {
Owen Anderson4e818902011-02-18 21:51:29 +00001347 unsigned Opc = Best.getSingletonOpc();
1348
Jim Grosbachecaef492012-08-14 19:06:05 +00001349 // complex singletons need predicate checks from the first singleton
1350 // to refer forward to the variable filterchooser that follows.
1351 TableInfo.FixupStack.push_back(FixupList());
Owen Anderson4e818902011-02-18 21:51:29 +00001352
Jim Grosbachecaef492012-08-14 19:06:05 +00001353 emitSingletonTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001354
Jim Grosbachecaef492012-08-14 19:06:05 +00001355 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1356 TableInfo.Table.size());
1357 TableInfo.FixupStack.pop_back();
1358
1359 Best.getVariableFC().emitTableEntries(TableInfo);
Owen Anderson4e818902011-02-18 21:51:29 +00001360}
1361
Jim Grosbachecaef492012-08-14 19:06:05 +00001362
Owen Anderson4e818902011-02-18 21:51:29 +00001363// Assign a single filter and run with it. Top level API client can initialize
1364// with a single filter to start the filtering process.
Craig Topper48c112b2012-03-16 05:58:09 +00001365void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1366 bool mixed) {
Owen Anderson4e818902011-02-18 21:51:29 +00001367 Filters.clear();
Craig Topper5c2b4ac2014-09-03 05:49:07 +00001368 Filters.push_back(Filter(*this, startBit, numBit, true));
Owen Anderson4e818902011-02-18 21:51:29 +00001369 BestIndex = 0; // Sole Filter instance to choose from.
1370 bestFilter().recurse();
1371}
1372
1373// reportRegion is a helper function for filterProcessor to mark a region as
1374// eligible for use as a filter region.
1375void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
Craig Topper82d0d5f2012-03-16 01:19:24 +00001376 unsigned BitIndex, bool AllowMixed) {
Owen Anderson4e818902011-02-18 21:51:29 +00001377 if (RA == ATTR_MIXED && AllowMixed)
1378 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
1379 else if (RA == ATTR_ALL_SET && !AllowMixed)
1380 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
1381}
1382
1383// FilterProcessor scans the well-known encoding bits of the instructions and
1384// builds up a list of candidate filters. It chooses the best filter and
1385// recursively descends down the decoding tree.
1386bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1387 Filters.clear();
1388 BestIndex = -1;
1389 unsigned numInstructions = Opcodes.size();
1390
1391 assert(numInstructions && "Filter created with no instructions");
1392
1393 // No further filtering is necessary.
1394 if (numInstructions == 1)
1395 return true;
1396
1397 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1398 // instructions is 3.
1399 if (AllowMixed && !Greedy) {
1400 assert(numInstructions == 3);
1401
1402 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1403 std::vector<unsigned> StartBits;
1404 std::vector<unsigned> EndBits;
1405 std::vector<uint64_t> FieldVals;
1406 insn_t Insn;
1407
1408 insnWithID(Insn, Opcodes[i]);
1409
1410 // Look for islands of undecoded bits of any instruction.
1411 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1412 // Found an instruction with island(s). Now just assign a filter.
Craig Topper48c112b2012-03-16 05:58:09 +00001413 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
Owen Anderson4e818902011-02-18 21:51:29 +00001414 return true;
1415 }
1416 }
1417 }
1418
Craig Topper29688ab2012-08-17 05:42:16 +00001419 unsigned BitIndex;
Owen Anderson4e818902011-02-18 21:51:29 +00001420
1421 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1422 // The automaton consumes the corresponding bit from each
1423 // instruction.
1424 //
1425 // Input symbols: 0, 1, and _ (unset).
1426 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1427 // Initial state: NONE.
1428 //
1429 // (NONE) ------- [01] -> (ALL_SET)
1430 // (NONE) ------- _ ----> (ALL_UNSET)
1431 // (ALL_SET) ---- [01] -> (ALL_SET)
1432 // (ALL_SET) ---- _ ----> (MIXED)
1433 // (ALL_UNSET) -- [01] -> (MIXED)
1434 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1435 // (MIXED) ------ . ----> (MIXED)
1436 // (FILTERED)---- . ----> (FILTERED)
1437
Owen Andersonc78e03c2011-07-19 21:06:00 +00001438 std::vector<bitAttr_t> bitAttrs;
Owen Anderson4e818902011-02-18 21:51:29 +00001439
1440 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1441 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
Owen Andersonc78e03c2011-07-19 21:06:00 +00001442 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
Owen Anderson4e818902011-02-18 21:51:29 +00001443 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1444 FilterBitValues[BitIndex] == BIT_FALSE)
Owen Andersonc78e03c2011-07-19 21:06:00 +00001445 bitAttrs.push_back(ATTR_FILTERED);
Owen Anderson4e818902011-02-18 21:51:29 +00001446 else
Owen Andersonc78e03c2011-07-19 21:06:00 +00001447 bitAttrs.push_back(ATTR_NONE);
Owen Anderson4e818902011-02-18 21:51:29 +00001448
Craig Topper29688ab2012-08-17 05:42:16 +00001449 for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001450 insn_t insn;
1451
1452 insnWithID(insn, Opcodes[InsnIndex]);
1453
Owen Andersonc78e03c2011-07-19 21:06:00 +00001454 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001455 switch (bitAttrs[BitIndex]) {
1456 case ATTR_NONE:
1457 if (insn[BitIndex] == BIT_UNSET)
1458 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1459 else
1460 bitAttrs[BitIndex] = ATTR_ALL_SET;
1461 break;
1462 case ATTR_ALL_SET:
1463 if (insn[BitIndex] == BIT_UNSET)
1464 bitAttrs[BitIndex] = ATTR_MIXED;
1465 break;
1466 case ATTR_ALL_UNSET:
1467 if (insn[BitIndex] != BIT_UNSET)
1468 bitAttrs[BitIndex] = ATTR_MIXED;
1469 break;
1470 case ATTR_MIXED:
1471 case ATTR_FILTERED:
1472 break;
1473 }
1474 }
1475 }
1476
1477 // The regionAttr automaton consumes the bitAttrs automatons' state,
1478 // lowest-to-highest.
1479 //
1480 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1481 // States: NONE, ALL_SET, MIXED
1482 // Initial state: NONE
1483 //
1484 // (NONE) ----- F --> (NONE)
1485 // (NONE) ----- S --> (ALL_SET) ; and set region start
1486 // (NONE) ----- U --> (NONE)
1487 // (NONE) ----- M --> (MIXED) ; and set region start
1488 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1489 // (ALL_SET) -- S --> (ALL_SET)
1490 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1491 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1492 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1493 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1494 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1495 // (MIXED) ---- M --> (MIXED)
1496
1497 bitAttr_t RA = ATTR_NONE;
1498 unsigned StartBit = 0;
1499
Craig Topper29688ab2012-08-17 05:42:16 +00001500 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001501 bitAttr_t bitAttr = bitAttrs[BitIndex];
1502
1503 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1504
1505 switch (RA) {
1506 case ATTR_NONE:
1507 switch (bitAttr) {
1508 case ATTR_FILTERED:
1509 break;
1510 case ATTR_ALL_SET:
1511 StartBit = BitIndex;
1512 RA = ATTR_ALL_SET;
1513 break;
1514 case ATTR_ALL_UNSET:
1515 break;
1516 case ATTR_MIXED:
1517 StartBit = BitIndex;
1518 RA = ATTR_MIXED;
1519 break;
1520 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001521 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001522 }
1523 break;
1524 case ATTR_ALL_SET:
1525 switch (bitAttr) {
1526 case ATTR_FILTERED:
1527 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1528 RA = ATTR_NONE;
1529 break;
1530 case ATTR_ALL_SET:
1531 break;
1532 case ATTR_ALL_UNSET:
1533 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1534 RA = ATTR_NONE;
1535 break;
1536 case ATTR_MIXED:
1537 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1538 StartBit = BitIndex;
1539 RA = ATTR_MIXED;
1540 break;
1541 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001542 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001543 }
1544 break;
1545 case ATTR_MIXED:
1546 switch (bitAttr) {
1547 case ATTR_FILTERED:
1548 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1549 StartBit = BitIndex;
1550 RA = ATTR_NONE;
1551 break;
1552 case ATTR_ALL_SET:
1553 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1554 StartBit = BitIndex;
1555 RA = ATTR_ALL_SET;
1556 break;
1557 case ATTR_ALL_UNSET:
1558 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1559 RA = ATTR_NONE;
1560 break;
1561 case ATTR_MIXED:
1562 break;
1563 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001564 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001565 }
1566 break;
1567 case ATTR_ALL_UNSET:
Craig Topperc4965bc2012-02-05 07:21:30 +00001568 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
Owen Anderson4e818902011-02-18 21:51:29 +00001569 case ATTR_FILTERED:
Craig Topperc4965bc2012-02-05 07:21:30 +00001570 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
Owen Anderson4e818902011-02-18 21:51:29 +00001571 }
1572 }
1573
1574 // At the end, if we're still in ALL_SET or MIXED states, report a region
1575 switch (RA) {
1576 case ATTR_NONE:
1577 break;
1578 case ATTR_FILTERED:
1579 break;
1580 case ATTR_ALL_SET:
1581 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1582 break;
1583 case ATTR_ALL_UNSET:
1584 break;
1585 case ATTR_MIXED:
1586 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1587 break;
1588 }
1589
1590 // We have finished with the filter processings. Now it's time to choose
1591 // the best performing filter.
1592 BestIndex = 0;
1593 bool AllUseless = true;
1594 unsigned BestScore = 0;
1595
1596 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1597 unsigned Usefulness = Filters[i].usefulness();
1598
1599 if (Usefulness)
1600 AllUseless = false;
1601
1602 if (Usefulness > BestScore) {
1603 BestIndex = i;
1604 BestScore = Usefulness;
1605 }
1606 }
1607
1608 if (!AllUseless)
1609 bestFilter().recurse();
1610
1611 return !AllUseless;
1612} // end of FilterChooser::filterProcessor(bool)
1613
1614// Decides on the best configuration of filter(s) to use in order to decode
1615// the instructions. A conflict of instructions may occur, in which case we
1616// dump the conflict set to the standard error.
1617void FilterChooser::doFilter() {
1618 unsigned Num = Opcodes.size();
1619 assert(Num && "FilterChooser created with no instructions");
1620
1621 // Try regions of consecutive known bit values first.
1622 if (filterProcessor(false))
1623 return;
1624
1625 // Then regions of mixed bits (both known and unitialized bit values allowed).
1626 if (filterProcessor(true))
1627 return;
1628
1629 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1630 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1631 // well-known encoding pattern. In such case, we backtrack and scan for the
1632 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1633 if (Num == 3 && filterProcessor(true, false))
1634 return;
1635
1636 // If we come to here, the instruction decoding has failed.
1637 // Set the BestIndex to -1 to indicate so.
1638 BestIndex = -1;
1639}
1640
Jim Grosbachecaef492012-08-14 19:06:05 +00001641// emitTableEntries - Emit state machine entries to decode our share of
1642// instructions.
1643void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1644 if (Opcodes.size() == 1) {
Owen Anderson4e818902011-02-18 21:51:29 +00001645 // There is only one instruction in the set, which is great!
1646 // Call emitSingletonDecoder() to see whether there are any remaining
1647 // encodings bits.
Jim Grosbachecaef492012-08-14 19:06:05 +00001648 emitSingletonTableEntry(TableInfo, Opcodes[0]);
1649 return;
1650 }
Owen Anderson4e818902011-02-18 21:51:29 +00001651
1652 // Choose the best filter to do the decodings!
1653 if (BestIndex != -1) {
Craig Topper48c112b2012-03-16 05:58:09 +00001654 const Filter &Best = Filters[BestIndex];
Owen Anderson4e818902011-02-18 21:51:29 +00001655 if (Best.getNumFiltered() == 1)
Jim Grosbachecaef492012-08-14 19:06:05 +00001656 emitSingletonTableEntry(TableInfo, Best);
Owen Anderson4e818902011-02-18 21:51:29 +00001657 else
Jim Grosbachecaef492012-08-14 19:06:05 +00001658 Best.emitTableEntry(TableInfo);
1659 return;
Owen Anderson4e818902011-02-18 21:51:29 +00001660 }
1661
Jim Grosbachecaef492012-08-14 19:06:05 +00001662 // We don't know how to decode these instructions! Dump the
1663 // conflict set and bail.
Owen Anderson4e818902011-02-18 21:51:29 +00001664
1665 // Print out useful conflict information for postmortem analysis.
1666 errs() << "Decoding Conflict:\n";
1667
1668 dumpStack(errs(), "\t\t");
1669
Craig Topper82d0d5f2012-03-16 01:19:24 +00001670 for (unsigned i = 0; i < Opcodes.size(); ++i) {
Owen Anderson4e818902011-02-18 21:51:29 +00001671 const std::string &Name = nameWithID(Opcodes[i]);
1672
1673 errs() << '\t' << Name << " ";
1674 dumpBits(errs(),
1675 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1676 errs() << '\n';
1677 }
Owen Anderson4e818902011-02-18 21:51:29 +00001678}
1679
Hal Finkel71b2e202013-12-19 16:12:53 +00001680static bool populateInstruction(CodeGenTarget &Target,
1681 const CodeGenInstruction &CGI, unsigned Opc,
Craig Topper82d0d5f2012-03-16 01:19:24 +00001682 std::map<unsigned, std::vector<OperandInfo> > &Operands){
Owen Anderson4e818902011-02-18 21:51:29 +00001683 const Record &Def = *CGI.TheDef;
1684 // If all the bit positions are not specified; do not decode this instruction.
1685 // We are bound to fail! For proper disassembly, the well-known encoding bits
1686 // of the instruction must be fully specified.
Owen Anderson4e818902011-02-18 21:51:29 +00001687
David Greeneaf8ee2c2011-07-29 22:43:06 +00001688 BitsInit &Bits = getBitsField(Def, "Inst");
Jim Grosbachf3fd36e2011-07-06 21:33:38 +00001689 if (Bits.allInComplete()) return false;
1690
Owen Anderson4e818902011-02-18 21:51:29 +00001691 std::vector<OperandInfo> InsnOperands;
1692
1693 // If the instruction has specified a custom decoding hook, use that instead
1694 // of trying to auto-generate the decoder.
1695 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1696 if (InstDecoder != "") {
Owen Andersone3591652011-07-28 21:54:31 +00001697 InsnOperands.push_back(OperandInfo(InstDecoder));
Owen Anderson4e818902011-02-18 21:51:29 +00001698 Operands[Opc] = InsnOperands;
1699 return true;
1700 }
1701
1702 // Generate a description of the operand of the instruction that we know
1703 // how to decode automatically.
1704 // FIXME: We'll need to have a way to manually override this as needed.
1705
1706 // Gather the outputs/inputs of the instruction, so we can find their
1707 // positions in the encoding. This assumes for now that they appear in the
1708 // MCInst in the order that they're listed.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001709 std::vector<std::pair<Init*, std::string> > InOutOperands;
1710 DagInit *Out = Def.getValueAsDag("OutOperandList");
1711 DagInit *In = Def.getValueAsDag("InOperandList");
Owen Anderson4e818902011-02-18 21:51:29 +00001712 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1713 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1714 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1715 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1716
Owen Anderson53562d02011-07-28 23:56:20 +00001717 // Search for tied operands, so that we can correctly instantiate
1718 // operands that are not explicitly represented in the encoding.
Owen Andersoncb32ce22011-07-29 18:28:52 +00001719 std::map<std::string, std::string> TiedNames;
Owen Anderson53562d02011-07-28 23:56:20 +00001720 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1721 int tiedTo = CGI.Operands[i].getTiedRegister();
Owen Andersoncb32ce22011-07-29 18:28:52 +00001722 if (tiedTo != -1) {
Hal Finkel71b2e202013-12-19 16:12:53 +00001723 std::pair<unsigned, unsigned> SO =
1724 CGI.Operands.getSubOperandNumber(tiedTo);
1725 TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
1726 TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
1727 }
1728 }
1729
1730 std::map<std::string, std::vector<OperandInfo> > NumberedInsnOperands;
1731 std::set<std::string> NumberedInsnOperandsNoTie;
1732 if (Target.getInstructionSet()->
1733 getValueAsBit("decodePositionallyEncodedOperands")) {
1734 const std::vector<RecordVal> &Vals = Def.getValues();
1735 unsigned NumberedOp = 0;
1736
Hal Finkel5457bd02014-03-13 07:57:54 +00001737 std::set<unsigned> NamedOpIndices;
1738 if (Target.getInstructionSet()->
1739 getValueAsBit("noNamedPositionallyEncodedOperands"))
1740 // Collect the set of operand indices that might correspond to named
1741 // operand, and skip these when assigning operands based on position.
1742 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1743 unsigned OpIdx;
1744 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1745 continue;
1746
1747 NamedOpIndices.insert(OpIdx);
1748 }
1749
Hal Finkel71b2e202013-12-19 16:12:53 +00001750 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1751 // Ignore fixed fields in the record, we're looking for values like:
1752 // bits<5> RST = { ?, ?, ?, ?, ? };
1753 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
1754 continue;
1755
1756 // Determine if Vals[i] actually contributes to the Inst encoding.
1757 unsigned bi = 0;
1758 for (; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001759 VarInit *Var = nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001760 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1761 if (BI)
1762 Var = dyn_cast<VarInit>(BI->getBitVar());
1763 else
1764 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1765
1766 if (Var && Var->getName() == Vals[i].getName())
1767 break;
1768 }
1769
1770 if (bi == Bits.getNumBits())
1771 continue;
1772
1773 // Skip variables that correspond to explicitly-named operands.
1774 unsigned OpIdx;
1775 if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1776 continue;
1777
1778 // Get the bit range for this operand:
1779 unsigned bitStart = bi++, bitWidth = 1;
1780 for (; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001781 VarInit *Var = nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001782 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1783 if (BI)
1784 Var = dyn_cast<VarInit>(BI->getBitVar());
1785 else
1786 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1787
1788 if (!Var)
1789 break;
1790
1791 if (Var->getName() != Vals[i].getName())
1792 break;
1793
1794 ++bitWidth;
1795 }
1796
1797 unsigned NumberOps = CGI.Operands.size();
1798 while (NumberedOp < NumberOps &&
Hal Finkel5457bd02014-03-13 07:57:54 +00001799 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
1800 (NamedOpIndices.size() && NamedOpIndices.count(
1801 CGI.Operands.getSubOperandNumber(NumberedOp).first))))
Hal Finkel71b2e202013-12-19 16:12:53 +00001802 ++NumberedOp;
1803
1804 OpIdx = NumberedOp++;
1805
1806 // OpIdx now holds the ordered operand number of Vals[i].
1807 std::pair<unsigned, unsigned> SO =
1808 CGI.Operands.getSubOperandNumber(OpIdx);
1809 const std::string &Name = CGI.Operands[SO.first].Name;
1810
1811 DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName() << ": " <<
1812 Name << "(" << SO.first << ", " << SO.second << ") => " <<
1813 Vals[i].getName() << "\n");
1814
1815 std::string Decoder = "";
1816 Record *TypeRecord = CGI.Operands[SO.first].Rec;
1817
1818 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1819 StringInit *String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001820 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001821 if (String && String->getValue() != "")
1822 Decoder = String->getValue();
1823
1824 if (Decoder == "" &&
1825 CGI.Operands[SO.first].MIOperandInfo &&
1826 CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
1827 Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
1828 getArg(SO.second);
1829 if (TypedInit *TI = cast<TypedInit>(Arg)) {
1830 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1831 TypeRecord = Type->getRecord();
1832 }
1833 }
1834
1835 bool isReg = false;
1836 if (TypeRecord->isSubClassOf("RegisterOperand"))
1837 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1838 if (TypeRecord->isSubClassOf("RegisterClass")) {
1839 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1840 isReg = true;
1841 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1842 Decoder = "DecodePointerLikeRegClass" +
1843 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1844 isReg = true;
1845 }
1846
1847 DecoderString = TypeRecord->getValue("DecoderMethod");
1848 String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001849 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001850 if (!isReg && String && String->getValue() != "")
1851 Decoder = String->getValue();
1852
1853 OperandInfo OpInfo(Decoder);
1854 OpInfo.addField(bitStart, bitWidth, 0);
1855
1856 NumberedInsnOperands[Name].push_back(OpInfo);
1857
1858 // FIXME: For complex operands with custom decoders we can't handle tied
1859 // sub-operands automatically. Skip those here and assume that this is
1860 // fixed up elsewhere.
1861 if (CGI.Operands[SO.first].MIOperandInfo &&
1862 CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
1863 String && String->getValue() != "")
1864 NumberedInsnOperandsNoTie.insert(Name);
Owen Andersoncb32ce22011-07-29 18:28:52 +00001865 }
Owen Anderson53562d02011-07-28 23:56:20 +00001866 }
1867
Owen Anderson4e818902011-02-18 21:51:29 +00001868 // For each operand, see if we can figure out where it is encoded.
Craig Topper501d95c2012-03-16 06:52:56 +00001869 for (std::vector<std::pair<Init*, std::string> >::const_iterator
Owen Anderson4e818902011-02-18 21:51:29 +00001870 NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) {
Hal Finkel71b2e202013-12-19 16:12:53 +00001871 if (!NumberedInsnOperands[NI->second].empty()) {
1872 InsnOperands.insert(InsnOperands.end(),
1873 NumberedInsnOperands[NI->second].begin(),
1874 NumberedInsnOperands[NI->second].end());
1875 continue;
1876 } else if (!NumberedInsnOperands[TiedNames[NI->second]].empty()) {
1877 if (!NumberedInsnOperandsNoTie.count(TiedNames[NI->second])) {
1878 // Figure out to which (sub)operand we're tied.
1879 unsigned i = CGI.Operands.getOperandNamed(TiedNames[NI->second]);
1880 int tiedTo = CGI.Operands[i].getTiedRegister();
1881 if (tiedTo == -1) {
1882 i = CGI.Operands.getOperandNamed(NI->second);
1883 tiedTo = CGI.Operands[i].getTiedRegister();
1884 }
1885
1886 if (tiedTo != -1) {
1887 std::pair<unsigned, unsigned> SO =
1888 CGI.Operands.getSubOperandNumber(tiedTo);
1889
1890 InsnOperands.push_back(NumberedInsnOperands[TiedNames[NI->second]]
1891 [SO.second]);
1892 }
1893 }
1894 continue;
1895 }
1896
Owen Anderson4e818902011-02-18 21:51:29 +00001897 std::string Decoder = "";
1898
Owen Andersone3591652011-07-28 21:54:31 +00001899 // At this point, we can locate the field, but we need to know how to
1900 // interpret it. As a first step, require the target to provide callbacks
1901 // for decoding register classes.
1902 // FIXME: This need to be extended to handle instructions with custom
1903 // decoder methods, and operands with (simple) MIOperandInfo's.
Sean Silva88eb8dd2012-10-10 20:24:47 +00001904 TypedInit *TI = cast<TypedInit>(NI->first);
1905 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
Owen Andersone3591652011-07-28 21:54:31 +00001906 Record *TypeRecord = Type->getRecord();
1907 bool isReg = false;
1908 if (TypeRecord->isSubClassOf("RegisterOperand"))
1909 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1910 if (TypeRecord->isSubClassOf("RegisterClass")) {
1911 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1912 isReg = true;
Hal Finkel9d95e8d2013-12-19 14:58:22 +00001913 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1914 Decoder = "DecodePointerLikeRegClass" +
1915 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1916 isReg = true;
Owen Andersone3591652011-07-28 21:54:31 +00001917 }
1918
1919 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
David Greeneaf8ee2c2011-07-29 22:43:06 +00001920 StringInit *String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001921 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Owen Andersone3591652011-07-28 21:54:31 +00001922 if (!isReg && String && String->getValue() != "")
1923 Decoder = String->getValue();
1924
1925 OperandInfo OpInfo(Decoder);
1926 unsigned Base = ~0U;
1927 unsigned Width = 0;
1928 unsigned Offset = 0;
1929
Owen Anderson4e818902011-02-18 21:51:29 +00001930 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001931 VarInit *Var = nullptr;
Sean Silvafb509ed2012-10-10 20:24:43 +00001932 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
Owen Anderson3022d672011-08-01 22:45:43 +00001933 if (BI)
Sean Silvafb509ed2012-10-10 20:24:43 +00001934 Var = dyn_cast<VarInit>(BI->getBitVar());
Owen Anderson3022d672011-08-01 22:45:43 +00001935 else
Sean Silvafb509ed2012-10-10 20:24:43 +00001936 Var = dyn_cast<VarInit>(Bits.getBit(bi));
Owen Anderson3022d672011-08-01 22:45:43 +00001937
1938 if (!Var) {
Owen Andersone3591652011-07-28 21:54:31 +00001939 if (Base != ~0U) {
1940 OpInfo.addField(Base, Width, Offset);
1941 Base = ~0U;
1942 Width = 0;
1943 Offset = 0;
1944 }
1945 continue;
1946 }
Owen Anderson4e818902011-02-18 21:51:29 +00001947
Owen Anderson53562d02011-07-28 23:56:20 +00001948 if (Var->getName() != NI->second &&
Owen Andersoncb32ce22011-07-29 18:28:52 +00001949 Var->getName() != TiedNames[NI->second]) {
Owen Andersone3591652011-07-28 21:54:31 +00001950 if (Base != ~0U) {
1951 OpInfo.addField(Base, Width, Offset);
1952 Base = ~0U;
1953 Width = 0;
1954 Offset = 0;
1955 }
1956 continue;
Owen Anderson4e818902011-02-18 21:51:29 +00001957 }
1958
Owen Andersone3591652011-07-28 21:54:31 +00001959 if (Base == ~0U) {
1960 Base = bi;
1961 Width = 1;
Owen Anderson3022d672011-08-01 22:45:43 +00001962 Offset = BI ? BI->getBitNum() : 0;
1963 } else if (BI && BI->getBitNum() != Offset + Width) {
Owen Andersone08f5b52011-07-29 23:01:18 +00001964 OpInfo.addField(Base, Width, Offset);
1965 Base = bi;
1966 Width = 1;
1967 Offset = BI->getBitNum();
Owen Andersone3591652011-07-28 21:54:31 +00001968 } else {
1969 ++Width;
Owen Anderson4e818902011-02-18 21:51:29 +00001970 }
Owen Anderson4e818902011-02-18 21:51:29 +00001971 }
1972
Owen Andersone3591652011-07-28 21:54:31 +00001973 if (Base != ~0U)
1974 OpInfo.addField(Base, Width, Offset);
1975
1976 if (OpInfo.numFields() > 0)
1977 InsnOperands.push_back(OpInfo);
Owen Anderson4e818902011-02-18 21:51:29 +00001978 }
1979
1980 Operands[Opc] = InsnOperands;
1981
1982
1983#if 0
1984 DEBUG({
1985 // Dumps the instruction encoding bits.
1986 dumpBits(errs(), Bits);
1987
1988 errs() << '\n';
1989
1990 // Dumps the list of operand info.
1991 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1992 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
1993 const std::string &OperandName = Info.Name;
1994 const Record &OperandDef = *Info.Rec;
1995
1996 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
1997 }
1998 });
1999#endif
2000
2001 return true;
2002}
2003
Jim Grosbachecaef492012-08-14 19:06:05 +00002004// emitFieldFromInstruction - Emit the templated helper function
2005// fieldFromInstruction().
2006static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
2007 OS << "// Helper function for extracting fields from encoded instructions.\n"
2008 << "template<typename InsnType>\n"
2009 << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
2010 << " unsigned numBits) {\n"
2011 << " assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
2012 << " \"Instruction field out of bounds!\");\n"
2013 << " InsnType fieldMask;\n"
2014 << " if (numBits == sizeof(InsnType)*8)\n"
2015 << " fieldMask = (InsnType)(-1LL);\n"
2016 << " else\n"
NAKAMURA Takumibf99a422012-12-26 06:43:14 +00002017 << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002018 << " return (insn & fieldMask) >> startBit;\n"
2019 << "}\n\n";
2020}
Owen Anderson4e818902011-02-18 21:51:29 +00002021
Jim Grosbachecaef492012-08-14 19:06:05 +00002022// emitDecodeInstruction - Emit the templated helper function
2023// decodeInstruction().
2024static void emitDecodeInstruction(formatted_raw_ostream &OS) {
2025 OS << "template<typename InsnType>\n"
2026 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
2027 << " InsnType insn, uint64_t Address,\n"
2028 << " const void *DisAsm,\n"
2029 << " const MCSubtargetInfo &STI) {\n"
2030 << " uint64_t Bits = STI.getFeatureBits();\n"
2031 << "\n"
2032 << " const uint8_t *Ptr = DecodeTable;\n"
Jim Grosbach4c363492012-09-17 18:00:53 +00002033 << " uint32_t CurFieldValue = 0;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002034 << " DecodeStatus S = MCDisassembler::Success;\n"
2035 << " for (;;) {\n"
2036 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
2037 << " switch (*Ptr) {\n"
2038 << " default:\n"
2039 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
2040 << " return MCDisassembler::Fail;\n"
2041 << " case MCD::OPC_ExtractField: {\n"
2042 << " unsigned Start = *++Ptr;\n"
2043 << " unsigned Len = *++Ptr;\n"
2044 << " ++Ptr;\n"
2045 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
2046 << " DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
2047 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
2048 << " break;\n"
2049 << " }\n"
2050 << " case MCD::OPC_FilterValue: {\n"
2051 << " // Decode the field value.\n"
2052 << " unsigned Len;\n"
2053 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
2054 << " Ptr += Len;\n"
2055 << " // NumToSkip is a plain 16-bit integer.\n"
2056 << " unsigned NumToSkip = *Ptr++;\n"
2057 << " NumToSkip |= (*Ptr++) << 8;\n"
2058 << "\n"
2059 << " // Perform the filter operation.\n"
2060 << " if (Val != CurFieldValue)\n"
2061 << " Ptr += NumToSkip;\n"
2062 << " DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
2063 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
2064 << " << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2065 << "\n"
2066 << " break;\n"
2067 << " }\n"
2068 << " case MCD::OPC_CheckField: {\n"
2069 << " unsigned Start = *++Ptr;\n"
2070 << " unsigned Len = *++Ptr;\n"
2071 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
2072 << " // Decode the field value.\n"
2073 << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
2074 << " Ptr += Len;\n"
2075 << " // NumToSkip is a plain 16-bit integer.\n"
2076 << " unsigned NumToSkip = *Ptr++;\n"
2077 << " NumToSkip |= (*Ptr++) << 8;\n"
2078 << "\n"
2079 << " // If the actual and expected values don't match, skip.\n"
2080 << " if (ExpectedValue != FieldValue)\n"
2081 << " Ptr += NumToSkip;\n"
2082 << " DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
2083 << " << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
2084 << " << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
2085 << " << ExpectedValue << \": \"\n"
2086 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2087 << " break;\n"
2088 << " }\n"
2089 << " case MCD::OPC_CheckPredicate: {\n"
2090 << " unsigned Len;\n"
2091 << " // Decode the Predicate Index value.\n"
2092 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
2093 << " Ptr += Len;\n"
2094 << " // NumToSkip is a plain 16-bit integer.\n"
2095 << " unsigned NumToSkip = *Ptr++;\n"
2096 << " NumToSkip |= (*Ptr++) << 8;\n"
2097 << " // Check the predicate.\n"
2098 << " bool Pred;\n"
2099 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
2100 << " Ptr += NumToSkip;\n"
2101 << " (void)Pred;\n"
2102 << " DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
2103 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2104 << "\n"
2105 << " break;\n"
2106 << " }\n"
2107 << " case MCD::OPC_Decode: {\n"
2108 << " unsigned Len;\n"
2109 << " // Decode the Opcode value.\n"
2110 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2111 << " Ptr += Len;\n"
2112 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2113 << " Ptr += Len;\n"
2114 << " DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
2115 << " << \", using decoder \" << DecodeIdx << \"\\n\" );\n"
2116 << " DEBUG(dbgs() << \"----- DECODE SUCCESSFUL -----\\n\");\n"
2117 << "\n"
2118 << " MI.setOpcode(Opc);\n"
Benjamin Kramer26b568d2012-08-15 10:26:44 +00002119 << " return decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm);\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002120 << " }\n"
2121 << " case MCD::OPC_SoftFail: {\n"
2122 << " // Decode the mask values.\n"
2123 << " unsigned Len;\n"
2124 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
2125 << " Ptr += Len;\n"
2126 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
2127 << " Ptr += Len;\n"
2128 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
2129 << " if (Fail)\n"
2130 << " S = MCDisassembler::SoftFail;\n"
2131 << " DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
2132 << " break;\n"
2133 << " }\n"
2134 << " case MCD::OPC_Fail: {\n"
2135 << " DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
2136 << " return MCDisassembler::Fail;\n"
2137 << " }\n"
2138 << " }\n"
2139 << " }\n"
2140 << " llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
2141 << "}\n\n";
Owen Anderson4e818902011-02-18 21:51:29 +00002142}
2143
2144// Emits disassembler code for instruction decoding.
Craig Topper82d0d5f2012-03-16 01:19:24 +00002145void FixedLenDecoderEmitter::run(raw_ostream &o) {
Jim Grosbachecaef492012-08-14 19:06:05 +00002146 formatted_raw_ostream OS(o);
2147 OS << "#include \"llvm/MC/MCInst.h\"\n";
2148 OS << "#include \"llvm/Support/Debug.h\"\n";
2149 OS << "#include \"llvm/Support/DataTypes.h\"\n";
2150 OS << "#include \"llvm/Support/LEB128.h\"\n";
2151 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2152 OS << "#include <assert.h>\n";
2153 OS << '\n';
2154 OS << "namespace llvm {\n\n";
2155
2156 emitFieldFromInstruction(OS);
Owen Anderson4e818902011-02-18 21:51:29 +00002157
Hal Finkel81e6fcc2013-12-17 22:37:50 +00002158 Target.reverseBitsForLittleEndianEncoding();
2159
Owen Andersonc78e03c2011-07-19 21:06:00 +00002160 // Parameterize the decoders based on namespace and instruction width.
Jim Grosbachecaef492012-08-14 19:06:05 +00002161 NumberedInstructions = &Target.getInstructionsByEnumValue();
Owen Andersonc78e03c2011-07-19 21:06:00 +00002162 std::map<std::pair<std::string, unsigned>,
2163 std::vector<unsigned> > OpcMap;
2164 std::map<unsigned, std::vector<OperandInfo> > Operands;
2165
Jim Grosbachecaef492012-08-14 19:06:05 +00002166 for (unsigned i = 0; i < NumberedInstructions->size(); ++i) {
2167 const CodeGenInstruction *Inst = NumberedInstructions->at(i);
Craig Topper48c112b2012-03-16 05:58:09 +00002168 const Record *Def = Inst->TheDef;
Owen Andersonc78e03c2011-07-19 21:06:00 +00002169 unsigned Size = Def->getValueAsInt("Size");
2170 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2171 Def->getValueAsBit("isPseudo") ||
2172 Def->getValueAsBit("isAsmParserOnly") ||
2173 Def->getValueAsBit("isCodeGenOnly"))
2174 continue;
2175
2176 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
2177
2178 if (Size) {
Hal Finkel71b2e202013-12-19 16:12:53 +00002179 if (populateInstruction(Target, *Inst, i, Operands)) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00002180 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2181 }
2182 }
2183 }
2184
Jim Grosbachecaef492012-08-14 19:06:05 +00002185 DecoderTableInfo TableInfo;
Owen Andersonc78e03c2011-07-19 21:06:00 +00002186 for (std::map<std::pair<std::string, unsigned>,
Craig Topper48c112b2012-03-16 05:58:09 +00002187 std::vector<unsigned> >::const_iterator
Owen Andersonc78e03c2011-07-19 21:06:00 +00002188 I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00002189 // Emit the decoder for this namespace+width combination.
Jim Grosbachecaef492012-08-14 19:06:05 +00002190 FilterChooser FC(*NumberedInstructions, I->second, Operands,
Owen Andersona4043c42011-08-17 17:44:15 +00002191 8*I->first.second, this);
Jim Grosbachecaef492012-08-14 19:06:05 +00002192
2193 // The decode table is cleared for each top level decoder function. The
2194 // predicates and decoders themselves, however, are shared across all
2195 // decoders to give more opportunities for uniqueing.
2196 TableInfo.Table.clear();
2197 TableInfo.FixupStack.clear();
2198 TableInfo.Table.reserve(16384);
2199 TableInfo.FixupStack.push_back(FixupList());
2200 FC.emitTableEntries(TableInfo);
2201 // Any NumToSkip fixups in the top level scope can resolve to the
2202 // OPC_Fail at the end of the table.
2203 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2204 // Resolve any NumToSkip fixups in the current scope.
2205 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2206 TableInfo.Table.size());
2207 TableInfo.FixupStack.clear();
2208
2209 TableInfo.Table.push_back(MCD::OPC_Fail);
2210
2211 // Print the table to the output stream.
2212 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), I->first.first);
2213 OS.flush();
Owen Andersonc78e03c2011-07-19 21:06:00 +00002214 }
Owen Anderson4e818902011-02-18 21:51:29 +00002215
Jim Grosbachecaef492012-08-14 19:06:05 +00002216 // Emit the predicate function.
2217 emitPredicateFunction(OS, TableInfo.Predicates, 0);
2218
2219 // Emit the decoder function.
2220 emitDecoderFunction(OS, TableInfo.Decoders, 0);
2221
2222 // Emit the main entry point for the decoder, decodeInstruction().
2223 emitDecodeInstruction(OS);
2224
2225 OS << "\n} // End llvm namespace\n";
Owen Anderson4e818902011-02-18 21:51:29 +00002226}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +00002227
2228namespace llvm {
2229
2230void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
2231 std::string PredicateNamespace,
2232 std::string GPrefix,
2233 std::string GPostfix,
2234 std::string ROK,
2235 std::string RFail,
2236 std::string L) {
2237 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2238 ROK, RFail, L).run(OS);
2239}
2240
2241} // End llvm namespace