1//===- CodeGenInstruction.h - Instruction Class Wrapper ---------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines a wrapper class for the 'Instruction' TableGen class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_UTILS_TABLEGEN_CODEGENINSTRUCTION_H
14#define LLVM_UTILS_TABLEGEN_CODEGENINSTRUCTION_H
15
16#include "llvm/ADT/StringRef.h"
17#include "llvm/Support/MachineValueType.h"
18#include "llvm/Support/SMLoc.h"
19#include <string>
20#include <utility>
21#include <vector>
22
23namespace llvm {
24template <typename T> class ArrayRef;
25  class Record;
26  class DagInit;
27  class CodeGenTarget;
28
29  class CGIOperandList {
30  public:
31    class ConstraintInfo {
32      enum { None, EarlyClobber, Tied } Kind = None;
33      unsigned OtherTiedOperand = 0;
34
35    public:
36      ConstraintInfo() = default;
37
38      static ConstraintInfo getEarlyClobber() {
39        ConstraintInfo I;
40        I.Kind = EarlyClobber;
41        I.OtherTiedOperand = 0;
42        return I;
43      }
44
45      static ConstraintInfo getTied(unsigned Op) {
46        ConstraintInfo I;
47        I.Kind = Tied;
48        I.OtherTiedOperand = Op;
49        return I;
50      }
51
52      bool isNone() const { return Kind == None; }
53      bool isEarlyClobber() const { return Kind == EarlyClobber; }
54      bool isTied() const { return Kind == Tied; }
55
56      unsigned getTiedOperand() const {
57        assert(isTied());
58        return OtherTiedOperand;
59      }
60
61      bool operator==(const ConstraintInfo &RHS) const {
62        if (Kind != RHS.Kind)
63          return false;
64        if (Kind == Tied && OtherTiedOperand != RHS.OtherTiedOperand)
65          return false;
66        return true;
67      }
68      bool operator!=(const ConstraintInfo &RHS) const {
69        return !(*this == RHS);
70      }
71    };
72
73    /// OperandInfo - The information we keep track of for each operand in the
74    /// operand list for a tablegen instruction.
75    struct OperandInfo {
76      /// Rec - The definition this operand is declared as.
77      ///
78      Record *Rec;
79
80      /// Name - If this operand was assigned a symbolic name, this is it,
81      /// otherwise, it's empty.
82      std::string Name;
83
84      /// PrinterMethodName - The method used to print operands of this type in
85      /// the asmprinter.
86      std::string PrinterMethodName;
87
88      /// EncoderMethodName - The method used to get the machine operand value
89      /// for binary encoding. "getMachineOpValue" by default.
90      std::string EncoderMethodName;
91
92      /// OperandType - A value from MCOI::OperandType representing the type of
93      /// the operand.
94      std::string OperandType;
95
96      /// MIOperandNo - Currently (this is meant to be phased out), some logical
97      /// operands correspond to multiple MachineInstr operands.  In the X86
98      /// target for example, one address operand is represented as 4
99      /// MachineOperands.  Because of this, the operand number in the
100      /// OperandList may not match the MachineInstr operand num.  Until it
101      /// does, this contains the MI operand index of this operand.
102      unsigned MIOperandNo;
103      unsigned MINumOperands;   // The number of operands.
104
105      /// DoNotEncode - Bools are set to true in this vector for each operand in
106      /// the DisableEncoding list.  These should not be emitted by the code
107      /// emitter.
108      std::vector<bool> DoNotEncode;
109
110      /// MIOperandInfo - Default MI operand type. Note an operand may be made
111      /// up of multiple MI operands.
112      DagInit *MIOperandInfo;
113
114      /// Constraint info for this operand.  This operand can have pieces, so we
115      /// track constraint info for each.
116      std::vector<ConstraintInfo> Constraints;
117
118      OperandInfo(Record *R, const std::string &N, const std::string &PMN,
119                  const std::string &EMN, const std::string &OT, unsigned MION,
120                  unsigned MINO, DagInit *MIOI)
121      : Rec(R), Name(N), PrinterMethodName(PMN), EncoderMethodName(EMN),
122        OperandType(OT), MIOperandNo(MION), MINumOperands(MINO),
123        MIOperandInfo(MIOI) {}
124
125
126      /// getTiedOperand - If this operand is tied to another one, return the
127      /// other operand number.  Otherwise, return -1.
128      int getTiedRegister() const {
129        for (unsigned j = 0, e = Constraints.size(); j != e; ++j) {
130          const CGIOperandList::ConstraintInfo &CI = Constraints[j];
131          if (CI.isTied()) return CI.getTiedOperand();
132        }
133        return -1;
134      }
135    };
136
137    CGIOperandList(Record *D);
138
139    Record *TheDef;            // The actual record containing this OperandList.
140
141    /// NumDefs - Number of def operands declared, this is the number of
142    /// elements in the instruction's (outs) list.
143    ///
144    unsigned NumDefs;
145
146    /// OperandList - The list of declared operands, along with their declared
147    /// type (which is a record).
148    std::vector<OperandInfo> OperandList;
149
150    // Information gleaned from the operand list.
151    bool isPredicable;
152    bool hasOptionalDef;
153    bool isVariadic;
154
155    // Provide transparent accessors to the operand list.
156    bool empty() const { return OperandList.empty(); }
157    unsigned size() const { return OperandList.size(); }
158    const OperandInfo &operator[](unsigned i) const { return OperandList[i]; }
159    OperandInfo &operator[](unsigned i) { return OperandList[i]; }
160    OperandInfo &back() { return OperandList.back(); }
161    const OperandInfo &back() const { return OperandList.back(); }
162
163    typedef std::vector<OperandInfo>::iterator iterator;
164    typedef std::vector<OperandInfo>::const_iterator const_iterator;
165    iterator begin() { return OperandList.begin(); }
166    const_iterator begin() const { return OperandList.begin(); }
167    iterator end() { return OperandList.end(); }
168    const_iterator end() const { return OperandList.end(); }
169
170    /// getOperandNamed - Return the index of the operand with the specified
171    /// non-empty name.  If the instruction does not have an operand with the
172    /// specified name, abort.
173    unsigned getOperandNamed(StringRef Name) const;
174
175    /// hasOperandNamed - Query whether the instruction has an operand of the
176    /// given name. If so, return true and set OpIdx to the index of the
177    /// operand. Otherwise, return false.
178    bool hasOperandNamed(StringRef Name, unsigned &OpIdx) const;
179
180    /// ParseOperandName - Parse an operand name like "$foo" or "$foo.bar",
181    /// where $foo is a whole operand and $foo.bar refers to a suboperand.
182    /// This aborts if the name is invalid.  If AllowWholeOp is true, references
183    /// to operands with suboperands are allowed, otherwise not.
184    std::pair<unsigned,unsigned> ParseOperandName(const std::string &Op,
185                                                  bool AllowWholeOp = true);
186
187    /// getFlattenedOperandNumber - Flatten a operand/suboperand pair into a
188    /// flat machineinstr operand #.
189    unsigned getFlattenedOperandNumber(std::pair<unsigned,unsigned> Op) const {
190      return OperandList[Op.first].MIOperandNo + Op.second;
191    }
192
193    /// getSubOperandNumber - Unflatten a operand number into an
194    /// operand/suboperand pair.
195    std::pair<unsigned,unsigned> getSubOperandNumber(unsigned Op) const {
196      for (unsigned i = 0; ; ++i) {
197        assert(i < OperandList.size() && "Invalid flat operand #");
198        if (OperandList[i].MIOperandNo+OperandList[i].MINumOperands > Op)
199          return std::make_pair(i, Op-OperandList[i].MIOperandNo);
200      }
201    }
202
203
204    /// isFlatOperandNotEmitted - Return true if the specified flat operand #
205    /// should not be emitted with the code emitter.
206    bool isFlatOperandNotEmitted(unsigned FlatOpNo) const {
207      std::pair<unsigned,unsigned> Op = getSubOperandNumber(FlatOpNo);
208      if (OperandList[Op.first].DoNotEncode.size() > Op.second)
209        return OperandList[Op.first].DoNotEncode[Op.second];
210      return false;
211    }
212
213    void ProcessDisableEncoding(std::string Value);
214  };
215
216
217  class CodeGenInstruction {
218  public:
219    Record *TheDef;            // The actual record defining this instruction.
220    StringRef Namespace;       // The namespace the instruction is in.
221
222    /// AsmString - The format string used to emit a .s file for the
223    /// instruction.
224    std::string AsmString;
225
226    /// Operands - This is information about the (ins) and (outs) list specified
227    /// to the instruction.
228    CGIOperandList Operands;
229
230    /// ImplicitDefs/ImplicitUses - These are lists of registers that are
231    /// implicitly defined and used by the instruction.
232    std::vector<Record*> ImplicitDefs, ImplicitUses;
233
234    // Various boolean values we track for the instruction.
235    bool isPreISelOpcode : 1;
236    bool isReturn : 1;
237    bool isEHScopeReturn : 1;
238    bool isBranch : 1;
239    bool isIndirectBranch : 1;
240    bool isCompare : 1;
241    bool isMoveImm : 1;
242    bool isMoveReg : 1;
243    bool isBitcast : 1;
244    bool isSelect : 1;
245    bool isBarrier : 1;
246    bool isCall : 1;
247    bool isAdd : 1;
248    bool isTrap : 1;
249    bool canFoldAsLoad : 1;
250    bool mayLoad : 1;
251    bool mayLoad_Unset : 1;
252    bool mayStore : 1;
253    bool mayStore_Unset : 1;
254    bool mayRaiseFPException : 1;
255    bool isPredicable : 1;
256    bool isConvertibleToThreeAddress : 1;
257    bool isCommutable : 1;
258    bool isTerminator : 1;
259    bool isReMaterializable : 1;
260    bool hasDelaySlot : 1;
261    bool usesCustomInserter : 1;
262    bool hasPostISelHook : 1;
263    bool hasCtrlDep : 1;
264    bool isNotDuplicable : 1;
265    bool hasSideEffects : 1;
266    bool hasSideEffects_Unset : 1;
267    bool isAsCheapAsAMove : 1;
268    bool hasExtraSrcRegAllocReq : 1;
269    bool hasExtraDefRegAllocReq : 1;
270    bool isCodeGenOnly : 1;
271    bool isPseudo : 1;
272    bool isRegSequence : 1;
273    bool isExtractSubreg : 1;
274    bool isInsertSubreg : 1;
275    bool isConvergent : 1;
276    bool hasNoSchedulingInfo : 1;
277    bool FastISelShouldIgnore : 1;
278    bool hasChain : 1;
279    bool hasChain_Inferred : 1;
280    bool variadicOpsAreDefs : 1;
281    bool isAuthenticated : 1;
282
283    std::string DeprecatedReason;
284    bool HasComplexDeprecationPredicate;
285
286    /// Are there any undefined flags?
287    bool hasUndefFlags() const {
288      return mayLoad_Unset || mayStore_Unset || hasSideEffects_Unset;
289    }
290
291    // The record used to infer instruction flags, or NULL if no flag values
292    // have been inferred.
293    Record *InferredFrom;
294
295    CodeGenInstruction(Record *R);
296
297    /// HasOneImplicitDefWithKnownVT - If the instruction has at least one
298    /// implicit def and it has a known VT, return the VT, otherwise return
299    /// MVT::Other.
300    MVT::SimpleValueType
301      HasOneImplicitDefWithKnownVT(const CodeGenTarget &TargetInfo) const;
302
303
304    /// FlattenAsmStringVariants - Flatten the specified AsmString to only
305    /// include text from the specified variant, returning the new string.
306    static std::string FlattenAsmStringVariants(StringRef AsmString,
307                                                unsigned Variant);
308
309    // Is the specified operand in a generic instruction implicitly a pointer.
310    // This can be used on intructions that use typeN or ptypeN to identify
311    // operands that should be considered as pointers even though SelectionDAG
312    // didn't make a distinction between integer and pointers.
313    bool isOperandAPointer(unsigned i) const {
314      return isOperandImpl(i, "IsPointer");
315    }
316
317    /// Check if the operand is required to be an immediate.
318    bool isOperandImmArg(unsigned i) const {
319      return isOperandImpl(i, "IsImmediate");
320    }
321
322  private:
323    bool isOperandImpl(unsigned i, StringRef PropertyName) const;
324  };
325
326
327  /// CodeGenInstAlias - This represents an InstAlias definition.
328  class CodeGenInstAlias {
329  public:
330    Record *TheDef;            // The actual record defining this InstAlias.
331
332    /// AsmString - The format string used to emit a .s file for the
333    /// instruction.
334    std::string AsmString;
335
336    /// Result - The result instruction.
337    DagInit *Result;
338
339    /// ResultInst - The instruction generated by the alias (decoded from
340    /// Result).
341    CodeGenInstruction *ResultInst;
342
343
344    struct ResultOperand {
345    private:
346      std::string Name;
347      Record *R = nullptr;
348      int64_t Imm = 0;
349
350    public:
351      enum {
352        K_Record,
353        K_Imm,
354        K_Reg
355      } Kind;
356
357      ResultOperand(std::string N, Record *r)
358          : Name(std::move(N)), R(r), Kind(K_Record) {}
359      ResultOperand(int64_t I) : Imm(I), Kind(K_Imm) {}
360      ResultOperand(Record *r) : R(r), Kind(K_Reg) {}
361
362      bool isRecord() const { return Kind == K_Record; }
363      bool isImm() const { return Kind == K_Imm; }
364      bool isReg() const { return Kind == K_Reg; }
365
366      StringRef getName() const { assert(isRecord()); return Name; }
367      Record *getRecord() const { assert(isRecord()); return R; }
368      int64_t getImm() const { assert(isImm()); return Imm; }
369      Record *getRegister() const { assert(isReg()); return R; }
370
371      unsigned getMINumOperands() const;
372    };
373
374    /// ResultOperands - The decoded operands for the result instruction.
375    std::vector<ResultOperand> ResultOperands;
376
377    /// ResultInstOperandIndex - For each operand, this vector holds a pair of
378    /// indices to identify the corresponding operand in the result
379    /// instruction.  The first index specifies the operand and the second
380    /// index specifies the suboperand.  If there are no suboperands or if all
381    /// of them are matched by the operand, the second value should be -1.
382    std::vector<std::pair<unsigned, int> > ResultInstOperandIndex;
383
384    CodeGenInstAlias(Record *R, CodeGenTarget &T);
385
386    bool tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo,
387                         Record *InstOpRec, bool hasSubOps, ArrayRef<SMLoc> Loc,
388                         CodeGenTarget &T, ResultOperand &ResOp);
389  };
390}
391
392#endif
393