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/APInt.h" 15 #include "llvm/CodeGen/CodeGenCommonISel.h" 16 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h" 17 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 18 #include "llvm/CodeGen/GlobalISel/GenericMachineInstrs.h" 19 #include "llvm/CodeGen/GlobalISel/LostDebugLocObserver.h" 20 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h" 21 #include "llvm/CodeGen/MachineInstr.h" 22 #include "llvm/CodeGen/MachineInstrBuilder.h" 23 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" 24 #include "llvm/CodeGen/MachineRegisterInfo.h" 25 #include "llvm/CodeGen/MachineSizeOpts.h" 26 #include "llvm/CodeGen/RegisterBankInfo.h" 27 #include "llvm/CodeGen/StackProtector.h" 28 #include "llvm/CodeGen/TargetInstrInfo.h" 29 #include "llvm/CodeGen/TargetLowering.h" 30 #include "llvm/CodeGen/TargetPassConfig.h" 31 #include "llvm/CodeGen/TargetRegisterInfo.h" 32 #include "llvm/IR/Constants.h" 33 #include "llvm/Target/TargetMachine.h" 34 #include "llvm/Transforms/Utils/SizeOpts.h" 35 #include <numeric> 36 #include <optional> 37 38 #define DEBUG_TYPE "globalisel-utils" 39 40 using namespace llvm; 41 using namespace MIPatternMatch; 42 43 Register llvm::constrainRegToClass(MachineRegisterInfo &MRI, 44 const TargetInstrInfo &TII, 45 const RegisterBankInfo &RBI, Register Reg, 46 const TargetRegisterClass &RegClass) { 47 if (!RBI.constrainGenericRegister(Reg, RegClass, MRI)) 48 return MRI.createVirtualRegister(&RegClass); 49 50 return Reg; 51 } 52 53 Register llvm::constrainOperandRegClass( 54 const MachineFunction &MF, const TargetRegisterInfo &TRI, 55 MachineRegisterInfo &MRI, const TargetInstrInfo &TII, 56 const RegisterBankInfo &RBI, MachineInstr &InsertPt, 57 const TargetRegisterClass &RegClass, MachineOperand &RegMO) { 58 Register Reg = RegMO.getReg(); 59 // Assume physical registers are properly constrained. 60 assert(Reg.isVirtual() && "PhysReg not implemented"); 61 62 // Save the old register class to check whether 63 // the change notifications will be required. 64 // TODO: A better approach would be to pass 65 // the observers to constrainRegToClass(). 66 auto *OldRegClass = MRI.getRegClassOrNull(Reg); 67 Register ConstrainedReg = constrainRegToClass(MRI, TII, RBI, Reg, RegClass); 68 // If we created a new virtual register because the class is not compatible 69 // then create a copy between the new and the old register. 70 if (ConstrainedReg != Reg) { 71 MachineBasicBlock::iterator InsertIt(&InsertPt); 72 MachineBasicBlock &MBB = *InsertPt.getParent(); 73 // FIXME: The copy needs to have the classes constrained for its operands. 74 // Use operand's regbank to get the class for old register (Reg). 75 if (RegMO.isUse()) { 76 BuildMI(MBB, InsertIt, InsertPt.getDebugLoc(), 77 TII.get(TargetOpcode::COPY), ConstrainedReg) 78 .addReg(Reg); 79 } else { 80 assert(RegMO.isDef() && "Must be a definition"); 81 BuildMI(MBB, std::next(InsertIt), InsertPt.getDebugLoc(), 82 TII.get(TargetOpcode::COPY), Reg) 83 .addReg(ConstrainedReg); 84 } 85 if (GISelChangeObserver *Observer = MF.getObserver()) { 86 Observer->changingInstr(*RegMO.getParent()); 87 } 88 RegMO.setReg(ConstrainedReg); 89 if (GISelChangeObserver *Observer = MF.getObserver()) { 90 Observer->changedInstr(*RegMO.getParent()); 91 } 92 } else if (OldRegClass != MRI.getRegClassOrNull(Reg)) { 93 if (GISelChangeObserver *Observer = MF.getObserver()) { 94 if (!RegMO.isDef()) { 95 MachineInstr *RegDef = MRI.getVRegDef(Reg); 96 Observer->changedInstr(*RegDef); 97 } 98 Observer->changingAllUsesOfReg(MRI, Reg); 99 Observer->finishedChangingAllUsesOfReg(); 100 } 101 } 102 return ConstrainedReg; 103 } 104 105 Register llvm::constrainOperandRegClass( 106 const MachineFunction &MF, const TargetRegisterInfo &TRI, 107 MachineRegisterInfo &MRI, const TargetInstrInfo &TII, 108 const RegisterBankInfo &RBI, MachineInstr &InsertPt, const MCInstrDesc &II, 109 MachineOperand &RegMO, unsigned OpIdx) { 110 Register Reg = RegMO.getReg(); 111 // Assume physical registers are properly constrained. 112 assert(Reg.isVirtual() && "PhysReg not implemented"); 113 114 const TargetRegisterClass *OpRC = TII.getRegClass(II, OpIdx, &TRI, MF); 115 // Some of the target independent instructions, like COPY, may not impose any 116 // register class constraints on some of their operands: If it's a use, we can 117 // skip constraining as the instruction defining the register would constrain 118 // it. 119 120 if (OpRC) { 121 // Obtain the RC from incoming regbank if it is a proper sub-class. Operands 122 // can have multiple regbanks for a superclass that combine different 123 // register types (E.g., AMDGPU's VGPR and AGPR). The regbank ambiguity 124 // resolved by targets during regbankselect should not be overridden. 125 if (const auto *SubRC = TRI.getCommonSubClass( 126 OpRC, TRI.getConstrainedRegClassForOperand(RegMO, MRI))) 127 OpRC = SubRC; 128 129 OpRC = TRI.getAllocatableClass(OpRC); 130 } 131 132 if (!OpRC) { 133 assert((!isTargetSpecificOpcode(II.getOpcode()) || RegMO.isUse()) && 134 "Register class constraint is required unless either the " 135 "instruction is target independent or the operand is a use"); 136 // FIXME: Just bailing out like this here could be not enough, unless we 137 // expect the users of this function to do the right thing for PHIs and 138 // COPY: 139 // v1 = COPY v0 140 // v2 = COPY v1 141 // v1 here may end up not being constrained at all. Please notice that to 142 // reproduce the issue we likely need a destination pattern of a selection 143 // rule producing such extra copies, not just an input GMIR with them as 144 // every existing target using selectImpl handles copies before calling it 145 // and they never reach this function. 146 return Reg; 147 } 148 return constrainOperandRegClass(MF, TRI, MRI, TII, RBI, InsertPt, *OpRC, 149 RegMO); 150 } 151 152 bool llvm::constrainSelectedInstRegOperands(MachineInstr &I, 153 const TargetInstrInfo &TII, 154 const TargetRegisterInfo &TRI, 155 const RegisterBankInfo &RBI) { 156 assert(!isPreISelGenericOpcode(I.getOpcode()) && 157 "A selected instruction is expected"); 158 MachineBasicBlock &MBB = *I.getParent(); 159 MachineFunction &MF = *MBB.getParent(); 160 MachineRegisterInfo &MRI = MF.getRegInfo(); 161 162 for (unsigned OpI = 0, OpE = I.getNumExplicitOperands(); OpI != OpE; ++OpI) { 163 MachineOperand &MO = I.getOperand(OpI); 164 165 // There's nothing to be done on non-register operands. 166 if (!MO.isReg()) 167 continue; 168 169 LLVM_DEBUG(dbgs() << "Converting operand: " << MO << '\n'); 170 assert(MO.isReg() && "Unsupported non-reg operand"); 171 172 Register Reg = MO.getReg(); 173 // Physical registers don't need to be constrained. 174 if (Reg.isPhysical()) 175 continue; 176 177 // Register operands with a value of 0 (e.g. predicate operands) don't need 178 // to be constrained. 179 if (Reg == 0) 180 continue; 181 182 // If the operand is a vreg, we should constrain its regclass, and only 183 // insert COPYs if that's impossible. 184 // constrainOperandRegClass does that for us. 185 constrainOperandRegClass(MF, TRI, MRI, TII, RBI, I, I.getDesc(), MO, OpI); 186 187 // Tie uses to defs as indicated in MCInstrDesc if this hasn't already been 188 // done. 189 if (MO.isUse()) { 190 int DefIdx = I.getDesc().getOperandConstraint(OpI, MCOI::TIED_TO); 191 if (DefIdx != -1 && !I.isRegTiedToUseOperand(DefIdx)) 192 I.tieOperands(DefIdx, OpI); 193 } 194 } 195 return true; 196 } 197 198 bool llvm::canReplaceReg(Register DstReg, Register SrcReg, 199 MachineRegisterInfo &MRI) { 200 // Give up if either DstReg or SrcReg is a physical register. 201 if (DstReg.isPhysical() || SrcReg.isPhysical()) 202 return false; 203 // Give up if the types don't match. 204 if (MRI.getType(DstReg) != MRI.getType(SrcReg)) 205 return false; 206 // Replace if either DstReg has no constraints or the register 207 // constraints match. 208 const auto &DstRBC = MRI.getRegClassOrRegBank(DstReg); 209 if (!DstRBC || DstRBC == MRI.getRegClassOrRegBank(SrcReg)) 210 return true; 211 212 // Otherwise match if the Src is already a regclass that is covered by the Dst 213 // RegBank. 214 return DstRBC.is<const RegisterBank *>() && MRI.getRegClassOrNull(SrcReg) && 215 DstRBC.get<const RegisterBank *>()->covers( 216 *MRI.getRegClassOrNull(SrcReg)); 217 } 218 219 bool llvm::isTriviallyDead(const MachineInstr &MI, 220 const MachineRegisterInfo &MRI) { 221 // FIXME: This logical is mostly duplicated with 222 // DeadMachineInstructionElim::isDead. Why is LOCAL_ESCAPE not considered in 223 // MachineInstr::isLabel? 224 225 // Don't delete frame allocation labels. 226 if (MI.getOpcode() == TargetOpcode::LOCAL_ESCAPE) 227 return false; 228 // LIFETIME markers should be preserved even if they seem dead. 229 if (MI.getOpcode() == TargetOpcode::LIFETIME_START || 230 MI.getOpcode() == TargetOpcode::LIFETIME_END) 231 return false; 232 233 // If we can move an instruction, we can remove it. Otherwise, it has 234 // a side-effect of some sort. 235 bool SawStore = false; 236 if (!MI.isSafeToMove(/*AA=*/nullptr, SawStore) && !MI.isPHI()) 237 return false; 238 239 // Instructions without side-effects are dead iff they only define dead vregs. 240 for (const auto &MO : MI.all_defs()) { 241 Register Reg = MO.getReg(); 242 if (Reg.isPhysical() || !MRI.use_nodbg_empty(Reg)) 243 return false; 244 } 245 return true; 246 } 247 248 static void reportGISelDiagnostic(DiagnosticSeverity Severity, 249 MachineFunction &MF, 250 const TargetPassConfig &TPC, 251 MachineOptimizationRemarkEmitter &MORE, 252 MachineOptimizationRemarkMissed &R) { 253 bool IsFatal = Severity == DS_Error && 254 TPC.isGlobalISelAbortEnabled(); 255 // Print the function name explicitly if we don't have a debug location (which 256 // makes the diagnostic less useful) or if we're going to emit a raw error. 257 if (!R.getLocation().isValid() || IsFatal) 258 R << (" (in function: " + MF.getName() + ")").str(); 259 260 if (IsFatal) 261 report_fatal_error(Twine(R.getMsg())); 262 else 263 MORE.emit(R); 264 } 265 266 void llvm::reportGISelWarning(MachineFunction &MF, const TargetPassConfig &TPC, 267 MachineOptimizationRemarkEmitter &MORE, 268 MachineOptimizationRemarkMissed &R) { 269 reportGISelDiagnostic(DS_Warning, MF, TPC, MORE, R); 270 } 271 272 void llvm::reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC, 273 MachineOptimizationRemarkEmitter &MORE, 274 MachineOptimizationRemarkMissed &R) { 275 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel); 276 reportGISelDiagnostic(DS_Error, MF, TPC, MORE, R); 277 } 278 279 void llvm::reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC, 280 MachineOptimizationRemarkEmitter &MORE, 281 const char *PassName, StringRef Msg, 282 const MachineInstr &MI) { 283 MachineOptimizationRemarkMissed R(PassName, "GISelFailure: ", 284 MI.getDebugLoc(), MI.getParent()); 285 R << Msg; 286 // Printing MI is expensive; only do it if expensive remarks are enabled. 287 if (TPC.isGlobalISelAbortEnabled() || MORE.allowExtraAnalysis(PassName)) 288 R << ": " << ore::MNV("Inst", MI); 289 reportGISelFailure(MF, TPC, MORE, R); 290 } 291 292 std::optional<APInt> llvm::getIConstantVRegVal(Register VReg, 293 const MachineRegisterInfo &MRI) { 294 std::optional<ValueAndVReg> ValAndVReg = getIConstantVRegValWithLookThrough( 295 VReg, MRI, /*LookThroughInstrs*/ false); 296 assert((!ValAndVReg || ValAndVReg->VReg == VReg) && 297 "Value found while looking through instrs"); 298 if (!ValAndVReg) 299 return std::nullopt; 300 return ValAndVReg->Value; 301 } 302 303 std::optional<int64_t> 304 llvm::getIConstantVRegSExtVal(Register VReg, const MachineRegisterInfo &MRI) { 305 std::optional<APInt> Val = getIConstantVRegVal(VReg, MRI); 306 if (Val && Val->getBitWidth() <= 64) 307 return Val->getSExtValue(); 308 return std::nullopt; 309 } 310 311 namespace { 312 313 typedef std::function<bool(const MachineInstr *)> IsOpcodeFn; 314 typedef std::function<std::optional<APInt>(const MachineInstr *MI)> GetAPCstFn; 315 316 std::optional<ValueAndVReg> getConstantVRegValWithLookThrough( 317 Register VReg, const MachineRegisterInfo &MRI, IsOpcodeFn IsConstantOpcode, 318 GetAPCstFn getAPCstValue, bool LookThroughInstrs = true, 319 bool LookThroughAnyExt = false) { 320 SmallVector<std::pair<unsigned, unsigned>, 4> SeenOpcodes; 321 MachineInstr *MI; 322 323 while ((MI = MRI.getVRegDef(VReg)) && !IsConstantOpcode(MI) && 324 LookThroughInstrs) { 325 switch (MI->getOpcode()) { 326 case TargetOpcode::G_ANYEXT: 327 if (!LookThroughAnyExt) 328 return std::nullopt; 329 [[fallthrough]]; 330 case TargetOpcode::G_TRUNC: 331 case TargetOpcode::G_SEXT: 332 case TargetOpcode::G_ZEXT: 333 SeenOpcodes.push_back(std::make_pair( 334 MI->getOpcode(), 335 MRI.getType(MI->getOperand(0).getReg()).getSizeInBits())); 336 VReg = MI->getOperand(1).getReg(); 337 break; 338 case TargetOpcode::COPY: 339 VReg = MI->getOperand(1).getReg(); 340 if (VReg.isPhysical()) 341 return std::nullopt; 342 break; 343 case TargetOpcode::G_INTTOPTR: 344 VReg = MI->getOperand(1).getReg(); 345 break; 346 default: 347 return std::nullopt; 348 } 349 } 350 if (!MI || !IsConstantOpcode(MI)) 351 return std::nullopt; 352 353 std::optional<APInt> MaybeVal = getAPCstValue(MI); 354 if (!MaybeVal) 355 return std::nullopt; 356 APInt &Val = *MaybeVal; 357 while (!SeenOpcodes.empty()) { 358 std::pair<unsigned, unsigned> OpcodeAndSize = SeenOpcodes.pop_back_val(); 359 switch (OpcodeAndSize.first) { 360 case TargetOpcode::G_TRUNC: 361 Val = Val.trunc(OpcodeAndSize.second); 362 break; 363 case TargetOpcode::G_ANYEXT: 364 case TargetOpcode::G_SEXT: 365 Val = Val.sext(OpcodeAndSize.second); 366 break; 367 case TargetOpcode::G_ZEXT: 368 Val = Val.zext(OpcodeAndSize.second); 369 break; 370 } 371 } 372 373 return ValueAndVReg{Val, VReg}; 374 } 375 376 bool isIConstant(const MachineInstr *MI) { 377 if (!MI) 378 return false; 379 return MI->getOpcode() == TargetOpcode::G_CONSTANT; 380 } 381 382 bool isFConstant(const MachineInstr *MI) { 383 if (!MI) 384 return false; 385 return MI->getOpcode() == TargetOpcode::G_FCONSTANT; 386 } 387 388 bool isAnyConstant(const MachineInstr *MI) { 389 if (!MI) 390 return false; 391 unsigned Opc = MI->getOpcode(); 392 return Opc == TargetOpcode::G_CONSTANT || Opc == TargetOpcode::G_FCONSTANT; 393 } 394 395 std::optional<APInt> getCImmAsAPInt(const MachineInstr *MI) { 396 const MachineOperand &CstVal = MI->getOperand(1); 397 if (CstVal.isCImm()) 398 return CstVal.getCImm()->getValue(); 399 return std::nullopt; 400 } 401 402 std::optional<APInt> getCImmOrFPImmAsAPInt(const MachineInstr *MI) { 403 const MachineOperand &CstVal = MI->getOperand(1); 404 if (CstVal.isCImm()) 405 return CstVal.getCImm()->getValue(); 406 if (CstVal.isFPImm()) 407 return CstVal.getFPImm()->getValueAPF().bitcastToAPInt(); 408 return std::nullopt; 409 } 410 411 } // end anonymous namespace 412 413 std::optional<ValueAndVReg> llvm::getIConstantVRegValWithLookThrough( 414 Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs) { 415 return getConstantVRegValWithLookThrough(VReg, MRI, isIConstant, 416 getCImmAsAPInt, LookThroughInstrs); 417 } 418 419 std::optional<ValueAndVReg> llvm::getAnyConstantVRegValWithLookThrough( 420 Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs, 421 bool LookThroughAnyExt) { 422 return getConstantVRegValWithLookThrough( 423 VReg, MRI, isAnyConstant, getCImmOrFPImmAsAPInt, LookThroughInstrs, 424 LookThroughAnyExt); 425 } 426 427 std::optional<FPValueAndVReg> llvm::getFConstantVRegValWithLookThrough( 428 Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs) { 429 auto Reg = getConstantVRegValWithLookThrough( 430 VReg, MRI, isFConstant, getCImmOrFPImmAsAPInt, LookThroughInstrs); 431 if (!Reg) 432 return std::nullopt; 433 return FPValueAndVReg{getConstantFPVRegVal(Reg->VReg, MRI)->getValueAPF(), 434 Reg->VReg}; 435 } 436 437 const ConstantFP * 438 llvm::getConstantFPVRegVal(Register VReg, const MachineRegisterInfo &MRI) { 439 MachineInstr *MI = MRI.getVRegDef(VReg); 440 if (TargetOpcode::G_FCONSTANT != MI->getOpcode()) 441 return nullptr; 442 return MI->getOperand(1).getFPImm(); 443 } 444 445 std::optional<DefinitionAndSourceRegister> 446 llvm::getDefSrcRegIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI) { 447 Register DefSrcReg = Reg; 448 auto *DefMI = MRI.getVRegDef(Reg); 449 auto DstTy = MRI.getType(DefMI->getOperand(0).getReg()); 450 if (!DstTy.isValid()) 451 return std::nullopt; 452 unsigned Opc = DefMI->getOpcode(); 453 while (Opc == TargetOpcode::COPY || isPreISelGenericOptimizationHint(Opc)) { 454 Register SrcReg = DefMI->getOperand(1).getReg(); 455 auto SrcTy = MRI.getType(SrcReg); 456 if (!SrcTy.isValid()) 457 break; 458 DefMI = MRI.getVRegDef(SrcReg); 459 DefSrcReg = SrcReg; 460 Opc = DefMI->getOpcode(); 461 } 462 return DefinitionAndSourceRegister{DefMI, DefSrcReg}; 463 } 464 465 MachineInstr *llvm::getDefIgnoringCopies(Register Reg, 466 const MachineRegisterInfo &MRI) { 467 std::optional<DefinitionAndSourceRegister> DefSrcReg = 468 getDefSrcRegIgnoringCopies(Reg, MRI); 469 return DefSrcReg ? DefSrcReg->MI : nullptr; 470 } 471 472 Register llvm::getSrcRegIgnoringCopies(Register Reg, 473 const MachineRegisterInfo &MRI) { 474 std::optional<DefinitionAndSourceRegister> DefSrcReg = 475 getDefSrcRegIgnoringCopies(Reg, MRI); 476 return DefSrcReg ? DefSrcReg->Reg : Register(); 477 } 478 479 MachineInstr *llvm::getOpcodeDef(unsigned Opcode, Register Reg, 480 const MachineRegisterInfo &MRI) { 481 MachineInstr *DefMI = getDefIgnoringCopies(Reg, MRI); 482 return DefMI && DefMI->getOpcode() == Opcode ? DefMI : nullptr; 483 } 484 485 APFloat llvm::getAPFloatFromSize(double Val, unsigned Size) { 486 if (Size == 32) 487 return APFloat(float(Val)); 488 if (Size == 64) 489 return APFloat(Val); 490 if (Size != 16) 491 llvm_unreachable("Unsupported FPConstant size"); 492 bool Ignored; 493 APFloat APF(Val); 494 APF.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &Ignored); 495 return APF; 496 } 497 498 std::optional<APInt> llvm::ConstantFoldBinOp(unsigned Opcode, 499 const Register Op1, 500 const Register Op2, 501 const MachineRegisterInfo &MRI) { 502 auto MaybeOp2Cst = getAnyConstantVRegValWithLookThrough(Op2, MRI, false); 503 if (!MaybeOp2Cst) 504 return std::nullopt; 505 506 auto MaybeOp1Cst = getAnyConstantVRegValWithLookThrough(Op1, MRI, false); 507 if (!MaybeOp1Cst) 508 return std::nullopt; 509 510 const APInt &C1 = MaybeOp1Cst->Value; 511 const APInt &C2 = MaybeOp2Cst->Value; 512 switch (Opcode) { 513 default: 514 break; 515 case TargetOpcode::G_ADD: 516 case TargetOpcode::G_PTR_ADD: 517 return C1 + C2; 518 case TargetOpcode::G_AND: 519 return C1 & C2; 520 case TargetOpcode::G_ASHR: 521 return C1.ashr(C2); 522 case TargetOpcode::G_LSHR: 523 return C1.lshr(C2); 524 case TargetOpcode::G_MUL: 525 return C1 * C2; 526 case TargetOpcode::G_OR: 527 return C1 | C2; 528 case TargetOpcode::G_SHL: 529 return C1 << C2; 530 case TargetOpcode::G_SUB: 531 return C1 - C2; 532 case TargetOpcode::G_XOR: 533 return C1 ^ C2; 534 case TargetOpcode::G_UDIV: 535 if (!C2.getBoolValue()) 536 break; 537 return C1.udiv(C2); 538 case TargetOpcode::G_SDIV: 539 if (!C2.getBoolValue()) 540 break; 541 return C1.sdiv(C2); 542 case TargetOpcode::G_UREM: 543 if (!C2.getBoolValue()) 544 break; 545 return C1.urem(C2); 546 case TargetOpcode::G_SREM: 547 if (!C2.getBoolValue()) 548 break; 549 return C1.srem(C2); 550 case TargetOpcode::G_SMIN: 551 return APIntOps::smin(C1, C2); 552 case TargetOpcode::G_SMAX: 553 return APIntOps::smax(C1, C2); 554 case TargetOpcode::G_UMIN: 555 return APIntOps::umin(C1, C2); 556 case TargetOpcode::G_UMAX: 557 return APIntOps::umax(C1, C2); 558 } 559 560 return std::nullopt; 561 } 562 563 std::optional<APFloat> 564 llvm::ConstantFoldFPBinOp(unsigned Opcode, const Register Op1, 565 const Register Op2, const MachineRegisterInfo &MRI) { 566 const ConstantFP *Op2Cst = getConstantFPVRegVal(Op2, MRI); 567 if (!Op2Cst) 568 return std::nullopt; 569 570 const ConstantFP *Op1Cst = getConstantFPVRegVal(Op1, MRI); 571 if (!Op1Cst) 572 return std::nullopt; 573 574 APFloat C1 = Op1Cst->getValueAPF(); 575 const APFloat &C2 = Op2Cst->getValueAPF(); 576 switch (Opcode) { 577 case TargetOpcode::G_FADD: 578 C1.add(C2, APFloat::rmNearestTiesToEven); 579 return C1; 580 case TargetOpcode::G_FSUB: 581 C1.subtract(C2, APFloat::rmNearestTiesToEven); 582 return C1; 583 case TargetOpcode::G_FMUL: 584 C1.multiply(C2, APFloat::rmNearestTiesToEven); 585 return C1; 586 case TargetOpcode::G_FDIV: 587 C1.divide(C2, APFloat::rmNearestTiesToEven); 588 return C1; 589 case TargetOpcode::G_FREM: 590 C1.mod(C2); 591 return C1; 592 case TargetOpcode::G_FCOPYSIGN: 593 C1.copySign(C2); 594 return C1; 595 case TargetOpcode::G_FMINNUM: 596 return minnum(C1, C2); 597 case TargetOpcode::G_FMAXNUM: 598 return maxnum(C1, C2); 599 case TargetOpcode::G_FMINIMUM: 600 return minimum(C1, C2); 601 case TargetOpcode::G_FMAXIMUM: 602 return maximum(C1, C2); 603 case TargetOpcode::G_FMINNUM_IEEE: 604 case TargetOpcode::G_FMAXNUM_IEEE: 605 // FIXME: These operations were unfortunately named. fminnum/fmaxnum do not 606 // follow the IEEE behavior for signaling nans and follow libm's fmin/fmax, 607 // and currently there isn't a nice wrapper in APFloat for the version with 608 // correct snan handling. 609 break; 610 default: 611 break; 612 } 613 614 return std::nullopt; 615 } 616 617 SmallVector<APInt> 618 llvm::ConstantFoldVectorBinop(unsigned Opcode, const Register Op1, 619 const Register Op2, 620 const MachineRegisterInfo &MRI) { 621 auto *SrcVec2 = getOpcodeDef<GBuildVector>(Op2, MRI); 622 if (!SrcVec2) 623 return SmallVector<APInt>(); 624 625 auto *SrcVec1 = getOpcodeDef<GBuildVector>(Op1, MRI); 626 if (!SrcVec1) 627 return SmallVector<APInt>(); 628 629 SmallVector<APInt> FoldedElements; 630 for (unsigned Idx = 0, E = SrcVec1->getNumSources(); Idx < E; ++Idx) { 631 auto MaybeCst = ConstantFoldBinOp(Opcode, SrcVec1->getSourceReg(Idx), 632 SrcVec2->getSourceReg(Idx), MRI); 633 if (!MaybeCst) 634 return SmallVector<APInt>(); 635 FoldedElements.push_back(*MaybeCst); 636 } 637 return FoldedElements; 638 } 639 640 bool llvm::isKnownNeverNaN(Register Val, const MachineRegisterInfo &MRI, 641 bool SNaN) { 642 const MachineInstr *DefMI = MRI.getVRegDef(Val); 643 if (!DefMI) 644 return false; 645 646 const TargetMachine& TM = DefMI->getMF()->getTarget(); 647 if (DefMI->getFlag(MachineInstr::FmNoNans) || TM.Options.NoNaNsFPMath) 648 return true; 649 650 // If the value is a constant, we can obviously see if it is a NaN or not. 651 if (const ConstantFP *FPVal = getConstantFPVRegVal(Val, MRI)) { 652 return !FPVal->getValueAPF().isNaN() || 653 (SNaN && !FPVal->getValueAPF().isSignaling()); 654 } 655 656 if (DefMI->getOpcode() == TargetOpcode::G_BUILD_VECTOR) { 657 for (const auto &Op : DefMI->uses()) 658 if (!isKnownNeverNaN(Op.getReg(), MRI, SNaN)) 659 return false; 660 return true; 661 } 662 663 switch (DefMI->getOpcode()) { 664 default: 665 break; 666 case TargetOpcode::G_FADD: 667 case TargetOpcode::G_FSUB: 668 case TargetOpcode::G_FMUL: 669 case TargetOpcode::G_FDIV: 670 case TargetOpcode::G_FREM: 671 case TargetOpcode::G_FSIN: 672 case TargetOpcode::G_FCOS: 673 case TargetOpcode::G_FMA: 674 case TargetOpcode::G_FMAD: 675 if (SNaN) 676 return true; 677 678 // TODO: Need isKnownNeverInfinity 679 return false; 680 case TargetOpcode::G_FMINNUM_IEEE: 681 case TargetOpcode::G_FMAXNUM_IEEE: { 682 if (SNaN) 683 return true; 684 // This can return a NaN if either operand is an sNaN, or if both operands 685 // are NaN. 686 return (isKnownNeverNaN(DefMI->getOperand(1).getReg(), MRI) && 687 isKnownNeverSNaN(DefMI->getOperand(2).getReg(), MRI)) || 688 (isKnownNeverSNaN(DefMI->getOperand(1).getReg(), MRI) && 689 isKnownNeverNaN(DefMI->getOperand(2).getReg(), MRI)); 690 } 691 case TargetOpcode::G_FMINNUM: 692 case TargetOpcode::G_FMAXNUM: { 693 // Only one needs to be known not-nan, since it will be returned if the 694 // other ends up being one. 695 return isKnownNeverNaN(DefMI->getOperand(1).getReg(), MRI, SNaN) || 696 isKnownNeverNaN(DefMI->getOperand(2).getReg(), MRI, SNaN); 697 } 698 } 699 700 if (SNaN) { 701 // FP operations quiet. For now, just handle the ones inserted during 702 // legalization. 703 switch (DefMI->getOpcode()) { 704 case TargetOpcode::G_FPEXT: 705 case TargetOpcode::G_FPTRUNC: 706 case TargetOpcode::G_FCANONICALIZE: 707 return true; 708 default: 709 return false; 710 } 711 } 712 713 return false; 714 } 715 716 Align llvm::inferAlignFromPtrInfo(MachineFunction &MF, 717 const MachinePointerInfo &MPO) { 718 auto PSV = dyn_cast_if_present<const PseudoSourceValue *>(MPO.V); 719 if (auto FSPV = dyn_cast_or_null<FixedStackPseudoSourceValue>(PSV)) { 720 MachineFrameInfo &MFI = MF.getFrameInfo(); 721 return commonAlignment(MFI.getObjectAlign(FSPV->getFrameIndex()), 722 MPO.Offset); 723 } 724 725 if (const Value *V = dyn_cast_if_present<const Value *>(MPO.V)) { 726 const Module *M = MF.getFunction().getParent(); 727 return V->getPointerAlignment(M->getDataLayout()); 728 } 729 730 return Align(1); 731 } 732 733 Register llvm::getFunctionLiveInPhysReg(MachineFunction &MF, 734 const TargetInstrInfo &TII, 735 MCRegister PhysReg, 736 const TargetRegisterClass &RC, 737 const DebugLoc &DL, LLT RegTy) { 738 MachineBasicBlock &EntryMBB = MF.front(); 739 MachineRegisterInfo &MRI = MF.getRegInfo(); 740 Register LiveIn = MRI.getLiveInVirtReg(PhysReg); 741 if (LiveIn) { 742 MachineInstr *Def = MRI.getVRegDef(LiveIn); 743 if (Def) { 744 // FIXME: Should the verifier check this is in the entry block? 745 assert(Def->getParent() == &EntryMBB && "live-in copy not in entry block"); 746 return LiveIn; 747 } 748 749 // It's possible the incoming argument register and copy was added during 750 // lowering, but later deleted due to being/becoming dead. If this happens, 751 // re-insert the copy. 752 } else { 753 // The live in register was not present, so add it. 754 LiveIn = MF.addLiveIn(PhysReg, &RC); 755 if (RegTy.isValid()) 756 MRI.setType(LiveIn, RegTy); 757 } 758 759 BuildMI(EntryMBB, EntryMBB.begin(), DL, TII.get(TargetOpcode::COPY), LiveIn) 760 .addReg(PhysReg); 761 if (!EntryMBB.isLiveIn(PhysReg)) 762 EntryMBB.addLiveIn(PhysReg); 763 return LiveIn; 764 } 765 766 std::optional<APInt> llvm::ConstantFoldExtOp(unsigned Opcode, 767 const Register Op1, uint64_t Imm, 768 const MachineRegisterInfo &MRI) { 769 auto MaybeOp1Cst = getIConstantVRegVal(Op1, MRI); 770 if (MaybeOp1Cst) { 771 switch (Opcode) { 772 default: 773 break; 774 case TargetOpcode::G_SEXT_INREG: { 775 LLT Ty = MRI.getType(Op1); 776 return MaybeOp1Cst->trunc(Imm).sext(Ty.getScalarSizeInBits()); 777 } 778 } 779 } 780 return std::nullopt; 781 } 782 783 std::optional<APFloat> 784 llvm::ConstantFoldIntToFloat(unsigned Opcode, LLT DstTy, Register Src, 785 const MachineRegisterInfo &MRI) { 786 assert(Opcode == TargetOpcode::G_SITOFP || Opcode == TargetOpcode::G_UITOFP); 787 if (auto MaybeSrcVal = getIConstantVRegVal(Src, MRI)) { 788 APFloat DstVal(getFltSemanticForLLT(DstTy)); 789 DstVal.convertFromAPInt(*MaybeSrcVal, Opcode == TargetOpcode::G_SITOFP, 790 APFloat::rmNearestTiesToEven); 791 return DstVal; 792 } 793 return std::nullopt; 794 } 795 796 std::optional<SmallVector<unsigned>> 797 llvm::ConstantFoldCTLZ(Register Src, const MachineRegisterInfo &MRI) { 798 LLT Ty = MRI.getType(Src); 799 SmallVector<unsigned> FoldedCTLZs; 800 auto tryFoldScalar = [&](Register R) -> std::optional<unsigned> { 801 auto MaybeCst = getIConstantVRegVal(R, MRI); 802 if (!MaybeCst) 803 return std::nullopt; 804 return MaybeCst->countl_zero(); 805 }; 806 if (Ty.isVector()) { 807 // Try to constant fold each element. 808 auto *BV = getOpcodeDef<GBuildVector>(Src, MRI); 809 if (!BV) 810 return std::nullopt; 811 for (unsigned SrcIdx = 0; SrcIdx < BV->getNumSources(); ++SrcIdx) { 812 if (auto MaybeFold = tryFoldScalar(BV->getSourceReg(SrcIdx))) { 813 FoldedCTLZs.emplace_back(*MaybeFold); 814 continue; 815 } 816 return std::nullopt; 817 } 818 return FoldedCTLZs; 819 } 820 if (auto MaybeCst = tryFoldScalar(Src)) { 821 FoldedCTLZs.emplace_back(*MaybeCst); 822 return FoldedCTLZs; 823 } 824 return std::nullopt; 825 } 826 827 bool llvm::isKnownToBeAPowerOfTwo(Register Reg, const MachineRegisterInfo &MRI, 828 GISelKnownBits *KB) { 829 std::optional<DefinitionAndSourceRegister> DefSrcReg = 830 getDefSrcRegIgnoringCopies(Reg, MRI); 831 if (!DefSrcReg) 832 return false; 833 834 const MachineInstr &MI = *DefSrcReg->MI; 835 const LLT Ty = MRI.getType(Reg); 836 837 switch (MI.getOpcode()) { 838 case TargetOpcode::G_CONSTANT: { 839 unsigned BitWidth = Ty.getScalarSizeInBits(); 840 const ConstantInt *CI = MI.getOperand(1).getCImm(); 841 return CI->getValue().zextOrTrunc(BitWidth).isPowerOf2(); 842 } 843 case TargetOpcode::G_SHL: { 844 // A left-shift of a constant one will have exactly one bit set because 845 // shifting the bit off the end is undefined. 846 847 // TODO: Constant splat 848 if (auto ConstLHS = getIConstantVRegVal(MI.getOperand(1).getReg(), MRI)) { 849 if (*ConstLHS == 1) 850 return true; 851 } 852 853 break; 854 } 855 case TargetOpcode::G_LSHR: { 856 if (auto ConstLHS = getIConstantVRegVal(MI.getOperand(1).getReg(), MRI)) { 857 if (ConstLHS->isSignMask()) 858 return true; 859 } 860 861 break; 862 } 863 case TargetOpcode::G_BUILD_VECTOR: { 864 // TODO: Probably should have a recursion depth guard since you could have 865 // bitcasted vector elements. 866 for (const MachineOperand &MO : llvm::drop_begin(MI.operands())) 867 if (!isKnownToBeAPowerOfTwo(MO.getReg(), MRI, KB)) 868 return false; 869 870 return true; 871 } 872 case TargetOpcode::G_BUILD_VECTOR_TRUNC: { 873 // Only handle constants since we would need to know if number of leading 874 // zeros is greater than the truncation amount. 875 const unsigned BitWidth = Ty.getScalarSizeInBits(); 876 for (const MachineOperand &MO : llvm::drop_begin(MI.operands())) { 877 auto Const = getIConstantVRegVal(MO.getReg(), MRI); 878 if (!Const || !Const->zextOrTrunc(BitWidth).isPowerOf2()) 879 return false; 880 } 881 882 return true; 883 } 884 default: 885 break; 886 } 887 888 if (!KB) 889 return false; 890 891 // More could be done here, though the above checks are enough 892 // to handle some common cases. 893 894 // Fall back to computeKnownBits to catch other known cases. 895 KnownBits Known = KB->getKnownBits(Reg); 896 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 897 } 898 899 void llvm::getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU) { 900 AU.addPreserved<StackProtector>(); 901 } 902 903 LLT llvm::getLCMType(LLT OrigTy, LLT TargetTy) { 904 const unsigned OrigSize = OrigTy.getSizeInBits(); 905 const unsigned TargetSize = TargetTy.getSizeInBits(); 906 907 if (OrigSize == TargetSize) 908 return OrigTy; 909 910 if (OrigTy.isVector()) { 911 const LLT OrigElt = OrigTy.getElementType(); 912 913 if (TargetTy.isVector()) { 914 const LLT TargetElt = TargetTy.getElementType(); 915 916 if (OrigElt.getSizeInBits() == TargetElt.getSizeInBits()) { 917 int GCDElts = 918 std::gcd(OrigTy.getNumElements(), TargetTy.getNumElements()); 919 // Prefer the original element type. 920 ElementCount Mul = OrigTy.getElementCount() * TargetTy.getNumElements(); 921 return LLT::vector(Mul.divideCoefficientBy(GCDElts), 922 OrigTy.getElementType()); 923 } 924 } else { 925 if (OrigElt.getSizeInBits() == TargetSize) 926 return OrigTy; 927 } 928 929 unsigned LCMSize = std::lcm(OrigSize, TargetSize); 930 return LLT::fixed_vector(LCMSize / OrigElt.getSizeInBits(), OrigElt); 931 } 932 933 if (TargetTy.isVector()) { 934 unsigned LCMSize = std::lcm(OrigSize, TargetSize); 935 return LLT::fixed_vector(LCMSize / OrigSize, OrigTy); 936 } 937 938 unsigned LCMSize = std::lcm(OrigSize, TargetSize); 939 940 // Preserve pointer types. 941 if (LCMSize == OrigSize) 942 return OrigTy; 943 if (LCMSize == TargetSize) 944 return TargetTy; 945 946 return LLT::scalar(LCMSize); 947 } 948 949 LLT llvm::getCoverTy(LLT OrigTy, LLT TargetTy) { 950 if (!OrigTy.isVector() || !TargetTy.isVector() || OrigTy == TargetTy || 951 (OrigTy.getScalarSizeInBits() != TargetTy.getScalarSizeInBits())) 952 return getLCMType(OrigTy, TargetTy); 953 954 unsigned OrigTyNumElts = OrigTy.getNumElements(); 955 unsigned TargetTyNumElts = TargetTy.getNumElements(); 956 if (OrigTyNumElts % TargetTyNumElts == 0) 957 return OrigTy; 958 959 unsigned NumElts = alignTo(OrigTyNumElts, TargetTyNumElts); 960 return LLT::scalarOrVector(ElementCount::getFixed(NumElts), 961 OrigTy.getElementType()); 962 } 963 964 LLT llvm::getGCDType(LLT OrigTy, LLT TargetTy) { 965 const unsigned OrigSize = OrigTy.getSizeInBits(); 966 const unsigned TargetSize = TargetTy.getSizeInBits(); 967 968 if (OrigSize == TargetSize) 969 return OrigTy; 970 971 if (OrigTy.isVector()) { 972 LLT OrigElt = OrigTy.getElementType(); 973 if (TargetTy.isVector()) { 974 LLT TargetElt = TargetTy.getElementType(); 975 if (OrigElt.getSizeInBits() == TargetElt.getSizeInBits()) { 976 int GCD = std::gcd(OrigTy.getNumElements(), TargetTy.getNumElements()); 977 return LLT::scalarOrVector(ElementCount::getFixed(GCD), OrigElt); 978 } 979 } else { 980 // If the source is a vector of pointers, return a pointer element. 981 if (OrigElt.getSizeInBits() == TargetSize) 982 return OrigElt; 983 } 984 985 unsigned GCD = std::gcd(OrigSize, TargetSize); 986 if (GCD == OrigElt.getSizeInBits()) 987 return OrigElt; 988 989 // If we can't produce the original element type, we have to use a smaller 990 // scalar. 991 if (GCD < OrigElt.getSizeInBits()) 992 return LLT::scalar(GCD); 993 return LLT::fixed_vector(GCD / OrigElt.getSizeInBits(), OrigElt); 994 } 995 996 if (TargetTy.isVector()) { 997 // Try to preserve the original element type. 998 LLT TargetElt = TargetTy.getElementType(); 999 if (TargetElt.getSizeInBits() == OrigSize) 1000 return OrigTy; 1001 } 1002 1003 unsigned GCD = std::gcd(OrigSize, TargetSize); 1004 return LLT::scalar(GCD); 1005 } 1006 1007 std::optional<int> llvm::getSplatIndex(MachineInstr &MI) { 1008 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR && 1009 "Only G_SHUFFLE_VECTOR can have a splat index!"); 1010 ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask(); 1011 auto FirstDefinedIdx = find_if(Mask, [](int Elt) { return Elt >= 0; }); 1012 1013 // If all elements are undefined, this shuffle can be considered a splat. 1014 // Return 0 for better potential for callers to simplify. 1015 if (FirstDefinedIdx == Mask.end()) 1016 return 0; 1017 1018 // Make sure all remaining elements are either undef or the same 1019 // as the first non-undef value. 1020 int SplatValue = *FirstDefinedIdx; 1021 if (any_of(make_range(std::next(FirstDefinedIdx), Mask.end()), 1022 [&SplatValue](int Elt) { return Elt >= 0 && Elt != SplatValue; })) 1023 return std::nullopt; 1024 1025 return SplatValue; 1026 } 1027 1028 static bool isBuildVectorOp(unsigned Opcode) { 1029 return Opcode == TargetOpcode::G_BUILD_VECTOR || 1030 Opcode == TargetOpcode::G_BUILD_VECTOR_TRUNC; 1031 } 1032 1033 namespace { 1034 1035 std::optional<ValueAndVReg> getAnyConstantSplat(Register VReg, 1036 const MachineRegisterInfo &MRI, 1037 bool AllowUndef) { 1038 MachineInstr *MI = getDefIgnoringCopies(VReg, MRI); 1039 if (!MI) 1040 return std::nullopt; 1041 1042 bool isConcatVectorsOp = MI->getOpcode() == TargetOpcode::G_CONCAT_VECTORS; 1043 if (!isBuildVectorOp(MI->getOpcode()) && !isConcatVectorsOp) 1044 return std::nullopt; 1045 1046 std::optional<ValueAndVReg> SplatValAndReg; 1047 for (MachineOperand &Op : MI->uses()) { 1048 Register Element = Op.getReg(); 1049 // If we have a G_CONCAT_VECTOR, we recursively look into the 1050 // vectors that we're concatenating to see if they're splats. 1051 auto ElementValAndReg = 1052 isConcatVectorsOp 1053 ? getAnyConstantSplat(Element, MRI, AllowUndef) 1054 : getAnyConstantVRegValWithLookThrough(Element, MRI, true, true); 1055 1056 // If AllowUndef, treat undef as value that will result in a constant splat. 1057 if (!ElementValAndReg) { 1058 if (AllowUndef && isa<GImplicitDef>(MRI.getVRegDef(Element))) 1059 continue; 1060 return std::nullopt; 1061 } 1062 1063 // Record splat value 1064 if (!SplatValAndReg) 1065 SplatValAndReg = ElementValAndReg; 1066 1067 // Different constant than the one already recorded, not a constant splat. 1068 if (SplatValAndReg->Value != ElementValAndReg->Value) 1069 return std::nullopt; 1070 } 1071 1072 return SplatValAndReg; 1073 } 1074 1075 } // end anonymous namespace 1076 1077 bool llvm::isBuildVectorConstantSplat(const Register Reg, 1078 const MachineRegisterInfo &MRI, 1079 int64_t SplatValue, bool AllowUndef) { 1080 if (auto SplatValAndReg = getAnyConstantSplat(Reg, MRI, AllowUndef)) 1081 return mi_match(SplatValAndReg->VReg, MRI, m_SpecificICst(SplatValue)); 1082 return false; 1083 } 1084 1085 bool llvm::isBuildVectorConstantSplat(const MachineInstr &MI, 1086 const MachineRegisterInfo &MRI, 1087 int64_t SplatValue, bool AllowUndef) { 1088 return isBuildVectorConstantSplat(MI.getOperand(0).getReg(), MRI, SplatValue, 1089 AllowUndef); 1090 } 1091 1092 std::optional<APInt> 1093 llvm::getIConstantSplatVal(const Register Reg, const MachineRegisterInfo &MRI) { 1094 if (auto SplatValAndReg = 1095 getAnyConstantSplat(Reg, MRI, /* AllowUndef */ false)) { 1096 std::optional<ValueAndVReg> ValAndVReg = 1097 getIConstantVRegValWithLookThrough(SplatValAndReg->VReg, MRI); 1098 return ValAndVReg->Value; 1099 } 1100 1101 return std::nullopt; 1102 } 1103 1104 std::optional<APInt> 1105 llvm::getIConstantSplatVal(const MachineInstr &MI, 1106 const MachineRegisterInfo &MRI) { 1107 return getIConstantSplatVal(MI.getOperand(0).getReg(), MRI); 1108 } 1109 1110 std::optional<int64_t> 1111 llvm::getIConstantSplatSExtVal(const Register Reg, 1112 const MachineRegisterInfo &MRI) { 1113 if (auto SplatValAndReg = 1114 getAnyConstantSplat(Reg, MRI, /* AllowUndef */ false)) 1115 return getIConstantVRegSExtVal(SplatValAndReg->VReg, MRI); 1116 return std::nullopt; 1117 } 1118 1119 std::optional<int64_t> 1120 llvm::getIConstantSplatSExtVal(const MachineInstr &MI, 1121 const MachineRegisterInfo &MRI) { 1122 return getIConstantSplatSExtVal(MI.getOperand(0).getReg(), MRI); 1123 } 1124 1125 std::optional<FPValueAndVReg> 1126 llvm::getFConstantSplat(Register VReg, const MachineRegisterInfo &MRI, 1127 bool AllowUndef) { 1128 if (auto SplatValAndReg = getAnyConstantSplat(VReg, MRI, AllowUndef)) 1129 return getFConstantVRegValWithLookThrough(SplatValAndReg->VReg, MRI); 1130 return std::nullopt; 1131 } 1132 1133 bool llvm::isBuildVectorAllZeros(const MachineInstr &MI, 1134 const MachineRegisterInfo &MRI, 1135 bool AllowUndef) { 1136 return isBuildVectorConstantSplat(MI, MRI, 0, AllowUndef); 1137 } 1138 1139 bool llvm::isBuildVectorAllOnes(const MachineInstr &MI, 1140 const MachineRegisterInfo &MRI, 1141 bool AllowUndef) { 1142 return isBuildVectorConstantSplat(MI, MRI, -1, AllowUndef); 1143 } 1144 1145 std::optional<RegOrConstant> 1146 llvm::getVectorSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI) { 1147 unsigned Opc = MI.getOpcode(); 1148 if (!isBuildVectorOp(Opc)) 1149 return std::nullopt; 1150 if (auto Splat = getIConstantSplatSExtVal(MI, MRI)) 1151 return RegOrConstant(*Splat); 1152 auto Reg = MI.getOperand(1).getReg(); 1153 if (any_of(make_range(MI.operands_begin() + 2, MI.operands_end()), 1154 [&Reg](const MachineOperand &Op) { return Op.getReg() != Reg; })) 1155 return std::nullopt; 1156 return RegOrConstant(Reg); 1157 } 1158 1159 static bool isConstantScalar(const MachineInstr &MI, 1160 const MachineRegisterInfo &MRI, 1161 bool AllowFP = true, 1162 bool AllowOpaqueConstants = true) { 1163 switch (MI.getOpcode()) { 1164 case TargetOpcode::G_CONSTANT: 1165 case TargetOpcode::G_IMPLICIT_DEF: 1166 return true; 1167 case TargetOpcode::G_FCONSTANT: 1168 return AllowFP; 1169 case TargetOpcode::G_GLOBAL_VALUE: 1170 case TargetOpcode::G_FRAME_INDEX: 1171 case TargetOpcode::G_BLOCK_ADDR: 1172 case TargetOpcode::G_JUMP_TABLE: 1173 return AllowOpaqueConstants; 1174 default: 1175 return false; 1176 } 1177 } 1178 1179 bool llvm::isConstantOrConstantVector(MachineInstr &MI, 1180 const MachineRegisterInfo &MRI) { 1181 Register Def = MI.getOperand(0).getReg(); 1182 if (auto C = getIConstantVRegValWithLookThrough(Def, MRI)) 1183 return true; 1184 GBuildVector *BV = dyn_cast<GBuildVector>(&MI); 1185 if (!BV) 1186 return false; 1187 for (unsigned SrcIdx = 0; SrcIdx < BV->getNumSources(); ++SrcIdx) { 1188 if (getIConstantVRegValWithLookThrough(BV->getSourceReg(SrcIdx), MRI) || 1189 getOpcodeDef<GImplicitDef>(BV->getSourceReg(SrcIdx), MRI)) 1190 continue; 1191 return false; 1192 } 1193 return true; 1194 } 1195 1196 bool llvm::isConstantOrConstantVector(const MachineInstr &MI, 1197 const MachineRegisterInfo &MRI, 1198 bool AllowFP, bool AllowOpaqueConstants) { 1199 if (isConstantScalar(MI, MRI, AllowFP, AllowOpaqueConstants)) 1200 return true; 1201 1202 if (!isBuildVectorOp(MI.getOpcode())) 1203 return false; 1204 1205 const unsigned NumOps = MI.getNumOperands(); 1206 for (unsigned I = 1; I != NumOps; ++I) { 1207 const MachineInstr *ElementDef = MRI.getVRegDef(MI.getOperand(I).getReg()); 1208 if (!isConstantScalar(*ElementDef, MRI, AllowFP, AllowOpaqueConstants)) 1209 return false; 1210 } 1211 1212 return true; 1213 } 1214 1215 std::optional<APInt> 1216 llvm::isConstantOrConstantSplatVector(MachineInstr &MI, 1217 const MachineRegisterInfo &MRI) { 1218 Register Def = MI.getOperand(0).getReg(); 1219 if (auto C = getIConstantVRegValWithLookThrough(Def, MRI)) 1220 return C->Value; 1221 auto MaybeCst = getIConstantSplatSExtVal(MI, MRI); 1222 if (!MaybeCst) 1223 return std::nullopt; 1224 const unsigned ScalarSize = MRI.getType(Def).getScalarSizeInBits(); 1225 return APInt(ScalarSize, *MaybeCst, true); 1226 } 1227 1228 bool llvm::isNullOrNullSplat(const MachineInstr &MI, 1229 const MachineRegisterInfo &MRI, bool AllowUndefs) { 1230 switch (MI.getOpcode()) { 1231 case TargetOpcode::G_IMPLICIT_DEF: 1232 return AllowUndefs; 1233 case TargetOpcode::G_CONSTANT: 1234 return MI.getOperand(1).getCImm()->isNullValue(); 1235 case TargetOpcode::G_FCONSTANT: { 1236 const ConstantFP *FPImm = MI.getOperand(1).getFPImm(); 1237 return FPImm->isZero() && !FPImm->isNegative(); 1238 } 1239 default: 1240 if (!AllowUndefs) // TODO: isBuildVectorAllZeros assumes undef is OK already 1241 return false; 1242 return isBuildVectorAllZeros(MI, MRI); 1243 } 1244 } 1245 1246 bool llvm::isAllOnesOrAllOnesSplat(const MachineInstr &MI, 1247 const MachineRegisterInfo &MRI, 1248 bool AllowUndefs) { 1249 switch (MI.getOpcode()) { 1250 case TargetOpcode::G_IMPLICIT_DEF: 1251 return AllowUndefs; 1252 case TargetOpcode::G_CONSTANT: 1253 return MI.getOperand(1).getCImm()->isAllOnesValue(); 1254 default: 1255 if (!AllowUndefs) // TODO: isBuildVectorAllOnes assumes undef is OK already 1256 return false; 1257 return isBuildVectorAllOnes(MI, MRI); 1258 } 1259 } 1260 1261 bool llvm::matchUnaryPredicate( 1262 const MachineRegisterInfo &MRI, Register Reg, 1263 std::function<bool(const Constant *ConstVal)> Match, bool AllowUndefs) { 1264 1265 const MachineInstr *Def = getDefIgnoringCopies(Reg, MRI); 1266 if (AllowUndefs && Def->getOpcode() == TargetOpcode::G_IMPLICIT_DEF) 1267 return Match(nullptr); 1268 1269 // TODO: Also handle fconstant 1270 if (Def->getOpcode() == TargetOpcode::G_CONSTANT) 1271 return Match(Def->getOperand(1).getCImm()); 1272 1273 if (Def->getOpcode() != TargetOpcode::G_BUILD_VECTOR) 1274 return false; 1275 1276 for (unsigned I = 1, E = Def->getNumOperands(); I != E; ++I) { 1277 Register SrcElt = Def->getOperand(I).getReg(); 1278 const MachineInstr *SrcDef = getDefIgnoringCopies(SrcElt, MRI); 1279 if (AllowUndefs && SrcDef->getOpcode() == TargetOpcode::G_IMPLICIT_DEF) { 1280 if (!Match(nullptr)) 1281 return false; 1282 continue; 1283 } 1284 1285 if (SrcDef->getOpcode() != TargetOpcode::G_CONSTANT || 1286 !Match(SrcDef->getOperand(1).getCImm())) 1287 return false; 1288 } 1289 1290 return true; 1291 } 1292 1293 bool llvm::isConstTrueVal(const TargetLowering &TLI, int64_t Val, bool IsVector, 1294 bool IsFP) { 1295 switch (TLI.getBooleanContents(IsVector, IsFP)) { 1296 case TargetLowering::UndefinedBooleanContent: 1297 return Val & 0x1; 1298 case TargetLowering::ZeroOrOneBooleanContent: 1299 return Val == 1; 1300 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1301 return Val == -1; 1302 } 1303 llvm_unreachable("Invalid boolean contents"); 1304 } 1305 1306 bool llvm::isConstFalseVal(const TargetLowering &TLI, int64_t Val, 1307 bool IsVector, bool IsFP) { 1308 switch (TLI.getBooleanContents(IsVector, IsFP)) { 1309 case TargetLowering::UndefinedBooleanContent: 1310 return ~Val & 0x1; 1311 case TargetLowering::ZeroOrOneBooleanContent: 1312 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1313 return Val == 0; 1314 } 1315 llvm_unreachable("Invalid boolean contents"); 1316 } 1317 1318 int64_t llvm::getICmpTrueVal(const TargetLowering &TLI, bool IsVector, 1319 bool IsFP) { 1320 switch (TLI.getBooleanContents(IsVector, IsFP)) { 1321 case TargetLowering::UndefinedBooleanContent: 1322 case TargetLowering::ZeroOrOneBooleanContent: 1323 return 1; 1324 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1325 return -1; 1326 } 1327 llvm_unreachable("Invalid boolean contents"); 1328 } 1329 1330 bool llvm::shouldOptForSize(const MachineBasicBlock &MBB, 1331 ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) { 1332 const auto &F = MBB.getParent()->getFunction(); 1333 return F.hasOptSize() || F.hasMinSize() || 1334 llvm::shouldOptimizeForSize(MBB.getBasicBlock(), PSI, BFI); 1335 } 1336 1337 void llvm::saveUsesAndErase(MachineInstr &MI, MachineRegisterInfo &MRI, 1338 LostDebugLocObserver *LocObserver, 1339 SmallInstListTy &DeadInstChain) { 1340 for (MachineOperand &Op : MI.uses()) { 1341 if (Op.isReg() && Op.getReg().isVirtual()) 1342 DeadInstChain.insert(MRI.getVRegDef(Op.getReg())); 1343 } 1344 LLVM_DEBUG(dbgs() << MI << "Is dead; erasing.\n"); 1345 DeadInstChain.remove(&MI); 1346 MI.eraseFromParent(); 1347 if (LocObserver) 1348 LocObserver->checkpoint(false); 1349 } 1350 1351 void llvm::eraseInstrs(ArrayRef<MachineInstr *> DeadInstrs, 1352 MachineRegisterInfo &MRI, 1353 LostDebugLocObserver *LocObserver) { 1354 SmallInstListTy DeadInstChain; 1355 for (MachineInstr *MI : DeadInstrs) 1356 saveUsesAndErase(*MI, MRI, LocObserver, DeadInstChain); 1357 1358 while (!DeadInstChain.empty()) { 1359 MachineInstr *Inst = DeadInstChain.pop_back_val(); 1360 if (!isTriviallyDead(*Inst, MRI)) 1361 continue; 1362 saveUsesAndErase(*Inst, MRI, LocObserver, DeadInstChain); 1363 } 1364 } 1365 1366 void llvm::eraseInstr(MachineInstr &MI, MachineRegisterInfo &MRI, 1367 LostDebugLocObserver *LocObserver) { 1368 return eraseInstrs({&MI}, MRI, LocObserver); 1369 } 1370 1371 void llvm::salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI) { 1372 for (auto &Def : MI.defs()) { 1373 assert(Def.isReg() && "Must be a reg"); 1374 1375 SmallVector<MachineOperand *, 16> DbgUsers; 1376 for (auto &MOUse : MRI.use_operands(Def.getReg())) { 1377 MachineInstr *DbgValue = MOUse.getParent(); 1378 // Ignore partially formed DBG_VALUEs. 1379 if (DbgValue->isNonListDebugValue() && DbgValue->getNumOperands() == 4) { 1380 DbgUsers.push_back(&MOUse); 1381 } 1382 } 1383 1384 if (!DbgUsers.empty()) { 1385 salvageDebugInfoForDbgValue(MRI, MI, DbgUsers); 1386 } 1387 } 1388 } 1389