Path: blob/main/contrib/llvm-project/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp
35266 views
//===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file defines a pattern matching instruction selector for PowerPC,9// converting from a legalized dag to a PPC dag.10//11//===----------------------------------------------------------------------===//1213#include "MCTargetDesc/PPCMCTargetDesc.h"14#include "MCTargetDesc/PPCPredicates.h"15#include "PPC.h"16#include "PPCISelLowering.h"17#include "PPCMachineFunctionInfo.h"18#include "PPCSubtarget.h"19#include "PPCTargetMachine.h"20#include "llvm/ADT/APInt.h"21#include "llvm/ADT/APSInt.h"22#include "llvm/ADT/DenseMap.h"23#include "llvm/ADT/STLExtras.h"24#include "llvm/ADT/SmallPtrSet.h"25#include "llvm/ADT/SmallVector.h"26#include "llvm/ADT/Statistic.h"27#include "llvm/Analysis/BranchProbabilityInfo.h"28#include "llvm/CodeGen/FunctionLoweringInfo.h"29#include "llvm/CodeGen/ISDOpcodes.h"30#include "llvm/CodeGen/MachineBasicBlock.h"31#include "llvm/CodeGen/MachineFrameInfo.h"32#include "llvm/CodeGen/MachineFunction.h"33#include "llvm/CodeGen/MachineInstrBuilder.h"34#include "llvm/CodeGen/MachineRegisterInfo.h"35#include "llvm/CodeGen/SelectionDAG.h"36#include "llvm/CodeGen/SelectionDAGISel.h"37#include "llvm/CodeGen/SelectionDAGNodes.h"38#include "llvm/CodeGen/TargetInstrInfo.h"39#include "llvm/CodeGen/TargetRegisterInfo.h"40#include "llvm/CodeGen/ValueTypes.h"41#include "llvm/CodeGenTypes/MachineValueType.h"42#include "llvm/IR/BasicBlock.h"43#include "llvm/IR/DebugLoc.h"44#include "llvm/IR/Function.h"45#include "llvm/IR/GlobalValue.h"46#include "llvm/IR/InlineAsm.h"47#include "llvm/IR/InstrTypes.h"48#include "llvm/IR/IntrinsicsPowerPC.h"49#include "llvm/IR/Module.h"50#include "llvm/Support/Casting.h"51#include "llvm/Support/CodeGen.h"52#include "llvm/Support/CommandLine.h"53#include "llvm/Support/Compiler.h"54#include "llvm/Support/Debug.h"55#include "llvm/Support/ErrorHandling.h"56#include "llvm/Support/KnownBits.h"57#include "llvm/Support/MathExtras.h"58#include "llvm/Support/raw_ostream.h"59#include <algorithm>60#include <cassert>61#include <cstdint>62#include <iterator>63#include <limits>64#include <memory>65#include <new>66#include <tuple>67#include <utility>6869using namespace llvm;7071#define DEBUG_TYPE "ppc-isel"72#define PASS_NAME "PowerPC DAG->DAG Pattern Instruction Selection"7374STATISTIC(NumSextSetcc,75"Number of (sext(setcc)) nodes expanded into GPR sequence.");76STATISTIC(NumZextSetcc,77"Number of (zext(setcc)) nodes expanded into GPR sequence.");78STATISTIC(SignExtensionsAdded,79"Number of sign extensions for compare inputs added.");80STATISTIC(ZeroExtensionsAdded,81"Number of zero extensions for compare inputs added.");82STATISTIC(NumLogicOpsOnComparison,83"Number of logical ops on i1 values calculated in GPR.");84STATISTIC(OmittedForNonExtendUses,85"Number of compares not eliminated as they have non-extending uses.");86STATISTIC(NumP9Setb,87"Number of compares lowered to setb.");8889// FIXME: Remove this once the bug has been fixed!90cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug",91cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden);9293static cl::opt<bool>94UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true),95cl::desc("use aggressive ppc isel for bit permutations"),96cl::Hidden);97static cl::opt<bool> BPermRewriterNoMasking(98"ppc-bit-perm-rewriter-stress-rotates",99cl::desc("stress rotate selection in aggressive ppc isel for "100"bit permutations"),101cl::Hidden);102103static cl::opt<bool> EnableBranchHint(104"ppc-use-branch-hint", cl::init(true),105cl::desc("Enable static hinting of branches on ppc"),106cl::Hidden);107108static cl::opt<bool> EnableTLSOpt(109"ppc-tls-opt", cl::init(true),110cl::desc("Enable tls optimization peephole"),111cl::Hidden);112113enum ICmpInGPRType { ICGPR_All, ICGPR_None, ICGPR_I32, ICGPR_I64,114ICGPR_NonExtIn, ICGPR_Zext, ICGPR_Sext, ICGPR_ZextI32,115ICGPR_SextI32, ICGPR_ZextI64, ICGPR_SextI64 };116117static cl::opt<ICmpInGPRType> CmpInGPR(118"ppc-gpr-icmps", cl::Hidden, cl::init(ICGPR_All),119cl::desc("Specify the types of comparisons to emit GPR-only code for."),120cl::values(clEnumValN(ICGPR_None, "none", "Do not modify integer comparisons."),121clEnumValN(ICGPR_All, "all", "All possible int comparisons in GPRs."),122clEnumValN(ICGPR_I32, "i32", "Only i32 comparisons in GPRs."),123clEnumValN(ICGPR_I64, "i64", "Only i64 comparisons in GPRs."),124clEnumValN(ICGPR_NonExtIn, "nonextin",125"Only comparisons where inputs don't need [sz]ext."),126clEnumValN(ICGPR_Zext, "zext", "Only comparisons with zext result."),127clEnumValN(ICGPR_ZextI32, "zexti32",128"Only i32 comparisons with zext result."),129clEnumValN(ICGPR_ZextI64, "zexti64",130"Only i64 comparisons with zext result."),131clEnumValN(ICGPR_Sext, "sext", "Only comparisons with sext result."),132clEnumValN(ICGPR_SextI32, "sexti32",133"Only i32 comparisons with sext result."),134clEnumValN(ICGPR_SextI64, "sexti64",135"Only i64 comparisons with sext result.")));136namespace {137138//===--------------------------------------------------------------------===//139/// PPCDAGToDAGISel - PPC specific code to select PPC machine140/// instructions for SelectionDAG operations.141///142class PPCDAGToDAGISel : public SelectionDAGISel {143const PPCTargetMachine &TM;144const PPCSubtarget *Subtarget = nullptr;145const PPCTargetLowering *PPCLowering = nullptr;146unsigned GlobalBaseReg = 0;147148public:149PPCDAGToDAGISel() = delete;150151explicit PPCDAGToDAGISel(PPCTargetMachine &tm, CodeGenOptLevel OptLevel)152: SelectionDAGISel(tm, OptLevel), TM(tm) {}153154bool runOnMachineFunction(MachineFunction &MF) override {155// Make sure we re-emit a set of the global base reg if necessary156GlobalBaseReg = 0;157Subtarget = &MF.getSubtarget<PPCSubtarget>();158PPCLowering = Subtarget->getTargetLowering();159if (Subtarget->hasROPProtect()) {160// Create a place on the stack for the ROP Protection Hash.161// The ROP Protection Hash will always be 8 bytes and aligned to 8162// bytes.163MachineFrameInfo &MFI = MF.getFrameInfo();164PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();165const int Result = MFI.CreateStackObject(8, Align(8), false);166FI->setROPProtectionHashSaveIndex(Result);167}168SelectionDAGISel::runOnMachineFunction(MF);169170return true;171}172173void PreprocessISelDAG() override;174void PostprocessISelDAG() override;175176/// getI16Imm - Return a target constant with the specified value, of type177/// i16.178inline SDValue getI16Imm(unsigned Imm, const SDLoc &dl) {179return CurDAG->getTargetConstant(Imm, dl, MVT::i16);180}181182/// getI32Imm - Return a target constant with the specified value, of type183/// i32.184inline SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {185return CurDAG->getTargetConstant(Imm, dl, MVT::i32);186}187188/// getI64Imm - Return a target constant with the specified value, of type189/// i64.190inline SDValue getI64Imm(uint64_t Imm, const SDLoc &dl) {191return CurDAG->getTargetConstant(Imm, dl, MVT::i64);192}193194/// getSmallIPtrImm - Return a target constant of pointer type.195inline SDValue getSmallIPtrImm(uint64_t Imm, const SDLoc &dl) {196return CurDAG->getTargetConstant(197Imm, dl, PPCLowering->getPointerTy(CurDAG->getDataLayout()));198}199200/// isRotateAndMask - Returns true if Mask and Shift can be folded into a201/// rotate and mask opcode and mask operation.202static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,203unsigned &SH, unsigned &MB, unsigned &ME);204205/// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC206/// base register. Return the virtual register that holds this value.207SDNode *getGlobalBaseReg();208209void selectFrameIndex(SDNode *SN, SDNode *N, uint64_t Offset = 0);210211// Select - Convert the specified operand from a target-independent to a212// target-specific node if it hasn't already been changed.213void Select(SDNode *N) override;214215bool tryBitfieldInsert(SDNode *N);216bool tryBitPermutation(SDNode *N);217bool tryIntCompareInGPR(SDNode *N);218219// tryTLSXFormLoad - Convert an ISD::LOAD fed by a PPCISD::ADD_TLS into220// an X-Form load instruction with the offset being a relocation coming from221// the PPCISD::ADD_TLS.222bool tryTLSXFormLoad(LoadSDNode *N);223// tryTLSXFormStore - Convert an ISD::STORE fed by a PPCISD::ADD_TLS into224// an X-Form store instruction with the offset being a relocation coming from225// the PPCISD::ADD_TLS.226bool tryTLSXFormStore(StoreSDNode *N);227/// SelectCC - Select a comparison of the specified values with the228/// specified condition code, returning the CR# of the expression.229SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,230const SDLoc &dl, SDValue Chain = SDValue());231232/// SelectAddrImmOffs - Return true if the operand is valid for a preinc233/// immediate field. Note that the operand at this point is already the234/// result of a prior SelectAddressRegImm call.235bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {236if (N.getOpcode() == ISD::TargetConstant ||237N.getOpcode() == ISD::TargetGlobalAddress) {238Out = N;239return true;240}241242return false;243}244245/// SelectDSForm - Returns true if address N can be represented by the246/// addressing mode of DSForm instructions (a base register, plus a signed247/// 16-bit displacement that is a multiple of 4.248bool SelectDSForm(SDNode *Parent, SDValue N, SDValue &Disp, SDValue &Base) {249return PPCLowering->SelectOptimalAddrMode(Parent, N, Disp, Base, *CurDAG,250Align(4)) == PPC::AM_DSForm;251}252253/// SelectDQForm - Returns true if address N can be represented by the254/// addressing mode of DQForm instructions (a base register, plus a signed255/// 16-bit displacement that is a multiple of 16.256bool SelectDQForm(SDNode *Parent, SDValue N, SDValue &Disp, SDValue &Base) {257return PPCLowering->SelectOptimalAddrMode(Parent, N, Disp, Base, *CurDAG,258Align(16)) == PPC::AM_DQForm;259}260261/// SelectDForm - Returns true if address N can be represented by262/// the addressing mode of DForm instructions (a base register, plus a263/// signed 16-bit immediate.264bool SelectDForm(SDNode *Parent, SDValue N, SDValue &Disp, SDValue &Base) {265return PPCLowering->SelectOptimalAddrMode(Parent, N, Disp, Base, *CurDAG,266std::nullopt) == PPC::AM_DForm;267}268269/// SelectPCRelForm - Returns true if address N can be represented by270/// PC-Relative addressing mode.271bool SelectPCRelForm(SDNode *Parent, SDValue N, SDValue &Disp,272SDValue &Base) {273return PPCLowering->SelectOptimalAddrMode(Parent, N, Disp, Base, *CurDAG,274std::nullopt) == PPC::AM_PCRel;275}276277/// SelectPDForm - Returns true if address N can be represented by Prefixed278/// DForm addressing mode (a base register, plus a signed 34-bit immediate.279bool SelectPDForm(SDNode *Parent, SDValue N, SDValue &Disp, SDValue &Base) {280return PPCLowering->SelectOptimalAddrMode(Parent, N, Disp, Base, *CurDAG,281std::nullopt) ==282PPC::AM_PrefixDForm;283}284285/// SelectXForm - Returns true if address N can be represented by the286/// addressing mode of XForm instructions (an indexed [r+r] operation).287bool SelectXForm(SDNode *Parent, SDValue N, SDValue &Disp, SDValue &Base) {288return PPCLowering->SelectOptimalAddrMode(Parent, N, Disp, Base, *CurDAG,289std::nullopt) == PPC::AM_XForm;290}291292/// SelectForceXForm - Given the specified address, force it to be293/// represented as an indexed [r+r] operation (an XForm instruction).294bool SelectForceXForm(SDNode *Parent, SDValue N, SDValue &Disp,295SDValue &Base) {296return PPCLowering->SelectForceXFormMode(N, Disp, Base, *CurDAG) ==297PPC::AM_XForm;298}299300/// SelectAddrIdx - Given the specified address, check to see if it can be301/// represented as an indexed [r+r] operation.302/// This is for xform instructions whose associated displacement form is D.303/// The last parameter \p 0 means associated D form has no requirment for 16304/// bit signed displacement.305/// Returns false if it can be represented by [r+imm], which are preferred.306bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {307return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG,308std::nullopt);309}310311/// SelectAddrIdx4 - Given the specified address, check to see if it can be312/// represented as an indexed [r+r] operation.313/// This is for xform instructions whose associated displacement form is DS.314/// The last parameter \p 4 means associated DS form 16 bit signed315/// displacement must be a multiple of 4.316/// Returns false if it can be represented by [r+imm], which are preferred.317bool SelectAddrIdxX4(SDValue N, SDValue &Base, SDValue &Index) {318return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG,319Align(4));320}321322/// SelectAddrIdx16 - Given the specified address, check to see if it can be323/// represented as an indexed [r+r] operation.324/// This is for xform instructions whose associated displacement form is DQ.325/// The last parameter \p 16 means associated DQ form 16 bit signed326/// displacement must be a multiple of 16.327/// Returns false if it can be represented by [r+imm], which are preferred.328bool SelectAddrIdxX16(SDValue N, SDValue &Base, SDValue &Index) {329return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG,330Align(16));331}332333/// SelectAddrIdxOnly - Given the specified address, force it to be334/// represented as an indexed [r+r] operation.335bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {336return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG);337}338339/// SelectAddrImm - Returns true if the address N can be represented by340/// a base register plus a signed 16-bit displacement [r+imm].341/// The last parameter \p 0 means D form has no requirment for 16 bit signed342/// displacement.343bool SelectAddrImm(SDValue N, SDValue &Disp,344SDValue &Base) {345return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG,346std::nullopt);347}348349/// SelectAddrImmX4 - Returns true if the address N can be represented by350/// a base register plus a signed 16-bit displacement that is a multiple of351/// 4 (last parameter). Suitable for use by STD and friends.352bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {353return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, Align(4));354}355356/// SelectAddrImmX16 - Returns true if the address N can be represented by357/// a base register plus a signed 16-bit displacement that is a multiple of358/// 16(last parameter). Suitable for use by STXV and friends.359bool SelectAddrImmX16(SDValue N, SDValue &Disp, SDValue &Base) {360return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG,361Align(16));362}363364/// SelectAddrImmX34 - Returns true if the address N can be represented by365/// a base register plus a signed 34-bit displacement. Suitable for use by366/// PSTXVP and friends.367bool SelectAddrImmX34(SDValue N, SDValue &Disp, SDValue &Base) {368return PPCLowering->SelectAddressRegImm34(N, Disp, Base, *CurDAG);369}370371// Select an address into a single register.372bool SelectAddr(SDValue N, SDValue &Base) {373Base = N;374return true;375}376377bool SelectAddrPCRel(SDValue N, SDValue &Base) {378return PPCLowering->SelectAddressPCRel(N, Base);379}380381/// SelectInlineAsmMemoryOperand - Implement addressing mode selection for382/// inline asm expressions. It is always correct to compute the value into383/// a register. The case of adding a (possibly relocatable) constant to a384/// register can be improved, but it is wrong to substitute Reg+Reg for385/// Reg in an asm, because the load or store opcode would have to change.386bool SelectInlineAsmMemoryOperand(const SDValue &Op,387InlineAsm::ConstraintCode ConstraintID,388std::vector<SDValue> &OutOps) override {389switch(ConstraintID) {390default:391errs() << "ConstraintID: "392<< InlineAsm::getMemConstraintName(ConstraintID) << "\n";393llvm_unreachable("Unexpected asm memory constraint");394case InlineAsm::ConstraintCode::es:395case InlineAsm::ConstraintCode::m:396case InlineAsm::ConstraintCode::o:397case InlineAsm::ConstraintCode::Q:398case InlineAsm::ConstraintCode::Z:399case InlineAsm::ConstraintCode::Zy:400// We need to make sure that this one operand does not end up in r0401// (because we might end up lowering this as 0(%op)).402const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();403const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1);404SDLoc dl(Op);405SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);406SDValue NewOp =407SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,408dl, Op.getValueType(),409Op, RC), 0);410411OutOps.push_back(NewOp);412return false;413}414return true;415}416417// Include the pieces autogenerated from the target description.418#include "PPCGenDAGISel.inc"419420private:421bool trySETCC(SDNode *N);422bool tryFoldSWTestBRCC(SDNode *N);423bool trySelectLoopCountIntrinsic(SDNode *N);424bool tryAsSingleRLDICL(SDNode *N);425bool tryAsSingleRLDCL(SDNode *N);426bool tryAsSingleRLDICR(SDNode *N);427bool tryAsSingleRLWINM(SDNode *N);428bool tryAsSingleRLWINM8(SDNode *N);429bool tryAsSingleRLWIMI(SDNode *N);430bool tryAsPairOfRLDICL(SDNode *N);431bool tryAsSingleRLDIMI(SDNode *N);432433void PeepholePPC64();434void PeepholePPC64ZExt();435void PeepholeCROps();436437SDValue combineToCMPB(SDNode *N);438void foldBoolExts(SDValue &Res, SDNode *&N);439440bool AllUsersSelectZero(SDNode *N);441void SwapAllSelectUsers(SDNode *N);442443bool isOffsetMultipleOf(SDNode *N, unsigned Val) const;444void transferMemOperands(SDNode *N, SDNode *Result);445};446447class PPCDAGToDAGISelLegacy : public SelectionDAGISelLegacy {448public:449static char ID;450explicit PPCDAGToDAGISelLegacy(PPCTargetMachine &tm,451CodeGenOptLevel OptLevel)452: SelectionDAGISelLegacy(453ID, std::make_unique<PPCDAGToDAGISel>(tm, OptLevel)) {}454};455} // end anonymous namespace456457char PPCDAGToDAGISelLegacy::ID = 0;458459INITIALIZE_PASS(PPCDAGToDAGISelLegacy, DEBUG_TYPE, PASS_NAME, false, false)460461/// getGlobalBaseReg - Output the instructions required to put the462/// base address to use for accessing globals into a register.463///464SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {465if (!GlobalBaseReg) {466const TargetInstrInfo &TII = *Subtarget->getInstrInfo();467// Insert the set of GlobalBaseReg into the first MBB of the function468MachineBasicBlock &FirstMBB = MF->front();469MachineBasicBlock::iterator MBBI = FirstMBB.begin();470const Module *M = MF->getFunction().getParent();471DebugLoc dl;472473if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) == MVT::i32) {474if (Subtarget->isTargetELF()) {475GlobalBaseReg = PPC::R30;476if (!Subtarget->isSecurePlt() &&477M->getPICLevel() == PICLevel::SmallPIC) {478BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR));479BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);480MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);481} else {482BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));483BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);484Register TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);485BuildMI(FirstMBB, MBBI, dl,486TII.get(PPC::UpdateGBR), GlobalBaseReg)487.addReg(TempReg, RegState::Define).addReg(GlobalBaseReg);488MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);489}490} else {491GlobalBaseReg =492RegInfo->createVirtualRegister(&PPC::GPRC_and_GPRC_NOR0RegClass);493BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));494BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);495}496} else {497// We must ensure that this sequence is dominated by the prologue.498// FIXME: This is a bit of a big hammer since we don't get the benefits499// of shrink-wrapping whenever we emit this instruction. Considering500// this is used in any function where we emit a jump table, this may be501// a significant limitation. We should consider inserting this in the502// block where it is used and then commoning this sequence up if it503// appears in multiple places.504// Note: on ISA 3.0 cores, we can use lnia (addpcis) instead of505// MovePCtoLR8.506MF->getInfo<PPCFunctionInfo>()->setShrinkWrapDisabled(true);507GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);508BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));509BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);510}511}512return CurDAG->getRegister(GlobalBaseReg,513PPCLowering->getPointerTy(CurDAG->getDataLayout()))514.getNode();515}516517// Check if a SDValue has the toc-data attribute.518static bool hasTocDataAttr(SDValue Val) {519GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Val);520if (!GA)521return false;522523const GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(GA->getGlobal());524if (!GV)525return false;526527if (!GV->hasAttribute("toc-data"))528return false;529return true;530}531532static CodeModel::Model getCodeModel(const PPCSubtarget &Subtarget,533const TargetMachine &TM,534const SDNode *Node) {535// If there isn't an attribute to override the module code model536// this will be the effective code model.537CodeModel::Model ModuleModel = TM.getCodeModel();538539GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Node->getOperand(0));540if (!GA)541return ModuleModel;542543const GlobalValue *GV = GA->getGlobal();544if (!GV)545return ModuleModel;546547return Subtarget.getCodeModel(TM, GV);548}549550/// isInt32Immediate - This method tests to see if the node is a 32-bit constant551/// operand. If so Imm will receive the 32-bit value.552static bool isInt32Immediate(SDNode *N, unsigned &Imm) {553if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {554Imm = N->getAsZExtVal();555return true;556}557return false;558}559560/// isInt64Immediate - This method tests to see if the node is a 64-bit constant561/// operand. If so Imm will receive the 64-bit value.562static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {563if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {564Imm = N->getAsZExtVal();565return true;566}567return false;568}569570// isInt32Immediate - This method tests to see if a constant operand.571// If so Imm will receive the 32 bit value.572static bool isInt32Immediate(SDValue N, unsigned &Imm) {573return isInt32Immediate(N.getNode(), Imm);574}575576/// isInt64Immediate - This method tests to see if the value is a 64-bit577/// constant operand. If so Imm will receive the 64-bit value.578static bool isInt64Immediate(SDValue N, uint64_t &Imm) {579return isInt64Immediate(N.getNode(), Imm);580}581582static unsigned getBranchHint(unsigned PCC,583const FunctionLoweringInfo &FuncInfo,584const SDValue &DestMBB) {585assert(isa<BasicBlockSDNode>(DestMBB));586587if (!FuncInfo.BPI) return PPC::BR_NO_HINT;588589const BasicBlock *BB = FuncInfo.MBB->getBasicBlock();590const Instruction *BBTerm = BB->getTerminator();591592if (BBTerm->getNumSuccessors() != 2) return PPC::BR_NO_HINT;593594const BasicBlock *TBB = BBTerm->getSuccessor(0);595const BasicBlock *FBB = BBTerm->getSuccessor(1);596597auto TProb = FuncInfo.BPI->getEdgeProbability(BB, TBB);598auto FProb = FuncInfo.BPI->getEdgeProbability(BB, FBB);599600// We only want to handle cases which are easy to predict at static time, e.g.601// C++ throw statement, that is very likely not taken, or calling never602// returned function, e.g. stdlib exit(). So we set Threshold to filter603// unwanted cases.604//605// Below is LLVM branch weight table, we only want to handle case 1, 2606//607// Case Taken:Nontaken Example608// 1. Unreachable 1048575:1 C++ throw, stdlib exit(),609// 2. Invoke-terminating 1:1048575610// 3. Coldblock 4:64 __builtin_expect611// 4. Loop Branch 124:4 For loop612// 5. PH/ZH/FPH 20:12613const uint32_t Threshold = 10000;614615if (std::max(TProb, FProb) / Threshold < std::min(TProb, FProb))616return PPC::BR_NO_HINT;617618LLVM_DEBUG(dbgs() << "Use branch hint for '" << FuncInfo.Fn->getName()619<< "::" << BB->getName() << "'\n"620<< " -> " << TBB->getName() << ": " << TProb << "\n"621<< " -> " << FBB->getName() << ": " << FProb << "\n");622623const BasicBlockSDNode *BBDN = cast<BasicBlockSDNode>(DestMBB);624625// If Dest BasicBlock is False-BasicBlock (FBB), swap branch probabilities,626// because we want 'TProb' stands for 'branch probability' to Dest BasicBlock627if (BBDN->getBasicBlock()->getBasicBlock() != TBB)628std::swap(TProb, FProb);629630return (TProb > FProb) ? PPC::BR_TAKEN_HINT : PPC::BR_NONTAKEN_HINT;631}632633// isOpcWithIntImmediate - This method tests to see if the node is a specific634// opcode and that it has a immediate integer right operand.635// If so Imm will receive the 32 bit value.636static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {637return N->getOpcode() == Opc638&& isInt32Immediate(N->getOperand(1).getNode(), Imm);639}640641void PPCDAGToDAGISel::selectFrameIndex(SDNode *SN, SDNode *N, uint64_t Offset) {642SDLoc dl(SN);643int FI = cast<FrameIndexSDNode>(N)->getIndex();644SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));645unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;646if (SN->hasOneUse())647CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI,648getSmallIPtrImm(Offset, dl));649else650ReplaceNode(SN, CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,651getSmallIPtrImm(Offset, dl)));652}653654bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,655bool isShiftMask, unsigned &SH,656unsigned &MB, unsigned &ME) {657// Don't even go down this path for i64, since different logic will be658// necessary for rldicl/rldicr/rldimi.659if (N->getValueType(0) != MVT::i32)660return false;661662unsigned Shift = 32;663unsigned Indeterminant = ~0; // bit mask marking indeterminant results664unsigned Opcode = N->getOpcode();665if (N->getNumOperands() != 2 ||666!isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))667return false;668669if (Opcode == ISD::SHL) {670// apply shift left to mask if it comes first671if (isShiftMask) Mask = Mask << Shift;672// determine which bits are made indeterminant by shift673Indeterminant = ~(0xFFFFFFFFu << Shift);674} else if (Opcode == ISD::SRL) {675// apply shift right to mask if it comes first676if (isShiftMask) Mask = Mask >> Shift;677// determine which bits are made indeterminant by shift678Indeterminant = ~(0xFFFFFFFFu >> Shift);679// adjust for the left rotate680Shift = 32 - Shift;681} else if (Opcode == ISD::ROTL) {682Indeterminant = 0;683} else {684return false;685}686687// if the mask doesn't intersect any Indeterminant bits688if (Mask && !(Mask & Indeterminant)) {689SH = Shift & 31;690// make sure the mask is still a mask (wrap arounds may not be)691return isRunOfOnes(Mask, MB, ME);692}693return false;694}695696// isThreadPointerAcquisitionNode - Check if the operands of an ADD_TLS697// instruction use the thread pointer.698static bool isThreadPointerAcquisitionNode(SDValue Base, SelectionDAG *CurDAG) {699assert(700Base.getOpcode() == PPCISD::ADD_TLS &&701"Only expecting the ADD_TLS instruction to acquire the thread pointer!");702const PPCSubtarget &Subtarget =703CurDAG->getMachineFunction().getSubtarget<PPCSubtarget>();704SDValue ADDTLSOp1 = Base.getOperand(0);705unsigned ADDTLSOp1Opcode = ADDTLSOp1.getOpcode();706707// Account for when ADD_TLS is used for the initial-exec TLS model on Linux.708//709// Although ADD_TLS does not explicitly use the thread pointer710// register when LD_GOT_TPREL_L is one of it's operands, the LD_GOT_TPREL_L711// instruction will have a relocation specifier, @got@tprel, that is used to712// generate a GOT entry. The linker replaces this entry with an offset for a713// for a thread local variable, which will be relative to the thread pointer.714if (ADDTLSOp1Opcode == PPCISD::LD_GOT_TPREL_L)715return true;716// When using PC-Relative instructions for initial-exec, a MAT_PCREL_ADDR717// node is produced instead to represent the aforementioned situation.718LoadSDNode *LD = dyn_cast<LoadSDNode>(ADDTLSOp1);719if (LD && LD->getBasePtr().getOpcode() == PPCISD::MAT_PCREL_ADDR)720return true;721722// A GET_TPOINTER PPCISD node (only produced on AIX 32-bit mode) as an operand723// to ADD_TLS represents a call to .__get_tpointer to get the thread pointer,724// later returning it into R3.725if (ADDTLSOp1Opcode == PPCISD::GET_TPOINTER)726return true;727728// The ADD_TLS note is explicitly acquiring the thread pointer (X13/R13).729RegisterSDNode *AddFirstOpReg =730dyn_cast_or_null<RegisterSDNode>(ADDTLSOp1.getNode());731if (AddFirstOpReg &&732AddFirstOpReg->getReg() == Subtarget.getThreadPointerRegister())733return true;734735return false;736}737738// canOptimizeTLSDFormToXForm - Optimize TLS accesses when an ADD_TLS739// instruction is present. An ADD_TLS instruction, followed by a D-Form memory740// operation, can be optimized to use an X-Form load or store, allowing the741// ADD_TLS node to be removed completely.742static bool canOptimizeTLSDFormToXForm(SelectionDAG *CurDAG, SDValue Base) {743744// Do not do this transformation at -O0.745if (CurDAG->getTarget().getOptLevel() == CodeGenOptLevel::None)746return false;747748// In order to perform this optimization inside tryTLSXForm[Load|Store],749// Base is expected to be an ADD_TLS node.750if (Base.getOpcode() != PPCISD::ADD_TLS)751return false;752for (auto *ADDTLSUse : Base.getNode()->uses()) {753// The optimization to convert the D-Form load/store into its X-Form754// counterpart should only occur if the source value offset of the load/755// store is 0. This also means that The offset should always be undefined.756if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ADDTLSUse)) {757if (LD->getSrcValueOffset() != 0 || !LD->getOffset().isUndef())758return false;759} else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(ADDTLSUse)) {760if (ST->getSrcValueOffset() != 0 || !ST->getOffset().isUndef())761return false;762} else // Don't optimize if there are ADD_TLS users that aren't load/stores.763return false;764}765766if (Base.getOperand(1).getOpcode() == PPCISD::TLS_LOCAL_EXEC_MAT_ADDR)767return false;768769// Does the ADD_TLS node of the load/store use the thread pointer?770// If the thread pointer is not used as one of the operands of ADD_TLS,771// then this optimization is not valid.772return isThreadPointerAcquisitionNode(Base, CurDAG);773}774775bool PPCDAGToDAGISel::tryTLSXFormStore(StoreSDNode *ST) {776SDValue Base = ST->getBasePtr();777if (!canOptimizeTLSDFormToXForm(CurDAG, Base))778return false;779780SDLoc dl(ST);781EVT MemVT = ST->getMemoryVT();782EVT RegVT = ST->getValue().getValueType();783784unsigned Opcode;785switch (MemVT.getSimpleVT().SimpleTy) {786default:787return false;788case MVT::i8: {789Opcode = (RegVT == MVT::i32) ? PPC::STBXTLS_32 : PPC::STBXTLS;790break;791}792case MVT::i16: {793Opcode = (RegVT == MVT::i32) ? PPC::STHXTLS_32 : PPC::STHXTLS;794break;795}796case MVT::i32: {797Opcode = (RegVT == MVT::i32) ? PPC::STWXTLS_32 : PPC::STWXTLS;798break;799}800case MVT::i64: {801Opcode = PPC::STDXTLS;802break;803}804case MVT::f32: {805Opcode = PPC::STFSXTLS;806break;807}808case MVT::f64: {809Opcode = PPC::STFDXTLS;810break;811}812}813SDValue Chain = ST->getChain();814SDVTList VTs = ST->getVTList();815SDValue Ops[] = {ST->getValue(), Base.getOperand(0), Base.getOperand(1),816Chain};817SDNode *MN = CurDAG->getMachineNode(Opcode, dl, VTs, Ops);818transferMemOperands(ST, MN);819ReplaceNode(ST, MN);820return true;821}822823bool PPCDAGToDAGISel::tryTLSXFormLoad(LoadSDNode *LD) {824SDValue Base = LD->getBasePtr();825if (!canOptimizeTLSDFormToXForm(CurDAG, Base))826return false;827828SDLoc dl(LD);829EVT MemVT = LD->getMemoryVT();830EVT RegVT = LD->getValueType(0);831bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;832unsigned Opcode;833switch (MemVT.getSimpleVT().SimpleTy) {834default:835return false;836case MVT::i8: {837Opcode = (RegVT == MVT::i32) ? PPC::LBZXTLS_32 : PPC::LBZXTLS;838break;839}840case MVT::i16: {841if (RegVT == MVT::i32)842Opcode = isSExt ? PPC::LHAXTLS_32 : PPC::LHZXTLS_32;843else844Opcode = isSExt ? PPC::LHAXTLS : PPC::LHZXTLS;845break;846}847case MVT::i32: {848if (RegVT == MVT::i32)849Opcode = isSExt ? PPC::LWAXTLS_32 : PPC::LWZXTLS_32;850else851Opcode = isSExt ? PPC::LWAXTLS : PPC::LWZXTLS;852break;853}854case MVT::i64: {855Opcode = PPC::LDXTLS;856break;857}858case MVT::f32: {859Opcode = PPC::LFSXTLS;860break;861}862case MVT::f64: {863Opcode = PPC::LFDXTLS;864break;865}866}867SDValue Chain = LD->getChain();868SDVTList VTs = LD->getVTList();869SDValue Ops[] = {Base.getOperand(0), Base.getOperand(1), Chain};870SDNode *MN = CurDAG->getMachineNode(Opcode, dl, VTs, Ops);871transferMemOperands(LD, MN);872ReplaceNode(LD, MN);873return true;874}875876/// Turn an or of two masked values into the rotate left word immediate then877/// mask insert (rlwimi) instruction.878bool PPCDAGToDAGISel::tryBitfieldInsert(SDNode *N) {879SDValue Op0 = N->getOperand(0);880SDValue Op1 = N->getOperand(1);881SDLoc dl(N);882883KnownBits LKnown = CurDAG->computeKnownBits(Op0);884KnownBits RKnown = CurDAG->computeKnownBits(Op1);885886unsigned TargetMask = LKnown.Zero.getZExtValue();887unsigned InsertMask = RKnown.Zero.getZExtValue();888889if ((TargetMask | InsertMask) == 0xFFFFFFFF) {890unsigned Op0Opc = Op0.getOpcode();891unsigned Op1Opc = Op1.getOpcode();892unsigned Value, SH = 0;893TargetMask = ~TargetMask;894InsertMask = ~InsertMask;895896// If the LHS has a foldable shift and the RHS does not, then swap it to the897// RHS so that we can fold the shift into the insert.898if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {899if (Op0.getOperand(0).getOpcode() == ISD::SHL ||900Op0.getOperand(0).getOpcode() == ISD::SRL) {901if (Op1.getOperand(0).getOpcode() != ISD::SHL &&902Op1.getOperand(0).getOpcode() != ISD::SRL) {903std::swap(Op0, Op1);904std::swap(Op0Opc, Op1Opc);905std::swap(TargetMask, InsertMask);906}907}908} else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {909if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&910Op1.getOperand(0).getOpcode() != ISD::SRL) {911std::swap(Op0, Op1);912std::swap(Op0Opc, Op1Opc);913std::swap(TargetMask, InsertMask);914}915}916917unsigned MB, ME;918if (isRunOfOnes(InsertMask, MB, ME)) {919if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&920isInt32Immediate(Op1.getOperand(1), Value)) {921Op1 = Op1.getOperand(0);922SH = (Op1Opc == ISD::SHL) ? Value : 32 - Value;923}924if (Op1Opc == ISD::AND) {925// The AND mask might not be a constant, and we need to make sure that926// if we're going to fold the masking with the insert, all bits not927// know to be zero in the mask are known to be one.928KnownBits MKnown = CurDAG->computeKnownBits(Op1.getOperand(1));929bool CanFoldMask = InsertMask == MKnown.One.getZExtValue();930931unsigned SHOpc = Op1.getOperand(0).getOpcode();932if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&933isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {934// Note that Value must be in range here (less than 32) because935// otherwise there would not be any bits set in InsertMask.936Op1 = Op1.getOperand(0).getOperand(0);937SH = (SHOpc == ISD::SHL) ? Value : 32 - Value;938}939}940941SH &= 31;942SDValue Ops[] = { Op0, Op1, getI32Imm(SH, dl), getI32Imm(MB, dl),943getI32Imm(ME, dl) };944ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops));945return true;946}947}948return false;949}950951static unsigned allUsesTruncate(SelectionDAG *CurDAG, SDNode *N) {952unsigned MaxTruncation = 0;953// Cannot use range-based for loop here as we need the actual use (i.e. we954// need the operand number corresponding to the use). A range-based for955// will unbox the use and provide an SDNode*.956for (SDNode::use_iterator Use = N->use_begin(), UseEnd = N->use_end();957Use != UseEnd; ++Use) {958unsigned Opc =959Use->isMachineOpcode() ? Use->getMachineOpcode() : Use->getOpcode();960switch (Opc) {961default: return 0;962case ISD::TRUNCATE:963if (Use->isMachineOpcode())964return 0;965MaxTruncation =966std::max(MaxTruncation, (unsigned)Use->getValueType(0).getSizeInBits());967continue;968case ISD::STORE: {969if (Use->isMachineOpcode())970return 0;971StoreSDNode *STN = cast<StoreSDNode>(*Use);972unsigned MemVTSize = STN->getMemoryVT().getSizeInBits();973if (MemVTSize == 64 || Use.getOperandNo() != 0)974return 0;975MaxTruncation = std::max(MaxTruncation, MemVTSize);976continue;977}978case PPC::STW8:979case PPC::STWX8:980case PPC::STWU8:981case PPC::STWUX8:982if (Use.getOperandNo() != 0)983return 0;984MaxTruncation = std::max(MaxTruncation, 32u);985continue;986case PPC::STH8:987case PPC::STHX8:988case PPC::STHU8:989case PPC::STHUX8:990if (Use.getOperandNo() != 0)991return 0;992MaxTruncation = std::max(MaxTruncation, 16u);993continue;994case PPC::STB8:995case PPC::STBX8:996case PPC::STBU8:997case PPC::STBUX8:998if (Use.getOperandNo() != 0)999return 0;1000MaxTruncation = std::max(MaxTruncation, 8u);1001continue;1002}1003}1004return MaxTruncation;1005}10061007// For any 32 < Num < 64, check if the Imm contains at least Num consecutive1008// zeros and return the number of bits by the left of these consecutive zeros.1009static int findContiguousZerosAtLeast(uint64_t Imm, unsigned Num) {1010unsigned HiTZ = llvm::countr_zero<uint32_t>(Hi_32(Imm));1011unsigned LoLZ = llvm::countl_zero<uint32_t>(Lo_32(Imm));1012if ((HiTZ + LoLZ) >= Num)1013return (32 + HiTZ);1014return 0;1015}10161017// Direct materialization of 64-bit constants by enumerated patterns.1018static SDNode *selectI64ImmDirect(SelectionDAG *CurDAG, const SDLoc &dl,1019uint64_t Imm, unsigned &InstCnt) {1020unsigned TZ = llvm::countr_zero<uint64_t>(Imm);1021unsigned LZ = llvm::countl_zero<uint64_t>(Imm);1022unsigned TO = llvm::countr_one<uint64_t>(Imm);1023unsigned LO = llvm::countl_one<uint64_t>(Imm);1024unsigned Hi32 = Hi_32(Imm);1025unsigned Lo32 = Lo_32(Imm);1026SDNode *Result = nullptr;1027unsigned Shift = 0;10281029auto getI32Imm = [CurDAG, dl](unsigned Imm) {1030return CurDAG->getTargetConstant(Imm, dl, MVT::i32);1031};10321033// Following patterns use 1 instructions to materialize the Imm.1034InstCnt = 1;1035// 1-1) Patterns : {zeros}{15-bit valve}1036// {ones}{15-bit valve}1037if (isInt<16>(Imm)) {1038SDValue SDImm = CurDAG->getTargetConstant(Imm, dl, MVT::i64);1039return CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, SDImm);1040}1041// 1-2) Patterns : {zeros}{15-bit valve}{16 zeros}1042// {ones}{15-bit valve}{16 zeros}1043if (TZ > 15 && (LZ > 32 || LO > 32))1044return CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64,1045getI32Imm((Imm >> 16) & 0xffff));10461047// Following patterns use 2 instructions to materialize the Imm.1048InstCnt = 2;1049assert(LZ < 64 && "Unexpected leading zeros here.");1050// Count of ones follwing the leading zeros.1051unsigned FO = llvm::countl_one<uint64_t>(Imm << LZ);1052// 2-1) Patterns : {zeros}{31-bit value}1053// {ones}{31-bit value}1054if (isInt<32>(Imm)) {1055uint64_t ImmHi16 = (Imm >> 16) & 0xffff;1056unsigned Opcode = ImmHi16 ? PPC::LIS8 : PPC::LI8;1057Result = CurDAG->getMachineNode(Opcode, dl, MVT::i64, getI32Imm(ImmHi16));1058return CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0),1059getI32Imm(Imm & 0xffff));1060}1061// 2-2) Patterns : {zeros}{ones}{15-bit value}{zeros}1062// {zeros}{15-bit value}{zeros}1063// {zeros}{ones}{15-bit value}1064// {ones}{15-bit value}{zeros}1065// We can take advantage of LI's sign-extension semantics to generate leading1066// ones, and then use RLDIC to mask off the ones in both sides after rotation.1067if ((LZ + FO + TZ) > 48) {1068Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64,1069getI32Imm((Imm >> TZ) & 0xffff));1070return CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, SDValue(Result, 0),1071getI32Imm(TZ), getI32Imm(LZ));1072}1073// 2-3) Pattern : {zeros}{15-bit value}{ones}1074// Shift right the Imm by (48 - LZ) bits to construct a negtive 16 bits value,1075// therefore we can take advantage of LI's sign-extension semantics, and then1076// mask them off after rotation.1077//1078// +--LZ--||-15-bit-||--TO--+ +-------------|--16-bit--+1079// |00000001bbbbbbbbb1111111| -> |00000000000001bbbbbbbbb1|1080// +------------------------+ +------------------------+1081// 63 0 63 01082// Imm (Imm >> (48 - LZ) & 0xffff)1083// +----sext-----|--16-bit--+ +clear-|-----------------+1084// |11111111111111bbbbbbbbb1| -> |00000001bbbbbbbbb1111111|1085// +------------------------+ +------------------------+1086// 63 0 63 01087// LI8: sext many leading zeros RLDICL: rotate left (48 - LZ), clear left LZ1088if ((LZ + TO) > 48) {1089// Since the immediates with (LZ > 32) have been handled by previous1090// patterns, here we have (LZ <= 32) to make sure we will not shift right1091// the Imm by a negative value.1092assert(LZ <= 32 && "Unexpected shift value.");1093Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64,1094getI32Imm((Imm >> (48 - LZ) & 0xffff)));1095return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),1096getI32Imm(48 - LZ), getI32Imm(LZ));1097}1098// 2-4) Patterns : {zeros}{ones}{15-bit value}{ones}1099// {ones}{15-bit value}{ones}1100// We can take advantage of LI's sign-extension semantics to generate leading1101// ones, and then use RLDICL to mask off the ones in left sides (if required)1102// after rotation.1103//1104// +-LZ-FO||-15-bit-||--TO--+ +-------------|--16-bit--+1105// |00011110bbbbbbbbb1111111| -> |000000000011110bbbbbbbbb|1106// +------------------------+ +------------------------+1107// 63 0 63 01108// Imm (Imm >> TO) & 0xffff1109// +----sext-----|--16-bit--+ +LZ|---------------------+1110// |111111111111110bbbbbbbbb| -> |00011110bbbbbbbbb1111111|1111// +------------------------+ +------------------------+1112// 63 0 63 01113// LI8: sext many leading zeros RLDICL: rotate left TO, clear left LZ1114if ((LZ + FO + TO) > 48) {1115Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64,1116getI32Imm((Imm >> TO) & 0xffff));1117return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),1118getI32Imm(TO), getI32Imm(LZ));1119}1120// 2-5) Pattern : {32 zeros}{****}{0}{15-bit value}1121// If Hi32 is zero and the Lo16(in Lo32) can be presented as a positive 16 bit1122// value, we can use LI for Lo16 without generating leading ones then add the1123// Hi16(in Lo32).1124if (LZ == 32 && ((Lo32 & 0x8000) == 0)) {1125Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64,1126getI32Imm(Lo32 & 0xffff));1127return CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64, SDValue(Result, 0),1128getI32Imm(Lo32 >> 16));1129}1130// 2-6) Patterns : {******}{49 zeros}{******}1131// {******}{49 ones}{******}1132// If the Imm contains 49 consecutive zeros/ones, it means that a total of 151133// bits remain on both sides. Rotate right the Imm to construct an int<16>1134// value, use LI for int<16> value and then use RLDICL without mask to rotate1135// it back.1136//1137// 1) findContiguousZerosAtLeast(Imm, 49)1138// +------|--zeros-|------+ +---ones--||---15 bit--+1139// |bbbbbb0000000000aaaaaa| -> |0000000000aaaaaabbbbbb|1140// +----------------------+ +----------------------+1141// 63 0 63 01142//1143// 2) findContiguousZerosAtLeast(~Imm, 49)1144// +------|--ones--|------+ +---ones--||---15 bit--+1145// |bbbbbb1111111111aaaaaa| -> |1111111111aaaaaabbbbbb|1146// +----------------------+ +----------------------+1147// 63 0 63 01148if ((Shift = findContiguousZerosAtLeast(Imm, 49)) ||1149(Shift = findContiguousZerosAtLeast(~Imm, 49))) {1150uint64_t RotImm = APInt(64, Imm).rotr(Shift).getZExtValue();1151Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64,1152getI32Imm(RotImm & 0xffff));1153return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),1154getI32Imm(Shift), getI32Imm(0));1155}1156// 2-7) Patterns : High word == Low word1157// This may require 2 to 3 instructions, depending on whether Lo32 can be1158// materialized in 1 instruction.1159if (Hi32 == Lo32) {1160// Handle the first 32 bits.1161uint64_t ImmHi16 = (Lo32 >> 16) & 0xffff;1162uint64_t ImmLo16 = Lo32 & 0xffff;1163if (isInt<16>(Lo32))1164Result =1165CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(ImmLo16));1166else if (!ImmLo16)1167Result =1168CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(ImmHi16));1169else {1170InstCnt = 3;1171Result =1172CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(ImmHi16));1173Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,1174SDValue(Result, 0), getI32Imm(ImmLo16));1175}1176// Use rldimi to insert the Low word into High word.1177SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(32),1178getI32Imm(0)};1179return CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops);1180}11811182// Following patterns use 3 instructions to materialize the Imm.1183InstCnt = 3;1184// 3-1) Patterns : {zeros}{ones}{31-bit value}{zeros}1185// {zeros}{31-bit value}{zeros}1186// {zeros}{ones}{31-bit value}1187// {ones}{31-bit value}{zeros}1188// We can take advantage of LIS's sign-extension semantics to generate leading1189// ones, add the remaining bits with ORI, and then use RLDIC to mask off the1190// ones in both sides after rotation.1191if ((LZ + FO + TZ) > 32) {1192uint64_t ImmHi16 = (Imm >> (TZ + 16)) & 0xffff;1193unsigned Opcode = ImmHi16 ? PPC::LIS8 : PPC::LI8;1194Result = CurDAG->getMachineNode(Opcode, dl, MVT::i64, getI32Imm(ImmHi16));1195Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0),1196getI32Imm((Imm >> TZ) & 0xffff));1197return CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, SDValue(Result, 0),1198getI32Imm(TZ), getI32Imm(LZ));1199}1200// 3-2) Pattern : {zeros}{31-bit value}{ones}1201// Shift right the Imm by (32 - LZ) bits to construct a negative 32 bits1202// value, therefore we can take advantage of LIS's sign-extension semantics,1203// add the remaining bits with ORI, and then mask them off after rotation.1204// This is similar to Pattern 2-3, please refer to the diagram there.1205if ((LZ + TO) > 32) {1206// Since the immediates with (LZ > 32) have been handled by previous1207// patterns, here we have (LZ <= 32) to make sure we will not shift right1208// the Imm by a negative value.1209assert(LZ <= 32 && "Unexpected shift value.");1210Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64,1211getI32Imm((Imm >> (48 - LZ)) & 0xffff));1212Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0),1213getI32Imm((Imm >> (32 - LZ)) & 0xffff));1214return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),1215getI32Imm(32 - LZ), getI32Imm(LZ));1216}1217// 3-3) Patterns : {zeros}{ones}{31-bit value}{ones}1218// {ones}{31-bit value}{ones}1219// We can take advantage of LIS's sign-extension semantics to generate leading1220// ones, add the remaining bits with ORI, and then use RLDICL to mask off the1221// ones in left sides (if required) after rotation.1222// This is similar to Pattern 2-4, please refer to the diagram there.1223if ((LZ + FO + TO) > 32) {1224Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64,1225getI32Imm((Imm >> (TO + 16)) & 0xffff));1226Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0),1227getI32Imm((Imm >> TO) & 0xffff));1228return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),1229getI32Imm(TO), getI32Imm(LZ));1230}1231// 3-4) Patterns : {******}{33 zeros}{******}1232// {******}{33 ones}{******}1233// If the Imm contains 33 consecutive zeros/ones, it means that a total of 311234// bits remain on both sides. Rotate right the Imm to construct an int<32>1235// value, use LIS + ORI for int<32> value and then use RLDICL without mask to1236// rotate it back.1237// This is similar to Pattern 2-6, please refer to the diagram there.1238if ((Shift = findContiguousZerosAtLeast(Imm, 33)) ||1239(Shift = findContiguousZerosAtLeast(~Imm, 33))) {1240uint64_t RotImm = APInt(64, Imm).rotr(Shift).getZExtValue();1241uint64_t ImmHi16 = (RotImm >> 16) & 0xffff;1242unsigned Opcode = ImmHi16 ? PPC::LIS8 : PPC::LI8;1243Result = CurDAG->getMachineNode(Opcode, dl, MVT::i64, getI32Imm(ImmHi16));1244Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0),1245getI32Imm(RotImm & 0xffff));1246return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),1247getI32Imm(Shift), getI32Imm(0));1248}12491250InstCnt = 0;1251return nullptr;1252}12531254// Try to select instructions to generate a 64 bit immediate using prefix as1255// well as non prefix instructions. The function will return the SDNode1256// to materialize that constant or it will return nullptr if it does not1257// find one. The variable InstCnt is set to the number of instructions that1258// were selected.1259static SDNode *selectI64ImmDirectPrefix(SelectionDAG *CurDAG, const SDLoc &dl,1260uint64_t Imm, unsigned &InstCnt) {1261unsigned TZ = llvm::countr_zero<uint64_t>(Imm);1262unsigned LZ = llvm::countl_zero<uint64_t>(Imm);1263unsigned TO = llvm::countr_one<uint64_t>(Imm);1264unsigned FO = llvm::countl_one<uint64_t>(LZ == 64 ? 0 : (Imm << LZ));1265unsigned Hi32 = Hi_32(Imm);1266unsigned Lo32 = Lo_32(Imm);12671268auto getI32Imm = [CurDAG, dl](unsigned Imm) {1269return CurDAG->getTargetConstant(Imm, dl, MVT::i32);1270};12711272auto getI64Imm = [CurDAG, dl](uint64_t Imm) {1273return CurDAG->getTargetConstant(Imm, dl, MVT::i64);1274};12751276// Following patterns use 1 instruction to materialize Imm.1277InstCnt = 1;12781279// The pli instruction can materialize up to 34 bits directly.1280// If a constant fits within 34-bits, emit the pli instruction here directly.1281if (isInt<34>(Imm))1282return CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64,1283CurDAG->getTargetConstant(Imm, dl, MVT::i64));12841285// Require at least two instructions.1286InstCnt = 2;1287SDNode *Result = nullptr;1288// Patterns : {zeros}{ones}{33-bit value}{zeros}1289// {zeros}{33-bit value}{zeros}1290// {zeros}{ones}{33-bit value}1291// {ones}{33-bit value}{zeros}1292// We can take advantage of PLI's sign-extension semantics to generate leading1293// ones, and then use RLDIC to mask off the ones on both sides after rotation.1294if ((LZ + FO + TZ) > 30) {1295APInt SignedInt34 = APInt(34, (Imm >> TZ) & 0x3ffffffff);1296APInt Extended = SignedInt34.sext(64);1297Result = CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64,1298getI64Imm(*Extended.getRawData()));1299return CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, SDValue(Result, 0),1300getI32Imm(TZ), getI32Imm(LZ));1301}1302// Pattern : {zeros}{33-bit value}{ones}1303// Shift right the Imm by (30 - LZ) bits to construct a negative 34 bit value,1304// therefore we can take advantage of PLI's sign-extension semantics, and then1305// mask them off after rotation.1306//1307// +--LZ--||-33-bit-||--TO--+ +-------------|--34-bit--+1308// |00000001bbbbbbbbb1111111| -> |00000000000001bbbbbbbbb1|1309// +------------------------+ +------------------------+1310// 63 0 63 01311//1312// +----sext-----|--34-bit--+ +clear-|-----------------+1313// |11111111111111bbbbbbbbb1| -> |00000001bbbbbbbbb1111111|1314// +------------------------+ +------------------------+1315// 63 0 63 01316if ((LZ + TO) > 30) {1317APInt SignedInt34 = APInt(34, (Imm >> (30 - LZ)) & 0x3ffffffff);1318APInt Extended = SignedInt34.sext(64);1319Result = CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64,1320getI64Imm(*Extended.getRawData()));1321return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),1322getI32Imm(30 - LZ), getI32Imm(LZ));1323}1324// Patterns : {zeros}{ones}{33-bit value}{ones}1325// {ones}{33-bit value}{ones}1326// Similar to LI we can take advantage of PLI's sign-extension semantics to1327// generate leading ones, and then use RLDICL to mask off the ones in left1328// sides (if required) after rotation.1329if ((LZ + FO + TO) > 30) {1330APInt SignedInt34 = APInt(34, (Imm >> TO) & 0x3ffffffff);1331APInt Extended = SignedInt34.sext(64);1332Result = CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64,1333getI64Imm(*Extended.getRawData()));1334return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),1335getI32Imm(TO), getI32Imm(LZ));1336}1337// Patterns : {******}{31 zeros}{******}1338// : {******}{31 ones}{******}1339// If Imm contains 31 consecutive zeros/ones then the remaining bit count1340// is 33. Rotate right the Imm to construct a int<33> value, we can use PLI1341// for the int<33> value and then use RLDICL without a mask to rotate it back.1342//1343// +------|--ones--|------+ +---ones--||---33 bit--+1344// |bbbbbb1111111111aaaaaa| -> |1111111111aaaaaabbbbbb|1345// +----------------------+ +----------------------+1346// 63 0 63 01347for (unsigned Shift = 0; Shift < 63; ++Shift) {1348uint64_t RotImm = APInt(64, Imm).rotr(Shift).getZExtValue();1349if (isInt<34>(RotImm)) {1350Result =1351CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64, getI64Imm(RotImm));1352return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,1353SDValue(Result, 0), getI32Imm(Shift),1354getI32Imm(0));1355}1356}13571358// Patterns : High word == Low word1359// This is basically a splat of a 32 bit immediate.1360if (Hi32 == Lo32) {1361Result = CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64, getI64Imm(Hi32));1362SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(32),1363getI32Imm(0)};1364return CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops);1365}13661367InstCnt = 3;1368// Catch-all1369// This pattern can form any 64 bit immediate in 3 instructions.1370SDNode *ResultHi =1371CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64, getI64Imm(Hi32));1372SDNode *ResultLo =1373CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64, getI64Imm(Lo32));1374SDValue Ops[] = {SDValue(ResultLo, 0), SDValue(ResultHi, 0), getI32Imm(32),1375getI32Imm(0)};1376return CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops);1377}13781379static SDNode *selectI64Imm(SelectionDAG *CurDAG, const SDLoc &dl, uint64_t Imm,1380unsigned *InstCnt = nullptr) {1381unsigned InstCntDirect = 0;1382// No more than 3 instructions are used if we can select the i64 immediate1383// directly.1384SDNode *Result = selectI64ImmDirect(CurDAG, dl, Imm, InstCntDirect);13851386const PPCSubtarget &Subtarget =1387CurDAG->getMachineFunction().getSubtarget<PPCSubtarget>();13881389// If we have prefixed instructions and there is a chance we can1390// materialize the constant with fewer prefixed instructions than1391// non-prefixed, try that.1392if (Subtarget.hasPrefixInstrs() && InstCntDirect != 1) {1393unsigned InstCntDirectP = 0;1394SDNode *ResultP = selectI64ImmDirectPrefix(CurDAG, dl, Imm, InstCntDirectP);1395// Use the prefix case in either of two cases:1396// 1) We have no result from the non-prefix case to use.1397// 2) The non-prefix case uses more instructions than the prefix case.1398// If the prefix and non-prefix cases use the same number of instructions1399// we will prefer the non-prefix case.1400if (ResultP && (!Result || InstCntDirectP < InstCntDirect)) {1401if (InstCnt)1402*InstCnt = InstCntDirectP;1403return ResultP;1404}1405}14061407if (Result) {1408if (InstCnt)1409*InstCnt = InstCntDirect;1410return Result;1411}1412auto getI32Imm = [CurDAG, dl](unsigned Imm) {1413return CurDAG->getTargetConstant(Imm, dl, MVT::i32);1414};14151416uint32_t Hi16OfLo32 = (Lo_32(Imm) >> 16) & 0xffff;1417uint32_t Lo16OfLo32 = Lo_32(Imm) & 0xffff;14181419// Try to use 4 instructions to materialize the immediate which is "almost" a1420// splat of a 32 bit immediate.1421if (Hi16OfLo32 && Lo16OfLo32) {1422uint32_t Hi16OfHi32 = (Hi_32(Imm) >> 16) & 0xffff;1423uint32_t Lo16OfHi32 = Hi_32(Imm) & 0xffff;1424bool IsSelected = false;14251426auto getSplat = [CurDAG, dl, getI32Imm](uint32_t Hi16, uint32_t Lo16) {1427SDNode *Result =1428CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi16));1429Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,1430SDValue(Result, 0), getI32Imm(Lo16));1431SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(32),1432getI32Imm(0)};1433return CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops);1434};14351436if (Hi16OfHi32 == Lo16OfHi32 && Lo16OfHi32 == Lo16OfLo32) {1437IsSelected = true;1438Result = getSplat(Hi16OfLo32, Lo16OfLo32);1439// Modify Hi16OfHi32.1440SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(48),1441getI32Imm(0)};1442Result = CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops);1443} else if (Hi16OfHi32 == Hi16OfLo32 && Hi16OfLo32 == Lo16OfLo32) {1444IsSelected = true;1445Result = getSplat(Hi16OfHi32, Lo16OfHi32);1446// Modify Lo16OfLo32.1447SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(16),1448getI32Imm(16), getI32Imm(31)};1449Result = CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64, Ops);1450} else if (Lo16OfHi32 == Lo16OfLo32 && Hi16OfLo32 == Lo16OfLo32) {1451IsSelected = true;1452Result = getSplat(Hi16OfHi32, Lo16OfHi32);1453// Modify Hi16OfLo32.1454SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(16),1455getI32Imm(0), getI32Imm(15)};1456Result = CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64, Ops);1457}1458if (IsSelected == true) {1459if (InstCnt)1460*InstCnt = 4;1461return Result;1462}1463}14641465// Handle the upper 32 bit value.1466Result =1467selectI64ImmDirect(CurDAG, dl, Imm & 0xffffffff00000000, InstCntDirect);1468// Add in the last bits as required.1469if (Hi16OfLo32) {1470Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,1471SDValue(Result, 0), getI32Imm(Hi16OfLo32));1472++InstCntDirect;1473}1474if (Lo16OfLo32) {1475Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0),1476getI32Imm(Lo16OfLo32));1477++InstCntDirect;1478}1479if (InstCnt)1480*InstCnt = InstCntDirect;1481return Result;1482}14831484// Select a 64-bit constant.1485static SDNode *selectI64Imm(SelectionDAG *CurDAG, SDNode *N) {1486SDLoc dl(N);14871488// Get 64 bit value.1489int64_t Imm = N->getAsZExtVal();1490if (unsigned MinSize = allUsesTruncate(CurDAG, N)) {1491uint64_t SextImm = SignExtend64(Imm, MinSize);1492SDValue SDImm = CurDAG->getTargetConstant(SextImm, dl, MVT::i64);1493if (isInt<16>(SextImm))1494return CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, SDImm);1495}1496return selectI64Imm(CurDAG, dl, Imm);1497}14981499namespace {15001501class BitPermutationSelector {1502struct ValueBit {1503SDValue V;15041505// The bit number in the value, using a convention where bit 0 is the1506// lowest-order bit.1507unsigned Idx;15081509// ConstZero means a bit we need to mask off.1510// Variable is a bit comes from an input variable.1511// VariableKnownToBeZero is also a bit comes from an input variable,1512// but it is known to be already zero. So we do not need to mask them.1513enum Kind {1514ConstZero,1515Variable,1516VariableKnownToBeZero1517} K;15181519ValueBit(SDValue V, unsigned I, Kind K = Variable)1520: V(V), Idx(I), K(K) {}1521ValueBit(Kind K = Variable) : Idx(UINT32_MAX), K(K) {}15221523bool isZero() const {1524return K == ConstZero || K == VariableKnownToBeZero;1525}15261527bool hasValue() const {1528return K == Variable || K == VariableKnownToBeZero;1529}15301531SDValue getValue() const {1532assert(hasValue() && "Cannot get the value of a constant bit");1533return V;1534}15351536unsigned getValueBitIndex() const {1537assert(hasValue() && "Cannot get the value bit index of a constant bit");1538return Idx;1539}1540};15411542// A bit group has the same underlying value and the same rotate factor.1543struct BitGroup {1544SDValue V;1545unsigned RLAmt;1546unsigned StartIdx, EndIdx;15471548// This rotation amount assumes that the lower 32 bits of the quantity are1549// replicated in the high 32 bits by the rotation operator (which is done1550// by rlwinm and friends in 64-bit mode).1551bool Repl32;1552// Did converting to Repl32 == true change the rotation factor? If it did,1553// it decreased it by 32.1554bool Repl32CR;1555// Was this group coalesced after setting Repl32 to true?1556bool Repl32Coalesced;15571558BitGroup(SDValue V, unsigned R, unsigned S, unsigned E)1559: V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false),1560Repl32Coalesced(false) {1561LLVM_DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R1562<< " [" << S << ", " << E << "]\n");1563}1564};15651566// Information on each (Value, RLAmt) pair (like the number of groups1567// associated with each) used to choose the lowering method.1568struct ValueRotInfo {1569SDValue V;1570unsigned RLAmt = std::numeric_limits<unsigned>::max();1571unsigned NumGroups = 0;1572unsigned FirstGroupStartIdx = std::numeric_limits<unsigned>::max();1573bool Repl32 = false;15741575ValueRotInfo() = default;15761577// For sorting (in reverse order) by NumGroups, and then by1578// FirstGroupStartIdx.1579bool operator < (const ValueRotInfo &Other) const {1580// We need to sort so that the non-Repl32 come first because, when we're1581// doing masking, the Repl32 bit groups might be subsumed into the 64-bit1582// masking operation.1583if (Repl32 < Other.Repl32)1584return true;1585else if (Repl32 > Other.Repl32)1586return false;1587else if (NumGroups > Other.NumGroups)1588return true;1589else if (NumGroups < Other.NumGroups)1590return false;1591else if (RLAmt == 0 && Other.RLAmt != 0)1592return true;1593else if (RLAmt != 0 && Other.RLAmt == 0)1594return false;1595else if (FirstGroupStartIdx < Other.FirstGroupStartIdx)1596return true;1597return false;1598}1599};16001601using ValueBitsMemoizedValue = std::pair<bool, SmallVector<ValueBit, 64>>;1602using ValueBitsMemoizer =1603DenseMap<SDValue, std::unique_ptr<ValueBitsMemoizedValue>>;1604ValueBitsMemoizer Memoizer;16051606// Return a pair of bool and a SmallVector pointer to a memoization entry.1607// The bool is true if something interesting was deduced, otherwise if we're1608// providing only a generic representation of V (or something else likewise1609// uninteresting for instruction selection) through the SmallVector.1610std::pair<bool, SmallVector<ValueBit, 64> *> getValueBits(SDValue V,1611unsigned NumBits) {1612auto &ValueEntry = Memoizer[V];1613if (ValueEntry)1614return std::make_pair(ValueEntry->first, &ValueEntry->second);1615ValueEntry.reset(new ValueBitsMemoizedValue());1616bool &Interesting = ValueEntry->first;1617SmallVector<ValueBit, 64> &Bits = ValueEntry->second;1618Bits.resize(NumBits);16191620switch (V.getOpcode()) {1621default: break;1622case ISD::ROTL:1623if (isa<ConstantSDNode>(V.getOperand(1))) {1624assert(isPowerOf2_32(NumBits) && "rotl bits should be power of 2!");1625unsigned RotAmt = V.getConstantOperandVal(1) & (NumBits - 1);16261627const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;16281629for (unsigned i = 0; i < NumBits; ++i)1630Bits[i] = LHSBits[i < RotAmt ? i + (NumBits - RotAmt) : i - RotAmt];16311632return std::make_pair(Interesting = true, &Bits);1633}1634break;1635case ISD::SHL:1636case PPCISD::SHL:1637if (isa<ConstantSDNode>(V.getOperand(1))) {1638// sld takes 7 bits, slw takes 6.1639unsigned ShiftAmt = V.getConstantOperandVal(1) & ((NumBits << 1) - 1);16401641const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;16421643if (ShiftAmt >= NumBits) {1644for (unsigned i = 0; i < NumBits; ++i)1645Bits[i] = ValueBit(ValueBit::ConstZero);1646} else {1647for (unsigned i = ShiftAmt; i < NumBits; ++i)1648Bits[i] = LHSBits[i - ShiftAmt];1649for (unsigned i = 0; i < ShiftAmt; ++i)1650Bits[i] = ValueBit(ValueBit::ConstZero);1651}16521653return std::make_pair(Interesting = true, &Bits);1654}1655break;1656case ISD::SRL:1657case PPCISD::SRL:1658if (isa<ConstantSDNode>(V.getOperand(1))) {1659// srd takes lowest 7 bits, srw takes 6.1660unsigned ShiftAmt = V.getConstantOperandVal(1) & ((NumBits << 1) - 1);16611662const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;16631664if (ShiftAmt >= NumBits) {1665for (unsigned i = 0; i < NumBits; ++i)1666Bits[i] = ValueBit(ValueBit::ConstZero);1667} else {1668for (unsigned i = 0; i < NumBits - ShiftAmt; ++i)1669Bits[i] = LHSBits[i + ShiftAmt];1670for (unsigned i = NumBits - ShiftAmt; i < NumBits; ++i)1671Bits[i] = ValueBit(ValueBit::ConstZero);1672}16731674return std::make_pair(Interesting = true, &Bits);1675}1676break;1677case ISD::AND:1678if (isa<ConstantSDNode>(V.getOperand(1))) {1679uint64_t Mask = V.getConstantOperandVal(1);16801681const SmallVector<ValueBit, 64> *LHSBits;1682// Mark this as interesting, only if the LHS was also interesting. This1683// prevents the overall procedure from matching a single immediate 'and'1684// (which is non-optimal because such an and might be folded with other1685// things if we don't select it here).1686std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0), NumBits);16871688for (unsigned i = 0; i < NumBits; ++i)1689if (((Mask >> i) & 1) == 1)1690Bits[i] = (*LHSBits)[i];1691else {1692// AND instruction masks this bit. If the input is already zero,1693// we have nothing to do here. Otherwise, make the bit ConstZero.1694if ((*LHSBits)[i].isZero())1695Bits[i] = (*LHSBits)[i];1696else1697Bits[i] = ValueBit(ValueBit::ConstZero);1698}16991700return std::make_pair(Interesting, &Bits);1701}1702break;1703case ISD::OR: {1704const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;1705const auto &RHSBits = *getValueBits(V.getOperand(1), NumBits).second;17061707bool AllDisjoint = true;1708SDValue LastVal = SDValue();1709unsigned LastIdx = 0;1710for (unsigned i = 0; i < NumBits; ++i) {1711if (LHSBits[i].isZero() && RHSBits[i].isZero()) {1712// If both inputs are known to be zero and one is ConstZero and1713// another is VariableKnownToBeZero, we can select whichever1714// we like. To minimize the number of bit groups, we select1715// VariableKnownToBeZero if this bit is the next bit of the same1716// input variable from the previous bit. Otherwise, we select1717// ConstZero.1718if (LHSBits[i].hasValue() && LHSBits[i].getValue() == LastVal &&1719LHSBits[i].getValueBitIndex() == LastIdx + 1)1720Bits[i] = LHSBits[i];1721else if (RHSBits[i].hasValue() && RHSBits[i].getValue() == LastVal &&1722RHSBits[i].getValueBitIndex() == LastIdx + 1)1723Bits[i] = RHSBits[i];1724else1725Bits[i] = ValueBit(ValueBit::ConstZero);1726}1727else if (LHSBits[i].isZero())1728Bits[i] = RHSBits[i];1729else if (RHSBits[i].isZero())1730Bits[i] = LHSBits[i];1731else {1732AllDisjoint = false;1733break;1734}1735// We remember the value and bit index of this bit.1736if (Bits[i].hasValue()) {1737LastVal = Bits[i].getValue();1738LastIdx = Bits[i].getValueBitIndex();1739}1740else {1741if (LastVal) LastVal = SDValue();1742LastIdx = 0;1743}1744}17451746if (!AllDisjoint)1747break;17481749return std::make_pair(Interesting = true, &Bits);1750}1751case ISD::ZERO_EXTEND: {1752// We support only the case with zero extension from i32 to i64 so far.1753if (V.getValueType() != MVT::i64 ||1754V.getOperand(0).getValueType() != MVT::i32)1755break;17561757const SmallVector<ValueBit, 64> *LHSBits;1758const unsigned NumOperandBits = 32;1759std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0),1760NumOperandBits);17611762for (unsigned i = 0; i < NumOperandBits; ++i)1763Bits[i] = (*LHSBits)[i];17641765for (unsigned i = NumOperandBits; i < NumBits; ++i)1766Bits[i] = ValueBit(ValueBit::ConstZero);17671768return std::make_pair(Interesting, &Bits);1769}1770case ISD::TRUNCATE: {1771EVT FromType = V.getOperand(0).getValueType();1772EVT ToType = V.getValueType();1773// We support only the case with truncate from i64 to i32.1774if (FromType != MVT::i64 || ToType != MVT::i32)1775break;1776const unsigned NumAllBits = FromType.getSizeInBits();1777SmallVector<ValueBit, 64> *InBits;1778std::tie(Interesting, InBits) = getValueBits(V.getOperand(0),1779NumAllBits);1780const unsigned NumValidBits = ToType.getSizeInBits();17811782// A 32-bit instruction cannot touch upper 32-bit part of 64-bit value.1783// So, we cannot include this truncate.1784bool UseUpper32bit = false;1785for (unsigned i = 0; i < NumValidBits; ++i)1786if ((*InBits)[i].hasValue() && (*InBits)[i].getValueBitIndex() >= 32) {1787UseUpper32bit = true;1788break;1789}1790if (UseUpper32bit)1791break;17921793for (unsigned i = 0; i < NumValidBits; ++i)1794Bits[i] = (*InBits)[i];17951796return std::make_pair(Interesting, &Bits);1797}1798case ISD::AssertZext: {1799// For AssertZext, we look through the operand and1800// mark the bits known to be zero.1801const SmallVector<ValueBit, 64> *LHSBits;1802std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0),1803NumBits);18041805EVT FromType = cast<VTSDNode>(V.getOperand(1))->getVT();1806const unsigned NumValidBits = FromType.getSizeInBits();1807for (unsigned i = 0; i < NumValidBits; ++i)1808Bits[i] = (*LHSBits)[i];18091810// These bits are known to be zero but the AssertZext may be from a value1811// that already has some constant zero bits (i.e. from a masking and).1812for (unsigned i = NumValidBits; i < NumBits; ++i)1813Bits[i] = (*LHSBits)[i].hasValue()1814? ValueBit((*LHSBits)[i].getValue(),1815(*LHSBits)[i].getValueBitIndex(),1816ValueBit::VariableKnownToBeZero)1817: ValueBit(ValueBit::ConstZero);18181819return std::make_pair(Interesting, &Bits);1820}1821case ISD::LOAD:1822LoadSDNode *LD = cast<LoadSDNode>(V);1823if (ISD::isZEXTLoad(V.getNode()) && V.getResNo() == 0) {1824EVT VT = LD->getMemoryVT();1825const unsigned NumValidBits = VT.getSizeInBits();18261827for (unsigned i = 0; i < NumValidBits; ++i)1828Bits[i] = ValueBit(V, i);18291830// These bits are known to be zero.1831for (unsigned i = NumValidBits; i < NumBits; ++i)1832Bits[i] = ValueBit(V, i, ValueBit::VariableKnownToBeZero);18331834// Zero-extending load itself cannot be optimized. So, it is not1835// interesting by itself though it gives useful information.1836return std::make_pair(Interesting = false, &Bits);1837}1838break;1839}18401841for (unsigned i = 0; i < NumBits; ++i)1842Bits[i] = ValueBit(V, i);18431844return std::make_pair(Interesting = false, &Bits);1845}18461847// For each value (except the constant ones), compute the left-rotate amount1848// to get it from its original to final position.1849void computeRotationAmounts() {1850NeedMask = false;1851RLAmt.resize(Bits.size());1852for (unsigned i = 0; i < Bits.size(); ++i)1853if (Bits[i].hasValue()) {1854unsigned VBI = Bits[i].getValueBitIndex();1855if (i >= VBI)1856RLAmt[i] = i - VBI;1857else1858RLAmt[i] = Bits.size() - (VBI - i);1859} else if (Bits[i].isZero()) {1860NeedMask = true;1861RLAmt[i] = UINT32_MAX;1862} else {1863llvm_unreachable("Unknown value bit type");1864}1865}18661867// Collect groups of consecutive bits with the same underlying value and1868// rotation factor. If we're doing late masking, we ignore zeros, otherwise1869// they break up groups.1870void collectBitGroups(bool LateMask) {1871BitGroups.clear();18721873unsigned LastRLAmt = RLAmt[0];1874SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue();1875unsigned LastGroupStartIdx = 0;1876bool IsGroupOfZeros = !Bits[LastGroupStartIdx].hasValue();1877for (unsigned i = 1; i < Bits.size(); ++i) {1878unsigned ThisRLAmt = RLAmt[i];1879SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue();1880if (LateMask && !ThisValue) {1881ThisValue = LastValue;1882ThisRLAmt = LastRLAmt;1883// If we're doing late masking, then the first bit group always starts1884// at zero (even if the first bits were zero).1885if (BitGroups.empty())1886LastGroupStartIdx = 0;1887}18881889// If this bit is known to be zero and the current group is a bit group1890// of zeros, we do not need to terminate the current bit group even the1891// Value or RLAmt does not match here. Instead, we terminate this group1892// when the first non-zero bit appears later.1893if (IsGroupOfZeros && Bits[i].isZero())1894continue;18951896// If this bit has the same underlying value and the same rotate factor as1897// the last one, then they're part of the same group.1898if (ThisRLAmt == LastRLAmt && ThisValue == LastValue)1899// We cannot continue the current group if this bits is not known to1900// be zero in a bit group of zeros.1901if (!(IsGroupOfZeros && ThisValue && !Bits[i].isZero()))1902continue;19031904if (LastValue.getNode())1905BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,1906i-1));1907LastRLAmt = ThisRLAmt;1908LastValue = ThisValue;1909LastGroupStartIdx = i;1910IsGroupOfZeros = !Bits[LastGroupStartIdx].hasValue();1911}1912if (LastValue.getNode())1913BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,1914Bits.size()-1));19151916if (BitGroups.empty())1917return;19181919// We might be able to combine the first and last groups.1920if (BitGroups.size() > 1) {1921// If the first and last groups are the same, then remove the first group1922// in favor of the last group, making the ending index of the last group1923// equal to the ending index of the to-be-removed first group.1924if (BitGroups[0].StartIdx == 0 &&1925BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 &&1926BitGroups[0].V == BitGroups[BitGroups.size()-1].V &&1927BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) {1928LLVM_DEBUG(dbgs() << "\tcombining final bit group with initial one\n");1929BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx;1930BitGroups.erase(BitGroups.begin());1931}1932}1933}19341935// Take all (SDValue, RLAmt) pairs and sort them by the number of groups1936// associated with each. If the number of groups are same, we prefer a group1937// which does not require rotate, i.e. RLAmt is 0, to avoid the first rotate1938// instruction. If there is a degeneracy, pick the one that occurs1939// first (in the final value).1940void collectValueRotInfo() {1941ValueRots.clear();19421943for (auto &BG : BitGroups) {1944unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0);1945ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)];1946VRI.V = BG.V;1947VRI.RLAmt = BG.RLAmt;1948VRI.Repl32 = BG.Repl32;1949VRI.NumGroups += 1;1950VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx);1951}19521953// Now that we've collected the various ValueRotInfo instances, we need to1954// sort them.1955ValueRotsVec.clear();1956for (auto &I : ValueRots) {1957ValueRotsVec.push_back(I.second);1958}1959llvm::sort(ValueRotsVec);1960}19611962// In 64-bit mode, rlwinm and friends have a rotation operator that1963// replicates the low-order 32 bits into the high-order 32-bits. The mask1964// indices of these instructions can only be in the lower 32 bits, so they1965// can only represent some 64-bit bit groups. However, when they can be used,1966// the 32-bit replication can be used to represent, as a single bit group,1967// otherwise separate bit groups. We'll convert to replicated-32-bit bit1968// groups when possible. Returns true if any of the bit groups were1969// converted.1970void assignRepl32BitGroups() {1971// If we have bits like this:1972//1973// Indices: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 01974// V bits: ... 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 241975// Groups: | RLAmt = 8 | RLAmt = 40 |1976//1977// But, making use of a 32-bit operation that replicates the low-order 321978// bits into the high-order 32 bits, this can be one bit group with a RLAmt1979// of 8.19801981auto IsAllLow32 = [this](BitGroup & BG) {1982if (BG.StartIdx <= BG.EndIdx) {1983for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) {1984if (!Bits[i].hasValue())1985continue;1986if (Bits[i].getValueBitIndex() >= 32)1987return false;1988}1989} else {1990for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) {1991if (!Bits[i].hasValue())1992continue;1993if (Bits[i].getValueBitIndex() >= 32)1994return false;1995}1996for (unsigned i = 0; i <= BG.EndIdx; ++i) {1997if (!Bits[i].hasValue())1998continue;1999if (Bits[i].getValueBitIndex() >= 32)2000return false;2001}2002}20032004return true;2005};20062007for (auto &BG : BitGroups) {2008// If this bit group has RLAmt of 0 and will not be merged with2009// another bit group, we don't benefit from Repl32. We don't mark2010// such group to give more freedom for later instruction selection.2011if (BG.RLAmt == 0) {2012auto PotentiallyMerged = [this](BitGroup & BG) {2013for (auto &BG2 : BitGroups)2014if (&BG != &BG2 && BG.V == BG2.V &&2015(BG2.RLAmt == 0 || BG2.RLAmt == 32))2016return true;2017return false;2018};2019if (!PotentiallyMerged(BG))2020continue;2021}2022if (BG.StartIdx < 32 && BG.EndIdx < 32) {2023if (IsAllLow32(BG)) {2024if (BG.RLAmt >= 32) {2025BG.RLAmt -= 32;2026BG.Repl32CR = true;2027}20282029BG.Repl32 = true;20302031LLVM_DEBUG(dbgs() << "\t32-bit replicated bit group for "2032<< BG.V.getNode() << " RLAmt = " << BG.RLAmt << " ["2033<< BG.StartIdx << ", " << BG.EndIdx << "]\n");2034}2035}2036}20372038// Now walk through the bit groups, consolidating where possible.2039for (auto I = BitGroups.begin(); I != BitGroups.end();) {2040// We might want to remove this bit group by merging it with the previous2041// group (which might be the ending group).2042auto IP = (I == BitGroups.begin()) ?2043std::prev(BitGroups.end()) : std::prev(I);2044if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt &&2045I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) {20462047LLVM_DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for "2048<< I->V.getNode() << " RLAmt = " << I->RLAmt << " ["2049<< I->StartIdx << ", " << I->EndIdx2050<< "] with group with range [" << IP->StartIdx << ", "2051<< IP->EndIdx << "]\n");20522053IP->EndIdx = I->EndIdx;2054IP->Repl32CR = IP->Repl32CR || I->Repl32CR;2055IP->Repl32Coalesced = true;2056I = BitGroups.erase(I);2057continue;2058} else {2059// There is a special case worth handling: If there is a single group2060// covering the entire upper 32 bits, and it can be merged with both2061// the next and previous groups (which might be the same group), then2062// do so. If it is the same group (so there will be only one group in2063// total), then we need to reverse the order of the range so that it2064// covers the entire 64 bits.2065if (I->StartIdx == 32 && I->EndIdx == 63) {2066assert(std::next(I) == BitGroups.end() &&2067"bit group ends at index 63 but there is another?");2068auto IN = BitGroups.begin();20692070if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V &&2071(I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt &&2072IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP &&2073IsAllLow32(*I)) {20742075LLVM_DEBUG(dbgs() << "\tcombining bit group for " << I->V.getNode()2076<< " RLAmt = " << I->RLAmt << " [" << I->StartIdx2077<< ", " << I->EndIdx2078<< "] with 32-bit replicated groups with ranges ["2079<< IP->StartIdx << ", " << IP->EndIdx << "] and ["2080<< IN->StartIdx << ", " << IN->EndIdx << "]\n");20812082if (IP == IN) {2083// There is only one other group; change it to cover the whole2084// range (backward, so that it can still be Repl32 but cover the2085// whole 64-bit range).2086IP->StartIdx = 31;2087IP->EndIdx = 30;2088IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32;2089IP->Repl32Coalesced = true;2090I = BitGroups.erase(I);2091} else {2092// There are two separate groups, one before this group and one2093// after us (at the beginning). We're going to remove this group,2094// but also the group at the very beginning.2095IP->EndIdx = IN->EndIdx;2096IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32;2097IP->Repl32Coalesced = true;2098I = BitGroups.erase(I);2099BitGroups.erase(BitGroups.begin());2100}21012102// This must be the last group in the vector (and we might have2103// just invalidated the iterator above), so break here.2104break;2105}2106}2107}21082109++I;2110}2111}21122113SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {2114return CurDAG->getTargetConstant(Imm, dl, MVT::i32);2115}21162117uint64_t getZerosMask() {2118uint64_t Mask = 0;2119for (unsigned i = 0; i < Bits.size(); ++i) {2120if (Bits[i].hasValue())2121continue;2122Mask |= (UINT64_C(1) << i);2123}21242125return ~Mask;2126}21272128// This method extends an input value to 64 bit if input is 32-bit integer.2129// While selecting instructions in BitPermutationSelector in 64-bit mode,2130// an input value can be a 32-bit integer if a ZERO_EXTEND node is included.2131// In such case, we extend it to 64 bit to be consistent with other values.2132SDValue ExtendToInt64(SDValue V, const SDLoc &dl) {2133if (V.getValueSizeInBits() == 64)2134return V;21352136assert(V.getValueSizeInBits() == 32);2137SDValue SubRegIdx = CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);2138SDValue ImDef = SDValue(CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl,2139MVT::i64), 0);2140SDValue ExtVal = SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl,2141MVT::i64, ImDef, V,2142SubRegIdx), 0);2143return ExtVal;2144}21452146SDValue TruncateToInt32(SDValue V, const SDLoc &dl) {2147if (V.getValueSizeInBits() == 32)2148return V;21492150assert(V.getValueSizeInBits() == 64);2151SDValue SubRegIdx = CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);2152SDValue SubVal = SDValue(CurDAG->getMachineNode(PPC::EXTRACT_SUBREG, dl,2153MVT::i32, V, SubRegIdx), 0);2154return SubVal;2155}21562157// Depending on the number of groups for a particular value, it might be2158// better to rotate, mask explicitly (using andi/andis), and then or the2159// result. Select this part of the result first.2160void SelectAndParts32(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {2161if (BPermRewriterNoMasking)2162return;21632164for (ValueRotInfo &VRI : ValueRotsVec) {2165unsigned Mask = 0;2166for (unsigned i = 0; i < Bits.size(); ++i) {2167if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V)2168continue;2169if (RLAmt[i] != VRI.RLAmt)2170continue;2171Mask |= (1u << i);2172}21732174// Compute the masks for andi/andis that would be necessary.2175unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;2176assert((ANDIMask != 0 || ANDISMask != 0) &&2177"No set bits in mask for value bit groups");2178bool NeedsRotate = VRI.RLAmt != 0;21792180// We're trying to minimize the number of instructions. If we have one2181// group, using one of andi/andis can break even. If we have three2182// groups, we can use both andi and andis and break even (to use both2183// andi and andis we also need to or the results together). We need four2184// groups if we also need to rotate. To use andi/andis we need to do more2185// than break even because rotate-and-mask instructions tend to be easier2186// to schedule.21872188// FIXME: We've biased here against using andi/andis, which is right for2189// POWER cores, but not optimal everywhere. For example, on the A2,2190// andi/andis have single-cycle latency whereas the rotate-and-mask2191// instructions take two cycles, and it would be better to bias toward2192// andi/andis in break-even cases.21932194unsigned NumAndInsts = (unsigned) NeedsRotate +2195(unsigned) (ANDIMask != 0) +2196(unsigned) (ANDISMask != 0) +2197(unsigned) (ANDIMask != 0 && ANDISMask != 0) +2198(unsigned) (bool) Res;21992200LLVM_DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode()2201<< " RL: " << VRI.RLAmt << ":"2202<< "\n\t\t\tisel using masking: " << NumAndInsts2203<< " using rotates: " << VRI.NumGroups << "\n");22042205if (NumAndInsts >= VRI.NumGroups)2206continue;22072208LLVM_DEBUG(dbgs() << "\t\t\t\tusing masking\n");22092210if (InstCnt) *InstCnt += NumAndInsts;22112212SDValue VRot;2213if (VRI.RLAmt) {2214SDValue Ops[] =2215{ TruncateToInt32(VRI.V, dl), getI32Imm(VRI.RLAmt, dl),2216getI32Imm(0, dl), getI32Imm(31, dl) };2217VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,2218Ops), 0);2219} else {2220VRot = TruncateToInt32(VRI.V, dl);2221}22222223SDValue ANDIVal, ANDISVal;2224if (ANDIMask != 0)2225ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI_rec, dl, MVT::i32,2226VRot, getI32Imm(ANDIMask, dl)),22270);2228if (ANDISMask != 0)2229ANDISVal =2230SDValue(CurDAG->getMachineNode(PPC::ANDIS_rec, dl, MVT::i32, VRot,2231getI32Imm(ANDISMask, dl)),22320);22332234SDValue TotalVal;2235if (!ANDIVal)2236TotalVal = ANDISVal;2237else if (!ANDISVal)2238TotalVal = ANDIVal;2239else2240TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,2241ANDIVal, ANDISVal), 0);22422243if (!Res)2244Res = TotalVal;2245else2246Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,2247Res, TotalVal), 0);22482249// Now, remove all groups with this underlying value and rotation2250// factor.2251eraseMatchingBitGroups([VRI](const BitGroup &BG) {2252return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;2253});2254}2255}22562257// Instruction selection for the 32-bit case.2258SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) {2259SDLoc dl(N);2260SDValue Res;22612262if (InstCnt) *InstCnt = 0;22632264// Take care of cases that should use andi/andis first.2265SelectAndParts32(dl, Res, InstCnt);22662267// If we've not yet selected a 'starting' instruction, and we have no zeros2268// to fill in, select the (Value, RLAmt) with the highest priority (largest2269// number of groups), and start with this rotated value.2270if ((!NeedMask || LateMask) && !Res) {2271ValueRotInfo &VRI = ValueRotsVec[0];2272if (VRI.RLAmt) {2273if (InstCnt) *InstCnt += 1;2274SDValue Ops[] =2275{ TruncateToInt32(VRI.V, dl), getI32Imm(VRI.RLAmt, dl),2276getI32Imm(0, dl), getI32Imm(31, dl) };2277Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),22780);2279} else {2280Res = TruncateToInt32(VRI.V, dl);2281}22822283// Now, remove all groups with this underlying value and rotation factor.2284eraseMatchingBitGroups([VRI](const BitGroup &BG) {2285return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;2286});2287}22882289if (InstCnt) *InstCnt += BitGroups.size();22902291// Insert the other groups (one at a time).2292for (auto &BG : BitGroups) {2293if (!Res) {2294SDValue Ops[] =2295{ TruncateToInt32(BG.V, dl), getI32Imm(BG.RLAmt, dl),2296getI32Imm(Bits.size() - BG.EndIdx - 1, dl),2297getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };2298Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);2299} else {2300SDValue Ops[] =2301{ Res, TruncateToInt32(BG.V, dl), getI32Imm(BG.RLAmt, dl),2302getI32Imm(Bits.size() - BG.EndIdx - 1, dl),2303getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };2304Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops), 0);2305}2306}23072308if (LateMask) {2309unsigned Mask = (unsigned) getZerosMask();23102311unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;2312assert((ANDIMask != 0 || ANDISMask != 0) &&2313"No set bits in zeros mask?");23142315if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +2316(unsigned) (ANDISMask != 0) +2317(unsigned) (ANDIMask != 0 && ANDISMask != 0);23182319SDValue ANDIVal, ANDISVal;2320if (ANDIMask != 0)2321ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI_rec, dl, MVT::i32,2322Res, getI32Imm(ANDIMask, dl)),23230);2324if (ANDISMask != 0)2325ANDISVal =2326SDValue(CurDAG->getMachineNode(PPC::ANDIS_rec, dl, MVT::i32, Res,2327getI32Imm(ANDISMask, dl)),23280);23292330if (!ANDIVal)2331Res = ANDISVal;2332else if (!ANDISVal)2333Res = ANDIVal;2334else2335Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,2336ANDIVal, ANDISVal), 0);2337}23382339return Res.getNode();2340}23412342unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32,2343unsigned MaskStart, unsigned MaskEnd,2344bool IsIns) {2345// In the notation used by the instructions, 'start' and 'end' are reversed2346// because bits are counted from high to low order.2347unsigned InstMaskStart = 64 - MaskEnd - 1,2348InstMaskEnd = 64 - MaskStart - 1;23492350if (Repl32)2351return 1;23522353if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) ||2354InstMaskEnd == 63 - RLAmt)2355return 1;23562357return 2;2358}23592360// For 64-bit values, not all combinations of rotates and masks are2361// available. Produce one if it is available.2362SDValue SelectRotMask64(SDValue V, const SDLoc &dl, unsigned RLAmt,2363bool Repl32, unsigned MaskStart, unsigned MaskEnd,2364unsigned *InstCnt = nullptr) {2365// In the notation used by the instructions, 'start' and 'end' are reversed2366// because bits are counted from high to low order.2367unsigned InstMaskStart = 64 - MaskEnd - 1,2368InstMaskEnd = 64 - MaskStart - 1;23692370if (InstCnt) *InstCnt += 1;23712372if (Repl32) {2373// This rotation amount assumes that the lower 32 bits of the quantity2374// are replicated in the high 32 bits by the rotation operator (which is2375// done by rlwinm and friends).2376assert(InstMaskStart >= 32 && "Mask cannot start out of range");2377assert(InstMaskEnd >= 32 && "Mask cannot end out of range");2378SDValue Ops[] =2379{ ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),2380getI32Imm(InstMaskStart - 32, dl), getI32Imm(InstMaskEnd - 32, dl) };2381return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64,2382Ops), 0);2383}23842385if (InstMaskEnd == 63) {2386SDValue Ops[] =2387{ ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),2388getI32Imm(InstMaskStart, dl) };2389return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0);2390}23912392if (InstMaskStart == 0) {2393SDValue Ops[] =2394{ ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),2395getI32Imm(InstMaskEnd, dl) };2396return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0);2397}23982399if (InstMaskEnd == 63 - RLAmt) {2400SDValue Ops[] =2401{ ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),2402getI32Imm(InstMaskStart, dl) };2403return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0);2404}24052406// We cannot do this with a single instruction, so we'll use two. The2407// problem is that we're not free to choose both a rotation amount and mask2408// start and end independently. We can choose an arbitrary mask start and2409// end, but then the rotation amount is fixed. Rotation, however, can be2410// inverted, and so by applying an "inverse" rotation first, we can get the2411// desired result.2412if (InstCnt) *InstCnt += 1;24132414// The rotation mask for the second instruction must be MaskStart.2415unsigned RLAmt2 = MaskStart;2416// The first instruction must rotate V so that the overall rotation amount2417// is RLAmt.2418unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;2419if (RLAmt1)2420V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);2421return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd);2422}24232424// For 64-bit values, not all combinations of rotates and masks are2425// available. Produce a rotate-mask-and-insert if one is available.2426SDValue SelectRotMaskIns64(SDValue Base, SDValue V, const SDLoc &dl,2427unsigned RLAmt, bool Repl32, unsigned MaskStart,2428unsigned MaskEnd, unsigned *InstCnt = nullptr) {2429// In the notation used by the instructions, 'start' and 'end' are reversed2430// because bits are counted from high to low order.2431unsigned InstMaskStart = 64 - MaskEnd - 1,2432InstMaskEnd = 64 - MaskStart - 1;24332434if (InstCnt) *InstCnt += 1;24352436if (Repl32) {2437// This rotation amount assumes that the lower 32 bits of the quantity2438// are replicated in the high 32 bits by the rotation operator (which is2439// done by rlwinm and friends).2440assert(InstMaskStart >= 32 && "Mask cannot start out of range");2441assert(InstMaskEnd >= 32 && "Mask cannot end out of range");2442SDValue Ops[] =2443{ ExtendToInt64(Base, dl), ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),2444getI32Imm(InstMaskStart - 32, dl), getI32Imm(InstMaskEnd - 32, dl) };2445return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64,2446Ops), 0);2447}24482449if (InstMaskEnd == 63 - RLAmt) {2450SDValue Ops[] =2451{ ExtendToInt64(Base, dl), ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),2452getI32Imm(InstMaskStart, dl) };2453return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0);2454}24552456// We cannot do this with a single instruction, so we'll use two. The2457// problem is that we're not free to choose both a rotation amount and mask2458// start and end independently. We can choose an arbitrary mask start and2459// end, but then the rotation amount is fixed. Rotation, however, can be2460// inverted, and so by applying an "inverse" rotation first, we can get the2461// desired result.2462if (InstCnt) *InstCnt += 1;24632464// The rotation mask for the second instruction must be MaskStart.2465unsigned RLAmt2 = MaskStart;2466// The first instruction must rotate V so that the overall rotation amount2467// is RLAmt.2468unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;2469if (RLAmt1)2470V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);2471return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd);2472}24732474void SelectAndParts64(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {2475if (BPermRewriterNoMasking)2476return;24772478// The idea here is the same as in the 32-bit version, but with additional2479// complications from the fact that Repl32 might be true. Because we2480// aggressively convert bit groups to Repl32 form (which, for small2481// rotation factors, involves no other change), and then coalesce, it might2482// be the case that a single 64-bit masking operation could handle both2483// some Repl32 groups and some non-Repl32 groups. If converting to Repl322484// form allowed coalescing, then we must use a 32-bit rotaton in order to2485// completely capture the new combined bit group.24862487for (ValueRotInfo &VRI : ValueRotsVec) {2488uint64_t Mask = 0;24892490// We need to add to the mask all bits from the associated bit groups.2491// If Repl32 is false, we need to add bits from bit groups that have2492// Repl32 true, but are trivially convertable to Repl32 false. Such a2493// group is trivially convertable if it overlaps only with the lower 322494// bits, and the group has not been coalesced.2495auto MatchingBG = [VRI](const BitGroup &BG) {2496if (VRI.V != BG.V)2497return false;24982499unsigned EffRLAmt = BG.RLAmt;2500if (!VRI.Repl32 && BG.Repl32) {2501if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx &&2502!BG.Repl32Coalesced) {2503if (BG.Repl32CR)2504EffRLAmt += 32;2505} else {2506return false;2507}2508} else if (VRI.Repl32 != BG.Repl32) {2509return false;2510}25112512return VRI.RLAmt == EffRLAmt;2513};25142515for (auto &BG : BitGroups) {2516if (!MatchingBG(BG))2517continue;25182519if (BG.StartIdx <= BG.EndIdx) {2520for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i)2521Mask |= (UINT64_C(1) << i);2522} else {2523for (unsigned i = BG.StartIdx; i < Bits.size(); ++i)2524Mask |= (UINT64_C(1) << i);2525for (unsigned i = 0; i <= BG.EndIdx; ++i)2526Mask |= (UINT64_C(1) << i);2527}2528}25292530// We can use the 32-bit andi/andis technique if the mask does not2531// require any higher-order bits. This can save an instruction compared2532// to always using the general 64-bit technique.2533bool Use32BitInsts = isUInt<32>(Mask);2534// Compute the masks for andi/andis that would be necessary.2535unsigned ANDIMask = (Mask & UINT16_MAX),2536ANDISMask = (Mask >> 16) & UINT16_MAX;25372538bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask));25392540unsigned NumAndInsts = (unsigned) NeedsRotate +2541(unsigned) (bool) Res;2542unsigned NumOfSelectInsts = 0;2543selectI64Imm(CurDAG, dl, Mask, &NumOfSelectInsts);2544assert(NumOfSelectInsts > 0 && "Failed to select an i64 constant.");2545if (Use32BitInsts)2546NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) +2547(unsigned) (ANDIMask != 0 && ANDISMask != 0);2548else2549NumAndInsts += NumOfSelectInsts + /* and */ 1;25502551unsigned NumRLInsts = 0;2552bool FirstBG = true;2553bool MoreBG = false;2554for (auto &BG : BitGroups) {2555if (!MatchingBG(BG)) {2556MoreBG = true;2557continue;2558}2559NumRLInsts +=2560SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx,2561!FirstBG);2562FirstBG = false;2563}25642565LLVM_DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode()2566<< " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":")2567<< "\n\t\t\tisel using masking: " << NumAndInsts2568<< " using rotates: " << NumRLInsts << "\n");25692570// When we'd use andi/andis, we bias toward using the rotates (andi only2571// has a record form, and is cracked on POWER cores). However, when using2572// general 64-bit constant formation, bias toward the constant form,2573// because that exposes more opportunities for CSE.2574if (NumAndInsts > NumRLInsts)2575continue;2576// When merging multiple bit groups, instruction or is used.2577// But when rotate is used, rldimi can inert the rotated value into any2578// register, so instruction or can be avoided.2579if ((Use32BitInsts || MoreBG) && NumAndInsts == NumRLInsts)2580continue;25812582LLVM_DEBUG(dbgs() << "\t\t\t\tusing masking\n");25832584if (InstCnt) *InstCnt += NumAndInsts;25852586SDValue VRot;2587// We actually need to generate a rotation if we have a non-zero rotation2588// factor or, in the Repl32 case, if we care about any of the2589// higher-order replicated bits. In the latter case, we generate a mask2590// backward so that it actually includes the entire 64 bits.2591if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)))2592VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,2593VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63);2594else2595VRot = VRI.V;25962597SDValue TotalVal;2598if (Use32BitInsts) {2599assert((ANDIMask != 0 || ANDISMask != 0) &&2600"No set bits in mask when using 32-bit ands for 64-bit value");26012602SDValue ANDIVal, ANDISVal;2603if (ANDIMask != 0)2604ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI8_rec, dl, MVT::i64,2605ExtendToInt64(VRot, dl),2606getI32Imm(ANDIMask, dl)),26070);2608if (ANDISMask != 0)2609ANDISVal =2610SDValue(CurDAG->getMachineNode(PPC::ANDIS8_rec, dl, MVT::i64,2611ExtendToInt64(VRot, dl),2612getI32Imm(ANDISMask, dl)),26130);26142615if (!ANDIVal)2616TotalVal = ANDISVal;2617else if (!ANDISVal)2618TotalVal = ANDIVal;2619else2620TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,2621ExtendToInt64(ANDIVal, dl), ANDISVal), 0);2622} else {2623TotalVal = SDValue(selectI64Imm(CurDAG, dl, Mask), 0);2624TotalVal =2625SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,2626ExtendToInt64(VRot, dl), TotalVal),26270);2628}26292630if (!Res)2631Res = TotalVal;2632else2633Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,2634ExtendToInt64(Res, dl), TotalVal),26350);26362637// Now, remove all groups with this underlying value and rotation2638// factor.2639eraseMatchingBitGroups(MatchingBG);2640}2641}26422643// Instruction selection for the 64-bit case.2644SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {2645SDLoc dl(N);2646SDValue Res;26472648if (InstCnt) *InstCnt = 0;26492650// Take care of cases that should use andi/andis first.2651SelectAndParts64(dl, Res, InstCnt);26522653// If we've not yet selected a 'starting' instruction, and we have no zeros2654// to fill in, select the (Value, RLAmt) with the highest priority (largest2655// number of groups), and start with this rotated value.2656if ((!NeedMask || LateMask) && !Res) {2657// If we have both Repl32 groups and non-Repl32 groups, the non-Repl322658// groups will come first, and so the VRI representing the largest number2659// of groups might not be first (it might be the first Repl32 groups).2660unsigned MaxGroupsIdx = 0;2661if (!ValueRotsVec[0].Repl32) {2662for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i)2663if (ValueRotsVec[i].Repl32) {2664if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups)2665MaxGroupsIdx = i;2666break;2667}2668}26692670ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];2671bool NeedsRotate = false;2672if (VRI.RLAmt) {2673NeedsRotate = true;2674} else if (VRI.Repl32) {2675for (auto &BG : BitGroups) {2676if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt ||2677BG.Repl32 != VRI.Repl32)2678continue;26792680// We don't need a rotate if the bit group is confined to the lower2681// 32 bits.2682if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)2683continue;26842685NeedsRotate = true;2686break;2687}2688}26892690if (NeedsRotate)2691Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,2692VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63,2693InstCnt);2694else2695Res = VRI.V;26962697// Now, remove all groups with this underlying value and rotation factor.2698if (Res)2699eraseMatchingBitGroups([VRI](const BitGroup &BG) {2700return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt &&2701BG.Repl32 == VRI.Repl32;2702});2703}27042705// Because 64-bit rotates are more flexible than inserts, we might have a2706// preference regarding which one we do first (to save one instruction).2707if (!Res)2708for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {2709if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,2710false) <2711SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,2712true)) {2713if (I != BitGroups.begin()) {2714BitGroup BG = *I;2715BitGroups.erase(I);2716BitGroups.insert(BitGroups.begin(), BG);2717}27182719break;2720}2721}27222723// Insert the other groups (one at a time).2724for (auto &BG : BitGroups) {2725if (!Res)2726Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,2727BG.EndIdx, InstCnt);2728else2729Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,2730BG.StartIdx, BG.EndIdx, InstCnt);2731}27322733if (LateMask) {2734uint64_t Mask = getZerosMask();27352736// We can use the 32-bit andi/andis technique if the mask does not2737// require any higher-order bits. This can save an instruction compared2738// to always using the general 64-bit technique.2739bool Use32BitInsts = isUInt<32>(Mask);2740// Compute the masks for andi/andis that would be necessary.2741unsigned ANDIMask = (Mask & UINT16_MAX),2742ANDISMask = (Mask >> 16) & UINT16_MAX;27432744if (Use32BitInsts) {2745assert((ANDIMask != 0 || ANDISMask != 0) &&2746"No set bits in mask when using 32-bit ands for 64-bit value");27472748if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +2749(unsigned) (ANDISMask != 0) +2750(unsigned) (ANDIMask != 0 && ANDISMask != 0);27512752SDValue ANDIVal, ANDISVal;2753if (ANDIMask != 0)2754ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI8_rec, dl, MVT::i64,2755ExtendToInt64(Res, dl),2756getI32Imm(ANDIMask, dl)),27570);2758if (ANDISMask != 0)2759ANDISVal =2760SDValue(CurDAG->getMachineNode(PPC::ANDIS8_rec, dl, MVT::i64,2761ExtendToInt64(Res, dl),2762getI32Imm(ANDISMask, dl)),27630);27642765if (!ANDIVal)2766Res = ANDISVal;2767else if (!ANDISVal)2768Res = ANDIVal;2769else2770Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,2771ExtendToInt64(ANDIVal, dl), ANDISVal), 0);2772} else {2773unsigned NumOfSelectInsts = 0;2774SDValue MaskVal =2775SDValue(selectI64Imm(CurDAG, dl, Mask, &NumOfSelectInsts), 0);2776Res = SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,2777ExtendToInt64(Res, dl), MaskVal),27780);2779if (InstCnt)2780*InstCnt += NumOfSelectInsts + /* and */ 1;2781}2782}27832784return Res.getNode();2785}27862787SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {2788// Fill in BitGroups.2789collectBitGroups(LateMask);2790if (BitGroups.empty())2791return nullptr;27922793// For 64-bit values, figure out when we can use 32-bit instructions.2794if (Bits.size() == 64)2795assignRepl32BitGroups();27962797// Fill in ValueRotsVec.2798collectValueRotInfo();27992800if (Bits.size() == 32) {2801return Select32(N, LateMask, InstCnt);2802} else {2803assert(Bits.size() == 64 && "Not 64 bits here?");2804return Select64(N, LateMask, InstCnt);2805}28062807return nullptr;2808}28092810void eraseMatchingBitGroups(function_ref<bool(const BitGroup &)> F) {2811erase_if(BitGroups, F);2812}28132814SmallVector<ValueBit, 64> Bits;28152816bool NeedMask = false;2817SmallVector<unsigned, 64> RLAmt;28182819SmallVector<BitGroup, 16> BitGroups;28202821DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;2822SmallVector<ValueRotInfo, 16> ValueRotsVec;28232824SelectionDAG *CurDAG = nullptr;28252826public:2827BitPermutationSelector(SelectionDAG *DAG)2828: CurDAG(DAG) {}28292830// Here we try to match complex bit permutations into a set of2831// rotate-and-shift/shift/and/or instructions, using a set of heuristics2832// known to produce optimal code for common cases (like i32 byte swapping).2833SDNode *Select(SDNode *N) {2834Memoizer.clear();2835auto Result =2836getValueBits(SDValue(N, 0), N->getValueType(0).getSizeInBits());2837if (!Result.first)2838return nullptr;2839Bits = std::move(*Result.second);28402841LLVM_DEBUG(dbgs() << "Considering bit-permutation-based instruction"2842" selection for: ");2843LLVM_DEBUG(N->dump(CurDAG));28442845// Fill it RLAmt and set NeedMask.2846computeRotationAmounts();28472848if (!NeedMask)2849return Select(N, false);28502851// We currently have two techniques for handling results with zeros: early2852// masking (the default) and late masking. Late masking is sometimes more2853// efficient, but because the structure of the bit groups is different, it2854// is hard to tell without generating both and comparing the results. With2855// late masking, we ignore zeros in the resulting value when inserting each2856// set of bit groups, and then mask in the zeros at the end. With early2857// masking, we only insert the non-zero parts of the result at every step.28582859unsigned InstCnt = 0, InstCntLateMask = 0;2860LLVM_DEBUG(dbgs() << "\tEarly masking:\n");2861SDNode *RN = Select(N, false, &InstCnt);2862LLVM_DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n");28632864LLVM_DEBUG(dbgs() << "\tLate masking:\n");2865SDNode *RNLM = Select(N, true, &InstCntLateMask);2866LLVM_DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask2867<< " instructions\n");28682869if (InstCnt <= InstCntLateMask) {2870LLVM_DEBUG(dbgs() << "\tUsing early-masking for isel\n");2871return RN;2872}28732874LLVM_DEBUG(dbgs() << "\tUsing late-masking for isel\n");2875return RNLM;2876}2877};28782879class IntegerCompareEliminator {2880SelectionDAG *CurDAG;2881PPCDAGToDAGISel *S;2882// Conversion type for interpreting results of a 32-bit instruction as2883// a 64-bit value or vice versa.2884enum ExtOrTruncConversion { Ext, Trunc };28852886// Modifiers to guide how an ISD::SETCC node's result is to be computed2887// in a GPR.2888// ZExtOrig - use the original condition code, zero-extend value2889// ZExtInvert - invert the condition code, zero-extend value2890// SExtOrig - use the original condition code, sign-extend value2891// SExtInvert - invert the condition code, sign-extend value2892enum SetccInGPROpts { ZExtOrig, ZExtInvert, SExtOrig, SExtInvert };28932894// Comparisons against zero to emit GPR code sequences for. Each of these2895// sequences may need to be emitted for two or more equivalent patterns.2896// For example (a >= 0) == (a > -1). The direction of the comparison (</>)2897// matters as well as the extension type: sext (-1/0), zext (1/0).2898// GEZExt - (zext (LHS >= 0))2899// GESExt - (sext (LHS >= 0))2900// LEZExt - (zext (LHS <= 0))2901// LESExt - (sext (LHS <= 0))2902enum ZeroCompare { GEZExt, GESExt, LEZExt, LESExt };29032904SDNode *tryEXTEND(SDNode *N);2905SDNode *tryLogicOpOfCompares(SDNode *N);2906SDValue computeLogicOpInGPR(SDValue LogicOp);2907SDValue signExtendInputIfNeeded(SDValue Input);2908SDValue zeroExtendInputIfNeeded(SDValue Input);2909SDValue addExtOrTrunc(SDValue NatWidthRes, ExtOrTruncConversion Conv);2910SDValue getCompoundZeroComparisonInGPR(SDValue LHS, SDLoc dl,2911ZeroCompare CmpTy);2912SDValue get32BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,2913int64_t RHSValue, SDLoc dl);2914SDValue get32BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,2915int64_t RHSValue, SDLoc dl);2916SDValue get64BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,2917int64_t RHSValue, SDLoc dl);2918SDValue get64BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,2919int64_t RHSValue, SDLoc dl);2920SDValue getSETCCInGPR(SDValue Compare, SetccInGPROpts ConvOpts);29212922public:2923IntegerCompareEliminator(SelectionDAG *DAG,2924PPCDAGToDAGISel *Sel) : CurDAG(DAG), S(Sel) {2925assert(CurDAG->getTargetLoweringInfo()2926.getPointerTy(CurDAG->getDataLayout()).getSizeInBits() == 64 &&2927"Only expecting to use this on 64 bit targets.");2928}2929SDNode *Select(SDNode *N) {2930if (CmpInGPR == ICGPR_None)2931return nullptr;2932switch (N->getOpcode()) {2933default: break;2934case ISD::ZERO_EXTEND:2935if (CmpInGPR == ICGPR_Sext || CmpInGPR == ICGPR_SextI32 ||2936CmpInGPR == ICGPR_SextI64)2937return nullptr;2938[[fallthrough]];2939case ISD::SIGN_EXTEND:2940if (CmpInGPR == ICGPR_Zext || CmpInGPR == ICGPR_ZextI32 ||2941CmpInGPR == ICGPR_ZextI64)2942return nullptr;2943return tryEXTEND(N);2944case ISD::AND:2945case ISD::OR:2946case ISD::XOR:2947return tryLogicOpOfCompares(N);2948}2949return nullptr;2950}2951};29522953// The obvious case for wanting to keep the value in a GPR. Namely, the2954// result of the comparison is actually needed in a GPR.2955SDNode *IntegerCompareEliminator::tryEXTEND(SDNode *N) {2956assert((N->getOpcode() == ISD::ZERO_EXTEND ||2957N->getOpcode() == ISD::SIGN_EXTEND) &&2958"Expecting a zero/sign extend node!");2959SDValue WideRes;2960// If we are zero-extending the result of a logical operation on i12961// values, we can keep the values in GPRs.2962if (ISD::isBitwiseLogicOp(N->getOperand(0).getOpcode()) &&2963N->getOperand(0).getValueType() == MVT::i1 &&2964N->getOpcode() == ISD::ZERO_EXTEND)2965WideRes = computeLogicOpInGPR(N->getOperand(0));2966else if (N->getOperand(0).getOpcode() != ISD::SETCC)2967return nullptr;2968else2969WideRes =2970getSETCCInGPR(N->getOperand(0),2971N->getOpcode() == ISD::SIGN_EXTEND ?2972SetccInGPROpts::SExtOrig : SetccInGPROpts::ZExtOrig);29732974if (!WideRes)2975return nullptr;29762977SDLoc dl(N);2978bool Input32Bit = WideRes.getValueType() == MVT::i32;2979bool Output32Bit = N->getValueType(0) == MVT::i32;29802981NumSextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 1 : 0;2982NumZextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 0 : 1;29832984SDValue ConvOp = WideRes;2985if (Input32Bit != Output32Bit)2986ConvOp = addExtOrTrunc(WideRes, Input32Bit ? ExtOrTruncConversion::Ext :2987ExtOrTruncConversion::Trunc);2988return ConvOp.getNode();2989}29902991// Attempt to perform logical operations on the results of comparisons while2992// keeping the values in GPRs. Without doing so, these would end up being2993// lowered to CR-logical operations which suffer from significant latency and2994// low ILP.2995SDNode *IntegerCompareEliminator::tryLogicOpOfCompares(SDNode *N) {2996if (N->getValueType(0) != MVT::i1)2997return nullptr;2998assert(ISD::isBitwiseLogicOp(N->getOpcode()) &&2999"Expected a logic operation on setcc results.");3000SDValue LoweredLogical = computeLogicOpInGPR(SDValue(N, 0));3001if (!LoweredLogical)3002return nullptr;30033004SDLoc dl(N);3005bool IsBitwiseNegate = LoweredLogical.getMachineOpcode() == PPC::XORI8;3006unsigned SubRegToExtract = IsBitwiseNegate ? PPC::sub_eq : PPC::sub_gt;3007SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);3008SDValue LHS = LoweredLogical.getOperand(0);3009SDValue RHS = LoweredLogical.getOperand(1);3010SDValue WideOp;3011SDValue OpToConvToRecForm;30123013// Look through any 32-bit to 64-bit implicit extend nodes to find the3014// opcode that is input to the XORI.3015if (IsBitwiseNegate &&3016LoweredLogical.getOperand(0).getMachineOpcode() == PPC::INSERT_SUBREG)3017OpToConvToRecForm = LoweredLogical.getOperand(0).getOperand(1);3018else if (IsBitwiseNegate)3019// If the input to the XORI isn't an extension, that's what we're after.3020OpToConvToRecForm = LoweredLogical.getOperand(0);3021else3022// If this is not an XORI, it is a reg-reg logical op and we can convert3023// it to record-form.3024OpToConvToRecForm = LoweredLogical;30253026// Get the record-form version of the node we're looking to use to get the3027// CR result from.3028uint16_t NonRecOpc = OpToConvToRecForm.getMachineOpcode();3029int NewOpc = PPCInstrInfo::getRecordFormOpcode(NonRecOpc);30303031// Convert the right node to record-form. This is either the logical we're3032// looking at or it is the input node to the negation (if we're looking at3033// a bitwise negation).3034if (NewOpc != -1 && IsBitwiseNegate) {3035// The input to the XORI has a record-form. Use it.3036assert(LoweredLogical.getConstantOperandVal(1) == 1 &&3037"Expected a PPC::XORI8 only for bitwise negation.");3038// Emit the record-form instruction.3039std::vector<SDValue> Ops;3040for (int i = 0, e = OpToConvToRecForm.getNumOperands(); i < e; i++)3041Ops.push_back(OpToConvToRecForm.getOperand(i));30423043WideOp =3044SDValue(CurDAG->getMachineNode(NewOpc, dl,3045OpToConvToRecForm.getValueType(),3046MVT::Glue, Ops), 0);3047} else {3048assert((NewOpc != -1 || !IsBitwiseNegate) &&3049"No record form available for AND8/OR8/XOR8?");3050WideOp =3051SDValue(CurDAG->getMachineNode(NewOpc == -1 ? PPC::ANDI8_rec : NewOpc,3052dl, MVT::i64, MVT::Glue, LHS, RHS),30530);3054}30553056// Select this node to a single bit from CR0 set by the record-form node3057// just created. For bitwise negation, use the EQ bit which is the equivalent3058// of negating the result (i.e. it is a bit set when the result of the3059// operation is zero).3060SDValue SRIdxVal =3061CurDAG->getTargetConstant(SubRegToExtract, dl, MVT::i32);3062SDValue CRBit =3063SDValue(CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl,3064MVT::i1, CR0Reg, SRIdxVal,3065WideOp.getValue(1)), 0);3066return CRBit.getNode();3067}30683069// Lower a logical operation on i1 values into a GPR sequence if possible.3070// The result can be kept in a GPR if requested.3071// Three types of inputs can be handled:3072// - SETCC3073// - TRUNCATE3074// - Logical operation (AND/OR/XOR)3075// There is also a special case that is handled (namely a complement operation3076// achieved with xor %a, -1).3077SDValue IntegerCompareEliminator::computeLogicOpInGPR(SDValue LogicOp) {3078assert(ISD::isBitwiseLogicOp(LogicOp.getOpcode()) &&3079"Can only handle logic operations here.");3080assert(LogicOp.getValueType() == MVT::i1 &&3081"Can only handle logic operations on i1 values here.");3082SDLoc dl(LogicOp);3083SDValue LHS, RHS;30843085// Special case: xor %a, -13086bool IsBitwiseNegation = isBitwiseNot(LogicOp);30873088// Produces a GPR sequence for each operand of the binary logic operation.3089// For SETCC, it produces the respective comparison, for TRUNCATE it truncates3090// the value in a GPR and for logic operations, it will recursively produce3091// a GPR sequence for the operation.3092auto getLogicOperand = [&] (SDValue Operand) -> SDValue {3093unsigned OperandOpcode = Operand.getOpcode();3094if (OperandOpcode == ISD::SETCC)3095return getSETCCInGPR(Operand, SetccInGPROpts::ZExtOrig);3096else if (OperandOpcode == ISD::TRUNCATE) {3097SDValue InputOp = Operand.getOperand(0);3098EVT InVT = InputOp.getValueType();3099return SDValue(CurDAG->getMachineNode(InVT == MVT::i32 ? PPC::RLDICL_32 :3100PPC::RLDICL, dl, InVT, InputOp,3101S->getI64Imm(0, dl),3102S->getI64Imm(63, dl)), 0);3103} else if (ISD::isBitwiseLogicOp(OperandOpcode))3104return computeLogicOpInGPR(Operand);3105return SDValue();3106};3107LHS = getLogicOperand(LogicOp.getOperand(0));3108RHS = getLogicOperand(LogicOp.getOperand(1));31093110// If a GPR sequence can't be produced for the LHS we can't proceed.3111// Not producing a GPR sequence for the RHS is only a problem if this isn't3112// a bitwise negation operation.3113if (!LHS || (!RHS && !IsBitwiseNegation))3114return SDValue();31153116NumLogicOpsOnComparison++;31173118// We will use the inputs as 64-bit values.3119if (LHS.getValueType() == MVT::i32)3120LHS = addExtOrTrunc(LHS, ExtOrTruncConversion::Ext);3121if (!IsBitwiseNegation && RHS.getValueType() == MVT::i32)3122RHS = addExtOrTrunc(RHS, ExtOrTruncConversion::Ext);31233124unsigned NewOpc;3125switch (LogicOp.getOpcode()) {3126default: llvm_unreachable("Unknown logic operation.");3127case ISD::AND: NewOpc = PPC::AND8; break;3128case ISD::OR: NewOpc = PPC::OR8; break;3129case ISD::XOR: NewOpc = PPC::XOR8; break;3130}31313132if (IsBitwiseNegation) {3133RHS = S->getI64Imm(1, dl);3134NewOpc = PPC::XORI8;3135}31363137return SDValue(CurDAG->getMachineNode(NewOpc, dl, MVT::i64, LHS, RHS), 0);31383139}31403141/// If the value isn't guaranteed to be sign-extended to 64-bits, extend it.3142/// Otherwise just reinterpret it as a 64-bit value.3143/// Useful when emitting comparison code for 32-bit values without using3144/// the compare instruction (which only considers the lower 32-bits).3145SDValue IntegerCompareEliminator::signExtendInputIfNeeded(SDValue Input) {3146assert(Input.getValueType() == MVT::i32 &&3147"Can only sign-extend 32-bit values here.");3148unsigned Opc = Input.getOpcode();31493150// The value was sign extended and then truncated to 32-bits. No need to3151// sign extend it again.3152if (Opc == ISD::TRUNCATE &&3153(Input.getOperand(0).getOpcode() == ISD::AssertSext ||3154Input.getOperand(0).getOpcode() == ISD::SIGN_EXTEND))3155return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);31563157LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input);3158// The input is a sign-extending load. All ppc sign-extending loads3159// sign-extend to the full 64-bits.3160if (InputLoad && InputLoad->getExtensionType() == ISD::SEXTLOAD)3161return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);31623163ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input);3164// We don't sign-extend constants.3165if (InputConst)3166return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);31673168SDLoc dl(Input);3169SignExtensionsAdded++;3170return SDValue(CurDAG->getMachineNode(PPC::EXTSW_32_64, dl,3171MVT::i64, Input), 0);3172}31733174/// If the value isn't guaranteed to be zero-extended to 64-bits, extend it.3175/// Otherwise just reinterpret it as a 64-bit value.3176/// Useful when emitting comparison code for 32-bit values without using3177/// the compare instruction (which only considers the lower 32-bits).3178SDValue IntegerCompareEliminator::zeroExtendInputIfNeeded(SDValue Input) {3179assert(Input.getValueType() == MVT::i32 &&3180"Can only zero-extend 32-bit values here.");3181unsigned Opc = Input.getOpcode();31823183// The only condition under which we can omit the actual extend instruction:3184// - The value is a positive constant3185// - The value comes from a load that isn't a sign-extending load3186// An ISD::TRUNCATE needs to be zero-extended unless it is fed by a zext.3187bool IsTruncateOfZExt = Opc == ISD::TRUNCATE &&3188(Input.getOperand(0).getOpcode() == ISD::AssertZext ||3189Input.getOperand(0).getOpcode() == ISD::ZERO_EXTEND);3190if (IsTruncateOfZExt)3191return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);31923193ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input);3194if (InputConst && InputConst->getSExtValue() >= 0)3195return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);31963197LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input);3198// The input is a load that doesn't sign-extend (it will be zero-extended).3199if (InputLoad && InputLoad->getExtensionType() != ISD::SEXTLOAD)3200return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);32013202// None of the above, need to zero-extend.3203SDLoc dl(Input);3204ZeroExtensionsAdded++;3205return SDValue(CurDAG->getMachineNode(PPC::RLDICL_32_64, dl, MVT::i64, Input,3206S->getI64Imm(0, dl),3207S->getI64Imm(32, dl)), 0);3208}32093210// Handle a 32-bit value in a 64-bit register and vice-versa. These are of3211// course not actual zero/sign extensions that will generate machine code,3212// they're just a way to reinterpret a 32 bit value in a register as a3213// 64 bit value and vice-versa.3214SDValue IntegerCompareEliminator::addExtOrTrunc(SDValue NatWidthRes,3215ExtOrTruncConversion Conv) {3216SDLoc dl(NatWidthRes);32173218// For reinterpreting 32-bit values as 64 bit values, we generate3219// INSERT_SUBREG IMPLICIT_DEF:i64, <input>, TargetConstant:i32<1>3220if (Conv == ExtOrTruncConversion::Ext) {3221SDValue ImDef(CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl, MVT::i64), 0);3222SDValue SubRegIdx =3223CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);3224return SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, MVT::i64,3225ImDef, NatWidthRes, SubRegIdx), 0);3226}32273228assert(Conv == ExtOrTruncConversion::Trunc &&3229"Unknown convertion between 32 and 64 bit values.");3230// For reinterpreting 64-bit values as 32-bit values, we just need to3231// EXTRACT_SUBREG (i.e. extract the low word).3232SDValue SubRegIdx =3233CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);3234return SDValue(CurDAG->getMachineNode(PPC::EXTRACT_SUBREG, dl, MVT::i32,3235NatWidthRes, SubRegIdx), 0);3236}32373238// Produce a GPR sequence for compound comparisons (<=, >=) against zero.3239// Handle both zero-extensions and sign-extensions.3240SDValue3241IntegerCompareEliminator::getCompoundZeroComparisonInGPR(SDValue LHS, SDLoc dl,3242ZeroCompare CmpTy) {3243EVT InVT = LHS.getValueType();3244bool Is32Bit = InVT == MVT::i32;3245SDValue ToExtend;32463247// Produce the value that needs to be either zero or sign extended.3248switch (CmpTy) {3249case ZeroCompare::GEZExt:3250case ZeroCompare::GESExt:3251ToExtend = SDValue(CurDAG->getMachineNode(Is32Bit ? PPC::NOR : PPC::NOR8,3252dl, InVT, LHS, LHS), 0);3253break;3254case ZeroCompare::LEZExt:3255case ZeroCompare::LESExt: {3256if (Is32Bit) {3257// Upper 32 bits cannot be undefined for this sequence.3258LHS = signExtendInputIfNeeded(LHS);3259SDValue Neg =3260SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0);3261ToExtend =3262SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,3263Neg, S->getI64Imm(1, dl),3264S->getI64Imm(63, dl)), 0);3265} else {3266SDValue Addi =3267SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS,3268S->getI64Imm(~0ULL, dl)), 0);3269ToExtend = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,3270Addi, LHS), 0);3271}3272break;3273}3274}32753276// For 64-bit sequences, the extensions are the same for the GE/LE cases.3277if (!Is32Bit &&3278(CmpTy == ZeroCompare::GEZExt || CmpTy == ZeroCompare::LEZExt))3279return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,3280ToExtend, S->getI64Imm(1, dl),3281S->getI64Imm(63, dl)), 0);3282if (!Is32Bit &&3283(CmpTy == ZeroCompare::GESExt || CmpTy == ZeroCompare::LESExt))3284return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, ToExtend,3285S->getI64Imm(63, dl)), 0);32863287assert(Is32Bit && "Should have handled the 32-bit sequences above.");3288// For 32-bit sequences, the extensions differ between GE/LE cases.3289switch (CmpTy) {3290case ZeroCompare::GEZExt: {3291SDValue ShiftOps[] = { ToExtend, S->getI32Imm(1, dl), S->getI32Imm(31, dl),3292S->getI32Imm(31, dl) };3293return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,3294ShiftOps), 0);3295}3296case ZeroCompare::GESExt:3297return SDValue(CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, ToExtend,3298S->getI32Imm(31, dl)), 0);3299case ZeroCompare::LEZExt:3300return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, ToExtend,3301S->getI32Imm(1, dl)), 0);3302case ZeroCompare::LESExt:3303return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, ToExtend,3304S->getI32Imm(-1, dl)), 0);3305}33063307// The above case covers all the enumerators so it can't have a default clause3308// to avoid compiler warnings.3309llvm_unreachable("Unknown zero-comparison type.");3310}33113312/// Produces a zero-extended result of comparing two 32-bit values according to3313/// the passed condition code.3314SDValue3315IntegerCompareEliminator::get32BitZExtCompare(SDValue LHS, SDValue RHS,3316ISD::CondCode CC,3317int64_t RHSValue, SDLoc dl) {3318if (CmpInGPR == ICGPR_I64 || CmpInGPR == ICGPR_SextI64 ||3319CmpInGPR == ICGPR_ZextI64 || CmpInGPR == ICGPR_Sext)3320return SDValue();3321bool IsRHSZero = RHSValue == 0;3322bool IsRHSOne = RHSValue == 1;3323bool IsRHSNegOne = RHSValue == -1LL;3324switch (CC) {3325default: return SDValue();3326case ISD::SETEQ: {3327// (zext (setcc %a, %b, seteq)) -> (lshr (cntlzw (xor %a, %b)), 5)3328// (zext (setcc %a, 0, seteq)) -> (lshr (cntlzw %a), 5)3329SDValue Xor = IsRHSZero ? LHS :3330SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);3331SDValue Clz =3332SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);3333SDValue ShiftOps[] = { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl),3334S->getI32Imm(31, dl) };3335return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,3336ShiftOps), 0);3337}3338case ISD::SETNE: {3339// (zext (setcc %a, %b, setne)) -> (xor (lshr (cntlzw (xor %a, %b)), 5), 1)3340// (zext (setcc %a, 0, setne)) -> (xor (lshr (cntlzw %a), 5), 1)3341SDValue Xor = IsRHSZero ? LHS :3342SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);3343SDValue Clz =3344SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);3345SDValue ShiftOps[] = { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl),3346S->getI32Imm(31, dl) };3347SDValue Shift =3348SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0);3349return SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift,3350S->getI32Imm(1, dl)), 0);3351}3352case ISD::SETGE: {3353// (zext (setcc %a, %b, setge)) -> (xor (lshr (sub %a, %b), 63), 1)3354// (zext (setcc %a, 0, setge)) -> (lshr (~ %a), 31)3355if(IsRHSZero)3356return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);33573358// Not a special case (i.e. RHS == 0). Handle (%a >= %b) as (%b <= %a)3359// by swapping inputs and falling through.3360std::swap(LHS, RHS);3361ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);3362IsRHSZero = RHSConst && RHSConst->isZero();3363[[fallthrough]];3364}3365case ISD::SETLE: {3366if (CmpInGPR == ICGPR_NonExtIn)3367return SDValue();3368// (zext (setcc %a, %b, setle)) -> (xor (lshr (sub %b, %a), 63), 1)3369// (zext (setcc %a, 0, setle)) -> (xor (lshr (- %a), 63), 1)3370if(IsRHSZero) {3371if (CmpInGPR == ICGPR_NonExtIn)3372return SDValue();3373return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);3374}33753376// The upper 32-bits of the register can't be undefined for this sequence.3377LHS = signExtendInputIfNeeded(LHS);3378RHS = signExtendInputIfNeeded(RHS);3379SDValue Sub =3380SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0);3381SDValue Shift =3382SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Sub,3383S->getI64Imm(1, dl), S->getI64Imm(63, dl)),33840);3385return3386SDValue(CurDAG->getMachineNode(PPC::XORI8, dl,3387MVT::i64, Shift, S->getI32Imm(1, dl)), 0);3388}3389case ISD::SETGT: {3390// (zext (setcc %a, %b, setgt)) -> (lshr (sub %b, %a), 63)3391// (zext (setcc %a, -1, setgt)) -> (lshr (~ %a), 31)3392// (zext (setcc %a, 0, setgt)) -> (lshr (- %a), 63)3393// Handle SETLT -1 (which is equivalent to SETGE 0).3394if (IsRHSNegOne)3395return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);33963397if (IsRHSZero) {3398if (CmpInGPR == ICGPR_NonExtIn)3399return SDValue();3400// The upper 32-bits of the register can't be undefined for this sequence.3401LHS = signExtendInputIfNeeded(LHS);3402RHS = signExtendInputIfNeeded(RHS);3403SDValue Neg =3404SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0);3405return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,3406Neg, S->getI32Imm(1, dl), S->getI32Imm(63, dl)), 0);3407}3408// Not a special case (i.e. RHS == 0 or RHS == -1). Handle (%a > %b) as3409// (%b < %a) by swapping inputs and falling through.3410std::swap(LHS, RHS);3411ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);3412IsRHSZero = RHSConst && RHSConst->isZero();3413IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;3414[[fallthrough]];3415}3416case ISD::SETLT: {3417// (zext (setcc %a, %b, setlt)) -> (lshr (sub %a, %b), 63)3418// (zext (setcc %a, 1, setlt)) -> (xor (lshr (- %a), 63), 1)3419// (zext (setcc %a, 0, setlt)) -> (lshr %a, 31)3420// Handle SETLT 1 (which is equivalent to SETLE 0).3421if (IsRHSOne) {3422if (CmpInGPR == ICGPR_NonExtIn)3423return SDValue();3424return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);3425}34263427if (IsRHSZero) {3428SDValue ShiftOps[] = { LHS, S->getI32Imm(1, dl), S->getI32Imm(31, dl),3429S->getI32Imm(31, dl) };3430return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,3431ShiftOps), 0);3432}34333434if (CmpInGPR == ICGPR_NonExtIn)3435return SDValue();3436// The upper 32-bits of the register can't be undefined for this sequence.3437LHS = signExtendInputIfNeeded(LHS);3438RHS = signExtendInputIfNeeded(RHS);3439SDValue SUBFNode =3440SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);3441return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,3442SUBFNode, S->getI64Imm(1, dl),3443S->getI64Imm(63, dl)), 0);3444}3445case ISD::SETUGE:3446// (zext (setcc %a, %b, setuge)) -> (xor (lshr (sub %b, %a), 63), 1)3447// (zext (setcc %a, %b, setule)) -> (xor (lshr (sub %a, %b), 63), 1)3448std::swap(LHS, RHS);3449[[fallthrough]];3450case ISD::SETULE: {3451if (CmpInGPR == ICGPR_NonExtIn)3452return SDValue();3453// The upper 32-bits of the register can't be undefined for this sequence.3454LHS = zeroExtendInputIfNeeded(LHS);3455RHS = zeroExtendInputIfNeeded(RHS);3456SDValue Subtract =3457SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0);3458SDValue SrdiNode =3459SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,3460Subtract, S->getI64Imm(1, dl),3461S->getI64Imm(63, dl)), 0);3462return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, SrdiNode,3463S->getI32Imm(1, dl)), 0);3464}3465case ISD::SETUGT:3466// (zext (setcc %a, %b, setugt)) -> (lshr (sub %b, %a), 63)3467// (zext (setcc %a, %b, setult)) -> (lshr (sub %a, %b), 63)3468std::swap(LHS, RHS);3469[[fallthrough]];3470case ISD::SETULT: {3471if (CmpInGPR == ICGPR_NonExtIn)3472return SDValue();3473// The upper 32-bits of the register can't be undefined for this sequence.3474LHS = zeroExtendInputIfNeeded(LHS);3475RHS = zeroExtendInputIfNeeded(RHS);3476SDValue Subtract =3477SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);3478return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,3479Subtract, S->getI64Imm(1, dl),3480S->getI64Imm(63, dl)), 0);3481}3482}3483}34843485/// Produces a sign-extended result of comparing two 32-bit values according to3486/// the passed condition code.3487SDValue3488IntegerCompareEliminator::get32BitSExtCompare(SDValue LHS, SDValue RHS,3489ISD::CondCode CC,3490int64_t RHSValue, SDLoc dl) {3491if (CmpInGPR == ICGPR_I64 || CmpInGPR == ICGPR_SextI64 ||3492CmpInGPR == ICGPR_ZextI64 || CmpInGPR == ICGPR_Zext)3493return SDValue();3494bool IsRHSZero = RHSValue == 0;3495bool IsRHSOne = RHSValue == 1;3496bool IsRHSNegOne = RHSValue == -1LL;34973498switch (CC) {3499default: return SDValue();3500case ISD::SETEQ: {3501// (sext (setcc %a, %b, seteq)) ->3502// (ashr (shl (ctlz (xor %a, %b)), 58), 63)3503// (sext (setcc %a, 0, seteq)) ->3504// (ashr (shl (ctlz %a), 58), 63)3505SDValue CountInput = IsRHSZero ? LHS :3506SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);3507SDValue Cntlzw =3508SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, CountInput), 0);3509SDValue SHLOps[] = { Cntlzw, S->getI32Imm(27, dl),3510S->getI32Imm(5, dl), S->getI32Imm(31, dl) };3511SDValue Slwi =3512SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, SHLOps), 0);3513return SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Slwi), 0);3514}3515case ISD::SETNE: {3516// Bitwise xor the operands, count leading zeros, shift right by 5 bits and3517// flip the bit, finally take 2's complement.3518// (sext (setcc %a, %b, setne)) ->3519// (neg (xor (lshr (ctlz (xor %a, %b)), 5), 1))3520// Same as above, but the first xor is not needed.3521// (sext (setcc %a, 0, setne)) ->3522// (neg (xor (lshr (ctlz %a), 5), 1))3523SDValue Xor = IsRHSZero ? LHS :3524SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);3525SDValue Clz =3526SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);3527SDValue ShiftOps[] =3528{ Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl), S->getI32Imm(31, dl) };3529SDValue Shift =3530SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0);3531SDValue Xori =3532SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift,3533S->getI32Imm(1, dl)), 0);3534return SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Xori), 0);3535}3536case ISD::SETGE: {3537// (sext (setcc %a, %b, setge)) -> (add (lshr (sub %a, %b), 63), -1)3538// (sext (setcc %a, 0, setge)) -> (ashr (~ %a), 31)3539if (IsRHSZero)3540return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);35413542// Not a special case (i.e. RHS == 0). Handle (%a >= %b) as (%b <= %a)3543// by swapping inputs and falling through.3544std::swap(LHS, RHS);3545ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);3546IsRHSZero = RHSConst && RHSConst->isZero();3547[[fallthrough]];3548}3549case ISD::SETLE: {3550if (CmpInGPR == ICGPR_NonExtIn)3551return SDValue();3552// (sext (setcc %a, %b, setge)) -> (add (lshr (sub %b, %a), 63), -1)3553// (sext (setcc %a, 0, setle)) -> (add (lshr (- %a), 63), -1)3554if (IsRHSZero)3555return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);35563557// The upper 32-bits of the register can't be undefined for this sequence.3558LHS = signExtendInputIfNeeded(LHS);3559RHS = signExtendInputIfNeeded(RHS);3560SDValue SUBFNode =3561SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, MVT::Glue,3562LHS, RHS), 0);3563SDValue Srdi =3564SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,3565SUBFNode, S->getI64Imm(1, dl),3566S->getI64Imm(63, dl)), 0);3567return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, Srdi,3568S->getI32Imm(-1, dl)), 0);3569}3570case ISD::SETGT: {3571// (sext (setcc %a, %b, setgt)) -> (ashr (sub %b, %a), 63)3572// (sext (setcc %a, -1, setgt)) -> (ashr (~ %a), 31)3573// (sext (setcc %a, 0, setgt)) -> (ashr (- %a), 63)3574if (IsRHSNegOne)3575return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);3576if (IsRHSZero) {3577if (CmpInGPR == ICGPR_NonExtIn)3578return SDValue();3579// The upper 32-bits of the register can't be undefined for this sequence.3580LHS = signExtendInputIfNeeded(LHS);3581RHS = signExtendInputIfNeeded(RHS);3582SDValue Neg =3583SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0);3584return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, Neg,3585S->getI64Imm(63, dl)), 0);3586}3587// Not a special case (i.e. RHS == 0 or RHS == -1). Handle (%a > %b) as3588// (%b < %a) by swapping inputs and falling through.3589std::swap(LHS, RHS);3590ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);3591IsRHSZero = RHSConst && RHSConst->isZero();3592IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;3593[[fallthrough]];3594}3595case ISD::SETLT: {3596// (sext (setcc %a, %b, setgt)) -> (ashr (sub %a, %b), 63)3597// (sext (setcc %a, 1, setgt)) -> (add (lshr (- %a), 63), -1)3598// (sext (setcc %a, 0, setgt)) -> (ashr %a, 31)3599if (IsRHSOne) {3600if (CmpInGPR == ICGPR_NonExtIn)3601return SDValue();3602return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);3603}3604if (IsRHSZero)3605return SDValue(CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, LHS,3606S->getI32Imm(31, dl)), 0);36073608if (CmpInGPR == ICGPR_NonExtIn)3609return SDValue();3610// The upper 32-bits of the register can't be undefined for this sequence.3611LHS = signExtendInputIfNeeded(LHS);3612RHS = signExtendInputIfNeeded(RHS);3613SDValue SUBFNode =3614SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);3615return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,3616SUBFNode, S->getI64Imm(63, dl)), 0);3617}3618case ISD::SETUGE:3619// (sext (setcc %a, %b, setuge)) -> (add (lshr (sub %a, %b), 63), -1)3620// (sext (setcc %a, %b, setule)) -> (add (lshr (sub %b, %a), 63), -1)3621std::swap(LHS, RHS);3622[[fallthrough]];3623case ISD::SETULE: {3624if (CmpInGPR == ICGPR_NonExtIn)3625return SDValue();3626// The upper 32-bits of the register can't be undefined for this sequence.3627LHS = zeroExtendInputIfNeeded(LHS);3628RHS = zeroExtendInputIfNeeded(RHS);3629SDValue Subtract =3630SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0);3631SDValue Shift =3632SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Subtract,3633S->getI32Imm(1, dl), S->getI32Imm(63,dl)),36340);3635return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, Shift,3636S->getI32Imm(-1, dl)), 0);3637}3638case ISD::SETUGT:3639// (sext (setcc %a, %b, setugt)) -> (ashr (sub %b, %a), 63)3640// (sext (setcc %a, %b, setugt)) -> (ashr (sub %a, %b), 63)3641std::swap(LHS, RHS);3642[[fallthrough]];3643case ISD::SETULT: {3644if (CmpInGPR == ICGPR_NonExtIn)3645return SDValue();3646// The upper 32-bits of the register can't be undefined for this sequence.3647LHS = zeroExtendInputIfNeeded(LHS);3648RHS = zeroExtendInputIfNeeded(RHS);3649SDValue Subtract =3650SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);3651return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,3652Subtract, S->getI64Imm(63, dl)), 0);3653}3654}3655}36563657/// Produces a zero-extended result of comparing two 64-bit values according to3658/// the passed condition code.3659SDValue3660IntegerCompareEliminator::get64BitZExtCompare(SDValue LHS, SDValue RHS,3661ISD::CondCode CC,3662int64_t RHSValue, SDLoc dl) {3663if (CmpInGPR == ICGPR_I32 || CmpInGPR == ICGPR_SextI32 ||3664CmpInGPR == ICGPR_ZextI32 || CmpInGPR == ICGPR_Sext)3665return SDValue();3666bool IsRHSZero = RHSValue == 0;3667bool IsRHSOne = RHSValue == 1;3668bool IsRHSNegOne = RHSValue == -1LL;3669switch (CC) {3670default: return SDValue();3671case ISD::SETEQ: {3672// (zext (setcc %a, %b, seteq)) -> (lshr (ctlz (xor %a, %b)), 6)3673// (zext (setcc %a, 0, seteq)) -> (lshr (ctlz %a), 6)3674SDValue Xor = IsRHSZero ? LHS :3675SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);3676SDValue Clz =3677SDValue(CurDAG->getMachineNode(PPC::CNTLZD, dl, MVT::i64, Xor), 0);3678return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Clz,3679S->getI64Imm(58, dl),3680S->getI64Imm(63, dl)), 0);3681}3682case ISD::SETNE: {3683// {addc.reg, addc.CA} = (addcarry (xor %a, %b), -1)3684// (zext (setcc %a, %b, setne)) -> (sube addc.reg, addc.reg, addc.CA)3685// {addcz.reg, addcz.CA} = (addcarry %a, -1)3686// (zext (setcc %a, 0, setne)) -> (sube addcz.reg, addcz.reg, addcz.CA)3687SDValue Xor = IsRHSZero ? LHS :3688SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);3689SDValue AC =3690SDValue(CurDAG->getMachineNode(PPC::ADDIC8, dl, MVT::i64, MVT::Glue,3691Xor, S->getI32Imm(~0U, dl)), 0);3692return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, AC,3693Xor, AC.getValue(1)), 0);3694}3695case ISD::SETGE: {3696// {subc.reg, subc.CA} = (subcarry %a, %b)3697// (zext (setcc %a, %b, setge)) ->3698// (adde (lshr %b, 63), (ashr %a, 63), subc.CA)3699// (zext (setcc %a, 0, setge)) -> (lshr (~ %a), 63)3700if (IsRHSZero)3701return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);3702std::swap(LHS, RHS);3703ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);3704IsRHSZero = RHSConst && RHSConst->isZero();3705[[fallthrough]];3706}3707case ISD::SETLE: {3708// {subc.reg, subc.CA} = (subcarry %b, %a)3709// (zext (setcc %a, %b, setge)) ->3710// (adde (lshr %a, 63), (ashr %b, 63), subc.CA)3711// (zext (setcc %a, 0, setge)) -> (lshr (or %a, (add %a, -1)), 63)3712if (IsRHSZero)3713return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);3714SDValue ShiftL =3715SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS,3716S->getI64Imm(1, dl),3717S->getI64Imm(63, dl)), 0);3718SDValue ShiftR =3719SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, RHS,3720S->getI64Imm(63, dl)), 0);3721SDValue SubtractCarry =3722SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,3723LHS, RHS), 1);3724return SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue,3725ShiftR, ShiftL, SubtractCarry), 0);3726}3727case ISD::SETGT: {3728// {subc.reg, subc.CA} = (subcarry %b, %a)3729// (zext (setcc %a, %b, setgt)) ->3730// (xor (adde (lshr %a, 63), (ashr %b, 63), subc.CA), 1)3731// (zext (setcc %a, 0, setgt)) -> (lshr (nor (add %a, -1), %a), 63)3732if (IsRHSNegOne)3733return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);3734if (IsRHSZero) {3735SDValue Addi =3736SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS,3737S->getI64Imm(~0ULL, dl)), 0);3738SDValue Nor =3739SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64, Addi, LHS), 0);3740return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Nor,3741S->getI64Imm(1, dl),3742S->getI64Imm(63, dl)), 0);3743}3744std::swap(LHS, RHS);3745ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);3746IsRHSZero = RHSConst && RHSConst->isZero();3747IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;3748[[fallthrough]];3749}3750case ISD::SETLT: {3751// {subc.reg, subc.CA} = (subcarry %a, %b)3752// (zext (setcc %a, %b, setlt)) ->3753// (xor (adde (lshr %b, 63), (ashr %a, 63), subc.CA), 1)3754// (zext (setcc %a, 0, setlt)) -> (lshr %a, 63)3755if (IsRHSOne)3756return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);3757if (IsRHSZero)3758return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS,3759S->getI64Imm(1, dl),3760S->getI64Imm(63, dl)), 0);3761SDValue SRADINode =3762SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,3763LHS, S->getI64Imm(63, dl)), 0);3764SDValue SRDINode =3765SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,3766RHS, S->getI64Imm(1, dl),3767S->getI64Imm(63, dl)), 0);3768SDValue SUBFC8Carry =3769SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,3770RHS, LHS), 1);3771SDValue ADDE8Node =3772SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue,3773SRDINode, SRADINode, SUBFC8Carry), 0);3774return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64,3775ADDE8Node, S->getI64Imm(1, dl)), 0);3776}3777case ISD::SETUGE:3778// {subc.reg, subc.CA} = (subcarry %a, %b)3779// (zext (setcc %a, %b, setuge)) -> (add (sube %b, %b, subc.CA), 1)3780std::swap(LHS, RHS);3781[[fallthrough]];3782case ISD::SETULE: {3783// {subc.reg, subc.CA} = (subcarry %b, %a)3784// (zext (setcc %a, %b, setule)) -> (add (sube %a, %a, subc.CA), 1)3785SDValue SUBFC8Carry =3786SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,3787LHS, RHS), 1);3788SDValue SUBFE8Node =3789SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, MVT::Glue,3790LHS, LHS, SUBFC8Carry), 0);3791return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64,3792SUBFE8Node, S->getI64Imm(1, dl)), 0);3793}3794case ISD::SETUGT:3795// {subc.reg, subc.CA} = (subcarry %b, %a)3796// (zext (setcc %a, %b, setugt)) -> -(sube %b, %b, subc.CA)3797std::swap(LHS, RHS);3798[[fallthrough]];3799case ISD::SETULT: {3800// {subc.reg, subc.CA} = (subcarry %a, %b)3801// (zext (setcc %a, %b, setult)) -> -(sube %a, %a, subc.CA)3802SDValue SubtractCarry =3803SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,3804RHS, LHS), 1);3805SDValue ExtSub =3806SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64,3807LHS, LHS, SubtractCarry), 0);3808return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64,3809ExtSub), 0);3810}3811}3812}38133814/// Produces a sign-extended result of comparing two 64-bit values according to3815/// the passed condition code.3816SDValue3817IntegerCompareEliminator::get64BitSExtCompare(SDValue LHS, SDValue RHS,3818ISD::CondCode CC,3819int64_t RHSValue, SDLoc dl) {3820if (CmpInGPR == ICGPR_I32 || CmpInGPR == ICGPR_SextI32 ||3821CmpInGPR == ICGPR_ZextI32 || CmpInGPR == ICGPR_Zext)3822return SDValue();3823bool IsRHSZero = RHSValue == 0;3824bool IsRHSOne = RHSValue == 1;3825bool IsRHSNegOne = RHSValue == -1LL;3826switch (CC) {3827default: return SDValue();3828case ISD::SETEQ: {3829// {addc.reg, addc.CA} = (addcarry (xor %a, %b), -1)3830// (sext (setcc %a, %b, seteq)) -> (sube addc.reg, addc.reg, addc.CA)3831// {addcz.reg, addcz.CA} = (addcarry %a, -1)3832// (sext (setcc %a, 0, seteq)) -> (sube addcz.reg, addcz.reg, addcz.CA)3833SDValue AddInput = IsRHSZero ? LHS :3834SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);3835SDValue Addic =3836SDValue(CurDAG->getMachineNode(PPC::ADDIC8, dl, MVT::i64, MVT::Glue,3837AddInput, S->getI32Imm(~0U, dl)), 0);3838return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, Addic,3839Addic, Addic.getValue(1)), 0);3840}3841case ISD::SETNE: {3842// {subfc.reg, subfc.CA} = (subcarry 0, (xor %a, %b))3843// (sext (setcc %a, %b, setne)) -> (sube subfc.reg, subfc.reg, subfc.CA)3844// {subfcz.reg, subfcz.CA} = (subcarry 0, %a)3845// (sext (setcc %a, 0, setne)) -> (sube subfcz.reg, subfcz.reg, subfcz.CA)3846SDValue Xor = IsRHSZero ? LHS :3847SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);3848SDValue SC =3849SDValue(CurDAG->getMachineNode(PPC::SUBFIC8, dl, MVT::i64, MVT::Glue,3850Xor, S->getI32Imm(0, dl)), 0);3851return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, SC,3852SC, SC.getValue(1)), 0);3853}3854case ISD::SETGE: {3855// {subc.reg, subc.CA} = (subcarry %a, %b)3856// (zext (setcc %a, %b, setge)) ->3857// (- (adde (lshr %b, 63), (ashr %a, 63), subc.CA))3858// (zext (setcc %a, 0, setge)) -> (~ (ashr %a, 63))3859if (IsRHSZero)3860return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);3861std::swap(LHS, RHS);3862ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);3863IsRHSZero = RHSConst && RHSConst->isZero();3864[[fallthrough]];3865}3866case ISD::SETLE: {3867// {subc.reg, subc.CA} = (subcarry %b, %a)3868// (zext (setcc %a, %b, setge)) ->3869// (- (adde (lshr %a, 63), (ashr %b, 63), subc.CA))3870// (zext (setcc %a, 0, setge)) -> (ashr (or %a, (add %a, -1)), 63)3871if (IsRHSZero)3872return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);3873SDValue ShiftR =3874SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, RHS,3875S->getI64Imm(63, dl)), 0);3876SDValue ShiftL =3877SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS,3878S->getI64Imm(1, dl),3879S->getI64Imm(63, dl)), 0);3880SDValue SubtractCarry =3881SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,3882LHS, RHS), 1);3883SDValue Adde =3884SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue,3885ShiftR, ShiftL, SubtractCarry), 0);3886return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, Adde), 0);3887}3888case ISD::SETGT: {3889// {subc.reg, subc.CA} = (subcarry %b, %a)3890// (zext (setcc %a, %b, setgt)) ->3891// -(xor (adde (lshr %a, 63), (ashr %b, 63), subc.CA), 1)3892// (zext (setcc %a, 0, setgt)) -> (ashr (nor (add %a, -1), %a), 63)3893if (IsRHSNegOne)3894return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);3895if (IsRHSZero) {3896SDValue Add =3897SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS,3898S->getI64Imm(-1, dl)), 0);3899SDValue Nor =3900SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64, Add, LHS), 0);3901return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, Nor,3902S->getI64Imm(63, dl)), 0);3903}3904std::swap(LHS, RHS);3905ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);3906IsRHSZero = RHSConst && RHSConst->isZero();3907IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;3908[[fallthrough]];3909}3910case ISD::SETLT: {3911// {subc.reg, subc.CA} = (subcarry %a, %b)3912// (zext (setcc %a, %b, setlt)) ->3913// -(xor (adde (lshr %b, 63), (ashr %a, 63), subc.CA), 1)3914// (zext (setcc %a, 0, setlt)) -> (ashr %a, 63)3915if (IsRHSOne)3916return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);3917if (IsRHSZero) {3918return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, LHS,3919S->getI64Imm(63, dl)), 0);3920}3921SDValue SRADINode =3922SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,3923LHS, S->getI64Imm(63, dl)), 0);3924SDValue SRDINode =3925SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,3926RHS, S->getI64Imm(1, dl),3927S->getI64Imm(63, dl)), 0);3928SDValue SUBFC8Carry =3929SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,3930RHS, LHS), 1);3931SDValue ADDE8Node =3932SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64,3933SRDINode, SRADINode, SUBFC8Carry), 0);3934SDValue XORI8Node =3935SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64,3936ADDE8Node, S->getI64Imm(1, dl)), 0);3937return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64,3938XORI8Node), 0);3939}3940case ISD::SETUGE:3941// {subc.reg, subc.CA} = (subcarry %a, %b)3942// (sext (setcc %a, %b, setuge)) -> ~(sube %b, %b, subc.CA)3943std::swap(LHS, RHS);3944[[fallthrough]];3945case ISD::SETULE: {3946// {subc.reg, subc.CA} = (subcarry %b, %a)3947// (sext (setcc %a, %b, setule)) -> ~(sube %a, %a, subc.CA)3948SDValue SubtractCarry =3949SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,3950LHS, RHS), 1);3951SDValue ExtSub =3952SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, MVT::Glue, LHS,3953LHS, SubtractCarry), 0);3954return SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64,3955ExtSub, ExtSub), 0);3956}3957case ISD::SETUGT:3958// {subc.reg, subc.CA} = (subcarry %b, %a)3959// (sext (setcc %a, %b, setugt)) -> (sube %b, %b, subc.CA)3960std::swap(LHS, RHS);3961[[fallthrough]];3962case ISD::SETULT: {3963// {subc.reg, subc.CA} = (subcarry %a, %b)3964// (sext (setcc %a, %b, setult)) -> (sube %a, %a, subc.CA)3965SDValue SubCarry =3966SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,3967RHS, LHS), 1);3968return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64,3969LHS, LHS, SubCarry), 0);3970}3971}3972}39733974/// Do all uses of this SDValue need the result in a GPR?3975/// This is meant to be used on values that have type i1 since3976/// it is somewhat meaningless to ask if values of other types3977/// should be kept in GPR's.3978static bool allUsesExtend(SDValue Compare, SelectionDAG *CurDAG) {3979assert(Compare.getOpcode() == ISD::SETCC &&3980"An ISD::SETCC node required here.");39813982// For values that have a single use, the caller should obviously already have3983// checked if that use is an extending use. We check the other uses here.3984if (Compare.hasOneUse())3985return true;3986// We want the value in a GPR if it is being extended, used for a select, or3987// used in logical operations.3988for (auto *CompareUse : Compare.getNode()->uses())3989if (CompareUse->getOpcode() != ISD::SIGN_EXTEND &&3990CompareUse->getOpcode() != ISD::ZERO_EXTEND &&3991CompareUse->getOpcode() != ISD::SELECT &&3992!ISD::isBitwiseLogicOp(CompareUse->getOpcode())) {3993OmittedForNonExtendUses++;3994return false;3995}3996return true;3997}39983999/// Returns an equivalent of a SETCC node but with the result the same width as4000/// the inputs. This can also be used for SELECT_CC if either the true or false4001/// values is a power of two while the other is zero.4002SDValue IntegerCompareEliminator::getSETCCInGPR(SDValue Compare,4003SetccInGPROpts ConvOpts) {4004assert((Compare.getOpcode() == ISD::SETCC ||4005Compare.getOpcode() == ISD::SELECT_CC) &&4006"An ISD::SETCC node required here.");40074008// Don't convert this comparison to a GPR sequence because there are uses4009// of the i1 result (i.e. uses that require the result in the CR).4010if ((Compare.getOpcode() == ISD::SETCC) && !allUsesExtend(Compare, CurDAG))4011return SDValue();40124013SDValue LHS = Compare.getOperand(0);4014SDValue RHS = Compare.getOperand(1);40154016// The condition code is operand 2 for SETCC and operand 4 for SELECT_CC.4017int CCOpNum = Compare.getOpcode() == ISD::SELECT_CC ? 4 : 2;4018ISD::CondCode CC =4019cast<CondCodeSDNode>(Compare.getOperand(CCOpNum))->get();4020EVT InputVT = LHS.getValueType();4021if (InputVT != MVT::i32 && InputVT != MVT::i64)4022return SDValue();40234024if (ConvOpts == SetccInGPROpts::ZExtInvert ||4025ConvOpts == SetccInGPROpts::SExtInvert)4026CC = ISD::getSetCCInverse(CC, InputVT);40274028bool Inputs32Bit = InputVT == MVT::i32;40294030SDLoc dl(Compare);4031ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);4032int64_t RHSValue = RHSConst ? RHSConst->getSExtValue() : INT64_MAX;4033bool IsSext = ConvOpts == SetccInGPROpts::SExtOrig ||4034ConvOpts == SetccInGPROpts::SExtInvert;40354036if (IsSext && Inputs32Bit)4037return get32BitSExtCompare(LHS, RHS, CC, RHSValue, dl);4038else if (Inputs32Bit)4039return get32BitZExtCompare(LHS, RHS, CC, RHSValue, dl);4040else if (IsSext)4041return get64BitSExtCompare(LHS, RHS, CC, RHSValue, dl);4042return get64BitZExtCompare(LHS, RHS, CC, RHSValue, dl);4043}40444045} // end anonymous namespace40464047bool PPCDAGToDAGISel::tryIntCompareInGPR(SDNode *N) {4048if (N->getValueType(0) != MVT::i32 &&4049N->getValueType(0) != MVT::i64)4050return false;40514052// This optimization will emit code that assumes 64-bit registers4053// so we don't want to run it in 32-bit mode. Also don't run it4054// on functions that are not to be optimized.4055if (TM.getOptLevel() == CodeGenOptLevel::None || !TM.isPPC64())4056return false;40574058// For POWER10, it is more profitable to use the set boolean extension4059// instructions rather than the integer compare elimination codegen.4060// Users can override this via the command line option, `--ppc-gpr-icmps`.4061if (!(CmpInGPR.getNumOccurrences() > 0) && Subtarget->isISA3_1())4062return false;40634064switch (N->getOpcode()) {4065default: break;4066case ISD::ZERO_EXTEND:4067case ISD::SIGN_EXTEND:4068case ISD::AND:4069case ISD::OR:4070case ISD::XOR: {4071IntegerCompareEliminator ICmpElim(CurDAG, this);4072if (SDNode *New = ICmpElim.Select(N)) {4073ReplaceNode(N, New);4074return true;4075}4076}4077}4078return false;4079}40804081bool PPCDAGToDAGISel::tryBitPermutation(SDNode *N) {4082if (N->getValueType(0) != MVT::i32 &&4083N->getValueType(0) != MVT::i64)4084return false;40854086if (!UseBitPermRewriter)4087return false;40884089switch (N->getOpcode()) {4090default: break;4091case ISD::SRL:4092// If we are on P10, we have a pattern for 32-bit (srl (bswap r), 16) that4093// uses the BRH instruction.4094if (Subtarget->isISA3_1() && N->getValueType(0) == MVT::i32 &&4095N->getOperand(0).getOpcode() == ISD::BSWAP) {4096auto &OpRight = N->getOperand(1);4097ConstantSDNode *SRLConst = dyn_cast<ConstantSDNode>(OpRight);4098if (SRLConst && SRLConst->getSExtValue() == 16)4099return false;4100}4101[[fallthrough]];4102case ISD::ROTL:4103case ISD::SHL:4104case ISD::AND:4105case ISD::OR: {4106BitPermutationSelector BPS(CurDAG);4107if (SDNode *New = BPS.Select(N)) {4108ReplaceNode(N, New);4109return true;4110}4111return false;4112}4113}41144115return false;4116}41174118/// SelectCC - Select a comparison of the specified values with the specified4119/// condition code, returning the CR# of the expression.4120SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,4121const SDLoc &dl, SDValue Chain) {4122// Always select the LHS.4123unsigned Opc;41244125if (LHS.getValueType() == MVT::i32) {4126unsigned Imm;4127if (CC == ISD::SETEQ || CC == ISD::SETNE) {4128if (isInt32Immediate(RHS, Imm)) {4129// SETEQ/SETNE comparison with 16-bit immediate, fold it.4130if (isUInt<16>(Imm))4131return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,4132getI32Imm(Imm & 0xFFFF, dl)),41330);4134// If this is a 16-bit signed immediate, fold it.4135if (isInt<16>((int)Imm))4136return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,4137getI32Imm(Imm & 0xFFFF, dl)),41380);41394140// For non-equality comparisons, the default code would materialize the4141// constant, then compare against it, like this:4142// lis r2, 46604143// ori r2, r2, 221364144// cmpw cr0, r3, r24145// Since we are just comparing for equality, we can emit this instead:4146// xoris r0,r3,0x12344147// cmplwi cr0,r0,0x56784148// beq cr0,L64149SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,4150getI32Imm(Imm >> 16, dl)), 0);4151return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,4152getI32Imm(Imm & 0xFFFF, dl)), 0);4153}4154Opc = PPC::CMPLW;4155} else if (ISD::isUnsignedIntSetCC(CC)) {4156if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))4157return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,4158getI32Imm(Imm & 0xFFFF, dl)), 0);4159Opc = PPC::CMPLW;4160} else {4161int16_t SImm;4162if (isIntS16Immediate(RHS, SImm))4163return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,4164getI32Imm((int)SImm & 0xFFFF,4165dl)),41660);4167Opc = PPC::CMPW;4168}4169} else if (LHS.getValueType() == MVT::i64) {4170uint64_t Imm;4171if (CC == ISD::SETEQ || CC == ISD::SETNE) {4172if (isInt64Immediate(RHS.getNode(), Imm)) {4173// SETEQ/SETNE comparison with 16-bit immediate, fold it.4174if (isUInt<16>(Imm))4175return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,4176getI32Imm(Imm & 0xFFFF, dl)),41770);4178// If this is a 16-bit signed immediate, fold it.4179if (isInt<16>(Imm))4180return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,4181getI32Imm(Imm & 0xFFFF, dl)),41820);41834184// For non-equality comparisons, the default code would materialize the4185// constant, then compare against it, like this:4186// lis r2, 46604187// ori r2, r2, 221364188// cmpd cr0, r3, r24189// Since we are just comparing for equality, we can emit this instead:4190// xoris r0,r3,0x12344191// cmpldi cr0,r0,0x56784192// beq cr0,L64193if (isUInt<32>(Imm)) {4194SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,4195getI64Imm(Imm >> 16, dl)), 0);4196return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,4197getI64Imm(Imm & 0xFFFF, dl)),41980);4199}4200}4201Opc = PPC::CMPLD;4202} else if (ISD::isUnsignedIntSetCC(CC)) {4203if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))4204return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,4205getI64Imm(Imm & 0xFFFF, dl)), 0);4206Opc = PPC::CMPLD;4207} else {4208int16_t SImm;4209if (isIntS16Immediate(RHS, SImm))4210return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,4211getI64Imm(SImm & 0xFFFF, dl)),42120);4213Opc = PPC::CMPD;4214}4215} else if (LHS.getValueType() == MVT::f32) {4216if (Subtarget->hasSPE()) {4217switch (CC) {4218default:4219case ISD::SETEQ:4220case ISD::SETNE:4221Opc = PPC::EFSCMPEQ;4222break;4223case ISD::SETLT:4224case ISD::SETGE:4225case ISD::SETOLT:4226case ISD::SETOGE:4227case ISD::SETULT:4228case ISD::SETUGE:4229Opc = PPC::EFSCMPLT;4230break;4231case ISD::SETGT:4232case ISD::SETLE:4233case ISD::SETOGT:4234case ISD::SETOLE:4235case ISD::SETUGT:4236case ISD::SETULE:4237Opc = PPC::EFSCMPGT;4238break;4239}4240} else4241Opc = PPC::FCMPUS;4242} else if (LHS.getValueType() == MVT::f64) {4243if (Subtarget->hasSPE()) {4244switch (CC) {4245default:4246case ISD::SETEQ:4247case ISD::SETNE:4248Opc = PPC::EFDCMPEQ;4249break;4250case ISD::SETLT:4251case ISD::SETGE:4252case ISD::SETOLT:4253case ISD::SETOGE:4254case ISD::SETULT:4255case ISD::SETUGE:4256Opc = PPC::EFDCMPLT;4257break;4258case ISD::SETGT:4259case ISD::SETLE:4260case ISD::SETOGT:4261case ISD::SETOLE:4262case ISD::SETUGT:4263case ISD::SETULE:4264Opc = PPC::EFDCMPGT;4265break;4266}4267} else4268Opc = Subtarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;4269} else {4270assert(LHS.getValueType() == MVT::f128 && "Unknown vt!");4271assert(Subtarget->hasP9Vector() && "XSCMPUQP requires Power9 Vector");4272Opc = PPC::XSCMPUQP;4273}4274if (Chain)4275return SDValue(4276CurDAG->getMachineNode(Opc, dl, MVT::i32, MVT::Other, LHS, RHS, Chain),42770);4278else4279return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);4280}42814282static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC, const EVT &VT,4283const PPCSubtarget *Subtarget) {4284// For SPE instructions, the result is in GT bit of the CR4285bool UseSPE = Subtarget->hasSPE() && VT.isFloatingPoint();42864287switch (CC) {4288case ISD::SETUEQ:4289case ISD::SETONE:4290case ISD::SETOLE:4291case ISD::SETOGE:4292llvm_unreachable("Should be lowered by legalize!");4293default: llvm_unreachable("Unknown condition!");4294case ISD::SETOEQ:4295case ISD::SETEQ:4296return UseSPE ? PPC::PRED_GT : PPC::PRED_EQ;4297case ISD::SETUNE:4298case ISD::SETNE:4299return UseSPE ? PPC::PRED_LE : PPC::PRED_NE;4300case ISD::SETOLT:4301case ISD::SETLT:4302return UseSPE ? PPC::PRED_GT : PPC::PRED_LT;4303case ISD::SETULE:4304case ISD::SETLE:4305return PPC::PRED_LE;4306case ISD::SETOGT:4307case ISD::SETGT:4308return PPC::PRED_GT;4309case ISD::SETUGE:4310case ISD::SETGE:4311return UseSPE ? PPC::PRED_LE : PPC::PRED_GE;4312case ISD::SETO: return PPC::PRED_NU;4313case ISD::SETUO: return PPC::PRED_UN;4314// These two are invalid for floating point. Assume we have int.4315case ISD::SETULT: return PPC::PRED_LT;4316case ISD::SETUGT: return PPC::PRED_GT;4317}4318}43194320/// getCRIdxForSetCC - Return the index of the condition register field4321/// associated with the SetCC condition, and whether or not the field is4322/// treated as inverted. That is, lt = 0; ge = 0 inverted.4323static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {4324Invert = false;4325switch (CC) {4326default: llvm_unreachable("Unknown condition!");4327case ISD::SETOLT:4328case ISD::SETLT: return 0; // Bit #0 = SETOLT4329case ISD::SETOGT:4330case ISD::SETGT: return 1; // Bit #1 = SETOGT4331case ISD::SETOEQ:4332case ISD::SETEQ: return 2; // Bit #2 = SETOEQ4333case ISD::SETUO: return 3; // Bit #3 = SETUO4334case ISD::SETUGE:4335case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE4336case ISD::SETULE:4337case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE4338case ISD::SETUNE:4339case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE4340case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO4341case ISD::SETUEQ:4342case ISD::SETOGE:4343case ISD::SETOLE:4344case ISD::SETONE:4345llvm_unreachable("Invalid branch code: should be expanded by legalize");4346// These are invalid for floating point. Assume integer.4347case ISD::SETULT: return 0;4348case ISD::SETUGT: return 1;4349}4350}43514352// getVCmpInst: return the vector compare instruction for the specified4353// vector type and condition code. Since this is for altivec specific code,4354// only support the altivec types (v16i8, v8i16, v4i32, v2i64, v1i128,4355// and v4f32).4356static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,4357bool HasVSX, bool &Swap, bool &Negate) {4358Swap = false;4359Negate = false;43604361if (VecVT.isFloatingPoint()) {4362/* Handle some cases by swapping input operands. */4363switch (CC) {4364case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;4365case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;4366case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;4367case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;4368case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;4369case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;4370default: break;4371}4372/* Handle some cases by negating the result. */4373switch (CC) {4374case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;4375case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;4376case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;4377case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;4378default: break;4379}4380/* We have instructions implementing the remaining cases. */4381switch (CC) {4382case ISD::SETEQ:4383case ISD::SETOEQ:4384if (VecVT == MVT::v4f32)4385return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;4386else if (VecVT == MVT::v2f64)4387return PPC::XVCMPEQDP;4388break;4389case ISD::SETGT:4390case ISD::SETOGT:4391if (VecVT == MVT::v4f32)4392return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;4393else if (VecVT == MVT::v2f64)4394return PPC::XVCMPGTDP;4395break;4396case ISD::SETGE:4397case ISD::SETOGE:4398if (VecVT == MVT::v4f32)4399return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;4400else if (VecVT == MVT::v2f64)4401return PPC::XVCMPGEDP;4402break;4403default:4404break;4405}4406llvm_unreachable("Invalid floating-point vector compare condition");4407} else {4408/* Handle some cases by swapping input operands. */4409switch (CC) {4410case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;4411case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;4412case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;4413case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;4414default: break;4415}4416/* Handle some cases by negating the result. */4417switch (CC) {4418case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;4419case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;4420case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;4421case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;4422default: break;4423}4424/* We have instructions implementing the remaining cases. */4425switch (CC) {4426case ISD::SETEQ:4427case ISD::SETUEQ:4428if (VecVT == MVT::v16i8)4429return PPC::VCMPEQUB;4430else if (VecVT == MVT::v8i16)4431return PPC::VCMPEQUH;4432else if (VecVT == MVT::v4i32)4433return PPC::VCMPEQUW;4434else if (VecVT == MVT::v2i64)4435return PPC::VCMPEQUD;4436else if (VecVT == MVT::v1i128)4437return PPC::VCMPEQUQ;4438break;4439case ISD::SETGT:4440if (VecVT == MVT::v16i8)4441return PPC::VCMPGTSB;4442else if (VecVT == MVT::v8i16)4443return PPC::VCMPGTSH;4444else if (VecVT == MVT::v4i32)4445return PPC::VCMPGTSW;4446else if (VecVT == MVT::v2i64)4447return PPC::VCMPGTSD;4448else if (VecVT == MVT::v1i128)4449return PPC::VCMPGTSQ;4450break;4451case ISD::SETUGT:4452if (VecVT == MVT::v16i8)4453return PPC::VCMPGTUB;4454else if (VecVT == MVT::v8i16)4455return PPC::VCMPGTUH;4456else if (VecVT == MVT::v4i32)4457return PPC::VCMPGTUW;4458else if (VecVT == MVT::v2i64)4459return PPC::VCMPGTUD;4460else if (VecVT == MVT::v1i128)4461return PPC::VCMPGTUQ;4462break;4463default:4464break;4465}4466llvm_unreachable("Invalid integer vector compare condition");4467}4468}44694470bool PPCDAGToDAGISel::trySETCC(SDNode *N) {4471SDLoc dl(N);4472unsigned Imm;4473bool IsStrict = N->isStrictFPOpcode();4474ISD::CondCode CC =4475cast<CondCodeSDNode>(N->getOperand(IsStrict ? 3 : 2))->get();4476EVT PtrVT =4477CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());4478bool isPPC64 = (PtrVT == MVT::i64);4479SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();44804481SDValue LHS = N->getOperand(IsStrict ? 1 : 0);4482SDValue RHS = N->getOperand(IsStrict ? 2 : 1);44834484if (!IsStrict && !Subtarget->useCRBits() && isInt32Immediate(RHS, Imm)) {4485// We can codegen setcc op, imm very efficiently compared to a brcond.4486// Check for those cases here.4487// setcc op, 04488if (Imm == 0) {4489SDValue Op = LHS;4490switch (CC) {4491default: break;4492case ISD::SETEQ: {4493Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);4494SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl),4495getI32Imm(31, dl) };4496CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);4497return true;4498}4499case ISD::SETNE: {4500if (isPPC64) break;4501SDValue AD =4502SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,4503Op, getI32Imm(~0U, dl)), 0);4504CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, AD.getValue(1));4505return true;4506}4507case ISD::SETLT: {4508SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),4509getI32Imm(31, dl) };4510CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);4511return true;4512}4513case ISD::SETGT: {4514SDValue T =4515SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);4516T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);4517SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl),4518getI32Imm(31, dl) };4519CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);4520return true;4521}4522}4523} else if (Imm == ~0U) { // setcc op, -14524SDValue Op = LHS;4525switch (CC) {4526default: break;4527case ISD::SETEQ:4528if (isPPC64) break;4529Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,4530Op, getI32Imm(1, dl)), 0);4531CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,4532SDValue(CurDAG->getMachineNode(PPC::LI, dl,4533MVT::i32,4534getI32Imm(0, dl)),45350), Op.getValue(1));4536return true;4537case ISD::SETNE: {4538if (isPPC64) break;4539Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);4540SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,4541Op, getI32Imm(~0U, dl));4542CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0), Op,4543SDValue(AD, 1));4544return true;4545}4546case ISD::SETLT: {4547SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,4548getI32Imm(1, dl)), 0);4549SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,4550Op), 0);4551SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl),4552getI32Imm(31, dl) };4553CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);4554return true;4555}4556case ISD::SETGT: {4557SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),4558getI32Imm(31, dl) };4559Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);4560CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1, dl));4561return true;4562}4563}4564}4565}45664567// Altivec Vector compare instructions do not set any CR register by default and4568// vector compare operations return the same type as the operands.4569if (!IsStrict && LHS.getValueType().isVector()) {4570if (Subtarget->hasSPE())4571return false;45724573EVT VecVT = LHS.getValueType();4574bool Swap, Negate;4575unsigned int VCmpInst =4576getVCmpInst(VecVT.getSimpleVT(), CC, Subtarget->hasVSX(), Swap, Negate);4577if (Swap)4578std::swap(LHS, RHS);45794580EVT ResVT = VecVT.changeVectorElementTypeToInteger();4581if (Negate) {4582SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, ResVT, LHS, RHS), 0);4583CurDAG->SelectNodeTo(N, Subtarget->hasVSX() ? PPC::XXLNOR : PPC::VNOR,4584ResVT, VCmp, VCmp);4585return true;4586}45874588CurDAG->SelectNodeTo(N, VCmpInst, ResVT, LHS, RHS);4589return true;4590}45914592if (Subtarget->useCRBits())4593return false;45944595bool Inv;4596unsigned Idx = getCRIdxForSetCC(CC, Inv);4597SDValue CCReg = SelectCC(LHS, RHS, CC, dl, Chain);4598if (IsStrict)4599CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 1), CCReg.getValue(1));4600SDValue IntCR;46014602// SPE e*cmp* instructions only set the 'gt' bit, so hard-code that4603// The correct compare instruction is already set by SelectCC()4604if (Subtarget->hasSPE() && LHS.getValueType().isFloatingPoint()) {4605Idx = 1;4606}46074608// Force the ccreg into CR7.4609SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);46104611SDValue InGlue; // Null incoming flag value.4612CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,4613InGlue).getValue(1);46144615IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,4616CCReg), 0);46174618SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl),4619getI32Imm(31, dl), getI32Imm(31, dl) };4620if (!Inv) {4621CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);4622return true;4623}46244625// Get the specified bit.4626SDValue Tmp =4627SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);4628CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl));4629return true;4630}46314632/// Does this node represent a load/store node whose address can be represented4633/// with a register plus an immediate that's a multiple of \p Val:4634bool PPCDAGToDAGISel::isOffsetMultipleOf(SDNode *N, unsigned Val) const {4635LoadSDNode *LDN = dyn_cast<LoadSDNode>(N);4636StoreSDNode *STN = dyn_cast<StoreSDNode>(N);4637MemIntrinsicSDNode *MIN = dyn_cast<MemIntrinsicSDNode>(N);4638SDValue AddrOp;4639if (LDN || (MIN && MIN->getOpcode() == PPCISD::LD_SPLAT))4640AddrOp = N->getOperand(1);4641else if (STN)4642AddrOp = STN->getOperand(2);46434644// If the address points a frame object or a frame object with an offset,4645// we need to check the object alignment.4646short Imm = 0;4647if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(4648AddrOp.getOpcode() == ISD::ADD ? AddrOp.getOperand(0) :4649AddrOp)) {4650// If op0 is a frame index that is under aligned, we can't do it either,4651// because it is translated to r31 or r1 + slot + offset. We won't know the4652// slot number until the stack frame is finalized.4653const MachineFrameInfo &MFI = CurDAG->getMachineFunction().getFrameInfo();4654unsigned SlotAlign = MFI.getObjectAlign(FI->getIndex()).value();4655if ((SlotAlign % Val) != 0)4656return false;46574658// If we have an offset, we need further check on the offset.4659if (AddrOp.getOpcode() != ISD::ADD)4660return true;4661}46624663if (AddrOp.getOpcode() == ISD::ADD)4664return isIntS16Immediate(AddrOp.getOperand(1), Imm) && !(Imm % Val);46654666// If the address comes from the outside, the offset will be zero.4667return AddrOp.getOpcode() == ISD::CopyFromReg;4668}46694670void PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {4671// Transfer memoperands.4672MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();4673CurDAG->setNodeMemRefs(cast<MachineSDNode>(Result), {MemOp});4674}46754676static bool mayUseP9Setb(SDNode *N, const ISD::CondCode &CC, SelectionDAG *DAG,4677bool &NeedSwapOps, bool &IsUnCmp) {46784679assert(N->getOpcode() == ISD::SELECT_CC && "Expecting a SELECT_CC here.");46804681SDValue LHS = N->getOperand(0);4682SDValue RHS = N->getOperand(1);4683SDValue TrueRes = N->getOperand(2);4684SDValue FalseRes = N->getOperand(3);4685ConstantSDNode *TrueConst = dyn_cast<ConstantSDNode>(TrueRes);4686if (!TrueConst || (N->getSimpleValueType(0) != MVT::i64 &&4687N->getSimpleValueType(0) != MVT::i32))4688return false;46894690// We are looking for any of:4691// (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, cc2)), cc1)4692// (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, cc2)), cc1)4693// (select_cc lhs, rhs, 0, (select_cc [lr]hs, [lr]hs, 1, -1, cc2), seteq)4694// (select_cc lhs, rhs, 0, (select_cc [lr]hs, [lr]hs, -1, 1, cc2), seteq)4695int64_t TrueResVal = TrueConst->getSExtValue();4696if ((TrueResVal < -1 || TrueResVal > 1) ||4697(TrueResVal == -1 && FalseRes.getOpcode() != ISD::ZERO_EXTEND) ||4698(TrueResVal == 1 && FalseRes.getOpcode() != ISD::SIGN_EXTEND) ||4699(TrueResVal == 0 &&4700(FalseRes.getOpcode() != ISD::SELECT_CC || CC != ISD::SETEQ)))4701return false;47024703SDValue SetOrSelCC = FalseRes.getOpcode() == ISD::SELECT_CC4704? FalseRes4705: FalseRes.getOperand(0);4706bool InnerIsSel = SetOrSelCC.getOpcode() == ISD::SELECT_CC;4707if (SetOrSelCC.getOpcode() != ISD::SETCC &&4708SetOrSelCC.getOpcode() != ISD::SELECT_CC)4709return false;47104711// Without this setb optimization, the outer SELECT_CC will be manually4712// selected to SELECT_CC_I4/SELECT_CC_I8 Pseudo, then expand-isel-pseudos pass4713// transforms pseudo instruction to isel instruction. When there are more than4714// one use for result like zext/sext, with current optimization we only see4715// isel is replaced by setb but can't see any significant gain. Since4716// setb has longer latency than original isel, we should avoid this. Another4717// point is that setb requires comparison always kept, it can break the4718// opportunity to get the comparison away if we have in future.4719if (!SetOrSelCC.hasOneUse() || (!InnerIsSel && !FalseRes.hasOneUse()))4720return false;47214722SDValue InnerLHS = SetOrSelCC.getOperand(0);4723SDValue InnerRHS = SetOrSelCC.getOperand(1);4724ISD::CondCode InnerCC =4725cast<CondCodeSDNode>(SetOrSelCC.getOperand(InnerIsSel ? 4 : 2))->get();4726// If the inner comparison is a select_cc, make sure the true/false values are4727// 1/-1 and canonicalize it if needed.4728if (InnerIsSel) {4729ConstantSDNode *SelCCTrueConst =4730dyn_cast<ConstantSDNode>(SetOrSelCC.getOperand(2));4731ConstantSDNode *SelCCFalseConst =4732dyn_cast<ConstantSDNode>(SetOrSelCC.getOperand(3));4733if (!SelCCTrueConst || !SelCCFalseConst)4734return false;4735int64_t SelCCTVal = SelCCTrueConst->getSExtValue();4736int64_t SelCCFVal = SelCCFalseConst->getSExtValue();4737// The values must be -1/1 (requiring a swap) or 1/-1.4738if (SelCCTVal == -1 && SelCCFVal == 1) {4739std::swap(InnerLHS, InnerRHS);4740} else if (SelCCTVal != 1 || SelCCFVal != -1)4741return false;4742}47434744// Canonicalize unsigned case4745if (InnerCC == ISD::SETULT || InnerCC == ISD::SETUGT) {4746IsUnCmp = true;4747InnerCC = (InnerCC == ISD::SETULT) ? ISD::SETLT : ISD::SETGT;4748}47494750bool InnerSwapped = false;4751if (LHS == InnerRHS && RHS == InnerLHS)4752InnerSwapped = true;4753else if (LHS != InnerLHS || RHS != InnerRHS)4754return false;47554756switch (CC) {4757// (select_cc lhs, rhs, 0, \4758// (select_cc [lr]hs, [lr]hs, 1, -1, setlt/setgt), seteq)4759case ISD::SETEQ:4760if (!InnerIsSel)4761return false;4762if (InnerCC != ISD::SETLT && InnerCC != ISD::SETGT)4763return false;4764NeedSwapOps = (InnerCC == ISD::SETGT) ? InnerSwapped : !InnerSwapped;4765break;47664767// (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, setne)), setu?lt)4768// (select_cc lhs, rhs, -1, (zext (setcc lhs, rhs, setgt)), setu?lt)4769// (select_cc lhs, rhs, -1, (zext (setcc rhs, lhs, setlt)), setu?lt)4770// (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, setne)), setu?lt)4771// (select_cc lhs, rhs, 1, (sext (setcc lhs, rhs, setgt)), setu?lt)4772// (select_cc lhs, rhs, 1, (sext (setcc rhs, lhs, setlt)), setu?lt)4773case ISD::SETULT:4774if (!IsUnCmp && InnerCC != ISD::SETNE)4775return false;4776IsUnCmp = true;4777[[fallthrough]];4778case ISD::SETLT:4779if (InnerCC == ISD::SETNE || (InnerCC == ISD::SETGT && !InnerSwapped) ||4780(InnerCC == ISD::SETLT && InnerSwapped))4781NeedSwapOps = (TrueResVal == 1);4782else4783return false;4784break;47854786// (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, setne)), setu?gt)4787// (select_cc lhs, rhs, 1, (sext (setcc lhs, rhs, setlt)), setu?gt)4788// (select_cc lhs, rhs, 1, (sext (setcc rhs, lhs, setgt)), setu?gt)4789// (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, setne)), setu?gt)4790// (select_cc lhs, rhs, -1, (zext (setcc lhs, rhs, setlt)), setu?gt)4791// (select_cc lhs, rhs, -1, (zext (setcc rhs, lhs, setgt)), setu?gt)4792case ISD::SETUGT:4793if (!IsUnCmp && InnerCC != ISD::SETNE)4794return false;4795IsUnCmp = true;4796[[fallthrough]];4797case ISD::SETGT:4798if (InnerCC == ISD::SETNE || (InnerCC == ISD::SETLT && !InnerSwapped) ||4799(InnerCC == ISD::SETGT && InnerSwapped))4800NeedSwapOps = (TrueResVal == -1);4801else4802return false;4803break;48044805default:4806return false;4807}48084809LLVM_DEBUG(dbgs() << "Found a node that can be lowered to a SETB: ");4810LLVM_DEBUG(N->dump());48114812return true;4813}48144815// Return true if it's a software square-root/divide operand.4816static bool isSWTestOp(SDValue N) {4817if (N.getOpcode() == PPCISD::FTSQRT)4818return true;4819if (N.getNumOperands() < 1 || !isa<ConstantSDNode>(N.getOperand(0)) ||4820N.getOpcode() != ISD::INTRINSIC_WO_CHAIN)4821return false;4822switch (N.getConstantOperandVal(0)) {4823case Intrinsic::ppc_vsx_xvtdivdp:4824case Intrinsic::ppc_vsx_xvtdivsp:4825case Intrinsic::ppc_vsx_xvtsqrtdp:4826case Intrinsic::ppc_vsx_xvtsqrtsp:4827return true;4828}4829return false;4830}48314832bool PPCDAGToDAGISel::tryFoldSWTestBRCC(SDNode *N) {4833assert(N->getOpcode() == ISD::BR_CC && "ISD::BR_CC is expected.");4834// We are looking for following patterns, where `truncate to i1` actually has4835// the same semantic with `and 1`.4836// (br_cc seteq, (truncateToi1 SWTestOp), 0) -> (BCC PRED_NU, SWTestOp)4837// (br_cc seteq, (and SWTestOp, 2), 0) -> (BCC PRED_NE, SWTestOp)4838// (br_cc seteq, (and SWTestOp, 4), 0) -> (BCC PRED_LE, SWTestOp)4839// (br_cc seteq, (and SWTestOp, 8), 0) -> (BCC PRED_GE, SWTestOp)4840// (br_cc setne, (truncateToi1 SWTestOp), 0) -> (BCC PRED_UN, SWTestOp)4841// (br_cc setne, (and SWTestOp, 2), 0) -> (BCC PRED_EQ, SWTestOp)4842// (br_cc setne, (and SWTestOp, 4), 0) -> (BCC PRED_GT, SWTestOp)4843// (br_cc setne, (and SWTestOp, 8), 0) -> (BCC PRED_LT, SWTestOp)4844ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();4845if (CC != ISD::SETEQ && CC != ISD::SETNE)4846return false;48474848SDValue CmpRHS = N->getOperand(3);4849if (!isNullConstant(CmpRHS))4850return false;48514852SDValue CmpLHS = N->getOperand(2);4853if (CmpLHS.getNumOperands() < 1 || !isSWTestOp(CmpLHS.getOperand(0)))4854return false;48554856unsigned PCC = 0;4857bool IsCCNE = CC == ISD::SETNE;4858if (CmpLHS.getOpcode() == ISD::AND &&4859isa<ConstantSDNode>(CmpLHS.getOperand(1)))4860switch (CmpLHS.getConstantOperandVal(1)) {4861case 1:4862PCC = IsCCNE ? PPC::PRED_UN : PPC::PRED_NU;4863break;4864case 2:4865PCC = IsCCNE ? PPC::PRED_EQ : PPC::PRED_NE;4866break;4867case 4:4868PCC = IsCCNE ? PPC::PRED_GT : PPC::PRED_LE;4869break;4870case 8:4871PCC = IsCCNE ? PPC::PRED_LT : PPC::PRED_GE;4872break;4873default:4874return false;4875}4876else if (CmpLHS.getOpcode() == ISD::TRUNCATE &&4877CmpLHS.getValueType() == MVT::i1)4878PCC = IsCCNE ? PPC::PRED_UN : PPC::PRED_NU;48794880if (PCC) {4881SDLoc dl(N);4882SDValue Ops[] = {getI32Imm(PCC, dl), CmpLHS.getOperand(0), N->getOperand(4),4883N->getOperand(0)};4884CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);4885return true;4886}4887return false;4888}48894890bool PPCDAGToDAGISel::trySelectLoopCountIntrinsic(SDNode *N) {4891// Sometimes the promoted value of the intrinsic is ANDed by some non-zero4892// value, for example when crbits is disabled. If so, select the4893// loop_decrement intrinsics now.4894ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();4895SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);48964897if (LHS.getOpcode() != ISD::AND || !isa<ConstantSDNode>(LHS.getOperand(1)) ||4898isNullConstant(LHS.getOperand(1)))4899return false;49004901if (LHS.getOperand(0).getOpcode() != ISD::INTRINSIC_W_CHAIN ||4902LHS.getOperand(0).getConstantOperandVal(1) != Intrinsic::loop_decrement)4903return false;49044905if (!isa<ConstantSDNode>(RHS))4906return false;49074908assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&4909"Counter decrement comparison is not EQ or NE");49104911SDValue OldDecrement = LHS.getOperand(0);4912assert(OldDecrement.hasOneUse() && "loop decrement has more than one use!");49134914SDLoc DecrementLoc(OldDecrement);4915SDValue ChainInput = OldDecrement.getOperand(0);4916SDValue DecrementOps[] = {Subtarget->isPPC64() ? getI64Imm(1, DecrementLoc)4917: getI32Imm(1, DecrementLoc)};4918unsigned DecrementOpcode =4919Subtarget->isPPC64() ? PPC::DecreaseCTR8loop : PPC::DecreaseCTRloop;4920SDNode *NewDecrement = CurDAG->getMachineNode(DecrementOpcode, DecrementLoc,4921MVT::i1, DecrementOps);49224923unsigned Val = RHS->getAsZExtVal();4924bool IsBranchOnTrue = (CC == ISD::SETEQ && Val) || (CC == ISD::SETNE && !Val);4925unsigned Opcode = IsBranchOnTrue ? PPC::BC : PPC::BCn;49264927ReplaceUses(LHS.getValue(0), LHS.getOperand(1));4928CurDAG->RemoveDeadNode(LHS.getNode());49294930// Mark the old loop_decrement intrinsic as dead.4931ReplaceUses(OldDecrement.getValue(1), ChainInput);4932CurDAG->RemoveDeadNode(OldDecrement.getNode());49334934SDValue Chain = CurDAG->getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,4935ChainInput, N->getOperand(0));49364937CurDAG->SelectNodeTo(N, Opcode, MVT::Other, SDValue(NewDecrement, 0),4938N->getOperand(4), Chain);4939return true;4940}49414942bool PPCDAGToDAGISel::tryAsSingleRLWINM(SDNode *N) {4943assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");4944unsigned Imm;4945if (!isInt32Immediate(N->getOperand(1), Imm))4946return false;49474948SDLoc dl(N);4949SDValue Val = N->getOperand(0);4950unsigned SH, MB, ME;4951// If this is an and of a value rotated between 0 and 31 bits and then and'd4952// with a mask, emit rlwinm4953if (isRotateAndMask(Val.getNode(), Imm, false, SH, MB, ME)) {4954Val = Val.getOperand(0);4955SDValue Ops[] = {Val, getI32Imm(SH, dl), getI32Imm(MB, dl),4956getI32Imm(ME, dl)};4957CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);4958return true;4959}49604961// If this is just a masked value where the input is not handled, and4962// is not a rotate-left (handled by a pattern in the .td file), emit rlwinm4963if (isRunOfOnes(Imm, MB, ME) && Val.getOpcode() != ISD::ROTL) {4964SDValue Ops[] = {Val, getI32Imm(0, dl), getI32Imm(MB, dl),4965getI32Imm(ME, dl)};4966CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);4967return true;4968}49694970// AND X, 0 -> 0, not "rlwinm 32".4971if (Imm == 0) {4972ReplaceUses(SDValue(N, 0), N->getOperand(1));4973return true;4974}49754976return false;4977}49784979bool PPCDAGToDAGISel::tryAsSingleRLWINM8(SDNode *N) {4980assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");4981uint64_t Imm64;4982if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64))4983return false;49844985unsigned MB, ME;4986if (isRunOfOnes64(Imm64, MB, ME) && MB >= 32 && MB <= ME) {4987// MB ME4988// +----------------------+4989// |xxxxxxxxxxx00011111000|4990// +----------------------+4991// 0 32 644992// We can only do it if the MB is larger than 32 and MB <= ME4993// as RLWINM will replace the contents of [0 - 32) with [32 - 64) even4994// we didn't rotate it.4995SDLoc dl(N);4996SDValue Ops[] = {N->getOperand(0), getI64Imm(0, dl), getI64Imm(MB - 32, dl),4997getI64Imm(ME - 32, dl)};4998CurDAG->SelectNodeTo(N, PPC::RLWINM8, MVT::i64, Ops);4999return true;5000}50015002return false;5003}50045005bool PPCDAGToDAGISel::tryAsPairOfRLDICL(SDNode *N) {5006assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");5007uint64_t Imm64;5008if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64))5009return false;50105011// Do nothing if it is 16-bit imm as the pattern in the .td file handle5012// it well with "andi.".5013if (isUInt<16>(Imm64))5014return false;50155016SDLoc Loc(N);5017SDValue Val = N->getOperand(0);50185019// Optimized with two rldicl's as follows:5020// Add missing bits on left to the mask and check that the mask is a5021// wrapped run of ones, i.e.5022// Change pattern |0001111100000011111111|5023// to |1111111100000011111111|.5024unsigned NumOfLeadingZeros = llvm::countl_zero(Imm64);5025if (NumOfLeadingZeros != 0)5026Imm64 |= maskLeadingOnes<uint64_t>(NumOfLeadingZeros);50275028unsigned MB, ME;5029if (!isRunOfOnes64(Imm64, MB, ME))5030return false;50315032// ME MB MB-ME+635033// +----------------------+ +----------------------+5034// |1111111100000011111111| -> |0000001111111111111111|5035// +----------------------+ +----------------------+5036// 0 63 0 635037// There are ME + 1 ones on the left and (MB - ME + 63) & 63 zeros in between.5038unsigned OnesOnLeft = ME + 1;5039unsigned ZerosInBetween = (MB - ME + 63) & 63;5040// Rotate left by OnesOnLeft (so leading ones are now trailing ones) and clear5041// on the left the bits that are already zeros in the mask.5042Val = SDValue(CurDAG->getMachineNode(PPC::RLDICL, Loc, MVT::i64, Val,5043getI64Imm(OnesOnLeft, Loc),5044getI64Imm(ZerosInBetween, Loc)),50450);5046// MB-ME+63 ME MB5047// +----------------------+ +----------------------+5048// |0000001111111111111111| -> |0001111100000011111111|5049// +----------------------+ +----------------------+5050// 0 63 0 635051// Rotate back by 64 - OnesOnLeft to undo previous rotate. Then clear on the5052// left the number of ones we previously added.5053SDValue Ops[] = {Val, getI64Imm(64 - OnesOnLeft, Loc),5054getI64Imm(NumOfLeadingZeros, Loc)};5055CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);5056return true;5057}50585059bool PPCDAGToDAGISel::tryAsSingleRLWIMI(SDNode *N) {5060assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");5061unsigned Imm;5062if (!isInt32Immediate(N->getOperand(1), Imm))5063return false;50645065SDValue Val = N->getOperand(0);5066unsigned Imm2;5067// ISD::OR doesn't get all the bitfield insertion fun.5068// (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) might be a5069// bitfield insert.5070if (Val.getOpcode() != ISD::OR || !isInt32Immediate(Val.getOperand(1), Imm2))5071return false;50725073// The idea here is to check whether this is equivalent to:5074// (c1 & m) | (x & ~m)5075// where m is a run-of-ones mask. The logic here is that, for each bit in5076// c1 and c2:5077// - if both are 1, then the output will be 1.5078// - if both are 0, then the output will be 0.5079// - if the bit in c1 is 0, and the bit in c2 is 1, then the output will5080// come from x.5081// - if the bit in c1 is 1, and the bit in c2 is 0, then the output will5082// be 0.5083// If that last condition is never the case, then we can form m from the5084// bits that are the same between c1 and c2.5085unsigned MB, ME;5086if (isRunOfOnes(~(Imm ^ Imm2), MB, ME) && !(~Imm & Imm2)) {5087SDLoc dl(N);5088SDValue Ops[] = {Val.getOperand(0), Val.getOperand(1), getI32Imm(0, dl),5089getI32Imm(MB, dl), getI32Imm(ME, dl)};5090ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops));5091return true;5092}50935094return false;5095}50965097bool PPCDAGToDAGISel::tryAsSingleRLDCL(SDNode *N) {5098assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");50995100uint64_t Imm64;5101if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64) || !isMask_64(Imm64))5102return false;51035104SDValue Val = N->getOperand(0);51055106if (Val.getOpcode() != ISD::ROTL)5107return false;51085109// Looking to try to avoid a situation like this one:5110// %2 = tail call i64 @llvm.fshl.i64(i64 %word, i64 %word, i64 23)5111// %and1 = and i64 %2, 92233720368547758075112// In this function we are looking to try to match RLDCL. However, the above5113// DAG would better match RLDICL instead which is not what we are looking5114// for here.5115SDValue RotateAmt = Val.getOperand(1);5116if (RotateAmt.getOpcode() == ISD::Constant)5117return false;51185119unsigned MB = 64 - llvm::countr_one(Imm64);5120SDLoc dl(N);5121SDValue Ops[] = {Val.getOperand(0), RotateAmt, getI32Imm(MB, dl)};5122CurDAG->SelectNodeTo(N, PPC::RLDCL, MVT::i64, Ops);5123return true;5124}51255126bool PPCDAGToDAGISel::tryAsSingleRLDICL(SDNode *N) {5127assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");5128uint64_t Imm64;5129if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64) || !isMask_64(Imm64))5130return false;51315132// If this is a 64-bit zero-extension mask, emit rldicl.5133unsigned MB = 64 - llvm::countr_one(Imm64);5134unsigned SH = 0;5135unsigned Imm;5136SDValue Val = N->getOperand(0);5137SDLoc dl(N);51385139if (Val.getOpcode() == ISD::ANY_EXTEND) {5140auto Op0 = Val.getOperand(0);5141if (Op0.getOpcode() == ISD::SRL &&5142isInt32Immediate(Op0.getOperand(1).getNode(), Imm) && Imm <= MB) {51435144auto ResultType = Val.getNode()->getValueType(0);5145auto ImDef = CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl, ResultType);5146SDValue IDVal(ImDef, 0);51475148Val = SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, ResultType,5149IDVal, Op0.getOperand(0),5150getI32Imm(1, dl)),51510);5152SH = 64 - Imm;5153}5154}51555156// If the operand is a logical right shift, we can fold it into this5157// instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)5158// for n <= mb. The right shift is really a left rotate followed by a5159// mask, and this mask is a more-restrictive sub-mask of the mask implied5160// by the shift.5161if (Val.getOpcode() == ISD::SRL &&5162isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {5163assert(Imm < 64 && "Illegal shift amount");5164Val = Val.getOperand(0);5165SH = 64 - Imm;5166}51675168SDValue Ops[] = {Val, getI32Imm(SH, dl), getI32Imm(MB, dl)};5169CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);5170return true;5171}51725173bool PPCDAGToDAGISel::tryAsSingleRLDICR(SDNode *N) {5174assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");5175uint64_t Imm64;5176if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64) ||5177!isMask_64(~Imm64))5178return false;51795180// If this is a negated 64-bit zero-extension mask,5181// i.e. the immediate is a sequence of ones from most significant side5182// and all zero for reminder, we should use rldicr.5183unsigned MB = 63 - llvm::countr_one(~Imm64);5184unsigned SH = 0;5185SDLoc dl(N);5186SDValue Ops[] = {N->getOperand(0), getI32Imm(SH, dl), getI32Imm(MB, dl)};5187CurDAG->SelectNodeTo(N, PPC::RLDICR, MVT::i64, Ops);5188return true;5189}51905191bool PPCDAGToDAGISel::tryAsSingleRLDIMI(SDNode *N) {5192assert(N->getOpcode() == ISD::OR && "ISD::OR SDNode expected");5193uint64_t Imm64;5194unsigned MB, ME;5195SDValue N0 = N->getOperand(0);51965197// We won't get fewer instructions if the imm is 32-bit integer.5198// rldimi requires the imm to have consecutive ones with both sides zero.5199// Also, make sure the first Op has only one use, otherwise this may increase5200// register pressure since rldimi is destructive.5201if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64) ||5202isUInt<32>(Imm64) || !isRunOfOnes64(Imm64, MB, ME) || !N0.hasOneUse())5203return false;52045205unsigned SH = 63 - ME;5206SDLoc Dl(N);5207// Use select64Imm for making LI instr instead of directly putting Imm645208SDValue Ops[] = {5209N->getOperand(0),5210SDValue(selectI64Imm(CurDAG, getI64Imm(-1, Dl).getNode()), 0),5211getI32Imm(SH, Dl), getI32Imm(MB, Dl)};5212CurDAG->SelectNodeTo(N, PPC::RLDIMI, MVT::i64, Ops);5213return true;5214}52155216// Select - Convert the specified operand from a target-independent to a5217// target-specific node if it hasn't already been changed.5218void PPCDAGToDAGISel::Select(SDNode *N) {5219SDLoc dl(N);5220if (N->isMachineOpcode()) {5221N->setNodeId(-1);5222return; // Already selected.5223}52245225// In case any misguided DAG-level optimizations form an ADD with a5226// TargetConstant operand, crash here instead of miscompiling (by selecting5227// an r+r add instead of some kind of r+i add).5228if (N->getOpcode() == ISD::ADD &&5229N->getOperand(1).getOpcode() == ISD::TargetConstant)5230llvm_unreachable("Invalid ADD with TargetConstant operand");52315232// Try matching complex bit permutations before doing anything else.5233if (tryBitPermutation(N))5234return;52355236// Try to emit integer compares as GPR-only sequences (i.e. no use of CR).5237if (tryIntCompareInGPR(N))5238return;52395240switch (N->getOpcode()) {5241default: break;52425243case ISD::Constant:5244if (N->getValueType(0) == MVT::i64) {5245ReplaceNode(N, selectI64Imm(CurDAG, N));5246return;5247}5248break;52495250case ISD::INTRINSIC_VOID: {5251auto IntrinsicID = N->getConstantOperandVal(1);5252if (IntrinsicID != Intrinsic::ppc_tdw && IntrinsicID != Intrinsic::ppc_tw &&5253IntrinsicID != Intrinsic::ppc_trapd &&5254IntrinsicID != Intrinsic::ppc_trap)5255break;5256unsigned Opcode = (IntrinsicID == Intrinsic::ppc_tdw ||5257IntrinsicID == Intrinsic::ppc_trapd)5258? PPC::TDI5259: PPC::TWI;5260SmallVector<SDValue, 4> OpsWithMD;5261unsigned MDIndex;5262if (IntrinsicID == Intrinsic::ppc_tdw ||5263IntrinsicID == Intrinsic::ppc_tw) {5264SDValue Ops[] = {N->getOperand(4), N->getOperand(2), N->getOperand(3)};5265int16_t SImmOperand2;5266int16_t SImmOperand3;5267int16_t SImmOperand4;5268bool isOperand2IntS16Immediate =5269isIntS16Immediate(N->getOperand(2), SImmOperand2);5270bool isOperand3IntS16Immediate =5271isIntS16Immediate(N->getOperand(3), SImmOperand3);5272// We will emit PPC::TD or PPC::TW if the 2nd and 3rd operands are reg +5273// reg or imm + imm. The imm + imm form will be optimized to either an5274// unconditional trap or a nop in a later pass.5275if (isOperand2IntS16Immediate == isOperand3IntS16Immediate)5276Opcode = IntrinsicID == Intrinsic::ppc_tdw ? PPC::TD : PPC::TW;5277else if (isOperand3IntS16Immediate)5278// The 2nd and 3rd operands are reg + imm.5279Ops[2] = getI32Imm(int(SImmOperand3) & 0xFFFF, dl);5280else {5281// The 2nd and 3rd operands are imm + reg.5282bool isOperand4IntS16Immediate =5283isIntS16Immediate(N->getOperand(4), SImmOperand4);5284(void)isOperand4IntS16Immediate;5285assert(isOperand4IntS16Immediate &&5286"The 4th operand is not an Immediate");5287// We need to flip the condition immediate TO.5288int16_t TO = int(SImmOperand4) & 0x1F;5289// We swap the first and second bit of TO if they are not same.5290if ((TO & 0x1) != ((TO & 0x2) >> 1))5291TO = (TO & 0x1) ? TO + 1 : TO - 1;5292// We swap the fourth and fifth bit of TO if they are not same.5293if ((TO & 0x8) != ((TO & 0x10) >> 1))5294TO = (TO & 0x8) ? TO + 8 : TO - 8;5295Ops[0] = getI32Imm(TO, dl);5296Ops[1] = N->getOperand(3);5297Ops[2] = getI32Imm(int(SImmOperand2) & 0xFFFF, dl);5298}5299OpsWithMD = {Ops[0], Ops[1], Ops[2]};5300MDIndex = 5;5301} else {5302OpsWithMD = {getI32Imm(24, dl), N->getOperand(2), getI32Imm(0, dl)};5303MDIndex = 3;5304}53055306if (N->getNumOperands() > MDIndex) {5307SDValue MDV = N->getOperand(MDIndex);5308const MDNode *MD = cast<MDNodeSDNode>(MDV)->getMD();5309assert(MD->getNumOperands() != 0 && "Empty MDNode in operands!");5310assert((isa<MDString>(MD->getOperand(0)) &&5311cast<MDString>(MD->getOperand(0))->getString() ==5312"ppc-trap-reason") &&5313"Unsupported annotation data type!");5314for (unsigned i = 1; i < MD->getNumOperands(); i++) {5315assert(isa<MDString>(MD->getOperand(i)) &&5316"Invalid data type for annotation ppc-trap-reason!");5317OpsWithMD.push_back(5318getI32Imm(std::stoi(cast<MDString>(5319MD->getOperand(i))->getString().str()), dl));5320}5321}5322OpsWithMD.push_back(N->getOperand(0)); // chain5323CurDAG->SelectNodeTo(N, Opcode, MVT::Other, OpsWithMD);5324return;5325}53265327case ISD::INTRINSIC_WO_CHAIN: {5328// We emit the PPC::FSELS instruction here because of type conflicts with5329// the comparison operand. The FSELS instruction is defined to use an 8-byte5330// comparison like the FSELD version. The fsels intrinsic takes a 4-byte5331// value for the comparison. When selecting through a .td file, a type5332// error is raised. Must check this first so we never break on the5333// !Subtarget->isISA3_1() check.5334auto IntID = N->getConstantOperandVal(0);5335if (IntID == Intrinsic::ppc_fsels) {5336SDValue Ops[] = {N->getOperand(1), N->getOperand(2), N->getOperand(3)};5337CurDAG->SelectNodeTo(N, PPC::FSELS, MVT::f32, Ops);5338return;5339}53405341if (IntID == Intrinsic::ppc_bcdadd_p || IntID == Intrinsic::ppc_bcdsub_p) {5342auto Pred = N->getConstantOperandVal(1);5343unsigned Opcode =5344IntID == Intrinsic::ppc_bcdadd_p ? PPC::BCDADD_rec : PPC::BCDSUB_rec;5345unsigned SubReg = 0;5346unsigned ShiftVal = 0;5347bool Reverse = false;5348switch (Pred) {5349case 0:5350SubReg = PPC::sub_eq;5351ShiftVal = 1;5352break;5353case 1:5354SubReg = PPC::sub_eq;5355ShiftVal = 1;5356Reverse = true;5357break;5358case 2:5359SubReg = PPC::sub_lt;5360ShiftVal = 3;5361break;5362case 3:5363SubReg = PPC::sub_lt;5364ShiftVal = 3;5365Reverse = true;5366break;5367case 4:5368SubReg = PPC::sub_gt;5369ShiftVal = 2;5370break;5371case 5:5372SubReg = PPC::sub_gt;5373ShiftVal = 2;5374Reverse = true;5375break;5376case 6:5377SubReg = PPC::sub_un;5378break;5379case 7:5380SubReg = PPC::sub_un;5381Reverse = true;5382break;5383}53845385EVT VTs[] = {MVT::v16i8, MVT::Glue};5386SDValue Ops[] = {N->getOperand(2), N->getOperand(3),5387CurDAG->getTargetConstant(0, dl, MVT::i32)};5388SDValue BCDOp = SDValue(CurDAG->getMachineNode(Opcode, dl, VTs, Ops), 0);5389SDValue CR6Reg = CurDAG->getRegister(PPC::CR6, MVT::i32);5390// On Power10, we can use SETBC[R]. On prior architectures, we have to use5391// MFOCRF and shift/negate the value.5392if (Subtarget->isISA3_1()) {5393SDValue SubRegIdx = CurDAG->getTargetConstant(SubReg, dl, MVT::i32);5394SDValue CRBit = SDValue(5395CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::i1,5396CR6Reg, SubRegIdx, BCDOp.getValue(1)),53970);5398CurDAG->SelectNodeTo(N, Reverse ? PPC::SETBCR : PPC::SETBC, MVT::i32,5399CRBit);5400} else {5401SDValue Move =5402SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR6Reg,5403BCDOp.getValue(1)),54040);5405SDValue Ops[] = {Move, getI32Imm((32 - (4 + ShiftVal)) & 31, dl),5406getI32Imm(31, dl), getI32Imm(31, dl)};5407if (!Reverse)5408CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);5409else {5410SDValue Shift = SDValue(5411CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);5412CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Shift, getI32Imm(1, dl));5413}5414}5415return;5416}54175418if (!Subtarget->isISA3_1())5419break;5420unsigned Opcode = 0;5421switch (IntID) {5422default:5423break;5424case Intrinsic::ppc_altivec_vstribr_p:5425Opcode = PPC::VSTRIBR_rec;5426break;5427case Intrinsic::ppc_altivec_vstribl_p:5428Opcode = PPC::VSTRIBL_rec;5429break;5430case Intrinsic::ppc_altivec_vstrihr_p:5431Opcode = PPC::VSTRIHR_rec;5432break;5433case Intrinsic::ppc_altivec_vstrihl_p:5434Opcode = PPC::VSTRIHL_rec;5435break;5436}5437if (!Opcode)5438break;54395440// Generate the appropriate vector string isolate intrinsic to match.5441EVT VTs[] = {MVT::v16i8, MVT::Glue};5442SDValue VecStrOp =5443SDValue(CurDAG->getMachineNode(Opcode, dl, VTs, N->getOperand(2)), 0);5444// Vector string isolate instructions update the EQ bit of CR6.5445// Generate a SETBC instruction to extract the bit and place it in a GPR.5446SDValue SubRegIdx = CurDAG->getTargetConstant(PPC::sub_eq, dl, MVT::i32);5447SDValue CR6Reg = CurDAG->getRegister(PPC::CR6, MVT::i32);5448SDValue CRBit = SDValue(5449CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::i1,5450CR6Reg, SubRegIdx, VecStrOp.getValue(1)),54510);5452CurDAG->SelectNodeTo(N, PPC::SETBC, MVT::i32, CRBit);5453return;5454}54555456case ISD::SETCC:5457case ISD::STRICT_FSETCC:5458case ISD::STRICT_FSETCCS:5459if (trySETCC(N))5460return;5461break;5462// These nodes will be transformed into GETtlsADDR32 node, which5463// later becomes BL_TLS __tls_get_addr(sym at tlsgd)@PLT5464case PPCISD::ADDI_TLSLD_L_ADDR:5465case PPCISD::ADDI_TLSGD_L_ADDR: {5466const Module *Mod = MF->getFunction().getParent();5467if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) != MVT::i32 ||5468!Subtarget->isSecurePlt() || !Subtarget->isTargetELF() ||5469Mod->getPICLevel() == PICLevel::SmallPIC)5470break;5471// Attach global base pointer on GETtlsADDR32 node in order to5472// generate secure plt code for TLS symbols.5473getGlobalBaseReg();5474} break;5475case PPCISD::CALL: {5476if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) != MVT::i32 ||5477!TM.isPositionIndependent() || !Subtarget->isSecurePlt() ||5478!Subtarget->isTargetELF())5479break;54805481SDValue Op = N->getOperand(1);54825483if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {5484if (GA->getTargetFlags() == PPCII::MO_PLT)5485getGlobalBaseReg();5486}5487else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {5488if (ES->getTargetFlags() == PPCII::MO_PLT)5489getGlobalBaseReg();5490}5491}5492break;54935494case PPCISD::GlobalBaseReg:5495ReplaceNode(N, getGlobalBaseReg());5496return;54975498case ISD::FrameIndex:5499selectFrameIndex(N, N);5500return;55015502case PPCISD::MFOCRF: {5503SDValue InGlue = N->getOperand(1);5504ReplaceNode(N, CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,5505N->getOperand(0), InGlue));5506return;5507}55085509case PPCISD::READ_TIME_BASE:5510ReplaceNode(N, CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,5511MVT::Other, N->getOperand(0)));5512return;55135514case PPCISD::SRA_ADDZE: {5515SDValue N0 = N->getOperand(0);5516SDValue ShiftAmt =5517CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->5518getConstantIntValue(), dl,5519N->getValueType(0));5520if (N->getValueType(0) == MVT::i64) {5521SDNode *Op =5522CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,5523N0, ShiftAmt);5524CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64, SDValue(Op, 0),5525SDValue(Op, 1));5526return;5527} else {5528assert(N->getValueType(0) == MVT::i32 &&5529"Expecting i64 or i32 in PPCISD::SRA_ADDZE");5530SDNode *Op =5531CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,5532N0, ShiftAmt);5533CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, SDValue(Op, 0),5534SDValue(Op, 1));5535return;5536}5537}55385539case ISD::STORE: {5540// Change TLS initial-exec (or TLS local-exec on AIX) D-form stores to5541// X-form stores.5542StoreSDNode *ST = cast<StoreSDNode>(N);5543if (EnableTLSOpt && (Subtarget->isELFv2ABI() || Subtarget->isAIXABI()) &&5544ST->getAddressingMode() != ISD::PRE_INC)5545if (tryTLSXFormStore(ST))5546return;5547break;5548}5549case ISD::LOAD: {5550// Handle preincrement loads.5551LoadSDNode *LD = cast<LoadSDNode>(N);5552EVT LoadedVT = LD->getMemoryVT();55535554// Normal loads are handled by code generated from the .td file.5555if (LD->getAddressingMode() != ISD::PRE_INC) {5556// Change TLS initial-exec (or TLS local-exec on AIX) D-form loads to5557// X-form loads.5558if (EnableTLSOpt && (Subtarget->isELFv2ABI() || Subtarget->isAIXABI()))5559if (tryTLSXFormLoad(LD))5560return;5561break;5562}55635564SDValue Offset = LD->getOffset();5565if (Offset.getOpcode() == ISD::TargetConstant ||5566Offset.getOpcode() == ISD::TargetGlobalAddress) {55675568unsigned Opcode;5569bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;5570if (LD->getValueType(0) != MVT::i64) {5571// Handle PPC32 integer and normal FP loads.5572assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");5573switch (LoadedVT.getSimpleVT().SimpleTy) {5574default: llvm_unreachable("Invalid PPC load type!");5575case MVT::f64: Opcode = PPC::LFDU; break;5576case MVT::f32: Opcode = PPC::LFSU; break;5577case MVT::i32: Opcode = PPC::LWZU; break;5578case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;5579case MVT::i1:5580case MVT::i8: Opcode = PPC::LBZU; break;5581}5582} else {5583assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");5584assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");5585switch (LoadedVT.getSimpleVT().SimpleTy) {5586default: llvm_unreachable("Invalid PPC load type!");5587case MVT::i64: Opcode = PPC::LDU; break;5588case MVT::i32: Opcode = PPC::LWZU8; break;5589case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;5590case MVT::i1:5591case MVT::i8: Opcode = PPC::LBZU8; break;5592}5593}55945595SDValue Chain = LD->getChain();5596SDValue Base = LD->getBasePtr();5597SDValue Ops[] = { Offset, Base, Chain };5598SDNode *MN = CurDAG->getMachineNode(5599Opcode, dl, LD->getValueType(0),5600PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);5601transferMemOperands(N, MN);5602ReplaceNode(N, MN);5603return;5604} else {5605unsigned Opcode;5606bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;5607if (LD->getValueType(0) != MVT::i64) {5608// Handle PPC32 integer and normal FP loads.5609assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");5610switch (LoadedVT.getSimpleVT().SimpleTy) {5611default: llvm_unreachable("Invalid PPC load type!");5612case MVT::f64: Opcode = PPC::LFDUX; break;5613case MVT::f32: Opcode = PPC::LFSUX; break;5614case MVT::i32: Opcode = PPC::LWZUX; break;5615case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;5616case MVT::i1:5617case MVT::i8: Opcode = PPC::LBZUX; break;5618}5619} else {5620assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");5621assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&5622"Invalid sext update load");5623switch (LoadedVT.getSimpleVT().SimpleTy) {5624default: llvm_unreachable("Invalid PPC load type!");5625case MVT::i64: Opcode = PPC::LDUX; break;5626case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break;5627case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;5628case MVT::i1:5629case MVT::i8: Opcode = PPC::LBZUX8; break;5630}5631}56325633SDValue Chain = LD->getChain();5634SDValue Base = LD->getBasePtr();5635SDValue Ops[] = { Base, Offset, Chain };5636SDNode *MN = CurDAG->getMachineNode(5637Opcode, dl, LD->getValueType(0),5638PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);5639transferMemOperands(N, MN);5640ReplaceNode(N, MN);5641return;5642}5643}56445645case ISD::AND:5646// If this is an 'and' with a mask, try to emit rlwinm/rldicl/rldicr5647if (tryAsSingleRLWINM(N) || tryAsSingleRLWIMI(N) || tryAsSingleRLDCL(N) ||5648tryAsSingleRLDICL(N) || tryAsSingleRLDICR(N) || tryAsSingleRLWINM8(N) ||5649tryAsPairOfRLDICL(N))5650return;56515652// Other cases are autogenerated.5653break;5654case ISD::OR: {5655if (N->getValueType(0) == MVT::i32)5656if (tryBitfieldInsert(N))5657return;56585659int16_t Imm;5660if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&5661isIntS16Immediate(N->getOperand(1), Imm)) {5662KnownBits LHSKnown = CurDAG->computeKnownBits(N->getOperand(0));56635664// If this is equivalent to an add, then we can fold it with the5665// FrameIndex calculation.5666if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)Imm) == ~0ULL) {5667selectFrameIndex(N, N->getOperand(0).getNode(), (int64_t)Imm);5668return;5669}5670}56715672// If this is 'or' against an imm with consecutive ones and both sides zero,5673// try to emit rldimi5674if (tryAsSingleRLDIMI(N))5675return;56765677// OR with a 32-bit immediate can be handled by ori + oris5678// without creating an immediate in a GPR.5679uint64_t Imm64 = 0;5680bool IsPPC64 = Subtarget->isPPC64();5681if (IsPPC64 && isInt64Immediate(N->getOperand(1), Imm64) &&5682(Imm64 & ~0xFFFFFFFFuLL) == 0) {5683// If ImmHi (ImmHi) is zero, only one ori (oris) is generated later.5684uint64_t ImmHi = Imm64 >> 16;5685uint64_t ImmLo = Imm64 & 0xFFFF;5686if (ImmHi != 0 && ImmLo != 0) {5687SDNode *Lo = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,5688N->getOperand(0),5689getI16Imm(ImmLo, dl));5690SDValue Ops1[] = { SDValue(Lo, 0), getI16Imm(ImmHi, dl)};5691CurDAG->SelectNodeTo(N, PPC::ORIS8, MVT::i64, Ops1);5692return;5693}5694}56955696// Other cases are autogenerated.5697break;5698}5699case ISD::XOR: {5700// XOR with a 32-bit immediate can be handled by xori + xoris5701// without creating an immediate in a GPR.5702uint64_t Imm64 = 0;5703bool IsPPC64 = Subtarget->isPPC64();5704if (IsPPC64 && isInt64Immediate(N->getOperand(1), Imm64) &&5705(Imm64 & ~0xFFFFFFFFuLL) == 0) {5706// If ImmHi (ImmHi) is zero, only one xori (xoris) is generated later.5707uint64_t ImmHi = Imm64 >> 16;5708uint64_t ImmLo = Imm64 & 0xFFFF;5709if (ImmHi != 0 && ImmLo != 0) {5710SDNode *Lo = CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64,5711N->getOperand(0),5712getI16Imm(ImmLo, dl));5713SDValue Ops1[] = { SDValue(Lo, 0), getI16Imm(ImmHi, dl)};5714CurDAG->SelectNodeTo(N, PPC::XORIS8, MVT::i64, Ops1);5715return;5716}5717}57185719break;5720}5721case ISD::ADD: {5722int16_t Imm;5723if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&5724isIntS16Immediate(N->getOperand(1), Imm)) {5725selectFrameIndex(N, N->getOperand(0).getNode(), (int64_t)Imm);5726return;5727}57285729break;5730}5731case ISD::SHL: {5732unsigned Imm, SH, MB, ME;5733if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&5734isRotateAndMask(N, Imm, true, SH, MB, ME)) {5735SDValue Ops[] = { N->getOperand(0).getOperand(0),5736getI32Imm(SH, dl), getI32Imm(MB, dl),5737getI32Imm(ME, dl) };5738CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);5739return;5740}57415742// Other cases are autogenerated.5743break;5744}5745case ISD::SRL: {5746unsigned Imm, SH, MB, ME;5747if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&5748isRotateAndMask(N, Imm, true, SH, MB, ME)) {5749SDValue Ops[] = { N->getOperand(0).getOperand(0),5750getI32Imm(SH, dl), getI32Imm(MB, dl),5751getI32Imm(ME, dl) };5752CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);5753return;5754}57555756// Other cases are autogenerated.5757break;5758}5759case ISD::MUL: {5760SDValue Op1 = N->getOperand(1);5761if (Op1.getOpcode() != ISD::Constant ||5762(Op1.getValueType() != MVT::i64 && Op1.getValueType() != MVT::i32))5763break;57645765// If the multiplier fits int16, we can handle it with mulli.5766int64_t Imm = Op1->getAsZExtVal();5767unsigned Shift = llvm::countr_zero<uint64_t>(Imm);5768if (isInt<16>(Imm) || !Shift)5769break;57705771// If the shifted value fits int16, we can do this transformation:5772// (mul X, c1 << c2) -> (rldicr (mulli X, c1) c2). We do this in ISEL due to5773// DAGCombiner prefers (shl (mul X, c1), c2) -> (mul X, c1 << c2).5774uint64_t ImmSh = Imm >> Shift;5775if (!isInt<16>(ImmSh))5776break;57775778uint64_t SextImm = SignExtend64(ImmSh & 0xFFFF, 16);5779if (Op1.getValueType() == MVT::i64) {5780SDValue SDImm = CurDAG->getTargetConstant(SextImm, dl, MVT::i64);5781SDNode *MulNode = CurDAG->getMachineNode(PPC::MULLI8, dl, MVT::i64,5782N->getOperand(0), SDImm);57835784SDValue Ops[] = {SDValue(MulNode, 0), getI32Imm(Shift, dl),5785getI32Imm(63 - Shift, dl)};5786CurDAG->SelectNodeTo(N, PPC::RLDICR, MVT::i64, Ops);5787return;5788} else {5789SDValue SDImm = CurDAG->getTargetConstant(SextImm, dl, MVT::i32);5790SDNode *MulNode = CurDAG->getMachineNode(PPC::MULLI, dl, MVT::i32,5791N->getOperand(0), SDImm);57925793SDValue Ops[] = {SDValue(MulNode, 0), getI32Imm(Shift, dl),5794getI32Imm(0, dl), getI32Imm(31 - Shift, dl)};5795CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);5796return;5797}5798break;5799}5800// FIXME: Remove this once the ANDI glue bug is fixed:5801case PPCISD::ANDI_rec_1_EQ_BIT:5802case PPCISD::ANDI_rec_1_GT_BIT: {5803if (!ANDIGlueBug)5804break;58055806EVT InVT = N->getOperand(0).getValueType();5807assert((InVT == MVT::i64 || InVT == MVT::i32) &&5808"Invalid input type for ANDI_rec_1_EQ_BIT");58095810unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDI8_rec : PPC::ANDI_rec;5811SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,5812N->getOperand(0),5813CurDAG->getTargetConstant(1, dl, InVT)),58140);5815SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);5816SDValue SRIdxVal = CurDAG->getTargetConstant(5817N->getOpcode() == PPCISD::ANDI_rec_1_EQ_BIT ? PPC::sub_eq : PPC::sub_gt,5818dl, MVT::i32);58195820CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1, CR0Reg,5821SRIdxVal, SDValue(AndI.getNode(), 1) /* glue */);5822return;5823}5824case ISD::SELECT_CC: {5825ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();5826EVT PtrVT =5827CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());5828bool isPPC64 = (PtrVT == MVT::i64);58295830// If this is a select of i1 operands, we'll pattern match it.5831if (Subtarget->useCRBits() && N->getOperand(0).getValueType() == MVT::i1)5832break;58335834if (Subtarget->isISA3_0() && Subtarget->isPPC64()) {5835bool NeedSwapOps = false;5836bool IsUnCmp = false;5837if (mayUseP9Setb(N, CC, CurDAG, NeedSwapOps, IsUnCmp)) {5838SDValue LHS = N->getOperand(0);5839SDValue RHS = N->getOperand(1);5840if (NeedSwapOps)5841std::swap(LHS, RHS);58425843// Make use of SelectCC to generate the comparison to set CR bits, for5844// equality comparisons having one literal operand, SelectCC probably5845// doesn't need to materialize the whole literal and just use xoris to5846// check it first, it leads the following comparison result can't5847// exactly represent GT/LT relationship. So to avoid this we specify5848// SETGT/SETUGT here instead of SETEQ.5849SDValue GenCC =5850SelectCC(LHS, RHS, IsUnCmp ? ISD::SETUGT : ISD::SETGT, dl);5851CurDAG->SelectNodeTo(5852N, N->getSimpleValueType(0) == MVT::i64 ? PPC::SETB8 : PPC::SETB,5853N->getValueType(0), GenCC);5854NumP9Setb++;5855return;5856}5857}58585859// Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc5860if (!isPPC64 && isNullConstant(N->getOperand(1)) &&5861isOneConstant(N->getOperand(2)) && isNullConstant(N->getOperand(3)) &&5862CC == ISD::SETNE &&5863// FIXME: Implement this optzn for PPC64.5864N->getValueType(0) == MVT::i32) {5865SDNode *Tmp =5866CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,5867N->getOperand(0), getI32Imm(~0U, dl));5868CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(Tmp, 0),5869N->getOperand(0), SDValue(Tmp, 1));5870return;5871}58725873SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);58745875if (N->getValueType(0) == MVT::i1) {5876// An i1 select is: (c & t) | (!c & f).5877bool Inv;5878unsigned Idx = getCRIdxForSetCC(CC, Inv);58795880unsigned SRI;5881switch (Idx) {5882default: llvm_unreachable("Invalid CC index");5883case 0: SRI = PPC::sub_lt; break;5884case 1: SRI = PPC::sub_gt; break;5885case 2: SRI = PPC::sub_eq; break;5886case 3: SRI = PPC::sub_un; break;5887}58885889SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);58905891SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,5892CCBit, CCBit), 0);5893SDValue C = Inv ? NotCCBit : CCBit,5894NotC = Inv ? CCBit : NotCCBit;58955896SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,5897C, N->getOperand(2)), 0);5898SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,5899NotC, N->getOperand(3)), 0);59005901CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);5902return;5903}59045905unsigned BROpc =5906getPredicateForSetCC(CC, N->getOperand(0).getValueType(), Subtarget);59075908unsigned SelectCCOp;5909if (N->getValueType(0) == MVT::i32)5910SelectCCOp = PPC::SELECT_CC_I4;5911else if (N->getValueType(0) == MVT::i64)5912SelectCCOp = PPC::SELECT_CC_I8;5913else if (N->getValueType(0) == MVT::f32) {5914if (Subtarget->hasP8Vector())5915SelectCCOp = PPC::SELECT_CC_VSSRC;5916else if (Subtarget->hasSPE())5917SelectCCOp = PPC::SELECT_CC_SPE4;5918else5919SelectCCOp = PPC::SELECT_CC_F4;5920} else if (N->getValueType(0) == MVT::f64) {5921if (Subtarget->hasVSX())5922SelectCCOp = PPC::SELECT_CC_VSFRC;5923else if (Subtarget->hasSPE())5924SelectCCOp = PPC::SELECT_CC_SPE;5925else5926SelectCCOp = PPC::SELECT_CC_F8;5927} else if (N->getValueType(0) == MVT::f128)5928SelectCCOp = PPC::SELECT_CC_F16;5929else if (Subtarget->hasSPE())5930SelectCCOp = PPC::SELECT_CC_SPE;5931else if (N->getValueType(0) == MVT::v2f64 ||5932N->getValueType(0) == MVT::v2i64)5933SelectCCOp = PPC::SELECT_CC_VSRC;5934else5935SelectCCOp = PPC::SELECT_CC_VRRC;59365937SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),5938getI32Imm(BROpc, dl) };5939CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);5940return;5941}5942case ISD::VECTOR_SHUFFLE:5943if (Subtarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||5944N->getValueType(0) == MVT::v2i64)) {5945ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);59465947SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),5948Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);5949unsigned DM[2];59505951for (int i = 0; i < 2; ++i)5952if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)5953DM[i] = 0;5954else5955DM[i] = 1;59565957if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&5958Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&5959isa<LoadSDNode>(Op1.getOperand(0))) {5960LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));5961SDValue Base, Offset;59625963if (LD->isUnindexed() && LD->hasOneUse() && Op1.hasOneUse() &&5964(LD->getMemoryVT() == MVT::f64 ||5965LD->getMemoryVT() == MVT::i64) &&5966SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {5967SDValue Chain = LD->getChain();5968SDValue Ops[] = { Base, Offset, Chain };5969MachineMemOperand *MemOp = LD->getMemOperand();5970SDNode *NewN = CurDAG->SelectNodeTo(N, PPC::LXVDSX,5971N->getValueType(0), Ops);5972CurDAG->setNodeMemRefs(cast<MachineSDNode>(NewN), {MemOp});5973return;5974}5975}59765977// For little endian, we must swap the input operands and adjust5978// the mask elements (reverse and invert them).5979if (Subtarget->isLittleEndian()) {5980std::swap(Op1, Op2);5981unsigned tmp = DM[0];5982DM[0] = 1 - DM[1];5983DM[1] = 1 - tmp;5984}59855986SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), dl,5987MVT::i32);5988SDValue Ops[] = { Op1, Op2, DMV };5989CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);5990return;5991}59925993break;5994case PPCISD::BDNZ:5995case PPCISD::BDZ: {5996bool IsPPC64 = Subtarget->isPPC64();5997SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };5998CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ5999? (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ)6000: (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),6001MVT::Other, Ops);6002return;6003}6004case PPCISD::COND_BRANCH: {6005// Op #0 is the Chain.6006// Op #1 is the PPC::PRED_* number.6007// Op #2 is the CR#6008// Op #3 is the Dest MBB6009// Op #4 is the Flag.6010// Prevent PPC::PRED_* from being selected into LI.6011unsigned PCC = N->getConstantOperandVal(1);6012if (EnableBranchHint)6013PCC |= getBranchHint(PCC, *FuncInfo, N->getOperand(3));60146015SDValue Pred = getI32Imm(PCC, dl);6016SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),6017N->getOperand(0), N->getOperand(4) };6018CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);6019return;6020}6021case ISD::BR_CC: {6022if (tryFoldSWTestBRCC(N))6023return;6024if (trySelectLoopCountIntrinsic(N))6025return;6026ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();6027unsigned PCC =6028getPredicateForSetCC(CC, N->getOperand(2).getValueType(), Subtarget);60296030if (N->getOperand(2).getValueType() == MVT::i1) {6031unsigned Opc;6032bool Swap;6033switch (PCC) {6034default: llvm_unreachable("Unexpected Boolean-operand predicate");6035case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break;6036case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break;6037case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break;6038case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break;6039case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;6040case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break;6041}60426043// A signed comparison of i1 values produces the opposite result to an6044// unsigned one if the condition code includes less-than or greater-than.6045// This is because 1 is the most negative signed i1 number and the most6046// positive unsigned i1 number. The CR-logical operations used for such6047// comparisons are non-commutative so for signed comparisons vs. unsigned6048// ones, the input operands just need to be swapped.6049if (ISD::isSignedIntSetCC(CC))6050Swap = !Swap;60516052SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,6053N->getOperand(Swap ? 3 : 2),6054N->getOperand(Swap ? 2 : 3)), 0);6055CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other, BitComp, N->getOperand(4),6056N->getOperand(0));6057return;6058}60596060if (EnableBranchHint)6061PCC |= getBranchHint(PCC, *FuncInfo, N->getOperand(4));60626063SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);6064SDValue Ops[] = { getI32Imm(PCC, dl), CondCode,6065N->getOperand(4), N->getOperand(0) };6066CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);6067return;6068}6069case ISD::BRIND: {6070// FIXME: Should custom lower this.6071SDValue Chain = N->getOperand(0);6072SDValue Target = N->getOperand(1);6073unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;6074unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;6075Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,6076Chain), 0);6077CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);6078return;6079}6080case PPCISD::TOC_ENTRY: {6081const bool isPPC64 = Subtarget->isPPC64();6082const bool isELFABI = Subtarget->isSVR4ABI();6083const bool isAIXABI = Subtarget->isAIXABI();60846085// PowerPC only support small, medium and large code model.6086const CodeModel::Model CModel = getCodeModel(*Subtarget, TM, N);60876088assert(!(CModel == CodeModel::Tiny || CModel == CodeModel::Kernel) &&6089"PowerPC doesn't support tiny or kernel code models.");60906091if (isAIXABI && CModel == CodeModel::Medium)6092report_fatal_error("Medium code model is not supported on AIX.");60936094// For 64-bit ELF small code model, we allow SelectCodeCommon to handle6095// this, selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA. For AIX6096// small code model, we need to check for a toc-data attribute.6097if (isPPC64 && !isAIXABI && CModel == CodeModel::Small)6098break;60996100auto replaceWith = [this, &dl](unsigned OpCode, SDNode *TocEntry,6101EVT OperandTy) {6102SDValue GA = TocEntry->getOperand(0);6103SDValue TocBase = TocEntry->getOperand(1);6104SDNode *MN = nullptr;6105if (OpCode == PPC::ADDItoc || OpCode == PPC::ADDItoc8)6106// toc-data access doesn't involve in loading from got, no need to6107// keep memory operands.6108MN = CurDAG->getMachineNode(OpCode, dl, OperandTy, TocBase, GA);6109else {6110MN = CurDAG->getMachineNode(OpCode, dl, OperandTy, GA, TocBase);6111transferMemOperands(TocEntry, MN);6112}6113ReplaceNode(TocEntry, MN);6114};61156116// Handle 32-bit small code model.6117if (!isPPC64 && CModel == CodeModel::Small) {6118// Transforms the ISD::TOC_ENTRY node to passed in Opcode, either6119// PPC::ADDItoc, or PPC::LWZtoc6120if (isELFABI) {6121assert(TM.isPositionIndependent() &&6122"32-bit ELF can only have TOC entries in position independent"6123" code.");6124// 32-bit ELF always uses a small code model toc access.6125replaceWith(PPC::LWZtoc, N, MVT::i32);6126return;6127}61286129assert(isAIXABI && "ELF ABI already handled");61306131if (hasTocDataAttr(N->getOperand(0))) {6132replaceWith(PPC::ADDItoc, N, MVT::i32);6133return;6134}61356136replaceWith(PPC::LWZtoc, N, MVT::i32);6137return;6138}61396140if (isPPC64 && CModel == CodeModel::Small) {6141assert(isAIXABI && "ELF ABI handled in common SelectCode");61426143if (hasTocDataAttr(N->getOperand(0))) {6144replaceWith(PPC::ADDItoc8, N, MVT::i64);6145return;6146}6147// Break if it doesn't have toc data attribute. Proceed with common6148// SelectCode.6149break;6150}61516152assert(CModel != CodeModel::Small && "All small code models handled.");61536154assert((isPPC64 || (isAIXABI && !isPPC64)) && "We are dealing with 64-bit"6155" ELF/AIX or 32-bit AIX in the following.");61566157// Transforms the ISD::TOC_ENTRY node for 32-bit AIX large code model mode,6158// 64-bit medium (ELF-only), or 64-bit large (ELF and AIX) code model code6159// that does not contain TOC data symbols. We generate two instructions as6160// described below. The first source operand is a symbol reference. If it6161// must be referenced via the TOC according to Subtarget, we generate:6162// [32-bit AIX]6163// LWZtocL(@sym, ADDIStocHA(%r2, @sym))6164// [64-bit ELF/AIX]6165// LDtocL(@sym, ADDIStocHA8(%x2, @sym))6166// Otherwise for medium code model ELF we generate:6167// ADDItocL8(ADDIStocHA8(%x2, @sym), @sym)61686169// And finally for AIX with toc-data we generate:6170// [32-bit AIX]6171// ADDItocL(ADDIStocHA(%x2, @sym), @sym)6172// [64-bit AIX]6173// ADDItocL8(ADDIStocHA8(%x2, @sym), @sym)61746175SDValue GA = N->getOperand(0);6176SDValue TOCbase = N->getOperand(1);61776178EVT VT = isPPC64 ? MVT::i64 : MVT::i32;6179SDNode *Tmp = CurDAG->getMachineNode(6180isPPC64 ? PPC::ADDIStocHA8 : PPC::ADDIStocHA, dl, VT, TOCbase, GA);61816182// On AIX, if the symbol has the toc-data attribute it will be defined6183// in the TOC entry, so we use an ADDItocL/ADDItocL8.6184if (isAIXABI && hasTocDataAttr(GA)) {6185ReplaceNode(6186N, CurDAG->getMachineNode(isPPC64 ? PPC::ADDItocL8 : PPC::ADDItocL,6187dl, VT, SDValue(Tmp, 0), GA));6188return;6189}61906191if (PPCLowering->isAccessedAsGotIndirect(GA)) {6192// If it is accessed as got-indirect, we need an extra LWZ/LD to load6193// the address.6194SDNode *MN = CurDAG->getMachineNode(6195isPPC64 ? PPC::LDtocL : PPC::LWZtocL, dl, VT, GA, SDValue(Tmp, 0));61966197transferMemOperands(N, MN);6198ReplaceNode(N, MN);6199return;6200}62016202assert(isPPC64 && "TOC_ENTRY already handled for 32-bit.");6203// Build the address relative to the TOC-pointer.6204ReplaceNode(N, CurDAG->getMachineNode(PPC::ADDItocL8, dl, MVT::i64,6205SDValue(Tmp, 0), GA));6206return;6207}6208case PPCISD::PPC32_PICGOT:6209// Generate a PIC-safe GOT reference.6210assert(Subtarget->is32BitELFABI() &&6211"PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");6212CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT,6213PPCLowering->getPointerTy(CurDAG->getDataLayout()),6214MVT::i32);6215return;62166217case PPCISD::VADD_SPLAT: {6218// This expands into one of three sequences, depending on whether6219// the first operand is odd or even, positive or negative.6220assert(isa<ConstantSDNode>(N->getOperand(0)) &&6221isa<ConstantSDNode>(N->getOperand(1)) &&6222"Invalid operand on VADD_SPLAT!");62236224int Elt = N->getConstantOperandVal(0);6225int EltSize = N->getConstantOperandVal(1);6226unsigned Opc1, Opc2, Opc3;6227EVT VT;62286229if (EltSize == 1) {6230Opc1 = PPC::VSPLTISB;6231Opc2 = PPC::VADDUBM;6232Opc3 = PPC::VSUBUBM;6233VT = MVT::v16i8;6234} else if (EltSize == 2) {6235Opc1 = PPC::VSPLTISH;6236Opc2 = PPC::VADDUHM;6237Opc3 = PPC::VSUBUHM;6238VT = MVT::v8i16;6239} else {6240assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");6241Opc1 = PPC::VSPLTISW;6242Opc2 = PPC::VADDUWM;6243Opc3 = PPC::VSUBUWM;6244VT = MVT::v4i32;6245}62466247if ((Elt & 1) == 0) {6248// Elt is even, in the range [-32,-18] + [16,30].6249//6250// Convert: VADD_SPLAT elt, size6251// Into: tmp = VSPLTIS[BHW] elt6252// VADDU[BHW]M tmp, tmp6253// Where: [BHW] = B for size = 1, H for size = 2, W for size = 46254SDValue EltVal = getI32Imm(Elt >> 1, dl);6255SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);6256SDValue TmpVal = SDValue(Tmp, 0);6257ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal));6258return;6259} else if (Elt > 0) {6260// Elt is odd and positive, in the range [17,31].6261//6262// Convert: VADD_SPLAT elt, size6263// Into: tmp1 = VSPLTIS[BHW] elt-166264// tmp2 = VSPLTIS[BHW] -166265// VSUBU[BHW]M tmp1, tmp26266SDValue EltVal = getI32Imm(Elt - 16, dl);6267SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);6268EltVal = getI32Imm(-16, dl);6269SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);6270ReplaceNode(N, CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),6271SDValue(Tmp2, 0)));6272return;6273} else {6274// Elt is odd and negative, in the range [-31,-17].6275//6276// Convert: VADD_SPLAT elt, size6277// Into: tmp1 = VSPLTIS[BHW] elt+166278// tmp2 = VSPLTIS[BHW] -166279// VADDU[BHW]M tmp1, tmp26280SDValue EltVal = getI32Imm(Elt + 16, dl);6281SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);6282EltVal = getI32Imm(-16, dl);6283SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);6284ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),6285SDValue(Tmp2, 0)));6286return;6287}6288}6289case PPCISD::LD_SPLAT: {6290// Here we want to handle splat load for type v16i8 and v8i16 when there is6291// no direct move, we don't need to use stack for this case. If target has6292// direct move, we should be able to get the best selection in the .td file.6293if (!Subtarget->hasAltivec() || Subtarget->hasDirectMove())6294break;62956296EVT Type = N->getValueType(0);6297if (Type != MVT::v16i8 && Type != MVT::v8i16)6298break;62996300// If the alignment for the load is 16 or bigger, we don't need the6301// permutated mask to get the required value. The value must be the 06302// element in big endian target or 7/15 in little endian target in the6303// result vsx register of lvx instruction.6304// Select the instruction in the .td file.6305if (cast<MemIntrinsicSDNode>(N)->getAlign() >= Align(16) &&6306isOffsetMultipleOf(N, 16))6307break;63086309SDValue ZeroReg =6310CurDAG->getRegister(Subtarget->isPPC64() ? PPC::ZERO8 : PPC::ZERO,6311Subtarget->isPPC64() ? MVT::i64 : MVT::i32);6312unsigned LIOpcode = Subtarget->isPPC64() ? PPC::LI8 : PPC::LI;6313// v16i8 LD_SPLAT addr6314// ======>6315// Mask = LVSR/LVSL 0, addr6316// LoadLow = LVX 0, addr6317// Perm = VPERM LoadLow, LoadLow, Mask6318// Splat = VSPLTB 15/0, Perm6319//6320// v8i16 LD_SPLAT addr6321// ======>6322// Mask = LVSR/LVSL 0, addr6323// LoadLow = LVX 0, addr6324// LoadHigh = LVX (LI, 1), addr6325// Perm = VPERM LoadLow, LoadHigh, Mask6326// Splat = VSPLTH 7/0, Perm6327unsigned SplatOp = (Type == MVT::v16i8) ? PPC::VSPLTB : PPC::VSPLTH;6328unsigned SplatElemIndex =6329Subtarget->isLittleEndian() ? ((Type == MVT::v16i8) ? 15 : 7) : 0;63306331SDNode *Mask = CurDAG->getMachineNode(6332Subtarget->isLittleEndian() ? PPC::LVSR : PPC::LVSL, dl, Type, ZeroReg,6333N->getOperand(1));63346335SDNode *LoadLow =6336CurDAG->getMachineNode(PPC::LVX, dl, MVT::v16i8, MVT::Other,6337{ZeroReg, N->getOperand(1), N->getOperand(0)});63386339SDNode *LoadHigh = LoadLow;6340if (Type == MVT::v8i16) {6341LoadHigh = CurDAG->getMachineNode(6342PPC::LVX, dl, MVT::v16i8, MVT::Other,6343{SDValue(CurDAG->getMachineNode(6344LIOpcode, dl, MVT::i32,6345CurDAG->getTargetConstant(1, dl, MVT::i8)),63460),6347N->getOperand(1), SDValue(LoadLow, 1)});6348}63496350CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(LoadHigh, 1));6351transferMemOperands(N, LoadHigh);63526353SDNode *Perm =6354CurDAG->getMachineNode(PPC::VPERM, dl, Type, SDValue(LoadLow, 0),6355SDValue(LoadHigh, 0), SDValue(Mask, 0));6356CurDAG->SelectNodeTo(N, SplatOp, Type,6357CurDAG->getTargetConstant(SplatElemIndex, dl, MVT::i8),6358SDValue(Perm, 0));6359return;6360}6361}63626363SelectCode(N);6364}63656366// If the target supports the cmpb instruction, do the idiom recognition here.6367// We don't do this as a DAG combine because we don't want to do it as nodes6368// are being combined (because we might miss part of the eventual idiom). We6369// don't want to do it during instruction selection because we want to reuse6370// the logic for lowering the masking operations already part of the6371// instruction selector.6372SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {6373SDLoc dl(N);63746375assert(N->getOpcode() == ISD::OR &&6376"Only OR nodes are supported for CMPB");63776378SDValue Res;6379if (!Subtarget->hasCMPB())6380return Res;63816382if (N->getValueType(0) != MVT::i32 &&6383N->getValueType(0) != MVT::i64)6384return Res;63856386EVT VT = N->getValueType(0);63876388SDValue RHS, LHS;6389bool BytesFound[8] = {false, false, false, false, false, false, false, false};6390uint64_t Mask = 0, Alt = 0;63916392auto IsByteSelectCC = [this](SDValue O, unsigned &b,6393uint64_t &Mask, uint64_t &Alt,6394SDValue &LHS, SDValue &RHS) {6395if (O.getOpcode() != ISD::SELECT_CC)6396return false;6397ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();63986399if (!isa<ConstantSDNode>(O.getOperand(2)) ||6400!isa<ConstantSDNode>(O.getOperand(3)))6401return false;64026403uint64_t PM = O.getConstantOperandVal(2);6404uint64_t PAlt = O.getConstantOperandVal(3);6405for (b = 0; b < 8; ++b) {6406uint64_t Mask = UINT64_C(0xFF) << (8*b);6407if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)6408break;6409}64106411if (b == 8)6412return false;6413Mask |= PM;6414Alt |= PAlt;64156416if (!isa<ConstantSDNode>(O.getOperand(1)) ||6417O.getConstantOperandVal(1) != 0) {6418SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);6419if (Op0.getOpcode() == ISD::TRUNCATE)6420Op0 = Op0.getOperand(0);6421if (Op1.getOpcode() == ISD::TRUNCATE)6422Op1 = Op1.getOperand(0);64236424if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&6425Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&6426isa<ConstantSDNode>(Op0.getOperand(1))) {64276428unsigned Bits = Op0.getValueSizeInBits();6429if (b != Bits/8-1)6430return false;6431if (Op0.getConstantOperandVal(1) != Bits-8)6432return false;64336434LHS = Op0.getOperand(0);6435RHS = Op1.getOperand(0);6436return true;6437}64386439// When we have small integers (i16 to be specific), the form present6440// post-legalization uses SETULT in the SELECT_CC for the6441// higher-order byte, depending on the fact that the6442// even-higher-order bytes are known to all be zero, for example:6443// select_cc (xor $lhs, $rhs), 256, 65280, 0, setult6444// (so when the second byte is the same, because all higher-order6445// bits from bytes 3 and 4 are known to be zero, the result of the6446// xor can be at most 255)6447if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&6448isa<ConstantSDNode>(O.getOperand(1))) {64496450uint64_t ULim = O.getConstantOperandVal(1);6451if (ULim != (UINT64_C(1) << b*8))6452return false;64536454// Now we need to make sure that the upper bytes are known to be6455// zero.6456unsigned Bits = Op0.getValueSizeInBits();6457if (!CurDAG->MaskedValueIsZero(6458Op0, APInt::getHighBitsSet(Bits, Bits - (b + 1) * 8)))6459return false;64606461LHS = Op0.getOperand(0);6462RHS = Op0.getOperand(1);6463return true;6464}64656466return false;6467}64686469if (CC != ISD::SETEQ)6470return false;64716472SDValue Op = O.getOperand(0);6473if (Op.getOpcode() == ISD::AND) {6474if (!isa<ConstantSDNode>(Op.getOperand(1)))6475return false;6476if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))6477return false;64786479SDValue XOR = Op.getOperand(0);6480if (XOR.getOpcode() == ISD::TRUNCATE)6481XOR = XOR.getOperand(0);6482if (XOR.getOpcode() != ISD::XOR)6483return false;64846485LHS = XOR.getOperand(0);6486RHS = XOR.getOperand(1);6487return true;6488} else if (Op.getOpcode() == ISD::SRL) {6489if (!isa<ConstantSDNode>(Op.getOperand(1)))6490return false;6491unsigned Bits = Op.getValueSizeInBits();6492if (b != Bits/8-1)6493return false;6494if (Op.getConstantOperandVal(1) != Bits-8)6495return false;64966497SDValue XOR = Op.getOperand(0);6498if (XOR.getOpcode() == ISD::TRUNCATE)6499XOR = XOR.getOperand(0);6500if (XOR.getOpcode() != ISD::XOR)6501return false;65026503LHS = XOR.getOperand(0);6504RHS = XOR.getOperand(1);6505return true;6506}65076508return false;6509};65106511SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));6512while (!Queue.empty()) {6513SDValue V = Queue.pop_back_val();65146515for (const SDValue &O : V.getNode()->ops()) {6516unsigned b = 0;6517uint64_t M = 0, A = 0;6518SDValue OLHS, ORHS;6519if (O.getOpcode() == ISD::OR) {6520Queue.push_back(O);6521} else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {6522if (!LHS) {6523LHS = OLHS;6524RHS = ORHS;6525BytesFound[b] = true;6526Mask |= M;6527Alt |= A;6528} else if ((LHS == ORHS && RHS == OLHS) ||6529(RHS == ORHS && LHS == OLHS)) {6530BytesFound[b] = true;6531Mask |= M;6532Alt |= A;6533} else {6534return Res;6535}6536} else {6537return Res;6538}6539}6540}65416542unsigned LastB = 0, BCnt = 0;6543for (unsigned i = 0; i < 8; ++i)6544if (BytesFound[LastB]) {6545++BCnt;6546LastB = i;6547}65486549if (!LastB || BCnt < 2)6550return Res;65516552// Because we'll be zero-extending the output anyway if don't have a specific6553// value for each input byte (via the Mask), we can 'anyext' the inputs.6554if (LHS.getValueType() != VT) {6555LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);6556RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);6557}65586559Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);65606561bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);6562if (NonTrivialMask && !Alt) {6563// Res = Mask & CMPB6564Res = CurDAG->getNode(ISD::AND, dl, VT, Res,6565CurDAG->getConstant(Mask, dl, VT));6566} else if (Alt) {6567// Res = (CMPB & Mask) | (~CMPB & Alt)6568// Which, as suggested here:6569// https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge6570// can be written as:6571// Res = Alt ^ ((Alt ^ Mask) & CMPB)6572// useful because the (Alt ^ Mask) can be pre-computed.6573Res = CurDAG->getNode(ISD::AND, dl, VT, Res,6574CurDAG->getConstant(Mask ^ Alt, dl, VT));6575Res = CurDAG->getNode(ISD::XOR, dl, VT, Res,6576CurDAG->getConstant(Alt, dl, VT));6577}65786579return Res;6580}65816582// When CR bit registers are enabled, an extension of an i1 variable to a i326583// or i64 value is lowered in terms of a SELECT_I[48] operation, and thus6584// involves constant materialization of a 0 or a 1 or both. If the result of6585// the extension is then operated upon by some operator that can be constant6586// folded with a constant 0 or 1, and that constant can be materialized using6587// only one instruction (like a zero or one), then we should fold in those6588// operations with the select.6589void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {6590if (!Subtarget->useCRBits())6591return;65926593if (N->getOpcode() != ISD::ZERO_EXTEND &&6594N->getOpcode() != ISD::SIGN_EXTEND &&6595N->getOpcode() != ISD::ANY_EXTEND)6596return;65976598if (N->getOperand(0).getValueType() != MVT::i1)6599return;66006601if (!N->hasOneUse())6602return;66036604SDLoc dl(N);6605EVT VT = N->getValueType(0);6606SDValue Cond = N->getOperand(0);6607SDValue ConstTrue =6608CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, dl, VT);6609SDValue ConstFalse = CurDAG->getConstant(0, dl, VT);66106611do {6612SDNode *User = *N->use_begin();6613if (User->getNumOperands() != 2)6614break;66156616auto TryFold = [this, N, User, dl](SDValue Val) {6617SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1);6618SDValue O0 = UserO0.getNode() == N ? Val : UserO0;6619SDValue O1 = UserO1.getNode() == N ? Val : UserO1;66206621return CurDAG->FoldConstantArithmetic(User->getOpcode(), dl,6622User->getValueType(0), {O0, O1});6623};66246625// FIXME: When the semantics of the interaction between select and undef6626// are clearly defined, it may turn out to be unnecessary to break here.6627SDValue TrueRes = TryFold(ConstTrue);6628if (!TrueRes || TrueRes.isUndef())6629break;6630SDValue FalseRes = TryFold(ConstFalse);6631if (!FalseRes || FalseRes.isUndef())6632break;66336634// For us to materialize these using one instruction, we must be able to6635// represent them as signed 16-bit integers.6636uint64_t True = TrueRes->getAsZExtVal(), False = FalseRes->getAsZExtVal();6637if (!isInt<16>(True) || !isInt<16>(False))6638break;66396640// We can replace User with a new SELECT node, and try again to see if we6641// can fold the select with its user.6642Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes);6643N = User;6644ConstTrue = TrueRes;6645ConstFalse = FalseRes;6646} while (N->hasOneUse());6647}66486649void PPCDAGToDAGISel::PreprocessISelDAG() {6650SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();66516652bool MadeChange = false;6653while (Position != CurDAG->allnodes_begin()) {6654SDNode *N = &*--Position;6655if (N->use_empty())6656continue;66576658SDValue Res;6659switch (N->getOpcode()) {6660default: break;6661case ISD::OR:6662Res = combineToCMPB(N);6663break;6664}66656666if (!Res)6667foldBoolExts(Res, N);66686669if (Res) {6670LLVM_DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: ");6671LLVM_DEBUG(N->dump(CurDAG));6672LLVM_DEBUG(dbgs() << "\nNew: ");6673LLVM_DEBUG(Res.getNode()->dump(CurDAG));6674LLVM_DEBUG(dbgs() << "\n");66756676CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);6677MadeChange = true;6678}6679}66806681if (MadeChange)6682CurDAG->RemoveDeadNodes();6683}66846685/// PostprocessISelDAG - Perform some late peephole optimizations6686/// on the DAG representation.6687void PPCDAGToDAGISel::PostprocessISelDAG() {6688// Skip peepholes at -O0.6689if (TM.getOptLevel() == CodeGenOptLevel::None)6690return;66916692PeepholePPC64();6693PeepholeCROps();6694PeepholePPC64ZExt();6695}66966697// Check if all users of this node will become isel where the second operand6698// is the constant zero. If this is so, and if we can negate the condition,6699// then we can flip the true and false operands. This will allow the zero to6700// be folded with the isel so that we don't need to materialize a register6701// containing zero.6702bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {6703for (const SDNode *User : N->uses()) {6704if (!User->isMachineOpcode())6705return false;6706if (User->getMachineOpcode() != PPC::SELECT_I4 &&6707User->getMachineOpcode() != PPC::SELECT_I8)6708return false;67096710SDNode *Op1 = User->getOperand(1).getNode();6711SDNode *Op2 = User->getOperand(2).getNode();6712// If we have a degenerate select with two equal operands, swapping will6713// not do anything, and we may run into an infinite loop.6714if (Op1 == Op2)6715return false;67166717if (!Op2->isMachineOpcode())6718return false;67196720if (Op2->getMachineOpcode() != PPC::LI &&6721Op2->getMachineOpcode() != PPC::LI8)6722return false;67236724if (!isNullConstant(Op2->getOperand(0)))6725return false;6726}67276728return true;6729}67306731void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {6732SmallVector<SDNode *, 4> ToReplace;6733for (SDNode *User : N->uses()) {6734assert((User->getMachineOpcode() == PPC::SELECT_I4 ||6735User->getMachineOpcode() == PPC::SELECT_I8) &&6736"Must have all select users");6737ToReplace.push_back(User);6738}67396740for (SDNode *User : ToReplace) {6741SDNode *ResNode =6742CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),6743User->getValueType(0), User->getOperand(0),6744User->getOperand(2),6745User->getOperand(1));67466747LLVM_DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");6748LLVM_DEBUG(User->dump(CurDAG));6749LLVM_DEBUG(dbgs() << "\nNew: ");6750LLVM_DEBUG(ResNode->dump(CurDAG));6751LLVM_DEBUG(dbgs() << "\n");67526753ReplaceUses(User, ResNode);6754}6755}67566757void PPCDAGToDAGISel::PeepholeCROps() {6758bool IsModified;6759do {6760IsModified = false;6761for (SDNode &Node : CurDAG->allnodes()) {6762MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(&Node);6763if (!MachineNode || MachineNode->use_empty())6764continue;6765SDNode *ResNode = MachineNode;67666767bool Op1Set = false, Op1Unset = false,6768Op1Not = false,6769Op2Set = false, Op2Unset = false,6770Op2Not = false;67716772unsigned Opcode = MachineNode->getMachineOpcode();6773switch (Opcode) {6774default: break;6775case PPC::CRAND:6776case PPC::CRNAND:6777case PPC::CROR:6778case PPC::CRXOR:6779case PPC::CRNOR:6780case PPC::CREQV:6781case PPC::CRANDC:6782case PPC::CRORC: {6783SDValue Op = MachineNode->getOperand(1);6784if (Op.isMachineOpcode()) {6785if (Op.getMachineOpcode() == PPC::CRSET)6786Op2Set = true;6787else if (Op.getMachineOpcode() == PPC::CRUNSET)6788Op2Unset = true;6789else if ((Op.getMachineOpcode() == PPC::CRNOR &&6790Op.getOperand(0) == Op.getOperand(1)) ||6791Op.getMachineOpcode() == PPC::CRNOT)6792Op2Not = true;6793}6794[[fallthrough]];6795}6796case PPC::BC:6797case PPC::BCn:6798case PPC::SELECT_I4:6799case PPC::SELECT_I8:6800case PPC::SELECT_F4:6801case PPC::SELECT_F8:6802case PPC::SELECT_SPE:6803case PPC::SELECT_SPE4:6804case PPC::SELECT_VRRC:6805case PPC::SELECT_VSFRC:6806case PPC::SELECT_VSSRC:6807case PPC::SELECT_VSRC: {6808SDValue Op = MachineNode->getOperand(0);6809if (Op.isMachineOpcode()) {6810if (Op.getMachineOpcode() == PPC::CRSET)6811Op1Set = true;6812else if (Op.getMachineOpcode() == PPC::CRUNSET)6813Op1Unset = true;6814else if ((Op.getMachineOpcode() == PPC::CRNOR &&6815Op.getOperand(0) == Op.getOperand(1)) ||6816Op.getMachineOpcode() == PPC::CRNOT)6817Op1Not = true;6818}6819}6820break;6821}68226823bool SelectSwap = false;6824switch (Opcode) {6825default: break;6826case PPC::CRAND:6827if (MachineNode->getOperand(0) == MachineNode->getOperand(1))6828// x & x = x6829ResNode = MachineNode->getOperand(0).getNode();6830else if (Op1Set)6831// 1 & y = y6832ResNode = MachineNode->getOperand(1).getNode();6833else if (Op2Set)6834// x & 1 = x6835ResNode = MachineNode->getOperand(0).getNode();6836else if (Op1Unset || Op2Unset)6837// x & 0 = 0 & y = 06838ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),6839MVT::i1);6840else if (Op1Not)6841// ~x & y = andc(y, x)6842ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),6843MVT::i1, MachineNode->getOperand(1),6844MachineNode->getOperand(0).6845getOperand(0));6846else if (Op2Not)6847// x & ~y = andc(x, y)6848ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),6849MVT::i1, MachineNode->getOperand(0),6850MachineNode->getOperand(1).6851getOperand(0));6852else if (AllUsersSelectZero(MachineNode)) {6853ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),6854MVT::i1, MachineNode->getOperand(0),6855MachineNode->getOperand(1));6856SelectSwap = true;6857}6858break;6859case PPC::CRNAND:6860if (MachineNode->getOperand(0) == MachineNode->getOperand(1))6861// nand(x, x) -> nor(x, x)6862ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),6863MVT::i1, MachineNode->getOperand(0),6864MachineNode->getOperand(0));6865else if (Op1Set)6866// nand(1, y) -> nor(y, y)6867ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),6868MVT::i1, MachineNode->getOperand(1),6869MachineNode->getOperand(1));6870else if (Op2Set)6871// nand(x, 1) -> nor(x, x)6872ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),6873MVT::i1, MachineNode->getOperand(0),6874MachineNode->getOperand(0));6875else if (Op1Unset || Op2Unset)6876// nand(x, 0) = nand(0, y) = 16877ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),6878MVT::i1);6879else if (Op1Not)6880// nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)6881ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),6882MVT::i1, MachineNode->getOperand(0).6883getOperand(0),6884MachineNode->getOperand(1));6885else if (Op2Not)6886// nand(x, ~y) = ~x | y = orc(y, x)6887ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),6888MVT::i1, MachineNode->getOperand(1).6889getOperand(0),6890MachineNode->getOperand(0));6891else if (AllUsersSelectZero(MachineNode)) {6892ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),6893MVT::i1, MachineNode->getOperand(0),6894MachineNode->getOperand(1));6895SelectSwap = true;6896}6897break;6898case PPC::CROR:6899if (MachineNode->getOperand(0) == MachineNode->getOperand(1))6900// x | x = x6901ResNode = MachineNode->getOperand(0).getNode();6902else if (Op1Set || Op2Set)6903// x | 1 = 1 | y = 16904ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),6905MVT::i1);6906else if (Op1Unset)6907// 0 | y = y6908ResNode = MachineNode->getOperand(1).getNode();6909else if (Op2Unset)6910// x | 0 = x6911ResNode = MachineNode->getOperand(0).getNode();6912else if (Op1Not)6913// ~x | y = orc(y, x)6914ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),6915MVT::i1, MachineNode->getOperand(1),6916MachineNode->getOperand(0).6917getOperand(0));6918else if (Op2Not)6919// x | ~y = orc(x, y)6920ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),6921MVT::i1, MachineNode->getOperand(0),6922MachineNode->getOperand(1).6923getOperand(0));6924else if (AllUsersSelectZero(MachineNode)) {6925ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),6926MVT::i1, MachineNode->getOperand(0),6927MachineNode->getOperand(1));6928SelectSwap = true;6929}6930break;6931case PPC::CRXOR:6932if (MachineNode->getOperand(0) == MachineNode->getOperand(1))6933// xor(x, x) = 06934ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),6935MVT::i1);6936else if (Op1Set)6937// xor(1, y) -> nor(y, y)6938ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),6939MVT::i1, MachineNode->getOperand(1),6940MachineNode->getOperand(1));6941else if (Op2Set)6942// xor(x, 1) -> nor(x, x)6943ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),6944MVT::i1, MachineNode->getOperand(0),6945MachineNode->getOperand(0));6946else if (Op1Unset)6947// xor(0, y) = y6948ResNode = MachineNode->getOperand(1).getNode();6949else if (Op2Unset)6950// xor(x, 0) = x6951ResNode = MachineNode->getOperand(0).getNode();6952else if (Op1Not)6953// xor(~x, y) = eqv(x, y)6954ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),6955MVT::i1, MachineNode->getOperand(0).6956getOperand(0),6957MachineNode->getOperand(1));6958else if (Op2Not)6959// xor(x, ~y) = eqv(x, y)6960ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),6961MVT::i1, MachineNode->getOperand(0),6962MachineNode->getOperand(1).6963getOperand(0));6964else if (AllUsersSelectZero(MachineNode)) {6965ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),6966MVT::i1, MachineNode->getOperand(0),6967MachineNode->getOperand(1));6968SelectSwap = true;6969}6970break;6971case PPC::CRNOR:6972if (Op1Set || Op2Set)6973// nor(1, y) -> 06974ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),6975MVT::i1);6976else if (Op1Unset)6977// nor(0, y) = ~y -> nor(y, y)6978ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),6979MVT::i1, MachineNode->getOperand(1),6980MachineNode->getOperand(1));6981else if (Op2Unset)6982// nor(x, 0) = ~x6983ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),6984MVT::i1, MachineNode->getOperand(0),6985MachineNode->getOperand(0));6986else if (Op1Not)6987// nor(~x, y) = andc(x, y)6988ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),6989MVT::i1, MachineNode->getOperand(0).6990getOperand(0),6991MachineNode->getOperand(1));6992else if (Op2Not)6993// nor(x, ~y) = andc(y, x)6994ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),6995MVT::i1, MachineNode->getOperand(1).6996getOperand(0),6997MachineNode->getOperand(0));6998else if (AllUsersSelectZero(MachineNode)) {6999ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),7000MVT::i1, MachineNode->getOperand(0),7001MachineNode->getOperand(1));7002SelectSwap = true;7003}7004break;7005case PPC::CREQV:7006if (MachineNode->getOperand(0) == MachineNode->getOperand(1))7007// eqv(x, x) = 17008ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),7009MVT::i1);7010else if (Op1Set)7011// eqv(1, y) = y7012ResNode = MachineNode->getOperand(1).getNode();7013else if (Op2Set)7014// eqv(x, 1) = x7015ResNode = MachineNode->getOperand(0).getNode();7016else if (Op1Unset)7017// eqv(0, y) = ~y -> nor(y, y)7018ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),7019MVT::i1, MachineNode->getOperand(1),7020MachineNode->getOperand(1));7021else if (Op2Unset)7022// eqv(x, 0) = ~x7023ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),7024MVT::i1, MachineNode->getOperand(0),7025MachineNode->getOperand(0));7026else if (Op1Not)7027// eqv(~x, y) = xor(x, y)7028ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),7029MVT::i1, MachineNode->getOperand(0).7030getOperand(0),7031MachineNode->getOperand(1));7032else if (Op2Not)7033// eqv(x, ~y) = xor(x, y)7034ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),7035MVT::i1, MachineNode->getOperand(0),7036MachineNode->getOperand(1).7037getOperand(0));7038else if (AllUsersSelectZero(MachineNode)) {7039ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),7040MVT::i1, MachineNode->getOperand(0),7041MachineNode->getOperand(1));7042SelectSwap = true;7043}7044break;7045case PPC::CRANDC:7046if (MachineNode->getOperand(0) == MachineNode->getOperand(1))7047// andc(x, x) = 07048ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),7049MVT::i1);7050else if (Op1Set)7051// andc(1, y) = ~y7052ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),7053MVT::i1, MachineNode->getOperand(1),7054MachineNode->getOperand(1));7055else if (Op1Unset || Op2Set)7056// andc(0, y) = andc(x, 1) = 07057ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),7058MVT::i1);7059else if (Op2Unset)7060// andc(x, 0) = x7061ResNode = MachineNode->getOperand(0).getNode();7062else if (Op1Not)7063// andc(~x, y) = ~(x | y) = nor(x, y)7064ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),7065MVT::i1, MachineNode->getOperand(0).7066getOperand(0),7067MachineNode->getOperand(1));7068else if (Op2Not)7069// andc(x, ~y) = x & y7070ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),7071MVT::i1, MachineNode->getOperand(0),7072MachineNode->getOperand(1).7073getOperand(0));7074else if (AllUsersSelectZero(MachineNode)) {7075ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),7076MVT::i1, MachineNode->getOperand(1),7077MachineNode->getOperand(0));7078SelectSwap = true;7079}7080break;7081case PPC::CRORC:7082if (MachineNode->getOperand(0) == MachineNode->getOperand(1))7083// orc(x, x) = 17084ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),7085MVT::i1);7086else if (Op1Set || Op2Unset)7087// orc(1, y) = orc(x, 0) = 17088ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),7089MVT::i1);7090else if (Op2Set)7091// orc(x, 1) = x7092ResNode = MachineNode->getOperand(0).getNode();7093else if (Op1Unset)7094// orc(0, y) = ~y7095ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),7096MVT::i1, MachineNode->getOperand(1),7097MachineNode->getOperand(1));7098else if (Op1Not)7099// orc(~x, y) = ~(x & y) = nand(x, y)7100ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),7101MVT::i1, MachineNode->getOperand(0).7102getOperand(0),7103MachineNode->getOperand(1));7104else if (Op2Not)7105// orc(x, ~y) = x | y7106ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),7107MVT::i1, MachineNode->getOperand(0),7108MachineNode->getOperand(1).7109getOperand(0));7110else if (AllUsersSelectZero(MachineNode)) {7111ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),7112MVT::i1, MachineNode->getOperand(1),7113MachineNode->getOperand(0));7114SelectSwap = true;7115}7116break;7117case PPC::SELECT_I4:7118case PPC::SELECT_I8:7119case PPC::SELECT_F4:7120case PPC::SELECT_F8:7121case PPC::SELECT_SPE:7122case PPC::SELECT_SPE4:7123case PPC::SELECT_VRRC:7124case PPC::SELECT_VSFRC:7125case PPC::SELECT_VSSRC:7126case PPC::SELECT_VSRC:7127if (Op1Set)7128ResNode = MachineNode->getOperand(1).getNode();7129else if (Op1Unset)7130ResNode = MachineNode->getOperand(2).getNode();7131else if (Op1Not)7132ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),7133SDLoc(MachineNode),7134MachineNode->getValueType(0),7135MachineNode->getOperand(0).7136getOperand(0),7137MachineNode->getOperand(2),7138MachineNode->getOperand(1));7139break;7140case PPC::BC:7141case PPC::BCn:7142if (Op1Not)7143ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :7144PPC::BC,7145SDLoc(MachineNode),7146MVT::Other,7147MachineNode->getOperand(0).7148getOperand(0),7149MachineNode->getOperand(1),7150MachineNode->getOperand(2));7151// FIXME: Handle Op1Set, Op1Unset here too.7152break;7153}71547155// If we're inverting this node because it is used only by selects that7156// we'd like to swap, then swap the selects before the node replacement.7157if (SelectSwap)7158SwapAllSelectUsers(MachineNode);71597160if (ResNode != MachineNode) {7161LLVM_DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");7162LLVM_DEBUG(MachineNode->dump(CurDAG));7163LLVM_DEBUG(dbgs() << "\nNew: ");7164LLVM_DEBUG(ResNode->dump(CurDAG));7165LLVM_DEBUG(dbgs() << "\n");71667167ReplaceUses(MachineNode, ResNode);7168IsModified = true;7169}7170}7171if (IsModified)7172CurDAG->RemoveDeadNodes();7173} while (IsModified);7174}71757176// Gather the set of 32-bit operations that are known to have their7177// higher-order 32 bits zero, where ToPromote contains all such operations.7178static bool PeepholePPC64ZExtGather(SDValue Op32,7179SmallPtrSetImpl<SDNode *> &ToPromote) {7180if (!Op32.isMachineOpcode())7181return false;71827183// First, check for the "frontier" instructions (those that will clear the7184// higher-order 32 bits.71857186// For RLWINM and RLWNM, we need to make sure that the mask does not wrap7187// around. If it does not, then these instructions will clear the7188// higher-order bits.7189if ((Op32.getMachineOpcode() == PPC::RLWINM ||7190Op32.getMachineOpcode() == PPC::RLWNM) &&7191Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {7192ToPromote.insert(Op32.getNode());7193return true;7194}71957196// SLW and SRW always clear the higher-order bits.7197if (Op32.getMachineOpcode() == PPC::SLW ||7198Op32.getMachineOpcode() == PPC::SRW) {7199ToPromote.insert(Op32.getNode());7200return true;7201}72027203// For LI and LIS, we need the immediate to be positive (so that it is not7204// sign extended).7205if (Op32.getMachineOpcode() == PPC::LI ||7206Op32.getMachineOpcode() == PPC::LIS) {7207if (!isUInt<15>(Op32.getConstantOperandVal(0)))7208return false;72097210ToPromote.insert(Op32.getNode());7211return true;7212}72137214// LHBRX and LWBRX always clear the higher-order bits.7215if (Op32.getMachineOpcode() == PPC::LHBRX ||7216Op32.getMachineOpcode() == PPC::LWBRX) {7217ToPromote.insert(Op32.getNode());7218return true;7219}72207221// CNT[LT]ZW always produce a 64-bit value in [0,32], and so is zero extended.7222if (Op32.getMachineOpcode() == PPC::CNTLZW ||7223Op32.getMachineOpcode() == PPC::CNTTZW) {7224ToPromote.insert(Op32.getNode());7225return true;7226}72277228// Next, check for those instructions we can look through.72297230// Assuming the mask does not wrap around, then the higher-order bits are7231// taken directly from the first operand.7232if (Op32.getMachineOpcode() == PPC::RLWIMI &&7233Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {7234SmallPtrSet<SDNode *, 16> ToPromote1;7235if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))7236return false;72377238ToPromote.insert(Op32.getNode());7239ToPromote.insert(ToPromote1.begin(), ToPromote1.end());7240return true;7241}72427243// For OR, the higher-order bits are zero if that is true for both operands.7244// For SELECT_I4, the same is true (but the relevant operand numbers are7245// shifted by 1).7246if (Op32.getMachineOpcode() == PPC::OR ||7247Op32.getMachineOpcode() == PPC::SELECT_I4) {7248unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;7249SmallPtrSet<SDNode *, 16> ToPromote1;7250if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))7251return false;7252if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))7253return false;72547255ToPromote.insert(Op32.getNode());7256ToPromote.insert(ToPromote1.begin(), ToPromote1.end());7257return true;7258}72597260// For ORI and ORIS, we need the higher-order bits of the first operand to be7261// zero, and also for the constant to be positive (so that it is not sign7262// extended).7263if (Op32.getMachineOpcode() == PPC::ORI ||7264Op32.getMachineOpcode() == PPC::ORIS) {7265SmallPtrSet<SDNode *, 16> ToPromote1;7266if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))7267return false;7268if (!isUInt<15>(Op32.getConstantOperandVal(1)))7269return false;72707271ToPromote.insert(Op32.getNode());7272ToPromote.insert(ToPromote1.begin(), ToPromote1.end());7273return true;7274}72757276// The higher-order bits of AND are zero if that is true for at least one of7277// the operands.7278if (Op32.getMachineOpcode() == PPC::AND) {7279SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;7280bool Op0OK =7281PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);7282bool Op1OK =7283PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);7284if (!Op0OK && !Op1OK)7285return false;72867287ToPromote.insert(Op32.getNode());72887289if (Op0OK)7290ToPromote.insert(ToPromote1.begin(), ToPromote1.end());72917292if (Op1OK)7293ToPromote.insert(ToPromote2.begin(), ToPromote2.end());72947295return true;7296}72977298// For ANDI and ANDIS, the higher-order bits are zero if either that is true7299// of the first operand, or if the second operand is positive (so that it is7300// not sign extended).7301if (Op32.getMachineOpcode() == PPC::ANDI_rec ||7302Op32.getMachineOpcode() == PPC::ANDIS_rec) {7303SmallPtrSet<SDNode *, 16> ToPromote1;7304bool Op0OK =7305PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);7306bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));7307if (!Op0OK && !Op1OK)7308return false;73097310ToPromote.insert(Op32.getNode());73117312if (Op0OK)7313ToPromote.insert(ToPromote1.begin(), ToPromote1.end());73147315return true;7316}73177318return false;7319}73207321void PPCDAGToDAGISel::PeepholePPC64ZExt() {7322if (!Subtarget->isPPC64())7323return;73247325// When we zero-extend from i32 to i64, we use a pattern like this:7326// def : Pat<(i64 (zext i32:$in)),7327// (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),7328// 0, 32)>;7329// There are several 32-bit shift/rotate instructions, however, that will7330// clear the higher-order bits of their output, rendering the RLDICL7331// unnecessary. When that happens, we remove it here, and redefine the7332// relevant 32-bit operation to be a 64-bit operation.73337334SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();73357336bool MadeChange = false;7337while (Position != CurDAG->allnodes_begin()) {7338SDNode *N = &*--Position;7339// Skip dead nodes and any non-machine opcodes.7340if (N->use_empty() || !N->isMachineOpcode())7341continue;73427343if (N->getMachineOpcode() != PPC::RLDICL)7344continue;73457346if (N->getConstantOperandVal(1) != 0 ||7347N->getConstantOperandVal(2) != 32)7348continue;73497350SDValue ISR = N->getOperand(0);7351if (!ISR.isMachineOpcode() ||7352ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)7353continue;73547355if (!ISR.hasOneUse())7356continue;73577358if (ISR.getConstantOperandVal(2) != PPC::sub_32)7359continue;73607361SDValue IDef = ISR.getOperand(0);7362if (!IDef.isMachineOpcode() ||7363IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)7364continue;73657366// We now know that we're looking at a canonical i32 -> i64 zext. See if we7367// can get rid of it.73687369SDValue Op32 = ISR->getOperand(1);7370if (!Op32.isMachineOpcode())7371continue;73727373// There are some 32-bit instructions that always clear the high-order 327374// bits, there are also some instructions (like AND) that we can look7375// through.7376SmallPtrSet<SDNode *, 16> ToPromote;7377if (!PeepholePPC64ZExtGather(Op32, ToPromote))7378continue;73797380// If the ToPromote set contains nodes that have uses outside of the set7381// (except for the original INSERT_SUBREG), then abort the transformation.7382bool OutsideUse = false;7383for (SDNode *PN : ToPromote) {7384for (SDNode *UN : PN->uses()) {7385if (!ToPromote.count(UN) && UN != ISR.getNode()) {7386OutsideUse = true;7387break;7388}7389}73907391if (OutsideUse)7392break;7393}7394if (OutsideUse)7395continue;73967397MadeChange = true;73987399// We now know that this zero extension can be removed by promoting to7400// nodes in ToPromote to 64-bit operations, where for operations in the7401// frontier of the set, we need to insert INSERT_SUBREGs for their7402// operands.7403for (SDNode *PN : ToPromote) {7404unsigned NewOpcode;7405switch (PN->getMachineOpcode()) {7406default:7407llvm_unreachable("Don't know the 64-bit variant of this instruction");7408case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break;7409case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break;7410case PPC::SLW: NewOpcode = PPC::SLW8; break;7411case PPC::SRW: NewOpcode = PPC::SRW8; break;7412case PPC::LI: NewOpcode = PPC::LI8; break;7413case PPC::LIS: NewOpcode = PPC::LIS8; break;7414case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break;7415case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break;7416case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break;7417case PPC::CNTTZW: NewOpcode = PPC::CNTTZW8; break;7418case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break;7419case PPC::OR: NewOpcode = PPC::OR8; break;7420case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;7421case PPC::ORI: NewOpcode = PPC::ORI8; break;7422case PPC::ORIS: NewOpcode = PPC::ORIS8; break;7423case PPC::AND: NewOpcode = PPC::AND8; break;7424case PPC::ANDI_rec:7425NewOpcode = PPC::ANDI8_rec;7426break;7427case PPC::ANDIS_rec:7428NewOpcode = PPC::ANDIS8_rec;7429break;7430}74317432// Note: During the replacement process, the nodes will be in an7433// inconsistent state (some instructions will have operands with values7434// of the wrong type). Once done, however, everything should be right7435// again.74367437SmallVector<SDValue, 4> Ops;7438for (const SDValue &V : PN->ops()) {7439if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&7440!isa<ConstantSDNode>(V)) {7441SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };7442SDNode *ReplOp =7443CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),7444ISR.getNode()->getVTList(), ReplOpOps);7445Ops.push_back(SDValue(ReplOp, 0));7446} else {7447Ops.push_back(V);7448}7449}74507451// Because all to-be-promoted nodes only have users that are other7452// promoted nodes (or the original INSERT_SUBREG), we can safely replace7453// the i32 result value type with i64.74547455SmallVector<EVT, 2> NewVTs;7456SDVTList VTs = PN->getVTList();7457for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)7458if (VTs.VTs[i] == MVT::i32)7459NewVTs.push_back(MVT::i64);7460else7461NewVTs.push_back(VTs.VTs[i]);74627463LLVM_DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: ");7464LLVM_DEBUG(PN->dump(CurDAG));74657466CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);74677468LLVM_DEBUG(dbgs() << "\nNew: ");7469LLVM_DEBUG(PN->dump(CurDAG));7470LLVM_DEBUG(dbgs() << "\n");7471}74727473// Now we replace the original zero extend and its associated INSERT_SUBREG7474// with the value feeding the INSERT_SUBREG (which has now been promoted to7475// return an i64).74767477LLVM_DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: ");7478LLVM_DEBUG(N->dump(CurDAG));7479LLVM_DEBUG(dbgs() << "\nNew: ");7480LLVM_DEBUG(Op32.getNode()->dump(CurDAG));7481LLVM_DEBUG(dbgs() << "\n");74827483ReplaceUses(N, Op32.getNode());7484}74857486if (MadeChange)7487CurDAG->RemoveDeadNodes();7488}74897490static bool isVSXSwap(SDValue N) {7491if (!N->isMachineOpcode())7492return false;7493unsigned Opc = N->getMachineOpcode();74947495// Single-operand XXPERMDI or the regular XXPERMDI/XXSLDWI where the immediate7496// operand is 2.7497if (Opc == PPC::XXPERMDIs) {7498return isa<ConstantSDNode>(N->getOperand(1)) &&7499N->getConstantOperandVal(1) == 2;7500} else if (Opc == PPC::XXPERMDI || Opc == PPC::XXSLDWI) {7501return N->getOperand(0) == N->getOperand(1) &&7502isa<ConstantSDNode>(N->getOperand(2)) &&7503N->getConstantOperandVal(2) == 2;7504}75057506return false;7507}75087509// TODO: Make this complete and replace with a table-gen bit.7510static bool isLaneInsensitive(SDValue N) {7511if (!N->isMachineOpcode())7512return false;7513unsigned Opc = N->getMachineOpcode();75147515switch (Opc) {7516default:7517return false;7518case PPC::VAVGSB:7519case PPC::VAVGUB:7520case PPC::VAVGSH:7521case PPC::VAVGUH:7522case PPC::VAVGSW:7523case PPC::VAVGUW:7524case PPC::VMAXFP:7525case PPC::VMAXSB:7526case PPC::VMAXUB:7527case PPC::VMAXSH:7528case PPC::VMAXUH:7529case PPC::VMAXSW:7530case PPC::VMAXUW:7531case PPC::VMINFP:7532case PPC::VMINSB:7533case PPC::VMINUB:7534case PPC::VMINSH:7535case PPC::VMINUH:7536case PPC::VMINSW:7537case PPC::VMINUW:7538case PPC::VADDFP:7539case PPC::VADDUBM:7540case PPC::VADDUHM:7541case PPC::VADDUWM:7542case PPC::VSUBFP:7543case PPC::VSUBUBM:7544case PPC::VSUBUHM:7545case PPC::VSUBUWM:7546case PPC::VAND:7547case PPC::VANDC:7548case PPC::VOR:7549case PPC::VORC:7550case PPC::VXOR:7551case PPC::VNOR:7552case PPC::VMULUWM:7553return true;7554}7555}75567557// Try to simplify (xxswap (vec-op (xxswap) (xxswap))) where vec-op is7558// lane-insensitive.7559static void reduceVSXSwap(SDNode *N, SelectionDAG *DAG) {7560// Our desired xxswap might be source of COPY_TO_REGCLASS.7561// TODO: Can we put this a common method for DAG?7562auto SkipRCCopy = [](SDValue V) {7563while (V->isMachineOpcode() &&7564V->getMachineOpcode() == TargetOpcode::COPY_TO_REGCLASS) {7565// All values in the chain should have single use.7566if (V->use_empty() || !V->use_begin()->isOnlyUserOf(V.getNode()))7567return SDValue();7568V = V->getOperand(0);7569}7570return V.hasOneUse() ? V : SDValue();7571};75727573SDValue VecOp = SkipRCCopy(N->getOperand(0));7574if (!VecOp || !isLaneInsensitive(VecOp))7575return;75767577SDValue LHS = SkipRCCopy(VecOp.getOperand(0)),7578RHS = SkipRCCopy(VecOp.getOperand(1));7579if (!LHS || !RHS || !isVSXSwap(LHS) || !isVSXSwap(RHS))7580return;75817582// These swaps may still have chain-uses here, count on dead code elimination7583// in following passes to remove them.7584DAG->ReplaceAllUsesOfValueWith(LHS, LHS.getOperand(0));7585DAG->ReplaceAllUsesOfValueWith(RHS, RHS.getOperand(0));7586DAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), N->getOperand(0));7587}75887589// Check if an SDValue has the 'aix-small-tls' global variable attribute.7590static bool hasAIXSmallTLSAttr(SDValue Val) {7591if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Val))7592if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal()))7593if (GV->hasAttribute("aix-small-tls"))7594return true;75957596return false;7597}75987599// Is an ADDI eligible for folding for non-TOC-based local-[exec|dynamic]7600// accesses?7601static bool isEligibleToFoldADDIForFasterLocalAccesses(SelectionDAG *DAG,7602SDValue ADDIToFold) {7603// Check if ADDIToFold (the ADDI that we want to fold into local-exec7604// accesses), is truly an ADDI.7605if (!ADDIToFold.isMachineOpcode() ||7606(ADDIToFold.getMachineOpcode() != PPC::ADDI8))7607return false;76087609// Folding is only allowed for the AIX small-local-[exec|dynamic] TLS target7610// attribute or when the 'aix-small-tls' global variable attribute is present.7611const PPCSubtarget &Subtarget =7612DAG->getMachineFunction().getSubtarget<PPCSubtarget>();7613SDValue TLSVarNode = ADDIToFold.getOperand(1);7614if (!(Subtarget.hasAIXSmallLocalDynamicTLS() ||7615Subtarget.hasAIXSmallLocalExecTLS() || hasAIXSmallTLSAttr(TLSVarNode)))7616return false;76177618// The second operand of the ADDIToFold should be the global TLS address7619// (the local-exec TLS variable). We only perform the folding if the TLS7620// variable is the second operand.7621GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(TLSVarNode);7622if (!GA)7623return false;76247625if (DAG->getTarget().getTLSModel(GA->getGlobal()) == TLSModel::LocalExec) {7626// The first operand of the ADDIToFold should be the thread pointer.7627// This transformation is only performed if the first operand of the7628// addi is the thread pointer.7629SDValue TPRegNode = ADDIToFold.getOperand(0);7630RegisterSDNode *TPReg = dyn_cast<RegisterSDNode>(TPRegNode.getNode());7631if (!TPReg || (TPReg->getReg() != Subtarget.getThreadPointerRegister()))7632return false;7633}76347635// The local-[exec|dynamic] TLS variable should only have the7636// [MO_TPREL_FLAG|MO_TLSLD_FLAG] target flags, so this optimization is not7637// performed otherwise if the flag is not set.7638unsigned TargetFlags = GA->getTargetFlags();7639if (!(TargetFlags == PPCII::MO_TPREL_FLAG ||7640TargetFlags == PPCII::MO_TLSLD_FLAG))7641return false;76427643// If all conditions are satisfied, the ADDI is valid for folding.7644return true;7645}76467647// For non-TOC-based local-[exec|dynamic] access where an addi is feeding into7648// another addi, fold this sequence into a single addi if possible. Before this7649// optimization, the sequence appears as:7650// addi rN, r13, sym@[le|ld]7651// addi rM, rN, imm7652// After this optimization, we can fold the two addi into a single one:7653// addi rM, r13, sym@[le|ld] + imm7654static void foldADDIForFasterLocalAccesses(SDNode *N, SelectionDAG *DAG) {7655if (N->getMachineOpcode() != PPC::ADDI8)7656return;76577658// InitialADDI is the addi feeding into N (also an addi), and the addi that7659// we want optimized out.7660SDValue InitialADDI = N->getOperand(0);76617662if (!isEligibleToFoldADDIForFasterLocalAccesses(DAG, InitialADDI))7663return;76647665// The second operand of the InitialADDI should be the global TLS address7666// (the local-[exec|dynamic] TLS variable), with the7667// [MO_TPREL_FLAG|MO_TLSLD_FLAG] target flag. This has been checked in7668// isEligibleToFoldADDIForFasterLocalAccesses().7669SDValue TLSVarNode = InitialADDI.getOperand(1);7670GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(TLSVarNode);7671assert(GA && "Expecting a valid GlobalAddressSDNode when folding addi into "7672"local-[exec|dynamic] accesses!");7673unsigned TargetFlags = GA->getTargetFlags();76747675// The second operand of the addi that we want to preserve will be an7676// immediate. We add this immediate, together with the address of the TLS7677// variable found in InitialADDI, in order to preserve the correct TLS address7678// information during assembly printing. The offset is likely to be non-zero7679// when we end up in this case.7680int Offset = N->getConstantOperandVal(1);7681TLSVarNode = DAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(GA), MVT::i64,7682Offset, TargetFlags);76837684(void)DAG->UpdateNodeOperands(N, InitialADDI.getOperand(0), TLSVarNode);7685if (InitialADDI.getNode()->use_empty())7686DAG->RemoveDeadNode(InitialADDI.getNode());7687}76887689void PPCDAGToDAGISel::PeepholePPC64() {7690SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();76917692while (Position != CurDAG->allnodes_begin()) {7693SDNode *N = &*--Position;7694// Skip dead nodes and any non-machine opcodes.7695if (N->use_empty() || !N->isMachineOpcode())7696continue;76977698if (isVSXSwap(SDValue(N, 0)))7699reduceVSXSwap(N, CurDAG);77007701// This optimization is performed for non-TOC-based local-[exec|dynamic]7702// accesses.7703foldADDIForFasterLocalAccesses(N, CurDAG);77047705unsigned FirstOp;7706unsigned StorageOpcode = N->getMachineOpcode();7707bool RequiresMod4Offset = false;77087709switch (StorageOpcode) {7710default: continue;77117712case PPC::LWA:7713case PPC::LD:7714case PPC::DFLOADf64:7715case PPC::DFLOADf32:7716RequiresMod4Offset = true;7717[[fallthrough]];7718case PPC::LBZ:7719case PPC::LBZ8:7720case PPC::LFD:7721case PPC::LFS:7722case PPC::LHA:7723case PPC::LHA8:7724case PPC::LHZ:7725case PPC::LHZ8:7726case PPC::LWZ:7727case PPC::LWZ8:7728FirstOp = 0;7729break;77307731case PPC::STD:7732case PPC::DFSTOREf64:7733case PPC::DFSTOREf32:7734RequiresMod4Offset = true;7735[[fallthrough]];7736case PPC::STB:7737case PPC::STB8:7738case PPC::STFD:7739case PPC::STFS:7740case PPC::STH:7741case PPC::STH8:7742case PPC::STW:7743case PPC::STW8:7744FirstOp = 1;7745break;7746}77477748// If this is a load or store with a zero offset, or within the alignment,7749// we may be able to fold an add-immediate into the memory operation.7750// The check against alignment is below, as it can't occur until we check7751// the arguments to N7752if (!isa<ConstantSDNode>(N->getOperand(FirstOp)))7753continue;77547755SDValue Base = N->getOperand(FirstOp + 1);7756if (!Base.isMachineOpcode())7757continue;77587759unsigned Flags = 0;7760bool ReplaceFlags = true;77617762// When the feeding operation is an add-immediate of some sort,7763// determine whether we need to add relocation information to the7764// target flags on the immediate operand when we fold it into the7765// load instruction.7766//7767// For something like ADDItocL8, the relocation information is7768// inferred from the opcode; when we process it in the AsmPrinter,7769// we add the necessary relocation there. A load, though, can receive7770// relocation from various flavors of ADDIxxx, so we need to carry7771// the relocation information in the target flags.7772switch (Base.getMachineOpcode()) {7773default: continue;77747775case PPC::ADDI8:7776case PPC::ADDI:7777// In some cases (such as TLS) the relocation information7778// is already in place on the operand, so copying the operand7779// is sufficient.7780ReplaceFlags = false;7781break;7782case PPC::ADDIdtprelL:7783Flags = PPCII::MO_DTPREL_LO;7784break;7785case PPC::ADDItlsldL:7786Flags = PPCII::MO_TLSLD_LO;7787break;7788case PPC::ADDItocL8:7789// Skip the following peephole optimizations for ADDItocL8 on AIX which7790// is used for toc-data access.7791if (Subtarget->isAIXABI())7792continue;7793Flags = PPCII::MO_TOC_LO;7794break;7795}77967797SDValue ImmOpnd = Base.getOperand(1);77987799// On PPC64, the TOC base pointer is guaranteed by the ABI only to have7800// 8-byte alignment, and so we can only use offsets less than 8 (otherwise,7801// we might have needed different @ha relocation values for the offset7802// pointers).7803int MaxDisplacement = 7;7804if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {7805const GlobalValue *GV = GA->getGlobal();7806Align Alignment = GV->getPointerAlignment(CurDAG->getDataLayout());7807MaxDisplacement = std::min((int)Alignment.value() - 1, MaxDisplacement);7808}78097810bool UpdateHBase = false;7811SDValue HBase = Base.getOperand(0);78127813int Offset = N->getConstantOperandVal(FirstOp);7814if (ReplaceFlags) {7815if (Offset < 0 || Offset > MaxDisplacement) {7816// If we have a addi(toc@l)/addis(toc@ha) pair, and the addis has only7817// one use, then we can do this for any offset, we just need to also7818// update the offset (i.e. the symbol addend) on the addis also.7819if (Base.getMachineOpcode() != PPC::ADDItocL8)7820continue;78217822if (!HBase.isMachineOpcode() ||7823HBase.getMachineOpcode() != PPC::ADDIStocHA8)7824continue;78257826if (!Base.hasOneUse() || !HBase.hasOneUse())7827continue;78287829SDValue HImmOpnd = HBase.getOperand(1);7830if (HImmOpnd != ImmOpnd)7831continue;78327833UpdateHBase = true;7834}7835} else {7836// Global addresses can be folded, but only if they are sufficiently7837// aligned.7838if (RequiresMod4Offset) {7839if (GlobalAddressSDNode *GA =7840dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {7841const GlobalValue *GV = GA->getGlobal();7842Align Alignment = GV->getPointerAlignment(CurDAG->getDataLayout());7843if (Alignment < 4)7844continue;7845}7846}78477848// If we're directly folding the addend from an addi instruction, then:7849// 1. In general, the offset on the memory access must be zero.7850// 2. If the addend is a constant, then it can be combined with a7851// non-zero offset, but only if the result meets the encoding7852// requirements.7853if (auto *C = dyn_cast<ConstantSDNode>(ImmOpnd)) {7854Offset += C->getSExtValue();78557856if (RequiresMod4Offset && (Offset % 4) != 0)7857continue;78587859if (!isInt<16>(Offset))7860continue;78617862ImmOpnd = CurDAG->getTargetConstant(Offset, SDLoc(ImmOpnd),7863ImmOpnd.getValueType());7864} else if (Offset != 0) {7865// This optimization is performed for non-TOC-based local-[exec|dynamic]7866// accesses.7867if (isEligibleToFoldADDIForFasterLocalAccesses(CurDAG, Base)) {7868// Add the non-zero offset information into the load or store7869// instruction to be used for non-TOC-based local-[exec|dynamic]7870// accesses.7871GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd);7872assert(GA && "Expecting a valid GlobalAddressSDNode when folding "7873"addi into local-[exec|dynamic] accesses!");7874ImmOpnd = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(GA),7875MVT::i64, Offset,7876GA->getTargetFlags());7877} else7878continue;7879}7880}78817882// We found an opportunity. Reverse the operands from the add7883// immediate and substitute them into the load or store. If7884// needed, update the target flags for the immediate operand to7885// reflect the necessary relocation information.7886LLVM_DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: ");7887LLVM_DEBUG(Base->dump(CurDAG));7888LLVM_DEBUG(dbgs() << "\nN: ");7889LLVM_DEBUG(N->dump(CurDAG));7890LLVM_DEBUG(dbgs() << "\n");78917892// If the relocation information isn't already present on the7893// immediate operand, add it now.7894if (ReplaceFlags) {7895if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {7896SDLoc dl(GA);7897const GlobalValue *GV = GA->getGlobal();7898Align Alignment = GV->getPointerAlignment(CurDAG->getDataLayout());7899// We can't perform this optimization for data whose alignment7900// is insufficient for the instruction encoding.7901if (Alignment < 4 && (RequiresMod4Offset || (Offset % 4) != 0)) {7902LLVM_DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");7903continue;7904}7905ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, Offset, Flags);7906} else if (ConstantPoolSDNode *CP =7907dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {7908const Constant *C = CP->getConstVal();7909ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64, CP->getAlign(),7910Offset, Flags);7911}7912}79137914if (FirstOp == 1) // Store7915(void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,7916Base.getOperand(0), N->getOperand(3));7917else // Load7918(void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),7919N->getOperand(2));79207921if (UpdateHBase)7922(void)CurDAG->UpdateNodeOperands(HBase.getNode(), HBase.getOperand(0),7923ImmOpnd);79247925// The add-immediate may now be dead, in which case remove it.7926if (Base.getNode()->use_empty())7927CurDAG->RemoveDeadNode(Base.getNode());7928}7929}79307931/// createPPCISelDag - This pass converts a legalized DAG into a7932/// PowerPC-specific DAG, ready for instruction scheduling.7933///7934FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM,7935CodeGenOptLevel OptLevel) {7936return new PPCDAGToDAGISelLegacy(TM, OptLevel);7937}793879397940