1 //===- llvm/CodeGen/GlobalISel/InstructionSelector.cpp --------------------===//
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 /// \file
10 /// This file implements the InstructionSelector class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/GlobalISel/InstructionSelector.h"
15 #include "llvm/CodeGen/GlobalISel/Utils.h"
16 #include "llvm/CodeGen/MachineBasicBlock.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/CodeGen/MachineOperand.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/TargetRegisterInfo.h"
22 #include "llvm/MC/MCInstrDesc.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <cassert>
26 
27 #define DEBUG_TYPE "instructionselector"
28 
29 using namespace llvm;
30 
MatcherState(unsigned MaxRenderers)31 InstructionSelector::MatcherState::MatcherState(unsigned MaxRenderers)
32     : Renderers(MaxRenderers), MIs() {}
33 
34 InstructionSelector::InstructionSelector() = default;
35 
isOperandImmEqual(const MachineOperand & MO,int64_t Value,const MachineRegisterInfo & MRI) const36 bool InstructionSelector::isOperandImmEqual(
37     const MachineOperand &MO, int64_t Value,
38     const MachineRegisterInfo &MRI) const {
39   if (MO.isReg() && MO.getReg())
40     if (auto VRegVal = getIConstantVRegValWithLookThrough(MO.getReg(), MRI))
41       return VRegVal->Value.getSExtValue() == Value;
42   return false;
43 }
44 
isBaseWithConstantOffset(const MachineOperand & Root,const MachineRegisterInfo & MRI) const45 bool InstructionSelector::isBaseWithConstantOffset(
46     const MachineOperand &Root, const MachineRegisterInfo &MRI) const {
47   if (!Root.isReg())
48     return false;
49 
50   MachineInstr *RootI = MRI.getVRegDef(Root.getReg());
51   if (RootI->getOpcode() != TargetOpcode::G_PTR_ADD)
52     return false;
53 
54   MachineOperand &RHS = RootI->getOperand(2);
55   MachineInstr *RHSI = MRI.getVRegDef(RHS.getReg());
56   if (RHSI->getOpcode() != TargetOpcode::G_CONSTANT)
57     return false;
58 
59   return true;
60 }
61 
isObviouslySafeToFold(MachineInstr & MI,MachineInstr & IntoMI) const62 bool InstructionSelector::isObviouslySafeToFold(MachineInstr &MI,
63                                                 MachineInstr &IntoMI) const {
64   // Immediate neighbours are already folded.
65   if (MI.getParent() == IntoMI.getParent() &&
66       std::next(MI.getIterator()) == IntoMI.getIterator())
67     return true;
68 
69   return !MI.mayLoadOrStore() && !MI.mayRaiseFPException() &&
70          !MI.hasUnmodeledSideEffects() && MI.implicit_operands().empty();
71 }
72