1 //===- llvm/CodeGen/GlobalISel/Utils.cpp -------------------------*- 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 /// \file This file implements the utility functions used by the GlobalISel
9 /// pipeline.
10 //===----------------------------------------------------------------------===//
11 
12 #include "llvm/CodeGen/GlobalISel/Utils.h"
13 #include "llvm/ADT/APFloat.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
16 #include "llvm/CodeGen/MachineInstr.h"
17 #include "llvm/CodeGen/MachineInstrBuilder.h"
18 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/CodeGen/StackProtector.h"
21 #include "llvm/CodeGen/TargetInstrInfo.h"
22 #include "llvm/CodeGen/TargetPassConfig.h"
23 #include "llvm/CodeGen/TargetRegisterInfo.h"
24 #include "llvm/IR/Constants.h"
25 
26 #define DEBUG_TYPE "globalisel-utils"
27 
28 using namespace llvm;
29 
30 Register llvm::constrainRegToClass(MachineRegisterInfo &MRI,
31                                    const TargetInstrInfo &TII,
32                                    const RegisterBankInfo &RBI, Register Reg,
33                                    const TargetRegisterClass &RegClass) {
34   if (!RBI.constrainGenericRegister(Reg, RegClass, MRI))
35     return MRI.createVirtualRegister(&RegClass);
36 
37   return Reg;
38 }
39 
40 Register llvm::constrainOperandRegClass(
41     const MachineFunction &MF, const TargetRegisterInfo &TRI,
42     MachineRegisterInfo &MRI, const TargetInstrInfo &TII,
43     const RegisterBankInfo &RBI, MachineInstr &InsertPt,
44     const TargetRegisterClass &RegClass, const MachineOperand &RegMO) {
45   Register Reg = RegMO.getReg();
46   // Assume physical registers are properly constrained.
47   assert(Register::isVirtualRegister(Reg) && "PhysReg not implemented");
48 
49   Register ConstrainedReg = constrainRegToClass(MRI, TII, RBI, Reg, RegClass);
50   // If we created a new virtual register because the class is not compatible
51   // then create a copy between the new and the old register.
52   if (ConstrainedReg != Reg) {
53     MachineBasicBlock::iterator InsertIt(&InsertPt);
54     MachineBasicBlock &MBB = *InsertPt.getParent();
55     if (RegMO.isUse()) {
56       BuildMI(MBB, InsertIt, InsertPt.getDebugLoc(),
57               TII.get(TargetOpcode::COPY), ConstrainedReg)
58           .addReg(Reg);
59     } else {
60       assert(RegMO.isDef() && "Must be a definition");
61       BuildMI(MBB, std::next(InsertIt), InsertPt.getDebugLoc(),
62               TII.get(TargetOpcode::COPY), Reg)
63           .addReg(ConstrainedReg);
64     }
65   }
66   return ConstrainedReg;
67 }
68 
69 Register llvm::constrainOperandRegClass(
70     const MachineFunction &MF, const TargetRegisterInfo &TRI,
71     MachineRegisterInfo &MRI, const TargetInstrInfo &TII,
72     const RegisterBankInfo &RBI, MachineInstr &InsertPt, const MCInstrDesc &II,
73     const MachineOperand &RegMO, unsigned OpIdx) {
74   Register Reg = RegMO.getReg();
75   // Assume physical registers are properly constrained.
76   assert(Register::isVirtualRegister(Reg) && "PhysReg not implemented");
77 
78   const TargetRegisterClass *RegClass = TII.getRegClass(II, OpIdx, &TRI, MF);
79   // Some of the target independent instructions, like COPY, may not impose any
80   // register class constraints on some of their operands: If it's a use, we can
81   // skip constraining as the instruction defining the register would constrain
82   // it.
83 
84   // We can't constrain unallocatable register classes, because we can't create
85   // virtual registers for these classes, so we need to let targets handled this
86   // case.
87   if (RegClass && !RegClass->isAllocatable())
88     RegClass = TRI.getConstrainedRegClassForOperand(RegMO, MRI);
89 
90   if (!RegClass) {
91     assert((!isTargetSpecificOpcode(II.getOpcode()) || RegMO.isUse()) &&
92            "Register class constraint is required unless either the "
93            "instruction is target independent or the operand is a use");
94     // FIXME: Just bailing out like this here could be not enough, unless we
95     // expect the users of this function to do the right thing for PHIs and
96     // COPY:
97     //   v1 = COPY v0
98     //   v2 = COPY v1
99     // v1 here may end up not being constrained at all. Please notice that to
100     // reproduce the issue we likely need a destination pattern of a selection
101     // rule producing such extra copies, not just an input GMIR with them as
102     // every existing target using selectImpl handles copies before calling it
103     // and they never reach this function.
104     return Reg;
105   }
106   return constrainOperandRegClass(MF, TRI, MRI, TII, RBI, InsertPt, *RegClass,
107                                   RegMO);
108 }
109 
110 bool llvm::constrainSelectedInstRegOperands(MachineInstr &I,
111                                             const TargetInstrInfo &TII,
112                                             const TargetRegisterInfo &TRI,
113                                             const RegisterBankInfo &RBI) {
114   assert(!isPreISelGenericOpcode(I.getOpcode()) &&
115          "A selected instruction is expected");
116   MachineBasicBlock &MBB = *I.getParent();
117   MachineFunction &MF = *MBB.getParent();
118   MachineRegisterInfo &MRI = MF.getRegInfo();
119 
120   for (unsigned OpI = 0, OpE = I.getNumExplicitOperands(); OpI != OpE; ++OpI) {
121     MachineOperand &MO = I.getOperand(OpI);
122 
123     // There's nothing to be done on non-register operands.
124     if (!MO.isReg())
125       continue;
126 
127     LLVM_DEBUG(dbgs() << "Converting operand: " << MO << '\n');
128     assert(MO.isReg() && "Unsupported non-reg operand");
129 
130     Register Reg = MO.getReg();
131     // Physical registers don't need to be constrained.
132     if (Register::isPhysicalRegister(Reg))
133       continue;
134 
135     // Register operands with a value of 0 (e.g. predicate operands) don't need
136     // to be constrained.
137     if (Reg == 0)
138       continue;
139 
140     // If the operand is a vreg, we should constrain its regclass, and only
141     // insert COPYs if that's impossible.
142     // constrainOperandRegClass does that for us.
143     MO.setReg(constrainOperandRegClass(MF, TRI, MRI, TII, RBI, I, I.getDesc(),
144                                        MO, OpI));
145 
146     // Tie uses to defs as indicated in MCInstrDesc if this hasn't already been
147     // done.
148     if (MO.isUse()) {
149       int DefIdx = I.getDesc().getOperandConstraint(OpI, MCOI::TIED_TO);
150       if (DefIdx != -1 && !I.isRegTiedToUseOperand(DefIdx))
151         I.tieOperands(DefIdx, OpI);
152     }
153   }
154   return true;
155 }
156 
157 bool llvm::canReplaceReg(Register DstReg, Register SrcReg,
158                          MachineRegisterInfo &MRI) {
159   // Give up if either DstReg or SrcReg  is a physical register.
160   if (DstReg.isPhysical() || SrcReg.isPhysical())
161     return false;
162   // Give up if the types don't match.
163   if (MRI.getType(DstReg) != MRI.getType(SrcReg))
164     return false;
165   // Replace if either DstReg has no constraints or the register
166   // constraints match.
167   return !MRI.getRegClassOrRegBank(DstReg) ||
168          MRI.getRegClassOrRegBank(DstReg) == MRI.getRegClassOrRegBank(SrcReg);
169 }
170 
171 bool llvm::isTriviallyDead(const MachineInstr &MI,
172                            const MachineRegisterInfo &MRI) {
173   // If we can move an instruction, we can remove it.  Otherwise, it has
174   // a side-effect of some sort.
175   bool SawStore = false;
176   if (!MI.isSafeToMove(/*AA=*/nullptr, SawStore) && !MI.isPHI())
177     return false;
178 
179   // Instructions without side-effects are dead iff they only define dead vregs.
180   for (auto &MO : MI.operands()) {
181     if (!MO.isReg() || !MO.isDef())
182       continue;
183 
184     Register Reg = MO.getReg();
185     if (Register::isPhysicalRegister(Reg) || !MRI.use_nodbg_empty(Reg))
186       return false;
187   }
188   return true;
189 }
190 
191 void llvm::reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC,
192                               MachineOptimizationRemarkEmitter &MORE,
193                               MachineOptimizationRemarkMissed &R) {
194   MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
195 
196   // Print the function name explicitly if we don't have a debug location (which
197   // makes the diagnostic less useful) or if we're going to emit a raw error.
198   if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
199     R << (" (in function: " + MF.getName() + ")").str();
200 
201   if (TPC.isGlobalISelAbortEnabled())
202     report_fatal_error(R.getMsg());
203   else
204     MORE.emit(R);
205 }
206 
207 void llvm::reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC,
208                               MachineOptimizationRemarkEmitter &MORE,
209                               const char *PassName, StringRef Msg,
210                               const MachineInstr &MI) {
211   MachineOptimizationRemarkMissed R(PassName, "GISelFailure: ",
212                                     MI.getDebugLoc(), MI.getParent());
213   R << Msg;
214   // Printing MI is expensive;  only do it if expensive remarks are enabled.
215   if (TPC.isGlobalISelAbortEnabled() || MORE.allowExtraAnalysis(PassName))
216     R << ": " << ore::MNV("Inst", MI);
217   reportGISelFailure(MF, TPC, MORE, R);
218 }
219 
220 Optional<int64_t> llvm::getConstantVRegVal(Register VReg,
221                                            const MachineRegisterInfo &MRI) {
222   Optional<ValueAndVReg> ValAndVReg =
223       getConstantVRegValWithLookThrough(VReg, MRI, /*LookThroughInstrs*/ false);
224   assert((!ValAndVReg || ValAndVReg->VReg == VReg) &&
225          "Value found while looking through instrs");
226   if (!ValAndVReg)
227     return None;
228   return ValAndVReg->Value;
229 }
230 
231 Optional<ValueAndVReg> llvm::getConstantVRegValWithLookThrough(
232     Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs,
233     bool HandleFConstant) {
234   SmallVector<std::pair<unsigned, unsigned>, 4> SeenOpcodes;
235   MachineInstr *MI;
236   auto IsConstantOpcode = [HandleFConstant](unsigned Opcode) {
237     return Opcode == TargetOpcode::G_CONSTANT ||
238            (HandleFConstant && Opcode == TargetOpcode::G_FCONSTANT);
239   };
240   auto GetImmediateValue = [HandleFConstant,
241                             &MRI](const MachineInstr &MI) -> Optional<APInt> {
242     const MachineOperand &CstVal = MI.getOperand(1);
243     if (!CstVal.isImm() && !CstVal.isCImm() &&
244         (!HandleFConstant || !CstVal.isFPImm()))
245       return None;
246     if (!CstVal.isFPImm()) {
247       unsigned BitWidth =
248           MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
249       APInt Val = CstVal.isImm() ? APInt(BitWidth, CstVal.getImm())
250                                  : CstVal.getCImm()->getValue();
251       assert(Val.getBitWidth() == BitWidth &&
252              "Value bitwidth doesn't match definition type");
253       return Val;
254     }
255     return CstVal.getFPImm()->getValueAPF().bitcastToAPInt();
256   };
257   while ((MI = MRI.getVRegDef(VReg)) && !IsConstantOpcode(MI->getOpcode()) &&
258          LookThroughInstrs) {
259     switch (MI->getOpcode()) {
260     case TargetOpcode::G_TRUNC:
261     case TargetOpcode::G_SEXT:
262     case TargetOpcode::G_ZEXT:
263       SeenOpcodes.push_back(std::make_pair(
264           MI->getOpcode(),
265           MRI.getType(MI->getOperand(0).getReg()).getSizeInBits()));
266       VReg = MI->getOperand(1).getReg();
267       break;
268     case TargetOpcode::COPY:
269       VReg = MI->getOperand(1).getReg();
270       if (Register::isPhysicalRegister(VReg))
271         return None;
272       break;
273     case TargetOpcode::G_INTTOPTR:
274       VReg = MI->getOperand(1).getReg();
275       break;
276     default:
277       return None;
278     }
279   }
280   if (!MI || !IsConstantOpcode(MI->getOpcode()))
281     return None;
282 
283   Optional<APInt> MaybeVal = GetImmediateValue(*MI);
284   if (!MaybeVal)
285     return None;
286   APInt &Val = *MaybeVal;
287   while (!SeenOpcodes.empty()) {
288     std::pair<unsigned, unsigned> OpcodeAndSize = SeenOpcodes.pop_back_val();
289     switch (OpcodeAndSize.first) {
290     case TargetOpcode::G_TRUNC:
291       Val = Val.trunc(OpcodeAndSize.second);
292       break;
293     case TargetOpcode::G_SEXT:
294       Val = Val.sext(OpcodeAndSize.second);
295       break;
296     case TargetOpcode::G_ZEXT:
297       Val = Val.zext(OpcodeAndSize.second);
298       break;
299     }
300   }
301 
302   if (Val.getBitWidth() > 64)
303     return None;
304 
305   return ValueAndVReg{Val.getSExtValue(), VReg};
306 }
307 
308 const llvm::ConstantFP *
309 llvm::getConstantFPVRegVal(Register VReg, const MachineRegisterInfo &MRI) {
310   MachineInstr *MI = MRI.getVRegDef(VReg);
311   if (TargetOpcode::G_FCONSTANT != MI->getOpcode())
312     return nullptr;
313   return MI->getOperand(1).getFPImm();
314 }
315 
316 namespace {
317 struct DefinitionAndSourceRegister {
318   llvm::MachineInstr *MI;
319   Register Reg;
320 };
321 } // namespace
322 
323 static llvm::Optional<DefinitionAndSourceRegister>
324 getDefSrcRegIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI) {
325   Register DefSrcReg = Reg;
326   auto *DefMI = MRI.getVRegDef(Reg);
327   auto DstTy = MRI.getType(DefMI->getOperand(0).getReg());
328   if (!DstTy.isValid())
329     return None;
330   while (DefMI->getOpcode() == TargetOpcode::COPY) {
331     Register SrcReg = DefMI->getOperand(1).getReg();
332     auto SrcTy = MRI.getType(SrcReg);
333     if (!SrcTy.isValid() || SrcTy != DstTy)
334       break;
335     DefMI = MRI.getVRegDef(SrcReg);
336     DefSrcReg = SrcReg;
337   }
338   return DefinitionAndSourceRegister{DefMI, DefSrcReg};
339 }
340 
341 llvm::MachineInstr *llvm::getDefIgnoringCopies(Register Reg,
342                                                const MachineRegisterInfo &MRI) {
343   Optional<DefinitionAndSourceRegister> DefSrcReg =
344       getDefSrcRegIgnoringCopies(Reg, MRI);
345   return DefSrcReg ? DefSrcReg->MI : nullptr;
346 }
347 
348 Register llvm::getSrcRegIgnoringCopies(Register Reg,
349                                        const MachineRegisterInfo &MRI) {
350   Optional<DefinitionAndSourceRegister> DefSrcReg =
351       getDefSrcRegIgnoringCopies(Reg, MRI);
352   return DefSrcReg ? DefSrcReg->Reg : Register();
353 }
354 
355 llvm::MachineInstr *llvm::getOpcodeDef(unsigned Opcode, Register Reg,
356                                        const MachineRegisterInfo &MRI) {
357   MachineInstr *DefMI = getDefIgnoringCopies(Reg, MRI);
358   return DefMI && DefMI->getOpcode() == Opcode ? DefMI : nullptr;
359 }
360 
361 APFloat llvm::getAPFloatFromSize(double Val, unsigned Size) {
362   if (Size == 32)
363     return APFloat(float(Val));
364   if (Size == 64)
365     return APFloat(Val);
366   if (Size != 16)
367     llvm_unreachable("Unsupported FPConstant size");
368   bool Ignored;
369   APFloat APF(Val);
370   APF.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &Ignored);
371   return APF;
372 }
373 
374 Optional<APInt> llvm::ConstantFoldBinOp(unsigned Opcode, const unsigned Op1,
375                                         const unsigned Op2,
376                                         const MachineRegisterInfo &MRI) {
377   auto MaybeOp1Cst = getConstantVRegVal(Op1, MRI);
378   auto MaybeOp2Cst = getConstantVRegVal(Op2, MRI);
379   if (MaybeOp1Cst && MaybeOp2Cst) {
380     LLT Ty = MRI.getType(Op1);
381     APInt C1(Ty.getSizeInBits(), *MaybeOp1Cst, true);
382     APInt C2(Ty.getSizeInBits(), *MaybeOp2Cst, true);
383     switch (Opcode) {
384     default:
385       break;
386     case TargetOpcode::G_ADD:
387       return C1 + C2;
388     case TargetOpcode::G_AND:
389       return C1 & C2;
390     case TargetOpcode::G_ASHR:
391       return C1.ashr(C2);
392     case TargetOpcode::G_LSHR:
393       return C1.lshr(C2);
394     case TargetOpcode::G_MUL:
395       return C1 * C2;
396     case TargetOpcode::G_OR:
397       return C1 | C2;
398     case TargetOpcode::G_SHL:
399       return C1 << C2;
400     case TargetOpcode::G_SUB:
401       return C1 - C2;
402     case TargetOpcode::G_XOR:
403       return C1 ^ C2;
404     case TargetOpcode::G_UDIV:
405       if (!C2.getBoolValue())
406         break;
407       return C1.udiv(C2);
408     case TargetOpcode::G_SDIV:
409       if (!C2.getBoolValue())
410         break;
411       return C1.sdiv(C2);
412     case TargetOpcode::G_UREM:
413       if (!C2.getBoolValue())
414         break;
415       return C1.urem(C2);
416     case TargetOpcode::G_SREM:
417       if (!C2.getBoolValue())
418         break;
419       return C1.srem(C2);
420     }
421   }
422   return None;
423 }
424 
425 bool llvm::isKnownNeverNaN(Register Val, const MachineRegisterInfo &MRI,
426                            bool SNaN) {
427   const MachineInstr *DefMI = MRI.getVRegDef(Val);
428   if (!DefMI)
429     return false;
430 
431   if (DefMI->getFlag(MachineInstr::FmNoNans))
432     return true;
433 
434   if (SNaN) {
435     // FP operations quiet. For now, just handle the ones inserted during
436     // legalization.
437     switch (DefMI->getOpcode()) {
438     case TargetOpcode::G_FPEXT:
439     case TargetOpcode::G_FPTRUNC:
440     case TargetOpcode::G_FCANONICALIZE:
441       return true;
442     default:
443       return false;
444     }
445   }
446 
447   return false;
448 }
449 
450 Optional<APInt> llvm::ConstantFoldExtOp(unsigned Opcode, const unsigned Op1,
451                                         uint64_t Imm,
452                                         const MachineRegisterInfo &MRI) {
453   auto MaybeOp1Cst = getConstantVRegVal(Op1, MRI);
454   if (MaybeOp1Cst) {
455     LLT Ty = MRI.getType(Op1);
456     APInt C1(Ty.getSizeInBits(), *MaybeOp1Cst, true);
457     switch (Opcode) {
458     default:
459       break;
460     case TargetOpcode::G_SEXT_INREG:
461       return C1.trunc(Imm).sext(C1.getBitWidth());
462     }
463   }
464   return None;
465 }
466 
467 void llvm::getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU) {
468   AU.addPreserved<StackProtector>();
469 }
470