1//===-- ARMBaseInstrInfo.h - ARM Base Instruction Information ---*- C++ -*-===//
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// This file contains the Base ARM implementation of the TargetInstrInfo class.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_LIB_TARGET_ARM_ARMBASEINSTRINFO_H
15#define LLVM_LIB_TARGET_ARM_ARMBASEINSTRINFO_H
16
17#include "MCTargetDesc/ARMBaseInfo.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/SmallSet.h"
20#include "llvm/CodeGen/MachineInstrBuilder.h"
21#include "llvm/Support/CodeGen.h"
22#include "llvm/Target/TargetInstrInfo.h"
23
24#define GET_INSTRINFO_HEADER
25#include "ARMGenInstrInfo.inc"
26
27namespace llvm {
28  class ARMSubtarget;
29  class ARMBaseRegisterInfo;
30
31class ARMBaseInstrInfo : public ARMGenInstrInfo {
32  const ARMSubtarget &Subtarget;
33
34protected:
35  // Can be only subclassed.
36  explicit ARMBaseInstrInfo(const ARMSubtarget &STI);
37
38  void expandLoadStackGuardBase(MachineBasicBlock::iterator MI,
39                                unsigned LoadImmOpc, unsigned LoadOpc,
40                                Reloc::Model RM) const;
41
42  /// Build the equivalent inputs of a REG_SEQUENCE for the given \p MI
43  /// and \p DefIdx.
44  /// \p [out] InputRegs of the equivalent REG_SEQUENCE. Each element of
45  /// the list is modeled as <Reg:SubReg, SubIdx>.
46  /// E.g., REG_SEQUENCE vreg1:sub1, sub0, vreg2, sub1 would produce
47  /// two elements:
48  /// - vreg1:sub1, sub0
49  /// - vreg2<:0>, sub1
50  ///
51  /// \returns true if it is possible to build such an input sequence
52  /// with the pair \p MI, \p DefIdx. False otherwise.
53  ///
54  /// \pre MI.isRegSequenceLike().
55  bool getRegSequenceLikeInputs(
56      const MachineInstr &MI, unsigned DefIdx,
57      SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const override;
58
59  /// Build the equivalent inputs of a EXTRACT_SUBREG for the given \p MI
60  /// and \p DefIdx.
61  /// \p [out] InputReg of the equivalent EXTRACT_SUBREG.
62  /// E.g., EXTRACT_SUBREG vreg1:sub1, sub0, sub1 would produce:
63  /// - vreg1:sub1, sub0
64  ///
65  /// \returns true if it is possible to build such an input sequence
66  /// with the pair \p MI, \p DefIdx. False otherwise.
67  ///
68  /// \pre MI.isExtractSubregLike().
69  bool getExtractSubregLikeInputs(const MachineInstr &MI, unsigned DefIdx,
70                                  RegSubRegPairAndIdx &InputReg) const override;
71
72  /// Build the equivalent inputs of a INSERT_SUBREG for the given \p MI
73  /// and \p DefIdx.
74  /// \p [out] BaseReg and \p [out] InsertedReg contain
75  /// the equivalent inputs of INSERT_SUBREG.
76  /// E.g., INSERT_SUBREG vreg0:sub0, vreg1:sub1, sub3 would produce:
77  /// - BaseReg: vreg0:sub0
78  /// - InsertedReg: vreg1:sub1, sub3
79  ///
80  /// \returns true if it is possible to build such an input sequence
81  /// with the pair \p MI, \p DefIdx. False otherwise.
82  ///
83  /// \pre MI.isInsertSubregLike().
84  bool
85  getInsertSubregLikeInputs(const MachineInstr &MI, unsigned DefIdx,
86                            RegSubRegPair &BaseReg,
87                            RegSubRegPairAndIdx &InsertedReg) const override;
88
89  /// Commutes the operands in the given instruction.
90  /// The commutable operands are specified by their indices OpIdx1 and OpIdx2.
91  ///
92  /// Do not call this method for a non-commutable instruction or for
93  /// non-commutable pair of operand indices OpIdx1 and OpIdx2.
94  /// Even though the instruction is commutable, the method may still
95  /// fail to commute the operands, null pointer is returned in such cases.
96  MachineInstr *commuteInstructionImpl(MachineInstr *MI,
97                                       bool NewMI,
98                                       unsigned OpIdx1,
99                                       unsigned OpIdx2) const override;
100
101public:
102  // Return whether the target has an explicit NOP encoding.
103  bool hasNOP() const;
104
105  // Return the non-pre/post incrementing version of 'Opc'. Return 0
106  // if there is not such an opcode.
107  virtual unsigned getUnindexedOpcode(unsigned Opc) const =0;
108
109  MachineInstr *convertToThreeAddress(MachineFunction::iterator &MFI,
110                                      MachineBasicBlock::iterator &MBBI,
111                                      LiveVariables *LV) const override;
112
113  virtual const ARMBaseRegisterInfo &getRegisterInfo() const = 0;
114  const ARMSubtarget &getSubtarget() const { return Subtarget; }
115
116  ScheduleHazardRecognizer *
117  CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
118                               const ScheduleDAG *DAG) const override;
119
120  ScheduleHazardRecognizer *
121  CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
122                                     const ScheduleDAG *DAG) const override;
123
124  // Branch analysis.
125  bool AnalyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
126                     MachineBasicBlock *&FBB,
127                     SmallVectorImpl<MachineOperand> &Cond,
128                     bool AllowModify = false) const override;
129  unsigned RemoveBranch(MachineBasicBlock &MBB) const override;
130  unsigned InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
131                        MachineBasicBlock *FBB, ArrayRef<MachineOperand> Cond,
132                        DebugLoc DL) const override;
133
134  bool
135  ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const override;
136
137  // Predication support.
138  bool isPredicated(const MachineInstr *MI) const override;
139
140  ARMCC::CondCodes getPredicate(const MachineInstr *MI) const {
141    int PIdx = MI->findFirstPredOperandIdx();
142    return PIdx != -1 ? (ARMCC::CondCodes)MI->getOperand(PIdx).getImm()
143                      : ARMCC::AL;
144  }
145
146  bool PredicateInstruction(MachineInstr *MI,
147                    ArrayRef<MachineOperand> Pred) const override;
148
149  bool SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
150                         ArrayRef<MachineOperand> Pred2) const override;
151
152  bool DefinesPredicate(MachineInstr *MI,
153                        std::vector<MachineOperand> &Pred) const override;
154
155  bool isPredicable(MachineInstr *MI) const override;
156
157  /// GetInstSize - Returns the size of the specified MachineInstr.
158  ///
159  virtual unsigned GetInstSizeInBytes(const MachineInstr* MI) const;
160
161  unsigned isLoadFromStackSlot(const MachineInstr *MI,
162                               int &FrameIndex) const override;
163  unsigned isStoreToStackSlot(const MachineInstr *MI,
164                              int &FrameIndex) const override;
165  unsigned isLoadFromStackSlotPostFE(const MachineInstr *MI,
166                                     int &FrameIndex) const override;
167  unsigned isStoreToStackSlotPostFE(const MachineInstr *MI,
168                                    int &FrameIndex) const override;
169
170  void copyToCPSR(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
171                  unsigned SrcReg, bool KillSrc,
172                  const ARMSubtarget &Subtarget) const;
173  void copyFromCPSR(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
174                    unsigned DestReg, bool KillSrc,
175                    const ARMSubtarget &Subtarget) const;
176
177  void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
178                   DebugLoc DL, unsigned DestReg, unsigned SrcReg,
179                   bool KillSrc) const override;
180
181  void storeRegToStackSlot(MachineBasicBlock &MBB,
182                           MachineBasicBlock::iterator MBBI,
183                           unsigned SrcReg, bool isKill, int FrameIndex,
184                           const TargetRegisterClass *RC,
185                           const TargetRegisterInfo *TRI) const override;
186
187  void loadRegFromStackSlot(MachineBasicBlock &MBB,
188                            MachineBasicBlock::iterator MBBI,
189                            unsigned DestReg, int FrameIndex,
190                            const TargetRegisterClass *RC,
191                            const TargetRegisterInfo *TRI) const override;
192
193  bool expandPostRAPseudo(MachineBasicBlock::iterator MI) const override;
194
195  void reMaterialize(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
196                     unsigned DestReg, unsigned SubIdx,
197                     const MachineInstr *Orig,
198                     const TargetRegisterInfo &TRI) const override;
199
200  MachineInstr *duplicate(MachineInstr *Orig,
201                          MachineFunction &MF) const override;
202
203  const MachineInstrBuilder &AddDReg(MachineInstrBuilder &MIB, unsigned Reg,
204                                     unsigned SubIdx, unsigned State,
205                                     const TargetRegisterInfo *TRI) const;
206
207  bool produceSameValue(const MachineInstr *MI0, const MachineInstr *MI1,
208                        const MachineRegisterInfo *MRI) const override;
209
210  /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to
211  /// determine if two loads are loading from the same base address. It should
212  /// only return true if the base pointers are the same and the only
213  /// differences between the two addresses is the offset. It also returns the
214  /// offsets by reference.
215  bool areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2, int64_t &Offset1,
216                               int64_t &Offset2) const override;
217
218  /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
219  /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads
220  /// should be scheduled togther. On some targets if two loads are loading from
221  /// addresses in the same cache line, it's better if they are scheduled
222  /// together. This function takes two integers that represent the load offsets
223  /// from the common base address. It returns true if it decides it's desirable
224  /// to schedule the two loads together. "NumLoads" is the number of loads that
225  /// have already been scheduled after Load1.
226  bool shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
227                               int64_t Offset1, int64_t Offset2,
228                               unsigned NumLoads) const override;
229
230  bool isSchedulingBoundary(const MachineInstr *MI,
231                            const MachineBasicBlock *MBB,
232                            const MachineFunction &MF) const override;
233
234  bool isProfitableToIfCvt(MachineBasicBlock &MBB,
235                           unsigned NumCycles, unsigned ExtraPredCycles,
236                           BranchProbability Probability) const override;
237
238  bool isProfitableToIfCvt(MachineBasicBlock &TMBB, unsigned NumT,
239                           unsigned ExtraT, MachineBasicBlock &FMBB,
240                           unsigned NumF, unsigned ExtraF,
241                           BranchProbability Probability) const override;
242
243  bool isProfitableToDupForIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
244                                 BranchProbability Probability) const override {
245    return NumCycles == 1;
246  }
247
248  bool isProfitableToUnpredicate(MachineBasicBlock &TMBB,
249                                 MachineBasicBlock &FMBB) const override;
250
251  /// analyzeCompare - For a comparison instruction, return the source registers
252  /// in SrcReg and SrcReg2 if having two register operands, and the value it
253  /// compares against in CmpValue. Return true if the comparison instruction
254  /// can be analyzed.
255  bool analyzeCompare(const MachineInstr *MI, unsigned &SrcReg,
256                      unsigned &SrcReg2, int &CmpMask,
257                      int &CmpValue) const override;
258
259  /// optimizeCompareInstr - Convert the instruction to set the zero flag so
260  /// that we can remove a "comparison with zero"; Remove a redundant CMP
261  /// instruction if the flags can be updated in the same way by an earlier
262  /// instruction such as SUB.
263  bool optimizeCompareInstr(MachineInstr *CmpInstr, unsigned SrcReg,
264                            unsigned SrcReg2, int CmpMask, int CmpValue,
265                            const MachineRegisterInfo *MRI) const override;
266
267  bool analyzeSelect(const MachineInstr *MI,
268                     SmallVectorImpl<MachineOperand> &Cond,
269                     unsigned &TrueOp, unsigned &FalseOp,
270                     bool &Optimizable) const override;
271
272  MachineInstr *optimizeSelect(MachineInstr *MI,
273                               SmallPtrSetImpl<MachineInstr *> &SeenMIs,
274                               bool) const override;
275
276  /// FoldImmediate - 'Reg' is known to be defined by a move immediate
277  /// instruction, try to fold the immediate into the use instruction.
278  bool FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
279                     unsigned Reg, MachineRegisterInfo *MRI) const override;
280
281  unsigned getNumMicroOps(const InstrItineraryData *ItinData,
282                          const MachineInstr *MI) const override;
283
284  int getOperandLatency(const InstrItineraryData *ItinData,
285                        const MachineInstr *DefMI, unsigned DefIdx,
286                        const MachineInstr *UseMI,
287                        unsigned UseIdx) const override;
288  int getOperandLatency(const InstrItineraryData *ItinData,
289                        SDNode *DefNode, unsigned DefIdx,
290                        SDNode *UseNode, unsigned UseIdx) const override;
291
292  /// VFP/NEON execution domains.
293  std::pair<uint16_t, uint16_t>
294  getExecutionDomain(const MachineInstr *MI) const override;
295  void setExecutionDomain(MachineInstr *MI, unsigned Domain) const override;
296
297  unsigned getPartialRegUpdateClearance(const MachineInstr*, unsigned,
298                                      const TargetRegisterInfo*) const override;
299  void breakPartialRegDependency(MachineBasicBlock::iterator, unsigned,
300                                 const TargetRegisterInfo *TRI) const override;
301
302  /// Get the number of addresses by LDM or VLDM or zero for unknown.
303  unsigned getNumLDMAddresses(const MachineInstr *MI) const;
304
305private:
306  unsigned getInstBundleLength(const MachineInstr *MI) const;
307
308  int getVLDMDefCycle(const InstrItineraryData *ItinData,
309                      const MCInstrDesc &DefMCID,
310                      unsigned DefClass,
311                      unsigned DefIdx, unsigned DefAlign) const;
312  int getLDMDefCycle(const InstrItineraryData *ItinData,
313                     const MCInstrDesc &DefMCID,
314                     unsigned DefClass,
315                     unsigned DefIdx, unsigned DefAlign) const;
316  int getVSTMUseCycle(const InstrItineraryData *ItinData,
317                      const MCInstrDesc &UseMCID,
318                      unsigned UseClass,
319                      unsigned UseIdx, unsigned UseAlign) const;
320  int getSTMUseCycle(const InstrItineraryData *ItinData,
321                     const MCInstrDesc &UseMCID,
322                     unsigned UseClass,
323                     unsigned UseIdx, unsigned UseAlign) const;
324  int getOperandLatency(const InstrItineraryData *ItinData,
325                        const MCInstrDesc &DefMCID,
326                        unsigned DefIdx, unsigned DefAlign,
327                        const MCInstrDesc &UseMCID,
328                        unsigned UseIdx, unsigned UseAlign) const;
329
330  unsigned getPredicationCost(const MachineInstr *MI) const override;
331
332  unsigned getInstrLatency(const InstrItineraryData *ItinData,
333                           const MachineInstr *MI,
334                           unsigned *PredCost = nullptr) const override;
335
336  int getInstrLatency(const InstrItineraryData *ItinData,
337                      SDNode *Node) const override;
338
339  bool hasHighOperandLatency(const TargetSchedModel &SchedModel,
340                             const MachineRegisterInfo *MRI,
341                             const MachineInstr *DefMI, unsigned DefIdx,
342                             const MachineInstr *UseMI,
343                             unsigned UseIdx) const override;
344  bool hasLowDefLatency(const TargetSchedModel &SchedModel,
345                        const MachineInstr *DefMI,
346                        unsigned DefIdx) const override;
347
348  /// verifyInstruction - Perform target specific instruction verification.
349  bool verifyInstruction(const MachineInstr *MI,
350                         StringRef &ErrInfo) const override;
351
352  virtual void expandLoadStackGuard(MachineBasicBlock::iterator MI,
353                                    Reloc::Model RM) const = 0;
354
355  void expandMEMCPY(MachineBasicBlock::iterator) const;
356
357private:
358  /// Modeling special VFP / NEON fp MLA / MLS hazards.
359
360  /// MLxEntryMap - Map fp MLA / MLS to the corresponding entry in the internal
361  /// MLx table.
362  DenseMap<unsigned, unsigned> MLxEntryMap;
363
364  /// MLxHazardOpcodes - Set of add / sub and multiply opcodes that would cause
365  /// stalls when scheduled together with fp MLA / MLS opcodes.
366  SmallSet<unsigned, 16> MLxHazardOpcodes;
367
368public:
369  /// isFpMLxInstruction - Return true if the specified opcode is a fp MLA / MLS
370  /// instruction.
371  bool isFpMLxInstruction(unsigned Opcode) const {
372    return MLxEntryMap.count(Opcode);
373  }
374
375  /// isFpMLxInstruction - This version also returns the multiply opcode and the
376  /// addition / subtraction opcode to expand to. Return true for 'HasLane' for
377  /// the MLX instructions with an extra lane operand.
378  bool isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc,
379                          unsigned &AddSubOpc, bool &NegAcc,
380                          bool &HasLane) const;
381
382  /// canCauseFpMLxStall - Return true if an instruction of the specified opcode
383  /// will cause stalls when scheduled after (within 4-cycle window) a fp
384  /// MLA / MLS instruction.
385  bool canCauseFpMLxStall(unsigned Opcode) const {
386    return MLxHazardOpcodes.count(Opcode);
387  }
388
389  /// Returns true if the instruction has a shift by immediate that can be
390  /// executed in one cycle less.
391  bool isSwiftFastImmShift(const MachineInstr *MI) const;
392};
393
394static inline
395const MachineInstrBuilder &AddDefaultPred(const MachineInstrBuilder &MIB) {
396  return MIB.addImm((int64_t)ARMCC::AL).addReg(0);
397}
398
399static inline
400const MachineInstrBuilder &AddDefaultCC(const MachineInstrBuilder &MIB) {
401  return MIB.addReg(0);
402}
403
404static inline
405const MachineInstrBuilder &AddDefaultT1CC(const MachineInstrBuilder &MIB,
406                                          bool isDead = false) {
407  return MIB.addReg(ARM::CPSR, getDefRegState(true) | getDeadRegState(isDead));
408}
409
410static inline
411const MachineInstrBuilder &AddNoT1CC(const MachineInstrBuilder &MIB) {
412  return MIB.addReg(0);
413}
414
415static inline
416bool isUncondBranchOpcode(int Opc) {
417  return Opc == ARM::B || Opc == ARM::tB || Opc == ARM::t2B;
418}
419
420static inline
421bool isCondBranchOpcode(int Opc) {
422  return Opc == ARM::Bcc || Opc == ARM::tBcc || Opc == ARM::t2Bcc;
423}
424
425static inline
426bool isJumpTableBranchOpcode(int Opc) {
427  return Opc == ARM::BR_JTr || Opc == ARM::BR_JTm || Opc == ARM::BR_JTadd ||
428    Opc == ARM::tBR_JTr || Opc == ARM::t2BR_JT;
429}
430
431static inline
432bool isIndirectBranchOpcode(int Opc) {
433  return Opc == ARM::BX || Opc == ARM::MOVPCRX || Opc == ARM::tBRIND;
434}
435
436static inline bool isPopOpcode(int Opc) {
437  return Opc == ARM::tPOP_RET || Opc == ARM::LDMIA_RET ||
438         Opc == ARM::t2LDMIA_RET || Opc == ARM::tPOP || Opc == ARM::LDMIA_UPD ||
439         Opc == ARM::t2LDMIA_UPD || Opc == ARM::VLDMDIA_UPD;
440}
441
442static inline bool isPushOpcode(int Opc) {
443  return Opc == ARM::tPUSH || Opc == ARM::t2STMDB_UPD ||
444         Opc == ARM::STMDB_UPD || Opc == ARM::VSTMDDB_UPD;
445}
446
447/// getInstrPredicate - If instruction is predicated, returns its predicate
448/// condition, otherwise returns AL. It also returns the condition code
449/// register by reference.
450ARMCC::CondCodes getInstrPredicate(const MachineInstr *MI, unsigned &PredReg);
451
452unsigned getMatchingCondBranchOpcode(unsigned Opc);
453
454/// Determine if MI can be folded into an ARM MOVCC instruction, and return the
455/// opcode of the SSA instruction representing the conditional MI.
456unsigned canFoldARMInstrIntoMOVCC(unsigned Reg,
457                                  MachineInstr *&MI,
458                                  const MachineRegisterInfo &MRI);
459
460/// Map pseudo instructions that imply an 'S' bit onto real opcodes. Whether
461/// the instruction is encoded with an 'S' bit is determined by the optional
462/// CPSR def operand.
463unsigned convertAddSubFlagsOpcode(unsigned OldOpc);
464
465/// emitARMRegPlusImmediate / emitT2RegPlusImmediate - Emits a series of
466/// instructions to materializea destreg = basereg + immediate in ARM / Thumb2
467/// code.
468void emitARMRegPlusImmediate(MachineBasicBlock &MBB,
469                             MachineBasicBlock::iterator &MBBI, DebugLoc dl,
470                             unsigned DestReg, unsigned BaseReg, int NumBytes,
471                             ARMCC::CondCodes Pred, unsigned PredReg,
472                             const ARMBaseInstrInfo &TII, unsigned MIFlags = 0);
473
474void emitT2RegPlusImmediate(MachineBasicBlock &MBB,
475                            MachineBasicBlock::iterator &MBBI, DebugLoc dl,
476                            unsigned DestReg, unsigned BaseReg, int NumBytes,
477                            ARMCC::CondCodes Pred, unsigned PredReg,
478                            const ARMBaseInstrInfo &TII, unsigned MIFlags = 0);
479void emitThumbRegPlusImmediate(MachineBasicBlock &MBB,
480                               MachineBasicBlock::iterator &MBBI, DebugLoc dl,
481                               unsigned DestReg, unsigned BaseReg,
482                               int NumBytes, const TargetInstrInfo &TII,
483                               const ARMBaseRegisterInfo& MRI,
484                               unsigned MIFlags = 0);
485
486/// Tries to add registers to the reglist of a given base-updating
487/// push/pop instruction to adjust the stack by an additional
488/// NumBytes. This can save a few bytes per function in code-size, but
489/// obviously generates more memory traffic. As such, it only takes
490/// effect in functions being optimised for size.
491bool tryFoldSPUpdateIntoPushPop(const ARMSubtarget &Subtarget,
492                                MachineFunction &MF, MachineInstr *MI,
493                                unsigned NumBytes);
494
495/// rewriteARMFrameIndex / rewriteT2FrameIndex -
496/// Rewrite MI to access 'Offset' bytes from the FP. Return false if the
497/// offset could not be handled directly in MI, and return the left-over
498/// portion by reference.
499bool rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
500                          unsigned FrameReg, int &Offset,
501                          const ARMBaseInstrInfo &TII);
502
503bool rewriteT2FrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
504                         unsigned FrameReg, int &Offset,
505                         const ARMBaseInstrInfo &TII);
506
507} // End llvm namespace
508
509#endif
510