Debian Codegraph @

suite/synctools/tablegen/include/llvm/CodeGen/TargetInstrInfo.h

raw symbols SCIP
1 //===- llvm/CodeGen/TargetInstrInfo.h - Instruction Info --------*- 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 describes the target machine instruction set to the code generator.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_CODEGEN_TARGETINSTRINFO_H
14 #define LLVM_CODEGEN_TARGETINSTRINFO_H
15
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DenseMapInfo.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/CodeGen/MIRFormatter.h"
21 #include "llvm/CodeGen/MachineBasicBlock.h"
22 #include "llvm/CodeGen/MachineCombinerPattern.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineOperand.h"
27 #include "llvm/CodeGen/MachineOutliner.h"
28 #include "llvm/CodeGen/RegisterClassInfo.h"
29 #include "llvm/CodeGen/VirtRegMap.h"
30 #include "llvm/MC/MCInstrInfo.h"
31 #include "llvm/Support/BranchProbability.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include <cassert>
34 #include <cstddef>
35 #include <cstdint>
36 #include <utility>
37 #include <vector>
38
39 namespace llvm {
40
41 class AAResults;
42 class DFAPacketizer;
43 class InstrItineraryData;
44 class LiveIntervals;
45 class LiveVariables;
46 class MachineLoop;
47 class MachineMemOperand;
48 class MachineRegisterInfo;
49 class MCAsmInfo;
50 class MCInst;
51 struct MCSchedModel;
52 class Module;
53 class ScheduleDAG;
54 class ScheduleDAGMI;
55 class ScheduleHazardRecognizer;
56 class SDNode;
57 class SelectionDAG;
58 class RegScavenger;
59 class TargetRegisterClass;
60 class TargetRegisterInfo;
61 class TargetSchedModel;
62 class TargetSubtargetInfo;
63
64 template <class T> class SmallVectorImpl;
65
66 using ParamLoadedValue = std::pair<MachineOperand, DIExpression*>;
67
68 struct DestSourcePair {
69 const MachineOperand *Destination;
70 const MachineOperand *Source;
71
72 DestSourcePair(const MachineOperand &Dest, const MachineOperand &Src)
73 : Destination(&Dest), Source(&Src) {}
74 };
75
76 /// Used to describe a register and immediate addition.
77 struct RegImmPair {
78 Register Reg;
79 int64_t Imm;
80
81 RegImmPair(Register Reg, int64_t Imm) : Reg(Reg), Imm(Imm) {}
82 };
83
84 /// Used to describe addressing mode similar to ExtAddrMode in CodeGenPrepare.
85 /// It holds the register values, the scale value and the displacement.
86 struct ExtAddrMode {
87 Register BaseReg;
88 Register ScaledReg;
89 int64_t Scale;
90 int64_t Displacement;
91 };
92
93 //---------------------------------------------------------------------------
94 ///
95 /// TargetInstrInfo - Interface to description of machine instruction set
96 ///
97 class TargetInstrInfo : public MCInstrInfo {
98 public:
99 TargetInstrInfo(unsigned CFSetupOpcode = ~0u, unsigned CFDestroyOpcode = ~0u,
100 unsigned CatchRetOpcode = ~0u, unsigned ReturnOpcode = ~0u)
101 : CallFrameSetupOpcode(CFSetupOpcode),
102 CallFrameDestroyOpcode(CFDestroyOpcode), CatchRetOpcode(CatchRetOpcode),
103 ReturnOpcode(ReturnOpcode) {}
104 TargetInstrInfo(const TargetInstrInfo &) = delete;
105 TargetInstrInfo &operator=(const TargetInstrInfo &) = delete;
106 virtual ~TargetInstrInfo();
107
108 static bool isGenericOpcode(unsigned Opc) {
109 return Opc <= TargetOpcode::GENERIC_OP_END;
110 }
111
112 /// Given a machine instruction descriptor, returns the register
113 /// class constraint for OpNum, or NULL.
114 virtual
115 const TargetRegisterClass *getRegClass(const MCInstrDesc &MCID, unsigned OpNum,
116 const TargetRegisterInfo *TRI,
117 const MachineFunction &MF) const;
118
119 /// Return true if the instruction is trivially rematerializable, meaning it
120 /// has no side effects and requires no operands that aren't always available.
121 /// This means the only allowed uses are constants and unallocatable physical
122 /// registers so that the instructions result is independent of the place
123 /// in the function.
124 bool isTriviallyReMaterializable(const MachineInstr &MI,
125 AAResults *AA = nullptr) const {
126 return MI.getOpcode() == TargetOpcode::IMPLICIT_DEF ||
127 (MI.getDesc().isRematerializable() &&
128 (isReallyTriviallyReMaterializable(MI, AA) ||
129 isReallyTriviallyReMaterializableGeneric(MI, AA)));
130 }
131
132 /// Given \p MO is a PhysReg use return if it can be ignored for the purpose
133 /// of instruction rematerialization or sinking.
134 virtual bool isIgnorableUse(const MachineOperand &MO) const {
135 return false;
136 }
137
138 protected:
139 /// For instructions with opcodes for which the M_REMATERIALIZABLE flag is
140 /// set, this hook lets the target specify whether the instruction is actually
141 /// trivially rematerializable, taking into consideration its operands. This
142 /// predicate must return false if the instruction has any side effects other
143 /// than producing a value, or if it requres any address registers that are
144 /// not always available.
145 /// Requirements must be check as stated in isTriviallyReMaterializable() .
146 virtual bool isReallyTriviallyReMaterializable(const MachineInstr &MI,
147 AAResults *AA) const {
148 return false;
149 }
150
151 /// This method commutes the operands of the given machine instruction MI.
152 /// The operands to be commuted are specified by their indices OpIdx1 and
153 /// OpIdx2.
154 ///
155 /// If a target has any instructions that are commutable but require
156 /// converting to different instructions or making non-trivial changes
157 /// to commute them, this method can be overloaded to do that.
158 /// The default implementation simply swaps the commutable operands.
159 ///
160 /// If NewMI is false, MI is modified in place and returned; otherwise, a
161 /// new machine instruction is created and returned.
162 ///
163 /// Do not call this method for a non-commutable instruction.
164 /// Even though the instruction is commutable, the method may still
165 /// fail to commute the operands, null pointer is returned in such cases.
166 virtual MachineInstr *commuteInstructionImpl(MachineInstr &MI, bool NewMI,
167 unsigned OpIdx1,
168 unsigned OpIdx2) const;
169
170 /// Assigns the (CommutableOpIdx1, CommutableOpIdx2) pair of commutable
171 /// operand indices to (ResultIdx1, ResultIdx2).
172 /// One or both input values of the pair: (ResultIdx1, ResultIdx2) may be
173 /// predefined to some indices or be undefined (designated by the special
174 /// value 'CommuteAnyOperandIndex').
175 /// The predefined result indices cannot be re-defined.
176 /// The function returns true iff after the result pair redefinition
177 /// the fixed result pair is equal to or equivalent to the source pair of
178 /// indices: (CommutableOpIdx1, CommutableOpIdx2). It is assumed here that
179 /// the pairs (x,y) and (y,x) are equivalent.
180 static bool fixCommutedOpIndices(unsigned &ResultIdx1, unsigned &ResultIdx2,
181 unsigned CommutableOpIdx1,
182 unsigned CommutableOpIdx2);
183
184 private:
185 /// For instructions with opcodes for which the M_REMATERIALIZABLE flag is
186 /// set and the target hook isReallyTriviallyReMaterializable returns false,
187 /// this function does target-independent tests to determine if the
188 /// instruction is really trivially rematerializable.
189 bool isReallyTriviallyReMaterializableGeneric(const MachineInstr &MI,
190 AAResults *AA) const;
191
192 public:
193 /// These methods return the opcode of the frame setup/destroy instructions
194 /// if they exist (-1 otherwise). Some targets use pseudo instructions in
195 /// order to abstract away the difference between operating with a frame
196 /// pointer and operating without, through the use of these two instructions.
197 ///
198 unsigned getCallFrameSetupOpcode() const { return CallFrameSetupOpcode; }
199 unsigned getCallFrameDestroyOpcode() const { return CallFrameDestroyOpcode; }
200
201 /// Returns true if the argument is a frame pseudo instruction.
202 bool isFrameInstr(const MachineInstr &I) const {
203 return I.getOpcode() == getCallFrameSetupOpcode() ||
204 I.getOpcode() == getCallFrameDestroyOpcode();
205 }
206
207 /// Returns true if the argument is a frame setup pseudo instruction.
208 bool isFrameSetup(const MachineInstr &I) const {
209 return I.getOpcode() == getCallFrameSetupOpcode();
210 }
211
212 /// Returns size of the frame associated with the given frame instruction.
213 /// For frame setup instruction this is frame that is set up space set up
214 /// after the instruction. For frame destroy instruction this is the frame
215 /// freed by the caller.
216 /// Note, in some cases a call frame (or a part of it) may be prepared prior
217 /// to the frame setup instruction. It occurs in the calls that involve
218 /// inalloca arguments. This function reports only the size of the frame part
219 /// that is set up between the frame setup and destroy pseudo instructions.
220 int64_t getFrameSize(const MachineInstr &I) const {
221 assert(isFrameInstr(I) && "Not a frame instruction");
222 assert(I.getOperand(0).getImm() >= 0);
223 return I.getOperand(0).getImm();
224 }
225
226 /// Returns the total frame size, which is made up of the space set up inside
227 /// the pair of frame start-stop instructions and the space that is set up
228 /// prior to the pair.
229 int64_t getFrameTotalSize(const MachineInstr &I) const {
230 if (isFrameSetup(I)) {
231 assert(I.getOperand(1).getImm() >= 0 &&
232 "Frame size must not be negative");
233 return getFrameSize(I) + I.getOperand(1).getImm();
234 }
235 return getFrameSize(I);
236 }
237
238 unsigned getCatchReturnOpcode() const { return CatchRetOpcode; }
239 unsigned getReturnOpcode() const { return ReturnOpcode; }
240
241 /// Returns the actual stack pointer adjustment made by an instruction
242 /// as part of a call sequence. By default, only call frame setup/destroy
243 /// instructions adjust the stack, but targets may want to override this
244 /// to enable more fine-grained adjustment, or adjust by a different value.
245 virtual int getSPAdjust(const MachineInstr &MI) const;
246
247 /// Return true if the instruction is a "coalescable" extension instruction.
248 /// That is, it's like a copy where it's legal for the source to overlap the
249 /// destination. e.g. X86::MOVSX64rr32. If this returns true, then it's
250 /// expected the pre-extension value is available as a subreg of the result
251 /// register. This also returns the sub-register index in SubIdx.
252 virtual bool isCoalescableExtInstr(const MachineInstr &MI, Register &SrcReg,
253 Register &DstReg, unsigned &SubIdx) const {
254 return false;
255 }
256
257 /// If the specified machine instruction is a direct
258 /// load from a stack slot, return the virtual or physical register number of
259 /// the destination along with the FrameIndex of the loaded stack slot. If
260 /// not, return 0. This predicate must return 0 if the instruction has
261 /// any side effects other than loading from the stack slot.
262 virtual unsigned isLoadFromStackSlot(const MachineInstr &MI,
263 int &FrameIndex) const {
264 return 0;
265 }
266
267 /// Optional extension of isLoadFromStackSlot that returns the number of
268 /// bytes loaded from the stack. This must be implemented if a backend
269 /// supports partial stack slot spills/loads to further disambiguate
270 /// what the load does.
271 virtual unsigned isLoadFromStackSlot(const MachineInstr &MI,
272 int &FrameIndex,
273 unsigned &MemBytes) const {
274 MemBytes = 0;
275 return isLoadFromStackSlot(MI, FrameIndex);
276 }
277
278 /// Check for post-frame ptr elimination stack locations as well.
279 /// This uses a heuristic so it isn't reliable for correctness.
280 virtual unsigned isLoadFromStackSlotPostFE(const MachineInstr &MI,
281 int &FrameIndex) const {
282 return 0;
283 }
284
285 /// If the specified machine instruction has a load from a stack slot,
286 /// return true along with the FrameIndices of the loaded stack slot and the
287 /// machine mem operands containing the reference.
288 /// If not, return false. Unlike isLoadFromStackSlot, this returns true for
289 /// any instructions that loads from the stack. This is just a hint, as some
290 /// cases may be missed.
291 virtual bool hasLoadFromStackSlot(
292 const MachineInstr &MI,
293 SmallVectorImpl<const MachineMemOperand *> &Accesses) const;
294
295 /// If the specified machine instruction is a direct
296 /// store to a stack slot, return the virtual or physical register number of
297 /// the source reg along with the FrameIndex of the loaded stack slot. If
298 /// not, return 0. This predicate must return 0 if the instruction has
299 /// any side effects other than storing to the stack slot.
300 virtual unsigned isStoreToStackSlot(const MachineInstr &MI,
301 int &FrameIndex) const {
302 return 0;
303 }
304
305 /// Optional extension of isStoreToStackSlot that returns the number of
306 /// bytes stored to the stack. This must be implemented if a backend
307 /// supports partial stack slot spills/loads to further disambiguate
308 /// what the store does.
309 virtual unsigned isStoreToStackSlot(const MachineInstr &MI,
310 int &FrameIndex,
311 unsigned &MemBytes) const {
312 MemBytes = 0;
313 return isStoreToStackSlot(MI, FrameIndex);
314 }
315
316 /// Check for post-frame ptr elimination stack locations as well.
317 /// This uses a heuristic, so it isn't reliable for correctness.
318 virtual unsigned isStoreToStackSlotPostFE(const MachineInstr &MI,
319 int &FrameIndex) const {
320 return 0;
321 }
322
323 /// If the specified machine instruction has a store to a stack slot,
324 /// return true along with the FrameIndices of the loaded stack slot and the
325 /// machine mem operands containing the reference.
326 /// If not, return false. Unlike isStoreToStackSlot,
327 /// this returns true for any instructions that stores to the
328 /// stack. This is just a hint, as some cases may be missed.
329 virtual bool hasStoreToStackSlot(
330 const MachineInstr &MI,
331 SmallVectorImpl<const MachineMemOperand *> &Accesses) const;
332
333 /// Return true if the specified machine instruction
334 /// is a copy of one stack slot to another and has no other effect.
335 /// Provide the identity of the two frame indices.
336 virtual bool isStackSlotCopy(const MachineInstr &MI, int &DestFrameIndex,
337 int &SrcFrameIndex) const {
338 return false;
339 }
340
341 /// Compute the size in bytes and offset within a stack slot of a spilled
342 /// register or subregister.
343 ///
344 /// \param [out] Size in bytes of the spilled value.
345 /// \param [out] Offset in bytes within the stack slot.
346 /// \returns true if both Size and Offset are successfully computed.
347 ///
348 /// Not all subregisters have computable spill slots. For example,
349 /// subregisters registers may not be byte-sized, and a pair of discontiguous
350 /// subregisters has no single offset.
351 ///
352 /// Targets with nontrivial bigendian implementations may need to override
353 /// this, particularly to support spilled vector registers.
354 virtual bool getStackSlotRange(const TargetRegisterClass *RC, unsigned SubIdx,
355 unsigned &Size, unsigned &Offset,
356 const MachineFunction &MF) const;
357
358 /// Return true if the given instruction is terminator that is unspillable,
359 /// according to isUnspillableTerminatorImpl.
360 bool isUnspillableTerminator(const MachineInstr *MI) const {
361 return MI->isTerminator() && isUnspillableTerminatorImpl(MI);
362 }
363
364 /// Returns the size in bytes of the specified MachineInstr, or ~0U
365 /// when this function is not implemented by a target.
366 virtual unsigned getInstSizeInBytes(const MachineInstr &MI) const {
367 return ~0U;
368 }
369
370 /// Return true if the instruction is as cheap as a move instruction.
371 ///
372 /// Targets for different archs need to override this, and different
373 /// micro-architectures can also be finely tuned inside.
374 virtual bool isAsCheapAsAMove(const MachineInstr &MI) const {
375 return MI.isAsCheapAsAMove();
376 }
377
378 /// Return true if the instruction should be sunk by MachineSink.
379 ///
380 /// MachineSink determines on its own whether the instruction is safe to sink;
381 /// this gives the target a hook to override the default behavior with regards
382 /// to which instructions should be sunk.
383 virtual bool shouldSink(const MachineInstr &MI) const { return true; }
384
385 /// Re-issue the specified 'original' instruction at the
386 /// specific location targeting a new destination register.
387 /// The register in Orig->getOperand(0).getReg() will be substituted by
388 /// DestReg:SubIdx. Any existing subreg index is preserved or composed with
389 /// SubIdx.
390 virtual void reMaterialize(MachineBasicBlock &MBB,
391 MachineBasicBlock::iterator MI, Register DestReg,
392 unsigned SubIdx, const MachineInstr &Orig,
393 const TargetRegisterInfo &TRI) const;
394
395 /// Clones instruction or the whole instruction bundle \p Orig and
396 /// insert into \p MBB before \p InsertBefore. The target may update operands
397 /// that are required to be unique.
398 ///
399 /// \p Orig must not return true for MachineInstr::isNotDuplicable().
400 virtual MachineInstr &duplicate(MachineBasicBlock &MBB,
401 MachineBasicBlock::iterator InsertBefore,
402 const MachineInstr &Orig) const;
403
404 /// This method must be implemented by targets that
405 /// set the M_CONVERTIBLE_TO_3_ADDR flag. When this flag is set, the target
406 /// may be able to convert a two-address instruction into one or more true
407 /// three-address instructions on demand. This allows the X86 target (for
408 /// example) to convert ADD and SHL instructions into LEA instructions if they
409 /// would require register copies due to two-addressness.
410 ///
411 /// This method returns a null pointer if the transformation cannot be
412 /// performed, otherwise it returns the last new instruction.
413 ///
414 /// If \p LIS is not nullptr, the LiveIntervals info should be updated for
415 /// replacing \p MI with new instructions, even though this function does not
416 /// remove MI.
417 virtual MachineInstr *convertToThreeAddress(MachineInstr &MI,
418 LiveVariables *LV,
419 LiveIntervals *LIS) const {
420 return nullptr;
421 }
422
423 // This constant can be used as an input value of operand index passed to
424 // the method findCommutedOpIndices() to tell the method that the
425 // corresponding operand index is not pre-defined and that the method
426 // can pick any commutable operand.
427 static const unsigned CommuteAnyOperandIndex = ~0U;
428
429 /// This method commutes the operands of the given machine instruction MI.
430 ///
431 /// The operands to be commuted are specified by their indices OpIdx1 and
432 /// OpIdx2. OpIdx1 and OpIdx2 arguments may be set to a special value
433 /// 'CommuteAnyOperandIndex', which means that the method is free to choose
434 /// any arbitrarily chosen commutable operand. If both arguments are set to
435 /// 'CommuteAnyOperandIndex' then the method looks for 2 different commutable
436 /// operands; then commutes them if such operands could be found.
437 ///
438 /// If NewMI is false, MI is modified in place and returned; otherwise, a
439 /// new machine instruction is created and returned.
440 ///
441 /// Do not call this method for a non-commutable instruction or
442 /// for non-commuable operands.
443 /// Even though the instruction is commutable, the method may still
444 /// fail to commute the operands, null pointer is returned in such cases.
445 MachineInstr *
446 commuteInstruction(MachineInstr &MI, bool NewMI = false,
447 unsigned OpIdx1 = CommuteAnyOperandIndex,
448 unsigned OpIdx2 = CommuteAnyOperandIndex) const;
449
450 /// Returns true iff the routine could find two commutable operands in the
451 /// given machine instruction.
452 /// The 'SrcOpIdx1' and 'SrcOpIdx2' are INPUT and OUTPUT arguments.
453 /// If any of the INPUT values is set to the special value
454 /// 'CommuteAnyOperandIndex' then the method arbitrarily picks a commutable
455 /// operand, then returns its index in the corresponding argument.
456 /// If both of INPUT values are set to 'CommuteAnyOperandIndex' then method
457 /// looks for 2 commutable operands.
458 /// If INPUT values refer to some operands of MI, then the method simply
459 /// returns true if the corresponding operands are commutable and returns
460 /// false otherwise.
461 ///
462 /// For example, calling this method this way:
463 /// unsigned Op1 = 1, Op2 = CommuteAnyOperandIndex;
464 /// findCommutedOpIndices(MI, Op1, Op2);
465 /// can be interpreted as a query asking to find an operand that would be
466 /// commutable with the operand#1.
467 virtual bool findCommutedOpIndices(const MachineInstr &MI,
468 unsigned &SrcOpIdx1,
469 unsigned &SrcOpIdx2) const;
470
471 /// Returns true if the target has a preference on the operands order of
472 /// the given machine instruction. And specify if \p Commute is required to
473 /// get the desired operands order.
474 virtual bool hasCommutePreference(MachineInstr &MI, bool &Commute) const {
475 return false;
476 }
477
478 /// A pair composed of a register and a sub-register index.
479 /// Used to give some type checking when modeling Reg:SubReg.
480 struct RegSubRegPair {
481 Register Reg;
482 unsigned SubReg;
483
484 RegSubRegPair(Register Reg = Register(), unsigned SubReg = 0)
485 : Reg(Reg), SubReg(SubReg) {}
486
487 bool operator==(const RegSubRegPair& P) const {
488 return Reg == P.Reg && SubReg == P.SubReg;
489 }
490 bool operator!=(const RegSubRegPair& P) const {
491 return !(*this == P);
492 }
493 };
494
495 /// A pair composed of a pair of a register and a sub-register index,
496 /// and another sub-register index.
497 /// Used to give some type checking when modeling Reg:SubReg1, SubReg2.
498 struct RegSubRegPairAndIdx : RegSubRegPair {
499 unsigned SubIdx;
500
501 RegSubRegPairAndIdx(Register Reg = Register(), unsigned SubReg = 0,
502 unsigned SubIdx = 0)
503 : RegSubRegPair(Reg, SubReg), SubIdx(SubIdx) {}
504 };
505
506 /// Build the equivalent inputs of a REG_SEQUENCE for the given \p MI
507 /// and \p DefIdx.
508 /// \p [out] InputRegs of the equivalent REG_SEQUENCE. Each element of
509 /// the list is modeled as <Reg:SubReg, SubIdx>. Operands with the undef
510 /// flag are not added to this list.
511 /// E.g., REG_SEQUENCE %1:sub1, sub0, %2, sub1 would produce
512 /// two elements:
513 /// - %1:sub1, sub0
514 /// - %2<:0>, sub1
515 ///
516 /// \returns true if it is possible to build such an input sequence
517 /// with the pair \p MI, \p DefIdx. False otherwise.
518 ///
519 /// \pre MI.isRegSequence() or MI.isRegSequenceLike().
520 ///
521 /// \note The generic implementation does not provide any support for
522 /// MI.isRegSequenceLike(). In other words, one has to override
523 /// getRegSequenceLikeInputs for target specific instructions.
524 bool
525 getRegSequenceInputs(const MachineInstr &MI, unsigned DefIdx,
526 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const;
527
528 /// Build the equivalent inputs of a EXTRACT_SUBREG for the given \p MI
529 /// and \p DefIdx.
530 /// \p [out] InputReg of the equivalent EXTRACT_SUBREG.
531 /// E.g., EXTRACT_SUBREG %1:sub1, sub0, sub1 would produce:
532 /// - %1:sub1, sub0
533 ///
534 /// \returns true if it is possible to build such an input sequence
535 /// with the pair \p MI, \p DefIdx and the operand has no undef flag set.
536 /// False otherwise.
537 ///
538 /// \pre MI.isExtractSubreg() or MI.isExtractSubregLike().
539 ///
540 /// \note The generic implementation does not provide any support for
541 /// MI.isExtractSubregLike(). In other words, one has to override
542 /// getExtractSubregLikeInputs for target specific instructions.
543 bool getExtractSubregInputs(const MachineInstr &MI, unsigned DefIdx,
544 RegSubRegPairAndIdx &InputReg) const;
545
546 /// Build the equivalent inputs of a INSERT_SUBREG for the given \p MI
547 /// and \p DefIdx.
548 /// \p [out] BaseReg and \p [out] InsertedReg contain
549 /// the equivalent inputs of INSERT_SUBREG.
550 /// E.g., INSERT_SUBREG %0:sub0, %1:sub1, sub3 would produce:
551 /// - BaseReg: %0:sub0
552 /// - InsertedReg: %1:sub1, sub3
553 ///
554 /// \returns true if it is possible to build such an input sequence
555 /// with the pair \p MI, \p DefIdx and the operand has no undef flag set.
556 /// False otherwise.
557 ///
558 /// \pre MI.isInsertSubreg() or MI.isInsertSubregLike().
559 ///
560 /// \note The generic implementation does not provide any support for
561 /// MI.isInsertSubregLike(). In other words, one has to override
562 /// getInsertSubregLikeInputs for target specific instructions.
563 bool getInsertSubregInputs(const MachineInstr &MI, unsigned DefIdx,
564 RegSubRegPair &BaseReg,
565 RegSubRegPairAndIdx &InsertedReg) const;
566
567 /// Return true if two machine instructions would produce identical values.
568 /// By default, this is only true when the two instructions
569 /// are deemed identical except for defs. If this function is called when the
570 /// IR is still in SSA form, the caller can pass the MachineRegisterInfo for
571 /// aggressive checks.
572 virtual bool produceSameValue(const MachineInstr &MI0,
573 const MachineInstr &MI1,
574 const MachineRegisterInfo *MRI = nullptr) const;
575
576 /// \returns true if a branch from an instruction with opcode \p BranchOpc
577 /// bytes is capable of jumping to a position \p BrOffset bytes away.
578 virtual bool isBranchOffsetInRange(unsigned BranchOpc,
579 int64_t BrOffset) const {
580 llvm_unreachable("target did not implement");
581 }
582
583 /// \returns The block that branch instruction \p MI jumps to.
584 virtual MachineBasicBlock *getBranchDestBlock(const MachineInstr &MI) const {
585 llvm_unreachable("target did not implement");
586 }
587
588 /// Insert an unconditional indirect branch at the end of \p MBB to \p
589 /// NewDestBB. Optionally, insert the clobbered register restoring in \p
590 /// RestoreBB. \p BrOffset indicates the offset of \p NewDestBB relative to
591 /// the offset of the position to insert the new branch.
592 virtual void insertIndirectBranch(MachineBasicBlock &MBB,
593 MachineBasicBlock &NewDestBB,
594 MachineBasicBlock &RestoreBB,
595 const DebugLoc &DL, int64_t BrOffset = 0,
596 RegScavenger *RS = nullptr) const {
597 llvm_unreachable("target did not implement");
598 }
599
600 /// Analyze the branching code at the end of MBB, returning
601 /// true if it cannot be understood (e.g. it's a switch dispatch or isn't
602 /// implemented for a target). Upon success, this returns false and returns
603 /// with the following information in various cases:
604 ///
605 /// 1. If this block ends with no branches (it just falls through to its succ)
606 /// just return false, leaving TBB/FBB null.
607 /// 2. If this block ends with only an unconditional branch, it sets TBB to be
608 /// the destination block.
609 /// 3. If this block ends with a conditional branch and it falls through to a
610 /// successor block, it sets TBB to be the branch destination block and a
611 /// list of operands that evaluate the condition. These operands can be
612 /// passed to other TargetInstrInfo methods to create new branches.
613 /// 4. If this block ends with a conditional branch followed by an
614 /// unconditional branch, it returns the 'true' destination in TBB, the
615 /// 'false' destination in FBB, and a list of operands that evaluate the
616 /// condition. These operands can be passed to other TargetInstrInfo
617 /// methods to create new branches.
618 ///
619 /// Note that removeBranch and insertBranch must be implemented to support
620 /// cases where this method returns success.
621 ///
622 /// If AllowModify is true, then this routine is allowed to modify the basic
623 /// block (e.g. delete instructions after the unconditional branch).
624 ///
625 /// The CFG information in MBB.Predecessors and MBB.Successors must be valid
626 /// before calling this function.
627 virtual bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
628 MachineBasicBlock *&FBB,
629 SmallVectorImpl<MachineOperand> &Cond,
630 bool AllowModify = false) const {
631 return true;
632 }
633
634 /// Represents a predicate at the MachineFunction level. The control flow a
635 /// MachineBranchPredicate represents is:
636 ///
637 /// Reg = LHS `Predicate` RHS == ConditionDef
638 /// if Reg then goto TrueDest else goto FalseDest
639 ///
640 struct MachineBranchPredicate {
641 enum ComparePredicate {
642 PRED_EQ, // True if two values are equal
643 PRED_NE, // True if two values are not equal
644 PRED_INVALID // Sentinel value
645 };
646
647 ComparePredicate Predicate = PRED_INVALID;
648 MachineOperand LHS = MachineOperand::CreateImm(0);
649 MachineOperand RHS = MachineOperand::CreateImm(0);
650 MachineBasicBlock *TrueDest = nullptr;
651 MachineBasicBlock *FalseDest = nullptr;
652 MachineInstr *ConditionDef = nullptr;
653
654 /// SingleUseCondition is true if ConditionDef is dead except for the
655 /// branch(es) at the end of the basic block.
656 ///
657 bool SingleUseCondition = false;
658
659 explicit MachineBranchPredicate() = default;
660 };
661
662 /// Analyze the branching code at the end of MBB and parse it into the
663 /// MachineBranchPredicate structure if possible. Returns false on success
664 /// and true on failure.
665 ///
666 /// If AllowModify is true, then this routine is allowed to modify the basic
667 /// block (e.g. delete instructions after the unconditional branch).
668 ///
669 virtual bool analyzeBranchPredicate(MachineBasicBlock &MBB,
670 MachineBranchPredicate &MBP,
671 bool AllowModify = false) const {
672 return true;
673 }
674
675 /// Remove the branching code at the end of the specific MBB.
676 /// This is only invoked in cases where analyzeBranch returns success. It
677 /// returns the number of instructions that were removed.
678 /// If \p BytesRemoved is non-null, report the change in code size from the
679 /// removed instructions.
680 virtual unsigned removeBranch(MachineBasicBlock &MBB,
681 int *BytesRemoved = nullptr) const {
682 llvm_unreachable("Target didn't implement TargetInstrInfo::removeBranch!");
683 }
684
685 /// Insert branch code into the end of the specified MachineBasicBlock. The
686 /// operands to this method are the same as those returned by analyzeBranch.
687 /// This is only invoked in cases where analyzeBranch returns success. It
688 /// returns the number of instructions inserted. If \p BytesAdded is non-null,
689 /// report the change in code size from the added instructions.
690 ///
691 /// It is also invoked by tail merging to add unconditional branches in
692 /// cases where analyzeBranch doesn't apply because there was no original
693 /// branch to analyze. At least this much must be implemented, else tail
694 /// merging needs to be disabled.
695 ///
696 /// The CFG information in MBB.Predecessors and MBB.Successors must be valid
697 /// before calling this function.
698 virtual unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
699 MachineBasicBlock *FBB,
700 ArrayRef<MachineOperand> Cond,
701 const DebugLoc &DL,
702 int *BytesAdded = nullptr) const {
703 llvm_unreachable("Target didn't implement TargetInstrInfo::insertBranch!");
704 }
705
706 unsigned insertUnconditionalBranch(MachineBasicBlock &MBB,
707 MachineBasicBlock *DestBB,
708 const DebugLoc &DL,
709 int *BytesAdded = nullptr) const {
710 return insertBranch(MBB, DestBB, nullptr, ArrayRef<MachineOperand>(), DL,
711 BytesAdded);
712 }
713
714 /// Object returned by analyzeLoopForPipelining. Allows software pipelining
715 /// implementations to query attributes of the loop being pipelined and to
716 /// apply target-specific updates to the loop once pipelining is complete.
717 class PipelinerLoopInfo {
718 public:
719 virtual ~PipelinerLoopInfo();
720 /// Return true if the given instruction should not be pipelined and should
721 /// be ignored. An example could be a loop comparison, or induction variable
722 /// update with no users being pipelined.
723 virtual bool shouldIgnoreForPipelining(const MachineInstr *MI) const = 0;
724
725 /// Create a condition to determine if the trip count of the loop is greater
726 /// than TC.
727 ///
728 /// If the trip count is statically known to be greater than TC, return
729 /// true. If the trip count is statically known to be not greater than TC,
730 /// return false. Otherwise return nullopt and fill out Cond with the test
731 /// condition.
732 virtual Optional<bool>
733 createTripCountGreaterCondition(int TC, MachineBasicBlock &MBB,
734 SmallVectorImpl<MachineOperand> &Cond) = 0;
735
736 /// Modify the loop such that the trip count is
737 /// OriginalTC + TripCountAdjust.
738 virtual void adjustTripCount(int TripCountAdjust) = 0;
739
740 /// Called when the loop's preheader has been modified to NewPreheader.
741 virtual void setPreheader(MachineBasicBlock *NewPreheader) = 0;
742
743 /// Called when the loop is being removed. Any instructions in the preheader
744 /// should be removed.
745 ///
746 /// Once this function is called, no other functions on this object are
747 /// valid; the loop has been removed.
748 virtual void disposed() = 0;
749 };
750
751 /// Analyze loop L, which must be a single-basic-block loop, and if the
752 /// conditions can be understood enough produce a PipelinerLoopInfo object.
753 virtual std::unique_ptr<PipelinerLoopInfo>
754 analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const {
755 return nullptr;
756 }
757
758 /// Analyze the loop code, return true if it cannot be understood. Upon
759 /// success, this function returns false and returns information about the
760 /// induction variable and compare instruction used at the end.
761 virtual bool analyzeLoop(MachineLoop &L, MachineInstr *&IndVarInst,
762 MachineInstr *&CmpInst) const {
763 return true;
764 }
765
766 /// Generate code to reduce the loop iteration by one and check if the loop
767 /// is finished. Return the value/register of the new loop count. We need
768 /// this function when peeling off one or more iterations of a loop. This
769 /// function assumes the nth iteration is peeled first.
770 virtual unsigned reduceLoopCount(MachineBasicBlock &MBB,
771 MachineBasicBlock &PreHeader,
772 MachineInstr *IndVar, MachineInstr &Cmp,
773 SmallVectorImpl<MachineOperand> &Cond,
774 SmallVectorImpl<MachineInstr *> &PrevInsts,
775 unsigned Iter, unsigned MaxIter) const {
776 llvm_unreachable("Target didn't implement ReduceLoopCount");
777 }
778
779 /// Delete the instruction OldInst and everything after it, replacing it with
780 /// an unconditional branch to NewDest. This is used by the tail merging pass.
781 virtual void ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
782 MachineBasicBlock *NewDest) const;
783
784 /// Return true if it's legal to split the given basic
785 /// block at the specified instruction (i.e. instruction would be the start
786 /// of a new basic block).
787 virtual bool isLegalToSplitMBBAt(MachineBasicBlock &MBB,
788 MachineBasicBlock::iterator MBBI) const {
789 return true;
790 }
791
792 /// Return true if it's profitable to predicate
793 /// instructions with accumulated instruction latency of "NumCycles"
794 /// of the specified basic block, where the probability of the instructions
795 /// being executed is given by Probability, and Confidence is a measure
796 /// of our confidence that it will be properly predicted.
797 virtual bool isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
798 unsigned ExtraPredCycles,
799 BranchProbability Probability) const {
800 return false;
801 }
802
803 /// Second variant of isProfitableToIfCvt. This one
804 /// checks for the case where two basic blocks from true and false path
805 /// of a if-then-else (diamond) are predicated on mutually exclusive
806 /// predicates, where the probability of the true path being taken is given
807 /// by Probability, and Confidence is a measure of our confidence that it
808 /// will be properly predicted.
809 virtual bool isProfitableToIfCvt(MachineBasicBlock &TMBB, unsigned NumTCycles,
810 unsigned ExtraTCycles,
811 MachineBasicBlock &FMBB, unsigned NumFCycles,
812 unsigned ExtraFCycles,
813 BranchProbability Probability) const {
814 return false;
815 }
816
817 /// Return true if it's profitable for if-converter to duplicate instructions
818 /// of specified accumulated instruction latencies in the specified MBB to
819 /// enable if-conversion.
820 /// The probability of the instructions being executed is given by
821 /// Probability, and Confidence is a measure of our confidence that it
822 /// will be properly predicted.
823 virtual bool isProfitableToDupForIfCvt(MachineBasicBlock &MBB,
824 unsigned NumCycles,
825 BranchProbability Probability) const {
826 return false;
827 }
828
829 /// Return the increase in code size needed to predicate a contiguous run of
830 /// NumInsts instructions.
831 virtual unsigned extraSizeToPredicateInstructions(const MachineFunction &MF,
832 unsigned NumInsts) const {
833 return 0;
834 }
835
836 /// Return an estimate for the code size reduction (in bytes) which will be
837 /// caused by removing the given branch instruction during if-conversion.
838 virtual unsigned predictBranchSizeForIfCvt(MachineInstr &MI) const {
839 return getInstSizeInBytes(MI);
840 }
841
842 /// Return true if it's profitable to unpredicate
843 /// one side of a 'diamond', i.e. two sides of if-else predicated on mutually
844 /// exclusive predicates.
845 /// e.g.
846 /// subeq r0, r1, #1
847 /// addne r0, r1, #1
848 /// =>
849 /// sub r0, r1, #1
850 /// addne r0, r1, #1
851 ///
852 /// This may be profitable is conditional instructions are always executed.
853 virtual bool isProfitableToUnpredicate(MachineBasicBlock &TMBB,
854 MachineBasicBlock &FMBB) const {
855 return false;
856 }
857
858 /// Return true if it is possible to insert a select
859 /// instruction that chooses between TrueReg and FalseReg based on the
860 /// condition code in Cond.
861 ///
862 /// When successful, also return the latency in cycles from TrueReg,
863 /// FalseReg, and Cond to the destination register. In most cases, a select
864 /// instruction will be 1 cycle, so CondCycles = TrueCycles = FalseCycles = 1
865 ///
866 /// Some x86 implementations have 2-cycle cmov instructions.
867 ///
868 /// @param MBB Block where select instruction would be inserted.
869 /// @param Cond Condition returned by analyzeBranch.
870 /// @param DstReg Virtual dest register that the result should write to.
871 /// @param TrueReg Virtual register to select when Cond is true.
872 /// @param FalseReg Virtual register to select when Cond is false.
873 /// @param CondCycles Latency from Cond+Branch to select output.
874 /// @param TrueCycles Latency from TrueReg to select output.
875 /// @param FalseCycles Latency from FalseReg to select output.
876 virtual bool canInsertSelect(const MachineBasicBlock &MBB,
877 ArrayRef<MachineOperand> Cond, Register DstReg,
878 Register TrueReg, Register FalseReg,
879 int &CondCycles, int &TrueCycles,
880 int &FalseCycles) const {
881 return false;
882 }
883
884 /// Insert a select instruction into MBB before I that will copy TrueReg to
885 /// DstReg when Cond is true, and FalseReg to DstReg when Cond is false.
886 ///
887 /// This function can only be called after canInsertSelect() returned true.
888 /// The condition in Cond comes from analyzeBranch, and it can be assumed
889 /// that the same flags or registers required by Cond are available at the
890 /// insertion point.
891 ///
892 /// @param MBB Block where select instruction should be inserted.
893 /// @param I Insertion point.
894 /// @param DL Source location for debugging.
895 /// @param DstReg Virtual register to be defined by select instruction.
896 /// @param Cond Condition as computed by analyzeBranch.
897 /// @param TrueReg Virtual register to copy when Cond is true.
898 /// @param FalseReg Virtual register to copy when Cons is false.
899 virtual void insertSelect(MachineBasicBlock &MBB,
900 MachineBasicBlock::iterator I, const DebugLoc &DL,
901 Register DstReg, ArrayRef<MachineOperand> Cond,
902 Register TrueReg, Register FalseReg) const {
903 llvm_unreachable("Target didn't implement TargetInstrInfo::insertSelect!");
904 }
905
906 /// Analyze the given select instruction, returning true if
907 /// it cannot be understood. It is assumed that MI->isSelect() is true.
908 ///
909 /// When successful, return the controlling condition and the operands that
910 /// determine the true and false result values.
911 ///
912 /// Result = SELECT Cond, TrueOp, FalseOp
913 ///
914 /// Some targets can optimize select instructions, for example by predicating
915 /// the instruction defining one of the operands. Such targets should set
916 /// Optimizable.
917 ///
918 /// @param MI Select instruction to analyze.
919 /// @param Cond Condition controlling the select.
920 /// @param TrueOp Operand number of the value selected when Cond is true.
921 /// @param FalseOp Operand number of the value selected when Cond is false.
922 /// @param Optimizable Returned as true if MI is optimizable.
923 /// @returns False on success.
924 virtual bool analyzeSelect(const MachineInstr &MI,
925 SmallVectorImpl<MachineOperand> &Cond,
926 unsigned &TrueOp, unsigned &FalseOp,
927 bool &Optimizable) const {
928 assert(MI.getDesc().isSelect() && "MI must be a select instruction");
929 return true;
930 }
931
932 /// Given a select instruction that was understood by
933 /// analyzeSelect and returned Optimizable = true, attempt to optimize MI by
934 /// merging it with one of its operands. Returns NULL on failure.
935 ///
936 /// When successful, returns the new select instruction. The client is
937 /// responsible for deleting MI.
938 ///
939 /// If both sides of the select can be optimized, PreferFalse is used to pick
940 /// a side.
941 ///
942 /// @param MI Optimizable select instruction.
943 /// @param NewMIs Set that record all MIs in the basic block up to \p
944 /// MI. Has to be updated with any newly created MI or deleted ones.
945 /// @param PreferFalse Try to optimize FalseOp instead of TrueOp.
946 /// @returns Optimized instruction or NULL.
947 virtual MachineInstr *optimizeSelect(MachineInstr &MI,
948 SmallPtrSetImpl<MachineInstr *> &NewMIs,
949 bool PreferFalse = false) const {
950 // This function must be implemented if Optimizable is ever set.
951 llvm_unreachable("Target must implement TargetInstrInfo::optimizeSelect!");
952 }
953
954 /// Emit instructions to copy a pair of physical registers.
955 ///
956 /// This function should support copies within any legal register class as
957 /// well as any cross-class copies created during instruction selection.
958 ///
959 /// The source and destination registers may overlap, which may require a
960 /// careful implementation when multiple copy instructions are required for
961 /// large registers. See for example the ARM target.
962 virtual void copyPhysReg(MachineBasicBlock &MBB,
963 MachineBasicBlock::iterator MI, const DebugLoc &DL,
964 MCRegister DestReg, MCRegister SrcReg,
965 bool KillSrc) const {
966 llvm_unreachable("Target didn't implement TargetInstrInfo::copyPhysReg!");
967 }
968
969 /// Allow targets to tell MachineVerifier whether a specific register
970 /// MachineOperand can be used as part of PC-relative addressing.
971 /// PC-relative addressing modes in many CISC architectures contain
972 /// (non-PC) registers as offsets or scaling values, which inherently
973 /// tags the corresponding MachineOperand with OPERAND_PCREL.
974 ///
975 /// @param MO The MachineOperand in question. MO.isReg() should always
976 /// be true.
977 /// @return Whether this operand is allowed to be used PC-relatively.
978 virtual bool isPCRelRegisterOperandLegal(const MachineOperand &MO) const {
979 return false;
980 }
981
982 protected:
983 /// Target-dependent implementation for IsCopyInstr.
984 /// If the specific machine instruction is a instruction that moves/copies
985 /// value from one register to another register return destination and source
986 /// registers as machine operands.
987 virtual Optional<DestSourcePair>
988 isCopyInstrImpl(const MachineInstr &MI) const {
989 return None;
990 }
991
992 /// Return true if the given terminator MI is not expected to spill. This
993 /// sets the live interval as not spillable and adjusts phi node lowering to
994 /// not introduce copies after the terminator. Use with care, these are
995 /// currently used for hardware loop intrinsics in very controlled situations,
996 /// created prior to registry allocation in loops that only have single phi
997 /// users for the terminators value. They may run out of registers if not used
998 /// carefully.
999 virtual bool isUnspillableTerminatorImpl(const MachineInstr *MI) const {
1000 return false;
1001 }
1002
1003 public:
1004 /// If the specific machine instruction is a instruction that moves/copies
1005 /// value from one register to another register return destination and source
1006 /// registers as machine operands.
1007 /// For COPY-instruction the method naturally returns destination and source
1008 /// registers as machine operands, for all other instructions the method calls
1009 /// target-dependent implementation.
1010 Optional<DestSourcePair> isCopyInstr(const MachineInstr &MI) const {
1011 if (MI.isCopy()) {
1012 return DestSourcePair{MI.getOperand(0), MI.getOperand(1)};
1013 }
1014 return isCopyInstrImpl(MI);
1015 }
1016
1017 /// If the specific machine instruction is an instruction that adds an
1018 /// immediate value and a physical register, and stores the result in
1019 /// the given physical register \c Reg, return a pair of the source
1020 /// register and the offset which has been added.
1021 virtual Optional<RegImmPair> isAddImmediate(const MachineInstr &MI,
1022 Register Reg) const {
1023 return None;
1024 }
1025
1026 /// Returns true if MI is an instruction that defines Reg to have a constant
1027 /// value and the value is recorded in ImmVal. The ImmVal is a result that
1028 /// should be interpreted as modulo size of Reg.
1029 virtual bool getConstValDefinedInReg(const MachineInstr &MI,
1030 const Register Reg,
1031 int64_t &ImmVal) const {
1032 return false;
1033 }
1034
1035 /// Store the specified register of the given register class to the specified
1036 /// stack frame index. The store instruction is to be added to the given
1037 /// machine basic block before the specified machine instruction. If isKill
1038 /// is true, the register operand is the last use and must be marked kill.
1039 virtual void storeRegToStackSlot(MachineBasicBlock &MBB,
1040 MachineBasicBlock::iterator MI,
1041 Register SrcReg, bool isKill, int FrameIndex,
1042 const TargetRegisterClass *RC,
1043 const TargetRegisterInfo *TRI) const {
1044 llvm_unreachable("Target didn't implement "
1045 "TargetInstrInfo::storeRegToStackSlot!");
1046 }
1047
1048 /// Load the specified register of the given register class from the specified
1049 /// stack frame index. The load instruction is to be added to the given
1050 /// machine basic block before the specified machine instruction.
1051 virtual void loadRegFromStackSlot(MachineBasicBlock &MBB,
1052 MachineBasicBlock::iterator MI,
1053 Register DestReg, int FrameIndex,
1054 const TargetRegisterClass *RC,
1055 const TargetRegisterInfo *TRI) const {
1056 llvm_unreachable("Target didn't implement "
1057 "TargetInstrInfo::loadRegFromStackSlot!");
1058 }
1059
1060 /// This function is called for all pseudo instructions
1061 /// that remain after register allocation. Many pseudo instructions are
1062 /// created to help register allocation. This is the place to convert them
1063 /// into real instructions. The target can edit MI in place, or it can insert
1064 /// new instructions and erase MI. The function should return true if
1065 /// anything was changed.
1066 virtual bool expandPostRAPseudo(MachineInstr &MI) const { return false; }
1067
1068 /// Check whether the target can fold a load that feeds a subreg operand
1069 /// (or a subreg operand that feeds a store).
1070 /// For example, X86 may want to return true if it can fold
1071 /// movl (%esp), %eax
1072 /// subb, %al, ...
1073 /// Into:
1074 /// subb (%esp), ...
1075 ///
1076 /// Ideally, we'd like the target implementation of foldMemoryOperand() to
1077 /// reject subregs - but since this behavior used to be enforced in the
1078 /// target-independent code, moving this responsibility to the targets
1079 /// has the potential of causing nasty silent breakage in out-of-tree targets.
1080 virtual bool isSubregFoldable() const { return false; }
1081
1082 /// For a patchpoint, stackmap, or statepoint intrinsic, return the range of
1083 /// operands which can't be folded into stack references. Operands outside
1084 /// of the range are most likely foldable but it is not guaranteed.
1085 /// These instructions are unique in that stack references for some operands
1086 /// have the same execution cost (e.g. none) as the unfolded register forms.
1087 /// The ranged return is guaranteed to include all operands which can't be
1088 /// folded at zero cost.
1089 virtual std::pair<unsigned, unsigned>
1090 getPatchpointUnfoldableRange(const MachineInstr &MI) const;
1091
1092 /// Attempt to fold a load or store of the specified stack
1093 /// slot into the specified machine instruction for the specified operand(s).
1094 /// If this is possible, a new instruction is returned with the specified
1095 /// operand folded, otherwise NULL is returned.
1096 /// The new instruction is inserted before MI, and the client is responsible
1097 /// for removing the old instruction.
1098 /// If VRM is passed, the assigned physregs can be inspected by target to
1099 /// decide on using an opcode (note that those assignments can still change).
1100 MachineInstr *foldMemoryOperand(MachineInstr &MI, ArrayRef<unsigned> Ops,
1101 int FI,
1102 LiveIntervals *LIS = nullptr,
1103 VirtRegMap *VRM = nullptr) const;
1104
1105 /// Same as the previous version except it allows folding of any load and
1106 /// store from / to any address, not just from a specific stack slot.
1107 MachineInstr *foldMemoryOperand(MachineInstr &MI, ArrayRef<unsigned> Ops,
1108 MachineInstr &LoadMI,
1109 LiveIntervals *LIS = nullptr) const;
1110
1111 /// Return true when there is potentially a faster code sequence
1112 /// for an instruction chain ending in \p Root. All potential patterns are
1113 /// returned in the \p Pattern vector. Pattern should be sorted in priority
1114 /// order since the pattern evaluator stops checking as soon as it finds a
1115 /// faster sequence.
1116 /// \param Root - Instruction that could be combined with one of its operands
1117 /// \param Patterns - Vector of possible combination patterns
1118 virtual bool
1119 getMachineCombinerPatterns(MachineInstr &Root,
1120 SmallVectorImpl<MachineCombinerPattern> &Patterns,
1121 bool DoRegPressureReduce) const;
1122
1123 /// Return true if target supports reassociation of instructions in machine
1124 /// combiner pass to reduce register pressure for a given BB.
1125 virtual bool
1126 shouldReduceRegisterPressure(MachineBasicBlock *MBB,
1127 RegisterClassInfo *RegClassInfo) const {
1128 return false;
1129 }
1130
1131 /// Fix up the placeholder we may add in genAlternativeCodeSequence().
1132 virtual void
1133 finalizeInsInstrs(MachineInstr &Root, MachineCombinerPattern &P,
1134 SmallVectorImpl<MachineInstr *> &InsInstrs) const {}
1135
1136 /// Return true when a code sequence can improve throughput. It
1137 /// should be called only for instructions in loops.
1138 /// \param Pattern - combiner pattern
1139 virtual bool isThroughputPattern(MachineCombinerPattern Pattern) const;
1140
1141 /// Return true if the input \P Inst is part of a chain of dependent ops
1142 /// that are suitable for reassociation, otherwise return false.
1143 /// If the instruction's operands must be commuted to have a previous
1144 /// instruction of the same type define the first source operand, \P Commuted
1145 /// will be set to true.
1146 bool isReassociationCandidate(const MachineInstr &Inst, bool &Commuted) const;
1147
1148 /// Return true when \P Inst is both associative and commutative.
1149 virtual bool isAssociativeAndCommutative(const MachineInstr &Inst) const {
1150 return false;
1151 }
1152
1153 /// Return true when \P Inst has reassociable operands in the same \P MBB.
1154 virtual bool hasReassociableOperands(const MachineInstr &Inst,
1155 const MachineBasicBlock *MBB) const;
1156
1157 /// Return true when \P Inst has reassociable sibling.
1158 bool hasReassociableSibling(const MachineInstr &Inst, bool &Commuted) const;
1159
1160 /// When getMachineCombinerPatterns() finds patterns, this function generates
1161 /// the instructions that could replace the original code sequence. The client
1162 /// has to decide whether the actual replacement is beneficial or not.
1163 /// \param Root - Instruction that could be combined with one of its operands
1164 /// \param Pattern - Combination pattern for Root
1165 /// \param InsInstrs - Vector of new instructions that implement P
1166 /// \param DelInstrs - Old instructions, including Root, that could be
1167 /// replaced by InsInstr
1168 /// \param InstIdxForVirtReg - map of virtual register to instruction in
1169 /// InsInstr that defines it
1170 virtual void genAlternativeCodeSequence(
1171 MachineInstr &Root, MachineCombinerPattern Pattern,
1172 SmallVectorImpl<MachineInstr *> &InsInstrs,
1173 SmallVectorImpl<MachineInstr *> &DelInstrs,
1174 DenseMap<unsigned, unsigned> &InstIdxForVirtReg) const;
1175
1176 /// Attempt to reassociate \P Root and \P Prev according to \P Pattern to
1177 /// reduce critical path length.
1178 void reassociateOps(MachineInstr &Root, MachineInstr &Prev,
1179 MachineCombinerPattern Pattern,
1180 SmallVectorImpl<MachineInstr *> &InsInstrs,
1181 SmallVectorImpl<MachineInstr *> &DelInstrs,
1182 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const;
1183
1184 /// The limit on resource length extension we accept in MachineCombiner Pass.
1185 virtual int getExtendResourceLenLimit() const { return 0; }
1186
1187 /// This is an architecture-specific helper function of reassociateOps.
1188 /// Set special operand attributes for new instructions after reassociation.
1189 virtual void setSpecialOperandAttr(MachineInstr &OldMI1, MachineInstr &OldMI2,
1190 MachineInstr &NewMI1,
1191 MachineInstr &NewMI2) const {}
1192
1193 /// Return true when a target supports MachineCombiner.
1194 virtual bool useMachineCombiner() const { return false; }
1195
1196 /// Return true if the given SDNode can be copied during scheduling
1197 /// even if it has glue.
1198 virtual bool canCopyGluedNodeDuringSchedule(SDNode *N) const { return false; }
1199
1200 protected:
1201 /// Target-dependent implementation for foldMemoryOperand.
1202 /// Target-independent code in foldMemoryOperand will
1203 /// take care of adding a MachineMemOperand to the newly created instruction.
1204 /// The instruction and any auxiliary instructions necessary will be inserted
1205 /// at InsertPt.
1206 virtual MachineInstr *
1207 foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI,
1208 ArrayRef<unsigned> Ops,
1209 MachineBasicBlock::iterator InsertPt, int FrameIndex,
1210 LiveIntervals *LIS = nullptr,
1211 VirtRegMap *VRM = nullptr) const {
1212 return nullptr;
1213 }
1214
1215 /// Target-dependent implementation for foldMemoryOperand.
1216 /// Target-independent code in foldMemoryOperand will
1217 /// take care of adding a MachineMemOperand to the newly created instruction.
1218 /// The instruction and any auxiliary instructions necessary will be inserted
1219 /// at InsertPt.
1220 virtual MachineInstr *foldMemoryOperandImpl(
1221 MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
1222 MachineBasicBlock::iterator InsertPt, MachineInstr &LoadMI,
1223 LiveIntervals *LIS = nullptr) const {
1224 return nullptr;
1225 }
1226
1227 /// Target-dependent implementation of getRegSequenceInputs.
1228 ///
1229 /// \returns true if it is possible to build the equivalent
1230 /// REG_SEQUENCE inputs with the pair \p MI, \p DefIdx. False otherwise.
1231 ///
1232 /// \pre MI.isRegSequenceLike().
1233 ///
1234 /// \see TargetInstrInfo::getRegSequenceInputs.
1235 virtual bool getRegSequenceLikeInputs(
1236 const MachineInstr &MI, unsigned DefIdx,
1237 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
1238 return false;
1239 }
1240
1241 /// Target-dependent implementation of getExtractSubregInputs.
1242 ///
1243 /// \returns true if it is possible to build the equivalent
1244 /// EXTRACT_SUBREG inputs with the pair \p MI, \p DefIdx. False otherwise.
1245 ///
1246 /// \pre MI.isExtractSubregLike().
1247 ///
1248 /// \see TargetInstrInfo::getExtractSubregInputs.
1249 virtual bool getExtractSubregLikeInputs(const MachineInstr &MI,
1250 unsigned DefIdx,
1251 RegSubRegPairAndIdx &InputReg) const {
1252 return false;
1253 }
1254
1255 /// Target-dependent implementation of getInsertSubregInputs.
1256 ///
1257 /// \returns true if it is possible to build the equivalent
1258 /// INSERT_SUBREG inputs with the pair \p MI, \p DefIdx. False otherwise.
1259 ///
1260 /// \pre MI.isInsertSubregLike().
1261 ///
1262 /// \see TargetInstrInfo::getInsertSubregInputs.
1263 virtual bool
1264 getInsertSubregLikeInputs(const MachineInstr &MI, unsigned DefIdx,
1265 RegSubRegPair &BaseReg,
1266 RegSubRegPairAndIdx &InsertedReg) const {
1267 return false;
1268 }
1269
1270 public:
1271 /// getAddressSpaceForPseudoSourceKind - Given the kind of memory
1272 /// (e.g. stack) the target returns the corresponding address space.
1273 virtual unsigned
1274 getAddressSpaceForPseudoSourceKind(unsigned Kind) const {
1275 return 0;
1276 }
1277
1278 /// unfoldMemoryOperand - Separate a single instruction which folded a load or
1279 /// a store or a load and a store into two or more instruction. If this is
1280 /// possible, returns true as well as the new instructions by reference.
1281 virtual bool
1282 unfoldMemoryOperand(MachineFunction &MF, MachineInstr &MI, unsigned Reg,
1283 bool UnfoldLoad, bool UnfoldStore,
1284 SmallVectorImpl<MachineInstr *> &NewMIs) const {
1285 return false;
1286 }
1287
1288 virtual bool unfoldMemoryOperand(SelectionDAG &DAG, SDNode *N,
1289 SmallVectorImpl<SDNode *> &NewNodes) const {
1290 return false;
1291 }
1292
1293 /// Returns the opcode of the would be new
1294 /// instruction after load / store are unfolded from an instruction of the
1295 /// specified opcode. It returns zero if the specified unfolding is not
1296 /// possible. If LoadRegIndex is non-null, it is filled in with the operand
1297 /// index of the operand which will hold the register holding the loaded
1298 /// value.
1299 virtual unsigned
1300 getOpcodeAfterMemoryUnfold(unsigned Opc, bool UnfoldLoad, bool UnfoldStore,
1301 unsigned *LoadRegIndex = nullptr) const {
1302 return 0;
1303 }
1304
1305 /// This is used by the pre-regalloc scheduler to determine if two loads are
1306 /// loading from the same base address. It should only return true if the base
1307 /// pointers are the same and the only differences between the two addresses
1308 /// are the offset. It also returns the offsets by reference.
1309 virtual bool areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
1310 int64_t &Offset1,
1311 int64_t &Offset2) const {
1312 return false;
1313 }
1314
1315 /// This is a used by the pre-regalloc scheduler to determine (in conjunction
1316 /// with areLoadsFromSameBasePtr) if two loads should be scheduled together.
1317 /// On some targets if two loads are loading from
1318 /// addresses in the same cache line, it's better if they are scheduled
1319 /// together. This function takes two integers that represent the load offsets
1320 /// from the common base address. It returns true if it decides it's desirable
1321 /// to schedule the two loads together. "NumLoads" is the number of loads that
1322 /// have already been scheduled after Load1.
1323 virtual bool shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
1324 int64_t Offset1, int64_t Offset2,
1325 unsigned NumLoads) const {
1326 return false;
1327 }
1328
1329 /// Get the base operand and byte offset of an instruction that reads/writes
1330 /// memory. This is a convenience function for callers that are only prepared
1331 /// to handle a single base operand.
1332 bool getMemOperandWithOffset(const MachineInstr &MI,
1333 const MachineOperand *&BaseOp, int64_t &Offset,
1334 bool &OffsetIsScalable,
1335 const TargetRegisterInfo *TRI) const;
1336
1337 /// Get zero or more base operands and the byte offset of an instruction that
1338 /// reads/writes memory. Note that there may be zero base operands if the
1339 /// instruction accesses a constant address.
1340 /// It returns false if MI does not read/write memory.
1341 /// It returns false if base operands and offset could not be determined.
1342 /// It is not guaranteed to always recognize base operands and offsets in all
1343 /// cases.
1344 virtual bool getMemOperandsWithOffsetWidth(
1345 const MachineInstr &MI, SmallVectorImpl<const MachineOperand *> &BaseOps,
1346 int64_t &Offset, bool &OffsetIsScalable, unsigned &Width,
1347 const TargetRegisterInfo *TRI) const {
1348 return false;
1349 }
1350
1351 /// Return true if the instruction contains a base register and offset. If
1352 /// true, the function also sets the operand position in the instruction
1353 /// for the base register and offset.
1354 virtual bool getBaseAndOffsetPosition(const MachineInstr &MI,
1355 unsigned &BasePos,
1356 unsigned &OffsetPos) const {
1357 return false;
1358 }
1359
1360 /// Target dependent implementation to get the values constituting the address
1361 /// MachineInstr that is accessing memory. These values are returned as a
1362 /// struct ExtAddrMode which contains all relevant information to make up the
1363 /// address.
1364 virtual Optional<ExtAddrMode>
1365 getAddrModeFromMemoryOp(const MachineInstr &MemI,
1366 const TargetRegisterInfo *TRI) const {
1367 return None;
1368 }
1369
1370 /// Returns true if MI's Def is NullValueReg, and the MI
1371 /// does not change the Zero value. i.e. cases such as rax = shr rax, X where
1372 /// NullValueReg = rax. Note that if the NullValueReg is non-zero, this
1373 /// function can return true even if becomes zero. Specifically cases such as
1374 /// NullValueReg = shl NullValueReg, 63.
1375 virtual bool preservesZeroValueInReg(const MachineInstr *MI,
1376 const Register NullValueReg,
1377 const TargetRegisterInfo *TRI) const {
1378 return false;
1379 }
1380
1381 /// If the instruction is an increment of a constant value, return the amount.
1382 virtual bool getIncrementValue(const MachineInstr &MI, int &Value) const {
1383 return false;
1384 }
1385
1386 /// Returns true if the two given memory operations should be scheduled
1387 /// adjacent. Note that you have to add:
1388 /// DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
1389 /// or
1390 /// DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
1391 /// to TargetPassConfig::createMachineScheduler() to have an effect.
1392 ///
1393 /// \p BaseOps1 and \p BaseOps2 are memory operands of two memory operations.
1394 /// \p NumLoads is the number of loads that will be in the cluster if this
1395 /// hook returns true.
1396 /// \p NumBytes is the number of bytes that will be loaded from all the
1397 /// clustered loads if this hook returns true.
1398 virtual bool shouldClusterMemOps(ArrayRef<const MachineOperand *> BaseOps1,
1399 ArrayRef<const MachineOperand *> BaseOps2,
1400 unsigned NumLoads, unsigned NumBytes) const {
1401 llvm_unreachable("target did not implement shouldClusterMemOps()");
1402 }
1403
1404 /// Reverses the branch condition of the specified condition list,
1405 /// returning false on success and true if it cannot be reversed.
1406 virtual bool
1407 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
1408 return true;
1409 }
1410
1411 /// Insert a noop into the instruction stream at the specified point.
1412 virtual void insertNoop(MachineBasicBlock &MBB,
1413 MachineBasicBlock::iterator MI) const;
1414
1415 /// Insert noops into the instruction stream at the specified point.
1416 virtual void insertNoops(MachineBasicBlock &MBB,
1417 MachineBasicBlock::iterator MI,
1418 unsigned Quantity) const;
1419
1420 /// Return the noop instruction to use for a noop.
1421 virtual MCInst getNop() const;
1422
1423 /// Return true for post-incremented instructions.
1424 virtual bool isPostIncrement(const MachineInstr &MI) const { return false; }
1425
1426 /// Returns true if the instruction is already predicated.
1427 virtual bool isPredicated(const MachineInstr &MI) const { return false; }
1428
1429 // Returns a MIRPrinter comment for this machine operand.
1430 virtual std::string
1431 createMIROperandComment(const MachineInstr &MI, const MachineOperand &Op,
1432 unsigned OpIdx, const TargetRegisterInfo *TRI) const;
1433
1434 /// Returns true if the instruction is a
1435 /// terminator instruction that has not been predicated.
1436 bool isUnpredicatedTerminator(const MachineInstr &MI) const;
1437
1438 /// Returns true if MI is an unconditional tail call.
1439 virtual bool isUnconditionalTailCall(const MachineInstr &MI) const {
1440 return false;
1441 }
1442
1443 /// Returns true if the tail call can be made conditional on BranchCond.
1444 virtual bool canMakeTailCallConditional(SmallVectorImpl<MachineOperand> &Cond,
1445 const MachineInstr &TailCall) const {
1446 return false;
1447 }
1448
1449 /// Replace the conditional branch in MBB with a conditional tail call.
1450 virtual void replaceBranchWithTailCall(MachineBasicBlock &MBB,
1451 SmallVectorImpl<MachineOperand> &Cond,
1452 const MachineInstr &TailCall) const {
1453 llvm_unreachable("Target didn't implement replaceBranchWithTailCall!");
1454 }
1455
1456 /// Convert the instruction into a predicated instruction.
1457 /// It returns true if the operation was successful.
1458 virtual bool PredicateInstruction(MachineInstr &MI,
1459 ArrayRef<MachineOperand> Pred) const;
1460
1461 /// Returns true if the first specified predicate
1462 /// subsumes the second, e.g. GE subsumes GT.
1463 virtual bool SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
1464 ArrayRef<MachineOperand> Pred2) const {
1465 return false;
1466 }
1467
1468 /// If the specified instruction defines any predicate
1469 /// or condition code register(s) used for predication, returns true as well
1470 /// as the definition predicate(s) by reference.
1471 /// SkipDead should be set to false at any point that dead
1472 /// predicate instructions should be considered as being defined.
1473 /// A dead predicate instruction is one that is guaranteed to be removed
1474 /// after a call to PredicateInstruction.
1475 virtual bool ClobbersPredicate(MachineInstr &MI,
1476 std::vector<MachineOperand> &Pred,
1477 bool SkipDead) const {
1478 return false;
1479 }
1480
1481 /// Return true if the specified instruction can be predicated.
1482 /// By default, this returns true for every instruction with a
1483 /// PredicateOperand.
1484 virtual bool isPredicable(const MachineInstr &MI) const {
1485 return MI.getDesc().isPredicable();
1486 }
1487
1488 /// Return true if it's safe to move a machine
1489 /// instruction that defines the specified register class.
1490 virtual bool isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const {
1491 return true;
1492 }
1493
1494 /// Test if the given instruction should be considered a scheduling boundary.
1495 /// This primarily includes labels and terminators.
1496 virtual bool isSchedulingBoundary(const MachineInstr &MI,
1497 const MachineBasicBlock *MBB,
1498 const MachineFunction &MF) const;
1499
1500 /// Measure the specified inline asm to determine an approximation of its
1501 /// length.
1502 virtual unsigned getInlineAsmLength(
1503 const char *Str, const MCAsmInfo &MAI,
1504 const TargetSubtargetInfo *STI = nullptr) const;
1505
1506 /// Allocate and return a hazard recognizer to use for this target when
1507 /// scheduling the machine instructions before register allocation.
1508 virtual ScheduleHazardRecognizer *
1509 CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
1510 const ScheduleDAG *DAG) const;
1511
1512 /// Allocate and return a hazard recognizer to use for this target when
1513 /// scheduling the machine instructions before register allocation.
1514 virtual ScheduleHazardRecognizer *
1515 CreateTargetMIHazardRecognizer(const InstrItineraryData *,
1516 const ScheduleDAGMI *DAG) const;
1517
1518 /// Allocate and return a hazard recognizer to use for this target when
1519 /// scheduling the machine instructions after register allocation.
1520 virtual ScheduleHazardRecognizer *
1521 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *,
1522 const ScheduleDAG *DAG) const;
1523
1524 /// Allocate and return a hazard recognizer to use for by non-scheduling
1525 /// passes.
1526 virtual ScheduleHazardRecognizer *
1527 CreateTargetPostRAHazardRecognizer(const MachineFunction &MF) const {
1528 return nullptr;
1529 }
1530
1531 /// Provide a global flag for disabling the PreRA hazard recognizer that
1532 /// targets may choose to honor.
1533 bool usePreRAHazardRecognizer() const;
1534
1535 /// For a comparison instruction, return the source registers
1536 /// in SrcReg and SrcReg2 if having two register operands, and the value it
1537 /// compares against in CmpValue. Return true if the comparison instruction
1538 /// can be analyzed.
1539 virtual bool analyzeCompare(const MachineInstr &MI, Register &SrcReg,
1540 Register &SrcReg2, int64_t &Mask,
1541 int64_t &Value) const {
1542 return false;
1543 }
1544
1545 /// See if the comparison instruction can be converted
1546 /// into something more efficient. E.g., on ARM most instructions can set the
1547 /// flags register, obviating the need for a separate CMP.
1548 virtual bool optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg,
1549 Register SrcReg2, int64_t Mask,
1550 int64_t Value,
1551 const MachineRegisterInfo *MRI) const {
1552 return false;
1553 }
1554 virtual bool optimizeCondBranch(MachineInstr &MI) const { return false; }
1555
1556 /// Try to remove the load by folding it to a register operand at the use.
1557 /// We fold the load instructions if and only if the
1558 /// def and use are in the same BB. We only look at one load and see
1559 /// whether it can be folded into MI. FoldAsLoadDefReg is the virtual register
1560 /// defined by the load we are trying to fold. DefMI returns the machine
1561 /// instruction that defines FoldAsLoadDefReg, and the function returns
1562 /// the machine instruction generated due to folding.
1563 virtual MachineInstr *optimizeLoadInstr(MachineInstr &MI,
1564 const MachineRegisterInfo *MRI,
1565 Register &FoldAsLoadDefReg,
1566 MachineInstr *&DefMI) const {
1567 return nullptr;
1568 }
1569
1570 /// 'Reg' is known to be defined by a move immediate instruction,
1571 /// try to fold the immediate into the use instruction.
1572 /// If MRI->hasOneNonDBGUse(Reg) is true, and this function returns true,
1573 /// then the caller may assume that DefMI has been erased from its parent
1574 /// block. The caller may assume that it will not be erased by this
1575 /// function otherwise.
1576 virtual bool FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
1577 Register Reg, MachineRegisterInfo *MRI) const {
1578 return false;
1579 }
1580
1581 /// Return the number of u-operations the given machine
1582 /// instruction will be decoded to on the target cpu. The itinerary's
1583 /// IssueWidth is the number of microops that can be dispatched each
1584 /// cycle. An instruction with zero microops takes no dispatch resources.
1585 virtual unsigned getNumMicroOps(const InstrItineraryData *ItinData,
1586 const MachineInstr &MI) const;
1587
1588 /// Return true for pseudo instructions that don't consume any
1589 /// machine resources in their current form. These are common cases that the
1590 /// scheduler should consider free, rather than conservatively handling them
1591 /// as instructions with no itinerary.
1592 bool isZeroCost(unsigned Opcode) const {
1593 return Opcode <= TargetOpcode::COPY;
1594 }
1595
1596 virtual int getOperandLatency(const InstrItineraryData *ItinData,
1597 SDNode *DefNode, unsigned DefIdx,
1598 SDNode *UseNode, unsigned UseIdx) const;
1599
1600 /// Compute and return the use operand latency of a given pair of def and use.
1601 /// In most cases, the static scheduling itinerary was enough to determine the
1602 /// operand latency. But it may not be possible for instructions with variable
1603 /// number of defs / uses.
1604 ///
1605 /// This is a raw interface to the itinerary that may be directly overridden
1606 /// by a target. Use computeOperandLatency to get the best estimate of
1607 /// latency.
1608 virtual int getOperandLatency(const InstrItineraryData *ItinData,
1609 const MachineInstr &DefMI, unsigned DefIdx,
1610 const MachineInstr &UseMI,
1611 unsigned UseIdx) const;
1612
1613 /// Compute the instruction latency of a given instruction.
1614 /// If the instruction has higher cost when predicated, it's returned via
1615 /// PredCost.
1616 virtual unsigned getInstrLatency(const InstrItineraryData *ItinData,
1617 const MachineInstr &MI,
1618 unsigned *PredCost = nullptr) const;
1619
1620 virtual unsigned getPredicationCost(const MachineInstr &MI) const;
1621
1622 virtual int getInstrLatency(const InstrItineraryData *ItinData,
1623 SDNode *Node) const;
1624
1625 /// Return the default expected latency for a def based on its opcode.
1626 unsigned defaultDefLatency(const MCSchedModel &SchedModel,
1627 const MachineInstr &DefMI) const;
1628
1629 /// Return true if this opcode has high latency to its result.
1630 virtual bool isHighLatencyDef(int opc) const { return false; }
1631
1632 /// Compute operand latency between a def of 'Reg'
1633 /// and a use in the current loop. Return true if the target considered
1634 /// it 'high'. This is used by optimization passes such as machine LICM to
1635 /// determine whether it makes sense to hoist an instruction out even in a
1636 /// high register pressure situation.
1637 virtual bool hasHighOperandLatency(const TargetSchedModel &SchedModel,
1638 const MachineRegisterInfo *MRI,
1639 const MachineInstr &DefMI, unsigned DefIdx,
1640 const MachineInstr &UseMI,
1641 unsigned UseIdx) const {
1642 return false;
1643 }
1644
1645 /// Compute operand latency of a def of 'Reg'. Return true
1646 /// if the target considered it 'low'.
1647 virtual bool hasLowDefLatency(const TargetSchedModel &SchedModel,
1648 const MachineInstr &DefMI,
1649 unsigned DefIdx) const;
1650
1651 /// Perform target-specific instruction verification.
1652 virtual bool verifyInstruction(const MachineInstr &MI,
1653 StringRef &ErrInfo) const {
1654 return true;
1655 }
1656
1657 /// Return the current execution domain and bit mask of
1658 /// possible domains for instruction.
1659 ///
1660 /// Some micro-architectures have multiple execution domains, and multiple
1661 /// opcodes that perform the same operation in different domains. For
1662 /// example, the x86 architecture provides the por, orps, and orpd
1663 /// instructions that all do the same thing. There is a latency penalty if a
1664 /// register is written in one domain and read in another.
1665 ///
1666 /// This function returns a pair (domain, mask) containing the execution
1667 /// domain of MI, and a bit mask of possible domains. The setExecutionDomain
1668 /// function can be used to change the opcode to one of the domains in the
1669 /// bit mask. Instructions whose execution domain can't be changed should
1670 /// return a 0 mask.
1671 ///
1672 /// The execution domain numbers don't have any special meaning except domain
1673 /// 0 is used for instructions that are not associated with any interesting
1674 /// execution domain.
1675 ///
1676 virtual std::pair<uint16_t, uint16_t>
1677 getExecutionDomain(const MachineInstr &MI) const {
1678 return std::make_pair(0, 0);
1679 }
1680
1681 /// Change the opcode of MI to execute in Domain.
1682 ///
1683 /// The bit (1 << Domain) must be set in the mask returned from
1684 /// getExecutionDomain(MI).
1685 virtual void setExecutionDomain(MachineInstr &MI, unsigned Domain) const {}
1686
1687 /// Returns the preferred minimum clearance
1688 /// before an instruction with an unwanted partial register update.
1689 ///
1690 /// Some instructions only write part of a register, and implicitly need to
1691 /// read the other parts of the register. This may cause unwanted stalls
1692 /// preventing otherwise unrelated instructions from executing in parallel in
1693 /// an out-of-order CPU.
1694 ///
1695 /// For example, the x86 instruction cvtsi2ss writes its result to bits
1696 /// [31:0] of the destination xmm register. Bits [127:32] are unaffected, so
1697 /// the instruction needs to wait for the old value of the register to become
1698 /// available:
1699 ///
1700 /// addps %xmm1, %xmm0
1701 /// movaps %xmm0, (%rax)
1702 /// cvtsi2ss %rbx, %xmm0
1703 ///
1704 /// In the code above, the cvtsi2ss instruction needs to wait for the addps
1705 /// instruction before it can issue, even though the high bits of %xmm0
1706 /// probably aren't needed.
1707 ///
1708 /// This hook returns the preferred clearance before MI, measured in
1709 /// instructions. Other defs of MI's operand OpNum are avoided in the last N
1710 /// instructions before MI. It should only return a positive value for
1711 /// unwanted dependencies. If the old bits of the defined register have
1712 /// useful values, or if MI is determined to otherwise read the dependency,
1713 /// the hook should return 0.
1714 ///
1715 /// The unwanted dependency may be handled by:
1716 ///
1717 /// 1. Allocating the same register for an MI def and use. That makes the
1718 /// unwanted dependency identical to a required dependency.
1719 ///
1720 /// 2. Allocating a register for the def that has no defs in the previous N
1721 /// instructions.
1722 ///
1723 /// 3. Calling breakPartialRegDependency() with the same arguments. This
1724 /// allows the target to insert a dependency breaking instruction.
1725 ///
1726 virtual unsigned
1727 getPartialRegUpdateClearance(const MachineInstr &MI, unsigned OpNum,
1728 const TargetRegisterInfo *TRI) const {
1729 // The default implementation returns 0 for no partial register dependency.
1730 return 0;
1731 }
1732
1733 /// Return the minimum clearance before an instruction that reads an
1734 /// unused register.
1735 ///
1736 /// For example, AVX instructions may copy part of a register operand into
1737 /// the unused high bits of the destination register.
1738 ///
1739 /// vcvtsi2sdq %rax, undef %xmm0, %xmm14
1740 ///
1741 /// In the code above, vcvtsi2sdq copies %xmm0[127:64] into %xmm14 creating a
1742 /// false dependence on any previous write to %xmm0.
1743 ///
1744 /// This hook works similarly to getPartialRegUpdateClearance, except that it
1745 /// does not take an operand index. Instead sets \p OpNum to the index of the
1746 /// unused register.
1747 virtual unsigned getUndefRegClearance(const MachineInstr &MI, unsigned OpNum,
1748 const TargetRegisterInfo *TRI) const {
1749 // The default implementation returns 0 for no undef register dependency.
1750 return 0;
1751 }
1752
1753 /// Insert a dependency-breaking instruction
1754 /// before MI to eliminate an unwanted dependency on OpNum.
1755 ///
1756 /// If it wasn't possible to avoid a def in the last N instructions before MI
1757 /// (see getPartialRegUpdateClearance), this hook will be called to break the
1758 /// unwanted dependency.
1759 ///
1760 /// On x86, an xorps instruction can be used as a dependency breaker:
1761 ///
1762 /// addps %xmm1, %xmm0
1763 /// movaps %xmm0, (%rax)
1764 /// xorps %xmm0, %xmm0
1765 /// cvtsi2ss %rbx, %xmm0
1766 ///
1767 /// An <imp-kill> operand should be added to MI if an instruction was
1768 /// inserted. This ties the instructions together in the post-ra scheduler.
1769 ///
1770 virtual void breakPartialRegDependency(MachineInstr &MI, unsigned OpNum,
1771 const TargetRegisterInfo *TRI) const {}
1772
1773 /// Create machine specific model for scheduling.
1774 virtual DFAPacketizer *
1775 CreateTargetScheduleState(const TargetSubtargetInfo &) const {
1776 return nullptr;
1777 }
1778
1779 /// Sometimes, it is possible for the target
1780 /// to tell, even without aliasing information, that two MIs access different
1781 /// memory addresses. This function returns true if two MIs access different
1782 /// memory addresses and false otherwise.
1783 ///
1784 /// Assumes any physical registers used to compute addresses have the same
1785 /// value for both instructions. (This is the most useful assumption for
1786 /// post-RA scheduling.)
1787 ///
1788 /// See also MachineInstr::mayAlias, which is implemented on top of this
1789 /// function.
1790 virtual bool
1791 areMemAccessesTriviallyDisjoint(const MachineInstr &MIa,
1792 const MachineInstr &MIb) const {
1793 assert(MIa.mayLoadOrStore() &&
1794 "MIa must load from or modify a memory location");
1795 assert(MIb.mayLoadOrStore() &&
1796 "MIb must load from or modify a memory location");
1797 return false;
1798 }
1799
1800 /// Return the value to use for the MachineCSE's LookAheadLimit,
1801 /// which is a heuristic used for CSE'ing phys reg defs.
1802 virtual unsigned getMachineCSELookAheadLimit() const {
1803 // The default lookahead is small to prevent unprofitable quadratic
1804 // behavior.
1805 return 5;
1806 }
1807
1808 /// Return the maximal number of alias checks on memory operands. For
1809 /// instructions with more than one memory operands, the alias check on a
1810 /// single MachineInstr pair has quadratic overhead and results in
1811 /// unacceptable performance in the worst case. The limit here is to clamp
1812 /// that maximal checks performed. Usually, that's the product of memory
1813 /// operand numbers from that pair of MachineInstr to be checked. For
1814 /// instance, with two MachineInstrs with 4 and 5 memory operands
1815 /// correspondingly, a total of 20 checks are required. With this limit set to
1816 /// 16, their alias check is skipped. We choose to limit the product instead
1817 /// of the individual instruction as targets may have special MachineInstrs
1818 /// with a considerably high number of memory operands, such as `ldm` in ARM.
1819 /// Setting this limit per MachineInstr would result in either too high
1820 /// overhead or too rigid restriction.
1821 virtual unsigned getMemOperandAACheckLimit() const { return 16; }
1822
1823 /// Return an array that contains the ids of the target indices (used for the
1824 /// TargetIndex machine operand) and their names.
1825 ///
1826 /// MIR Serialization is able to serialize only the target indices that are
1827 /// defined by this method.
1828 virtual ArrayRef<std::pair<int, const char *>>
1829 getSerializableTargetIndices() const {
1830 return None;
1831 }
1832
1833 /// Decompose the machine operand's target flags into two values - the direct
1834 /// target flag value and any of bit flags that are applied.
1835 virtual std::pair<unsigned, unsigned>
1836 decomposeMachineOperandsTargetFlags(unsigned /*TF*/) const {
1837 return std::make_pair(0u, 0u);
1838 }
1839
1840 /// Return an array that contains the direct target flag values and their
1841 /// names.
1842 ///
1843 /// MIR Serialization is able to serialize only the target flags that are
1844 /// defined by this method.
1845 virtual ArrayRef<std::pair<unsigned, const char *>>
1846 getSerializableDirectMachineOperandTargetFlags() const {
1847 return None;
1848 }
1849
1850 /// Return an array that contains the bitmask target flag values and their
1851 /// names.
1852 ///
1853 /// MIR Serialization is able to serialize only the target flags that are
1854 /// defined by this method.
1855 virtual ArrayRef<std::pair<unsigned, const char *>>
1856 getSerializableBitmaskMachineOperandTargetFlags() const {
1857 return None;
1858 }
1859
1860 /// Return an array that contains the MMO target flag values and their
1861 /// names.
1862 ///
1863 /// MIR Serialization is able to serialize only the MMO target flags that are
1864 /// defined by this method.
1865 virtual ArrayRef<std::pair<MachineMemOperand::Flags, const char *>>
1866 getSerializableMachineMemOperandTargetFlags() const {
1867 return None;
1868 }
1869
1870 /// Determines whether \p Inst is a tail call instruction. Override this
1871 /// method on targets that do not properly set MCID::Return and MCID::Call on
1872 /// tail call instructions."
1873 virtual bool isTailCall(const MachineInstr &Inst) const {
1874 return Inst.isReturn() && Inst.isCall();
1875 }
1876
1877 /// True if the instruction is bound to the top of its basic block and no
1878 /// other instructions shall be inserted before it. This can be implemented
1879 /// to prevent register allocator to insert spills before such instructions.
1880 virtual bool isBasicBlockPrologue(const MachineInstr &MI) const {
1881 return false;
1882 }
1883
1884 /// During PHI eleimination lets target to make necessary checks and
1885 /// insert the copy to the PHI destination register in a target specific
1886 /// manner.
1887 virtual MachineInstr *createPHIDestinationCopy(
1888 MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt,
1889 const DebugLoc &DL, Register Src, Register Dst) const {
1890 return BuildMI(MBB, InsPt, DL, get(TargetOpcode::COPY), Dst)
1891 .addReg(Src);
1892 }
1893
1894 /// During PHI eleimination lets target to make necessary checks and
1895 /// insert the copy to the PHI destination register in a target specific
1896 /// manner.
1897 virtual MachineInstr *createPHISourceCopy(MachineBasicBlock &MBB,
1898 MachineBasicBlock::iterator InsPt,
1899 const DebugLoc &DL, Register Src,
1900 unsigned SrcSubReg,
1901 Register Dst) const {
1902 return BuildMI(MBB, InsPt, DL, get(TargetOpcode::COPY), Dst)
1903 .addReg(Src, 0, SrcSubReg);
1904 }
1905
1906 /// Returns a \p outliner::OutlinedFunction struct containing target-specific
1907 /// information for a set of outlining candidates.
1908 virtual outliner::OutlinedFunction getOutliningCandidateInfo(
1909 std::vector<outliner::Candidate> &RepeatedSequenceLocs) const {
1910 llvm_unreachable(
1911 "Target didn't implement TargetInstrInfo::getOutliningCandidateInfo!");
1912 }
1913
1914 /// Optional target hook to create the LLVM IR attributes for the outlined
1915 /// function. If overridden, the overriding function must call the default
1916 /// implementation.
1917 virtual void mergeOutliningCandidateAttributes(
1918 Function &F, std::vector<outliner::Candidate> &Candidates) const;
1919
1920 /// Returns how or if \p MI should be outlined.
1921 virtual outliner::InstrType
1922 getOutliningType(MachineBasicBlock::iterator &MIT, unsigned Flags) const {
1923 llvm_unreachable(
1924 "Target didn't implement TargetInstrInfo::getOutliningType!");
1925 }
1926
1927 /// Optional target hook that returns true if \p MBB is safe to outline from,
1928 /// and returns any target-specific information in \p Flags.
1929 virtual bool isMBBSafeToOutlineFrom(MachineBasicBlock &MBB,
1930 unsigned &Flags) const;
1931
1932 /// Insert a custom frame for outlined functions.
1933 virtual void buildOutlinedFrame(MachineBasicBlock &MBB, MachineFunction &MF,
1934 const outliner::OutlinedFunction &OF) const {
1935 llvm_unreachable(
1936 "Target didn't implement TargetInstrInfo::buildOutlinedFrame!");
1937 }
1938
1939 /// Insert a call to an outlined function into the program.
1940 /// Returns an iterator to the spot where we inserted the call. This must be
1941 /// implemented by the target.
1942 virtual MachineBasicBlock::iterator
1943 insertOutlinedCall(Module &M, MachineBasicBlock &MBB,
1944 MachineBasicBlock::iterator &It, MachineFunction &MF,
1945 const outliner::Candidate &C) const {
1946 llvm_unreachable(
1947 "Target didn't implement TargetInstrInfo::insertOutlinedCall!");
1948 }
1949
1950 /// Return true if the function can safely be outlined from.
1951 /// A function \p MF is considered safe for outlining if an outlined function
1952 /// produced from instructions in F will produce a program which produces the
1953 /// same output for any set of given inputs.
1954 virtual bool isFunctionSafeToOutlineFrom(MachineFunction &MF,
1955 bool OutlineFromLinkOnceODRs) const {
1956 llvm_unreachable("Target didn't implement "
1957 "TargetInstrInfo::isFunctionSafeToOutlineFrom!");
1958 }
1959
1960 /// Return true if the function should be outlined from by default.
1961 virtual bool shouldOutlineFromFunctionByDefault(MachineFunction &MF) const {
1962 return false;
1963 }
1964
1965 /// Produce the expression describing the \p MI loading a value into
1966 /// the physical register \p Reg. This hook should only be used with
1967 /// \p MIs belonging to VReg-less functions.
1968 virtual Optional<ParamLoadedValue> describeLoadedValue(const MachineInstr &MI,
1969 Register Reg) const;
1970
1971 /// Given the generic extension instruction \p ExtMI, returns true if this
1972 /// extension is a likely candidate for being folded into an another
1973 /// instruction.
1974 virtual bool isExtendLikelyToBeFolded(MachineInstr &ExtMI,
1975 MachineRegisterInfo &MRI) const {
1976 return false;
1977 }
1978
1979 /// Return MIR formatter to format/parse MIR operands. Target can override
1980 /// this virtual function and return target specific MIR formatter.
1981 virtual const MIRFormatter *getMIRFormatter() const {
1982 if (!Formatter.get())
1983 Formatter = std::make_unique<MIRFormatter>();
1984 return Formatter.get();
1985 }
1986
1987 /// Returns the target-specific default value for tail duplication.
1988 /// This value will be used if the tail-dup-placement-threshold argument is
1989 /// not provided.
1990 virtual unsigned getTailDuplicateSize(CodeGenOpt::Level OptLevel) const {
1991 return OptLevel >= CodeGenOpt::Aggressive ? 4 : 2;
1992 }
1993
1994 /// Returns the callee operand from the given \p MI.
1995 virtual const MachineOperand &getCalleeOperand(const MachineInstr &MI) const {
1996 return MI.getOperand(0);
1997 }
1998
1999 private:
2000 mutable std::unique_ptr<MIRFormatter> Formatter;
2001 unsigned CallFrameSetupOpcode, CallFrameDestroyOpcode;
2002 unsigned CatchRetOpcode;
2003 unsigned ReturnOpcode;
2004 };
2005
2006 /// Provide DenseMapInfo for TargetInstrInfo::RegSubRegPair.
2007 template <> struct DenseMapInfo<TargetInstrInfo::RegSubRegPair> {
2008 using RegInfo = DenseMapInfo<unsigned>;
2009
2010 static inline TargetInstrInfo::RegSubRegPair getEmptyKey() {
2011 return TargetInstrInfo::RegSubRegPair(RegInfo::getEmptyKey(),
2012 RegInfo::getEmptyKey());
2013 }
2014
2015 static inline TargetInstrInfo::RegSubRegPair getTombstoneKey() {
2016 return TargetInstrInfo::RegSubRegPair(RegInfo::getTombstoneKey(),
2017 RegInfo::getTombstoneKey());
2018 }
2019
2020 /// Reuse getHashValue implementation from
2021 /// std::pair<unsigned, unsigned>.
2022 static unsigned getHashValue(const TargetInstrInfo::RegSubRegPair &Val) {
2023 std::pair<unsigned, unsigned> PairVal = std::make_pair(Val.Reg, Val.SubReg);
2024 return DenseMapInfo<std::pair<unsigned, unsigned>>::getHashValue(PairVal);
2025 }
2026
2027 static bool isEqual(const TargetInstrInfo::RegSubRegPair &LHS,
2028 const TargetInstrInfo::RegSubRegPair &RHS) {
2029 return RegInfo::isEqual(LHS.Reg, RHS.Reg) &&
2030 RegInfo::isEqual(LHS.SubReg, RHS.SubReg);
2031 }
2032 };
2033
2034 } // end namespace llvm
2035
2036 #endif // LLVM_CODEGEN_TARGETINSTRINFO_H