1 //===- DAGCombiner.cpp - Implement a DAG node combiner --------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run 11 // both before and after the DAG is legalized. 12 // 13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is 14 // primarily intended to handle simplification opportunities that are implicit 15 // in the LLVM IR and exposed by the various codegen lowering phases. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/ADT/APFloat.h" 20 #include "llvm/ADT/APInt.h" 21 #include "llvm/ADT/ArrayRef.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/None.h" 24 #include "llvm/ADT/Optional.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SetVector.h" 27 #include "llvm/ADT/SmallBitVector.h" 28 #include "llvm/ADT/SmallPtrSet.h" 29 #include "llvm/ADT/SmallSet.h" 30 #include "llvm/ADT/SmallVector.h" 31 #include "llvm/ADT/Statistic.h" 32 #include "llvm/Analysis/AliasAnalysis.h" 33 #include "llvm/Analysis/MemoryLocation.h" 34 #include "llvm/CodeGen/DAGCombine.h" 35 #include "llvm/CodeGen/ISDOpcodes.h" 36 #include "llvm/CodeGen/MachineFrameInfo.h" 37 #include "llvm/CodeGen/MachineFunction.h" 38 #include "llvm/CodeGen/MachineMemOperand.h" 39 #include "llvm/CodeGen/MachineValueType.h" 40 #include "llvm/CodeGen/RuntimeLibcalls.h" 41 #include "llvm/CodeGen/SelectionDAG.h" 42 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 43 #include "llvm/CodeGen/SelectionDAGNodes.h" 44 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 45 #include "llvm/CodeGen/TargetLowering.h" 46 #include "llvm/CodeGen/TargetRegisterInfo.h" 47 #include "llvm/CodeGen/TargetSubtargetInfo.h" 48 #include "llvm/CodeGen/ValueTypes.h" 49 #include "llvm/IR/Attributes.h" 50 #include "llvm/IR/Constant.h" 51 #include "llvm/IR/DataLayout.h" 52 #include "llvm/IR/DerivedTypes.h" 53 #include "llvm/IR/Function.h" 54 #include "llvm/IR/LLVMContext.h" 55 #include "llvm/IR/Metadata.h" 56 #include "llvm/Support/Casting.h" 57 #include "llvm/Support/CodeGen.h" 58 #include "llvm/Support/CommandLine.h" 59 #include "llvm/Support/Compiler.h" 60 #include "llvm/Support/Debug.h" 61 #include "llvm/Support/ErrorHandling.h" 62 #include "llvm/Support/KnownBits.h" 63 #include "llvm/Support/MathExtras.h" 64 #include "llvm/Support/raw_ostream.h" 65 #include "llvm/Target/TargetMachine.h" 66 #include "llvm/Target/TargetOptions.h" 67 #include <algorithm> 68 #include <cassert> 69 #include <cstdint> 70 #include <functional> 71 #include <iterator> 72 #include <string> 73 #include <tuple> 74 #include <utility> 75 #include <vector> 76 77 using namespace llvm; 78 79 #define DEBUG_TYPE "dagcombine" 80 81 STATISTIC(NodesCombined , "Number of dag nodes combined"); 82 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 83 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 84 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 85 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 86 STATISTIC(SlicedLoads, "Number of load sliced"); 87 88 static cl::opt<bool> 89 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 90 cl::desc("Enable DAG combiner's use of IR alias analysis")); 91 92 static cl::opt<bool> 93 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 94 cl::desc("Enable DAG combiner's use of TBAA")); 95 96 #ifndef NDEBUG 97 static cl::opt<std::string> 98 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 99 cl::desc("Only use DAG-combiner alias analysis in this" 100 " function")); 101 #endif 102 103 /// Hidden option to stress test load slicing, i.e., when this option 104 /// is enabled, load slicing bypasses most of its profitability guards. 105 static cl::opt<bool> 106 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 107 cl::desc("Bypass the profitability model of load slicing"), 108 cl::init(false)); 109 110 static cl::opt<bool> 111 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 112 cl::desc("DAG combiner may split indexing from loads")); 113 114 namespace { 115 116 class DAGCombiner { 117 SelectionDAG &DAG; 118 const TargetLowering &TLI; 119 CombineLevel Level; 120 CodeGenOpt::Level OptLevel; 121 bool LegalOperations = false; 122 bool LegalTypes = false; 123 bool ForCodeSize; 124 125 /// \brief Worklist of all of the nodes that need to be simplified. 126 /// 127 /// This must behave as a stack -- new nodes to process are pushed onto the 128 /// back and when processing we pop off of the back. 129 /// 130 /// The worklist will not contain duplicates but may contain null entries 131 /// due to nodes being deleted from the underlying DAG. 132 SmallVector<SDNode *, 64> Worklist; 133 134 /// \brief Mapping from an SDNode to its position on the worklist. 135 /// 136 /// This is used to find and remove nodes from the worklist (by nulling 137 /// them) when they are deleted from the underlying DAG. It relies on 138 /// stable indices of nodes within the worklist. 139 DenseMap<SDNode *, unsigned> WorklistMap; 140 141 /// \brief Set of nodes which have been combined (at least once). 142 /// 143 /// This is used to allow us to reliably add any operands of a DAG node 144 /// which have not yet been combined to the worklist. 145 SmallPtrSet<SDNode *, 32> CombinedNodes; 146 147 // AA - Used for DAG load/store alias analysis. 148 AliasAnalysis *AA; 149 150 /// When an instruction is simplified, add all users of the instruction to 151 /// the work lists because they might get more simplified now. 152 void AddUsersToWorklist(SDNode *N) { 153 for (SDNode *Node : N->uses()) 154 AddToWorklist(Node); 155 } 156 157 /// Call the node-specific routine that folds each particular type of node. 158 SDValue visit(SDNode *N); 159 160 public: 161 DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL) 162 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 163 OptLevel(OL), AA(AA) { 164 ForCodeSize = DAG.getMachineFunction().getFunction().optForSize(); 165 166 MaximumLegalStoreInBits = 0; 167 for (MVT VT : MVT::all_valuetypes()) 168 if (EVT(VT).isSimple() && VT != MVT::Other && 169 TLI.isTypeLegal(EVT(VT)) && 170 VT.getSizeInBits() >= MaximumLegalStoreInBits) 171 MaximumLegalStoreInBits = VT.getSizeInBits(); 172 } 173 174 /// Add to the worklist making sure its instance is at the back (next to be 175 /// processed.) 176 void AddToWorklist(SDNode *N) { 177 assert(N->getOpcode() != ISD::DELETED_NODE && 178 "Deleted Node added to Worklist"); 179 180 // Skip handle nodes as they can't usefully be combined and confuse the 181 // zero-use deletion strategy. 182 if (N->getOpcode() == ISD::HANDLENODE) 183 return; 184 185 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 186 Worklist.push_back(N); 187 } 188 189 /// Remove all instances of N from the worklist. 190 void removeFromWorklist(SDNode *N) { 191 CombinedNodes.erase(N); 192 193 auto It = WorklistMap.find(N); 194 if (It == WorklistMap.end()) 195 return; // Not in the worklist. 196 197 // Null out the entry rather than erasing it to avoid a linear operation. 198 Worklist[It->second] = nullptr; 199 WorklistMap.erase(It); 200 } 201 202 void deleteAndRecombine(SDNode *N); 203 bool recursivelyDeleteUnusedNodes(SDNode *N); 204 205 /// Replaces all uses of the results of one DAG node with new values. 206 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 207 bool AddTo = true); 208 209 /// Replaces all uses of the results of one DAG node with new values. 210 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 211 return CombineTo(N, &Res, 1, AddTo); 212 } 213 214 /// Replaces all uses of the results of one DAG node with new values. 215 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 216 bool AddTo = true) { 217 SDValue To[] = { Res0, Res1 }; 218 return CombineTo(N, To, 2, AddTo); 219 } 220 221 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 222 223 private: 224 unsigned MaximumLegalStoreInBits; 225 226 /// Check the specified integer node value to see if it can be simplified or 227 /// if things it uses can be simplified by bit propagation. 228 /// If so, return true. 229 bool SimplifyDemandedBits(SDValue Op) { 230 unsigned BitWidth = Op.getScalarValueSizeInBits(); 231 APInt Demanded = APInt::getAllOnesValue(BitWidth); 232 return SimplifyDemandedBits(Op, Demanded); 233 } 234 235 /// Check the specified vector node value to see if it can be simplified or 236 /// if things it uses can be simplified as it only uses some of the 237 /// elements. If so, return true. 238 bool SimplifyDemandedVectorElts(SDValue Op) { 239 unsigned NumElts = Op.getValueType().getVectorNumElements(); 240 APInt Demanded = APInt::getAllOnesValue(NumElts); 241 return SimplifyDemandedVectorElts(Op, Demanded); 242 } 243 244 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 245 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &Demanded); 246 247 bool CombineToPreIndexedLoadStore(SDNode *N); 248 bool CombineToPostIndexedLoadStore(SDNode *N); 249 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 250 bool SliceUpLoad(SDNode *N); 251 252 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 253 /// load. 254 /// 255 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 256 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 257 /// \param EltNo index of the vector element to load. 258 /// \param OriginalLoad load that EVE came from to be replaced. 259 /// \returns EVE on success SDValue() on failure. 260 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 261 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 262 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 263 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 264 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 265 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 266 SDValue PromoteIntBinOp(SDValue Op); 267 SDValue PromoteIntShiftOp(SDValue Op); 268 SDValue PromoteExtend(SDValue Op); 269 bool PromoteLoad(SDValue Op); 270 271 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 272 SDValue OrigLoad, SDValue ExtLoad, 273 const SDLoc &DL, 274 ISD::NodeType ExtType); 275 276 /// Call the node-specific routine that knows how to fold each 277 /// particular type of node. If that doesn't do anything, try the 278 /// target-specific DAG combines. 279 SDValue combine(SDNode *N); 280 281 // Visitation implementation - Implement dag node combining for different 282 // node types. The semantics are as follows: 283 // Return Value: 284 // SDValue.getNode() == 0 - No change was made 285 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 286 // otherwise - N should be replaced by the returned Operand. 287 // 288 SDValue visitTokenFactor(SDNode *N); 289 SDValue visitMERGE_VALUES(SDNode *N); 290 SDValue visitADD(SDNode *N); 291 SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference); 292 SDValue visitSUB(SDNode *N); 293 SDValue visitADDC(SDNode *N); 294 SDValue visitUADDO(SDNode *N); 295 SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N); 296 SDValue visitSUBC(SDNode *N); 297 SDValue visitUSUBO(SDNode *N); 298 SDValue visitADDE(SDNode *N); 299 SDValue visitADDCARRY(SDNode *N); 300 SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N); 301 SDValue visitSUBE(SDNode *N); 302 SDValue visitSUBCARRY(SDNode *N); 303 SDValue visitMUL(SDNode *N); 304 SDValue useDivRem(SDNode *N); 305 SDValue visitSDIV(SDNode *N); 306 SDValue visitUDIV(SDNode *N); 307 SDValue visitREM(SDNode *N); 308 SDValue visitMULHU(SDNode *N); 309 SDValue visitMULHS(SDNode *N); 310 SDValue visitSMUL_LOHI(SDNode *N); 311 SDValue visitUMUL_LOHI(SDNode *N); 312 SDValue visitSMULO(SDNode *N); 313 SDValue visitUMULO(SDNode *N); 314 SDValue visitIMINMAX(SDNode *N); 315 SDValue visitAND(SDNode *N); 316 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference); 317 SDValue visitOR(SDNode *N); 318 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference); 319 SDValue visitXOR(SDNode *N); 320 SDValue SimplifyVBinOp(SDNode *N); 321 SDValue visitSHL(SDNode *N); 322 SDValue visitSRA(SDNode *N); 323 SDValue visitSRL(SDNode *N); 324 SDValue visitRotate(SDNode *N); 325 SDValue visitABS(SDNode *N); 326 SDValue visitBSWAP(SDNode *N); 327 SDValue visitBITREVERSE(SDNode *N); 328 SDValue visitCTLZ(SDNode *N); 329 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 330 SDValue visitCTTZ(SDNode *N); 331 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 332 SDValue visitCTPOP(SDNode *N); 333 SDValue visitSELECT(SDNode *N); 334 SDValue visitVSELECT(SDNode *N); 335 SDValue visitSELECT_CC(SDNode *N); 336 SDValue visitSETCC(SDNode *N); 337 SDValue visitSETCCE(SDNode *N); 338 SDValue visitSETCCCARRY(SDNode *N); 339 SDValue visitSIGN_EXTEND(SDNode *N); 340 SDValue visitZERO_EXTEND(SDNode *N); 341 SDValue visitANY_EXTEND(SDNode *N); 342 SDValue visitAssertExt(SDNode *N); 343 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 344 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 345 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N); 346 SDValue visitTRUNCATE(SDNode *N); 347 SDValue visitBITCAST(SDNode *N); 348 SDValue visitBUILD_PAIR(SDNode *N); 349 SDValue visitFADD(SDNode *N); 350 SDValue visitFSUB(SDNode *N); 351 SDValue visitFMUL(SDNode *N); 352 SDValue visitFMA(SDNode *N); 353 SDValue visitFDIV(SDNode *N); 354 SDValue visitFREM(SDNode *N); 355 SDValue visitFSQRT(SDNode *N); 356 SDValue visitFCOPYSIGN(SDNode *N); 357 SDValue visitSINT_TO_FP(SDNode *N); 358 SDValue visitUINT_TO_FP(SDNode *N); 359 SDValue visitFP_TO_SINT(SDNode *N); 360 SDValue visitFP_TO_UINT(SDNode *N); 361 SDValue visitFP_ROUND(SDNode *N); 362 SDValue visitFP_ROUND_INREG(SDNode *N); 363 SDValue visitFP_EXTEND(SDNode *N); 364 SDValue visitFNEG(SDNode *N); 365 SDValue visitFABS(SDNode *N); 366 SDValue visitFCEIL(SDNode *N); 367 SDValue visitFTRUNC(SDNode *N); 368 SDValue visitFFLOOR(SDNode *N); 369 SDValue visitFMINNUM(SDNode *N); 370 SDValue visitFMAXNUM(SDNode *N); 371 SDValue visitBRCOND(SDNode *N); 372 SDValue visitBR_CC(SDNode *N); 373 SDValue visitLOAD(SDNode *N); 374 375 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 376 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 377 378 SDValue visitSTORE(SDNode *N); 379 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 380 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 381 SDValue visitBUILD_VECTOR(SDNode *N); 382 SDValue visitCONCAT_VECTORS(SDNode *N); 383 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 384 SDValue visitVECTOR_SHUFFLE(SDNode *N); 385 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 386 SDValue visitINSERT_SUBVECTOR(SDNode *N); 387 SDValue visitMLOAD(SDNode *N); 388 SDValue visitMSTORE(SDNode *N); 389 SDValue visitMGATHER(SDNode *N); 390 SDValue visitMSCATTER(SDNode *N); 391 SDValue visitFP_TO_FP16(SDNode *N); 392 SDValue visitFP16_TO_FP(SDNode *N); 393 394 SDValue visitFADDForFMACombine(SDNode *N); 395 SDValue visitFSUBForFMACombine(SDNode *N); 396 SDValue visitFMULForFMADistributiveCombine(SDNode *N); 397 398 SDValue XformToShuffleWithZero(SDNode *N); 399 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS, 400 SDValue RHS); 401 402 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 403 404 SDValue foldSelectOfConstants(SDNode *N); 405 SDValue foldVSelectOfConstants(SDNode *N); 406 SDValue foldBinOpIntoSelect(SDNode *BO); 407 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 408 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 409 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2); 410 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 411 SDValue N2, SDValue N3, ISD::CondCode CC, 412 bool NotExtCompare = false); 413 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1, 414 SDValue N2, SDValue N3, ISD::CondCode CC); 415 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 416 const SDLoc &DL); 417 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 418 const SDLoc &DL, bool foldBooleans); 419 SDValue rebuildSetCC(SDValue N); 420 421 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 422 SDValue &CC) const; 423 bool isOneUseSetCC(SDValue N) const; 424 425 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 426 unsigned HiOp); 427 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 428 SDValue CombineExtLoad(SDNode *N); 429 SDValue combineRepeatedFPDivisors(SDNode *N); 430 SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex); 431 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 432 SDValue BuildSDIV(SDNode *N); 433 SDValue BuildSDIVPow2(SDNode *N); 434 SDValue BuildUDIV(SDNode *N); 435 SDValue BuildLogBase2(SDValue Op, const SDLoc &DL); 436 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags); 437 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags); 438 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags); 439 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip); 440 SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations, 441 SDNodeFlags Flags, bool Reciprocal); 442 SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations, 443 SDNodeFlags Flags, bool Reciprocal); 444 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 445 bool DemandHighBits = true); 446 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 447 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 448 SDValue InnerPos, SDValue InnerNeg, 449 unsigned PosOpcode, unsigned NegOpcode, 450 const SDLoc &DL); 451 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL); 452 SDValue MatchLoadCombine(SDNode *N); 453 SDValue ReduceLoadWidth(SDNode *N); 454 SDValue ReduceLoadOpStoreWidth(SDNode *N); 455 SDValue splitMergedValStore(StoreSDNode *ST); 456 SDValue TransformFPLoadStorePair(SDNode *N); 457 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 458 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 459 SDValue reduceBuildVecToShuffle(SDNode *N); 460 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N, 461 ArrayRef<int> VectorMask, SDValue VecIn1, 462 SDValue VecIn2, unsigned LeftIdx); 463 SDValue matchVSelectOpSizesWithSetCC(SDNode *N); 464 465 /// Walk up chain skipping non-aliasing memory nodes, 466 /// looking for aliasing nodes and adding them to the Aliases vector. 467 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 468 SmallVectorImpl<SDValue> &Aliases); 469 470 /// Return true if there is any possibility that the two addresses overlap. 471 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 472 473 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 474 /// chain (aliasing node.) 475 SDValue FindBetterChain(SDNode *N, SDValue Chain); 476 477 /// Try to replace a store and any possibly adjacent stores on 478 /// consecutive chains with better chains. Return true only if St is 479 /// replaced. 480 /// 481 /// Notice that other chains may still be replaced even if the function 482 /// returns false. 483 bool findBetterNeighborChains(StoreSDNode *St); 484 485 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 486 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask); 487 488 /// Holds a pointer to an LSBaseSDNode as well as information on where it 489 /// is located in a sequence of memory operations connected by a chain. 490 struct MemOpLink { 491 // Ptr to the mem node. 492 LSBaseSDNode *MemNode; 493 494 // Offset from the base ptr. 495 int64_t OffsetFromBase; 496 497 MemOpLink(LSBaseSDNode *N, int64_t Offset) 498 : MemNode(N), OffsetFromBase(Offset) {} 499 }; 500 501 /// This is a helper function for visitMUL to check the profitability 502 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 503 /// MulNode is the original multiply, AddNode is (add x, c1), 504 /// and ConstNode is c2. 505 bool isMulAddWithConstProfitable(SDNode *MulNode, 506 SDValue &AddNode, 507 SDValue &ConstNode); 508 509 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 510 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 511 /// the type of the loaded value to be extended. 512 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 513 EVT LoadResultTy, EVT &ExtVT); 514 515 /// Helper function to calculate whether the given Load can have its 516 /// width reduced to ExtVT. 517 bool isLegalNarrowLoad(LoadSDNode *LoadN, ISD::LoadExtType ExtType, 518 EVT &ExtVT, unsigned ShAmt = 0); 519 520 /// Used by BackwardsPropagateMask to find suitable loads. 521 bool SearchForAndLoads(SDNode *N, SmallPtrSetImpl<LoadSDNode*> &Loads, 522 SmallPtrSetImpl<SDNode*> &NodeWithConsts, 523 ConstantSDNode *Mask, SDNode *&UncombinedNode); 524 /// Attempt to propagate a given AND node back to load leaves so that they 525 /// can be combined into narrow loads. 526 bool BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG); 527 528 /// Helper function for MergeConsecutiveStores which merges the 529 /// component store chains. 530 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 531 unsigned NumStores); 532 533 /// This is a helper function for MergeConsecutiveStores. When the 534 /// source elements of the consecutive stores are all constants or 535 /// all extracted vector elements, try to merge them into one 536 /// larger store introducing bitcasts if necessary. \return True 537 /// if a merged store was created. 538 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 539 EVT MemVT, unsigned NumStores, 540 bool IsConstantSrc, bool UseVector, 541 bool UseTrunc); 542 543 /// This is a helper function for MergeConsecutiveStores. Stores 544 /// that potentially may be merged with St are placed in 545 /// StoreNodes. 546 void getStoreMergeCandidates(StoreSDNode *St, 547 SmallVectorImpl<MemOpLink> &StoreNodes); 548 549 /// Helper function for MergeConsecutiveStores. Checks if 550 /// candidate stores have indirect dependency through their 551 /// operands. \return True if safe to merge. 552 bool checkMergeStoreCandidatesForDependencies( 553 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores); 554 555 /// Merge consecutive store operations into a wide store. 556 /// This optimization uses wide integers or vectors when possible. 557 /// \return number of stores that were merged into a merged store (the 558 /// affected nodes are stored as a prefix in \p StoreNodes). 559 bool MergeConsecutiveStores(StoreSDNode *N); 560 561 /// \brief Try to transform a truncation where C is a constant: 562 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 563 /// 564 /// \p N needs to be a truncation and its first operand an AND. Other 565 /// requirements are checked by the function (e.g. that trunc is 566 /// single-use) and if missed an empty SDValue is returned. 567 SDValue distributeTruncateThroughAnd(SDNode *N); 568 569 public: 570 /// Runs the dag combiner on all nodes in the work list 571 void Run(CombineLevel AtLevel); 572 573 SelectionDAG &getDAG() const { return DAG; } 574 575 /// Returns a type large enough to hold any valid shift amount - before type 576 /// legalization these can be huge. 577 EVT getShiftAmountTy(EVT LHSTy) { 578 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 579 return TLI.getShiftAmountTy(LHSTy, DAG.getDataLayout(), LegalTypes); 580 } 581 582 /// This method returns true if we are running before type legalization or 583 /// if the specified VT is legal. 584 bool isTypeLegal(const EVT &VT) { 585 if (!LegalTypes) return true; 586 return TLI.isTypeLegal(VT); 587 } 588 589 /// Convenience wrapper around TargetLowering::getSetCCResultType 590 EVT getSetCCResultType(EVT VT) const { 591 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 592 } 593 }; 594 595 /// This class is a DAGUpdateListener that removes any deleted 596 /// nodes from the worklist. 597 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 598 DAGCombiner &DC; 599 600 public: 601 explicit WorklistRemover(DAGCombiner &dc) 602 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 603 604 void NodeDeleted(SDNode *N, SDNode *E) override { 605 DC.removeFromWorklist(N); 606 } 607 }; 608 609 } // end anonymous namespace 610 611 //===----------------------------------------------------------------------===// 612 // TargetLowering::DAGCombinerInfo implementation 613 //===----------------------------------------------------------------------===// 614 615 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 616 ((DAGCombiner*)DC)->AddToWorklist(N); 617 } 618 619 SDValue TargetLowering::DAGCombinerInfo:: 620 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 621 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 622 } 623 624 SDValue TargetLowering::DAGCombinerInfo:: 625 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 626 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 627 } 628 629 SDValue TargetLowering::DAGCombinerInfo:: 630 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 631 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 632 } 633 634 void TargetLowering::DAGCombinerInfo:: 635 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 636 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 637 } 638 639 //===----------------------------------------------------------------------===// 640 // Helper Functions 641 //===----------------------------------------------------------------------===// 642 643 void DAGCombiner::deleteAndRecombine(SDNode *N) { 644 removeFromWorklist(N); 645 646 // If the operands of this node are only used by the node, they will now be 647 // dead. Make sure to re-visit them and recursively delete dead nodes. 648 for (const SDValue &Op : N->ops()) 649 // For an operand generating multiple values, one of the values may 650 // become dead allowing further simplification (e.g. split index 651 // arithmetic from an indexed load). 652 if (Op->hasOneUse() || Op->getNumValues() > 1) 653 AddToWorklist(Op.getNode()); 654 655 DAG.DeleteNode(N); 656 } 657 658 /// Return 1 if we can compute the negated form of the specified expression for 659 /// the same cost as the expression itself, or 2 if we can compute the negated 660 /// form more cheaply than the expression itself. 661 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 662 const TargetLowering &TLI, 663 const TargetOptions *Options, 664 unsigned Depth = 0) { 665 // fneg is removable even if it has multiple uses. 666 if (Op.getOpcode() == ISD::FNEG) return 2; 667 668 // Don't allow anything with multiple uses. 669 if (!Op.hasOneUse()) return 0; 670 671 // Don't recurse exponentially. 672 if (Depth > 6) return 0; 673 674 switch (Op.getOpcode()) { 675 default: return false; 676 case ISD::ConstantFP: { 677 if (!LegalOperations) 678 return 1; 679 680 // Don't invert constant FP values after legalization unless the target says 681 // the negated constant is legal. 682 EVT VT = Op.getValueType(); 683 return TLI.isOperationLegal(ISD::ConstantFP, VT) || 684 TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT); 685 } 686 case ISD::FADD: 687 // FIXME: determine better conditions for this xform. 688 if (!Options->UnsafeFPMath) return 0; 689 690 // After operation legalization, it might not be legal to create new FSUBs. 691 if (LegalOperations && 692 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 693 return 0; 694 695 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 696 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 697 Options, Depth + 1)) 698 return V; 699 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 700 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 701 Depth + 1); 702 case ISD::FSUB: 703 // We can't turn -(A-B) into B-A when we honor signed zeros. 704 if (!Options->NoSignedZerosFPMath && 705 !Op.getNode()->getFlags().hasNoSignedZeros()) 706 return 0; 707 708 // fold (fneg (fsub A, B)) -> (fsub B, A) 709 return 1; 710 711 case ISD::FMUL: 712 case ISD::FDIV: 713 if (Options->HonorSignDependentRoundingFPMath()) return 0; 714 715 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 716 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 717 Options, Depth + 1)) 718 return V; 719 720 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 721 Depth + 1); 722 723 case ISD::FP_EXTEND: 724 case ISD::FP_ROUND: 725 case ISD::FSIN: 726 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 727 Depth + 1); 728 } 729 } 730 731 /// If isNegatibleForFree returns true, return the newly negated expression. 732 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 733 bool LegalOperations, unsigned Depth = 0) { 734 const TargetOptions &Options = DAG.getTarget().Options; 735 // fneg is removable even if it has multiple uses. 736 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 737 738 // Don't allow anything with multiple uses. 739 assert(Op.hasOneUse() && "Unknown reuse!"); 740 741 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 742 743 const SDNodeFlags Flags = Op.getNode()->getFlags(); 744 745 switch (Op.getOpcode()) { 746 default: llvm_unreachable("Unknown code"); 747 case ISD::ConstantFP: { 748 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 749 V.changeSign(); 750 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 751 } 752 case ISD::FADD: 753 // FIXME: determine better conditions for this xform. 754 assert(Options.UnsafeFPMath); 755 756 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 757 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 758 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 759 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 760 GetNegatedExpression(Op.getOperand(0), DAG, 761 LegalOperations, Depth+1), 762 Op.getOperand(1), Flags); 763 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 764 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 765 GetNegatedExpression(Op.getOperand(1), DAG, 766 LegalOperations, Depth+1), 767 Op.getOperand(0), Flags); 768 case ISD::FSUB: 769 // fold (fneg (fsub 0, B)) -> B 770 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 771 if (N0CFP->isZero()) 772 return Op.getOperand(1); 773 774 // fold (fneg (fsub A, B)) -> (fsub B, A) 775 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 776 Op.getOperand(1), Op.getOperand(0), Flags); 777 778 case ISD::FMUL: 779 case ISD::FDIV: 780 assert(!Options.HonorSignDependentRoundingFPMath()); 781 782 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 783 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 784 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 785 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 786 GetNegatedExpression(Op.getOperand(0), DAG, 787 LegalOperations, Depth+1), 788 Op.getOperand(1), Flags); 789 790 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 791 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 792 Op.getOperand(0), 793 GetNegatedExpression(Op.getOperand(1), DAG, 794 LegalOperations, Depth+1), Flags); 795 796 case ISD::FP_EXTEND: 797 case ISD::FSIN: 798 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 799 GetNegatedExpression(Op.getOperand(0), DAG, 800 LegalOperations, Depth+1)); 801 case ISD::FP_ROUND: 802 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 803 GetNegatedExpression(Op.getOperand(0), DAG, 804 LegalOperations, Depth+1), 805 Op.getOperand(1)); 806 } 807 } 808 809 // APInts must be the same size for most operations, this helper 810 // function zero extends the shorter of the pair so that they match. 811 // We provide an Offset so that we can create bitwidths that won't overflow. 812 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) { 813 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth()); 814 LHS = LHS.zextOrSelf(Bits); 815 RHS = RHS.zextOrSelf(Bits); 816 } 817 818 // Return true if this node is a setcc, or is a select_cc 819 // that selects between the target values used for true and false, making it 820 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 821 // the appropriate nodes based on the type of node we are checking. This 822 // simplifies life a bit for the callers. 823 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 824 SDValue &CC) const { 825 if (N.getOpcode() == ISD::SETCC) { 826 LHS = N.getOperand(0); 827 RHS = N.getOperand(1); 828 CC = N.getOperand(2); 829 return true; 830 } 831 832 if (N.getOpcode() != ISD::SELECT_CC || 833 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 834 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 835 return false; 836 837 if (TLI.getBooleanContents(N.getValueType()) == 838 TargetLowering::UndefinedBooleanContent) 839 return false; 840 841 LHS = N.getOperand(0); 842 RHS = N.getOperand(1); 843 CC = N.getOperand(4); 844 return true; 845 } 846 847 /// Return true if this is a SetCC-equivalent operation with only one use. 848 /// If this is true, it allows the users to invert the operation for free when 849 /// it is profitable to do so. 850 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 851 SDValue N0, N1, N2; 852 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 853 return true; 854 return false; 855 } 856 857 // \brief Returns the SDNode if it is a constant float BuildVector 858 // or constant float. 859 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 860 if (isa<ConstantFPSDNode>(N)) 861 return N.getNode(); 862 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 863 return N.getNode(); 864 return nullptr; 865 } 866 867 // Determines if it is a constant integer or a build vector of constant 868 // integers (and undefs). 869 // Do not permit build vector implicit truncation. 870 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) { 871 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N)) 872 return !(Const->isOpaque() && NoOpaques); 873 if (N.getOpcode() != ISD::BUILD_VECTOR) 874 return false; 875 unsigned BitWidth = N.getScalarValueSizeInBits(); 876 for (const SDValue &Op : N->op_values()) { 877 if (Op.isUndef()) 878 continue; 879 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op); 880 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth || 881 (Const->isOpaque() && NoOpaques)) 882 return false; 883 } 884 return true; 885 } 886 887 // Determines if it is a constant null integer or a splatted vector of a 888 // constant null integer (with no undefs). 889 // Build vector implicit truncation is not an issue for null values. 890 static bool isNullConstantOrNullSplatConstant(SDValue N) { 891 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 892 return Splat->isNullValue(); 893 return false; 894 } 895 896 // Determines if it is a constant integer of one or a splatted vector of a 897 // constant integer of one (with no undefs). 898 // Do not permit build vector implicit truncation. 899 static bool isOneConstantOrOneSplatConstant(SDValue N) { 900 unsigned BitWidth = N.getScalarValueSizeInBits(); 901 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 902 return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth; 903 return false; 904 } 905 906 // Determines if it is a constant integer of all ones or a splatted vector of a 907 // constant integer of all ones (with no undefs). 908 // Do not permit build vector implicit truncation. 909 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) { 910 unsigned BitWidth = N.getScalarValueSizeInBits(); 911 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 912 return Splat->isAllOnesValue() && 913 Splat->getAPIntValue().getBitWidth() == BitWidth; 914 return false; 915 } 916 917 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with 918 // undef's. 919 static bool isAnyConstantBuildVector(const SDNode *N) { 920 return ISD::isBuildVectorOfConstantSDNodes(N) || 921 ISD::isBuildVectorOfConstantFPSDNodes(N); 922 } 923 924 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 925 SDValue N1) { 926 EVT VT = N0.getValueType(); 927 if (N0.getOpcode() == Opc) { 928 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 929 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 930 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 931 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 932 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 933 return SDValue(); 934 } 935 if (N0.hasOneUse()) { 936 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 937 // use 938 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 939 if (!OpNode.getNode()) 940 return SDValue(); 941 AddToWorklist(OpNode.getNode()); 942 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 943 } 944 } 945 } 946 947 if (N1.getOpcode() == Opc) { 948 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 949 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 950 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 951 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 952 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 953 return SDValue(); 954 } 955 if (N1.hasOneUse()) { 956 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 957 // use 958 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 959 if (!OpNode.getNode()) 960 return SDValue(); 961 AddToWorklist(OpNode.getNode()); 962 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 963 } 964 } 965 } 966 967 return SDValue(); 968 } 969 970 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 971 bool AddTo) { 972 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 973 ++NodesCombined; 974 DEBUG(dbgs() << "\nReplacing.1 "; 975 N->dump(&DAG); 976 dbgs() << "\nWith: "; 977 To[0].getNode()->dump(&DAG); 978 dbgs() << " and " << NumTo-1 << " other values\n"); 979 for (unsigned i = 0, e = NumTo; i != e; ++i) 980 assert((!To[i].getNode() || 981 N->getValueType(i) == To[i].getValueType()) && 982 "Cannot combine value to value of different type!"); 983 984 WorklistRemover DeadNodes(*this); 985 DAG.ReplaceAllUsesWith(N, To); 986 if (AddTo) { 987 // Push the new nodes and any users onto the worklist 988 for (unsigned i = 0, e = NumTo; i != e; ++i) { 989 if (To[i].getNode()) { 990 AddToWorklist(To[i].getNode()); 991 AddUsersToWorklist(To[i].getNode()); 992 } 993 } 994 } 995 996 // Finally, if the node is now dead, remove it from the graph. The node 997 // may not be dead if the replacement process recursively simplified to 998 // something else needing this node. 999 if (N->use_empty()) 1000 deleteAndRecombine(N); 1001 return SDValue(N, 0); 1002 } 1003 1004 void DAGCombiner:: 1005 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 1006 // Replace all uses. If any nodes become isomorphic to other nodes and 1007 // are deleted, make sure to remove them from our worklist. 1008 WorklistRemover DeadNodes(*this); 1009 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 1010 1011 // Push the new node and any (possibly new) users onto the worklist. 1012 AddToWorklist(TLO.New.getNode()); 1013 AddUsersToWorklist(TLO.New.getNode()); 1014 1015 // Finally, if the node is now dead, remove it from the graph. The node 1016 // may not be dead if the replacement process recursively simplified to 1017 // something else needing this node. 1018 if (TLO.Old.getNode()->use_empty()) 1019 deleteAndRecombine(TLO.Old.getNode()); 1020 } 1021 1022 /// Check the specified integer node value to see if it can be simplified or if 1023 /// things it uses can be simplified by bit propagation. If so, return true. 1024 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 1025 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 1026 KnownBits Known; 1027 if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO)) 1028 return false; 1029 1030 // Revisit the node. 1031 AddToWorklist(Op.getNode()); 1032 1033 // Replace the old value with the new one. 1034 ++NodesCombined; 1035 DEBUG(dbgs() << "\nReplacing.2 "; 1036 TLO.Old.getNode()->dump(&DAG); 1037 dbgs() << "\nWith: "; 1038 TLO.New.getNode()->dump(&DAG); 1039 dbgs() << '\n'); 1040 1041 CommitTargetLoweringOpt(TLO); 1042 return true; 1043 } 1044 1045 /// Check the specified vector node value to see if it can be simplified or 1046 /// if things it uses can be simplified as it only uses some of the elements. 1047 /// If so, return true. 1048 bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op, 1049 const APInt &Demanded) { 1050 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 1051 APInt KnownUndef, KnownZero; 1052 if (!TLI.SimplifyDemandedVectorElts(Op, Demanded, KnownUndef, KnownZero, TLO)) 1053 return false; 1054 1055 // Revisit the node. 1056 AddToWorklist(Op.getNode()); 1057 1058 // Replace the old value with the new one. 1059 ++NodesCombined; 1060 DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG); 1061 dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG); dbgs() << '\n'); 1062 1063 CommitTargetLoweringOpt(TLO); 1064 return true; 1065 } 1066 1067 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 1068 SDLoc DL(Load); 1069 EVT VT = Load->getValueType(0); 1070 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0)); 1071 1072 DEBUG(dbgs() << "\nReplacing.9 "; 1073 Load->dump(&DAG); 1074 dbgs() << "\nWith: "; 1075 Trunc.getNode()->dump(&DAG); 1076 dbgs() << '\n'); 1077 WorklistRemover DeadNodes(*this); 1078 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 1079 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 1080 deleteAndRecombine(Load); 1081 AddToWorklist(Trunc.getNode()); 1082 } 1083 1084 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 1085 Replace = false; 1086 SDLoc DL(Op); 1087 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 1088 LoadSDNode *LD = cast<LoadSDNode>(Op); 1089 EVT MemVT = LD->getMemoryVT(); 1090 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1091 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1092 : ISD::EXTLOAD) 1093 : LD->getExtensionType(); 1094 Replace = true; 1095 return DAG.getExtLoad(ExtType, DL, PVT, 1096 LD->getChain(), LD->getBasePtr(), 1097 MemVT, LD->getMemOperand()); 1098 } 1099 1100 unsigned Opc = Op.getOpcode(); 1101 switch (Opc) { 1102 default: break; 1103 case ISD::AssertSext: 1104 if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT)) 1105 return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1)); 1106 break; 1107 case ISD::AssertZext: 1108 if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT)) 1109 return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1)); 1110 break; 1111 case ISD::Constant: { 1112 unsigned ExtOpc = 1113 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1114 return DAG.getNode(ExtOpc, DL, PVT, Op); 1115 } 1116 } 1117 1118 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 1119 return SDValue(); 1120 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op); 1121 } 1122 1123 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1124 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1125 return SDValue(); 1126 EVT OldVT = Op.getValueType(); 1127 SDLoc DL(Op); 1128 bool Replace = false; 1129 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1130 if (!NewOp.getNode()) 1131 return SDValue(); 1132 AddToWorklist(NewOp.getNode()); 1133 1134 if (Replace) 1135 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1136 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp, 1137 DAG.getValueType(OldVT)); 1138 } 1139 1140 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1141 EVT OldVT = Op.getValueType(); 1142 SDLoc DL(Op); 1143 bool Replace = false; 1144 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1145 if (!NewOp.getNode()) 1146 return SDValue(); 1147 AddToWorklist(NewOp.getNode()); 1148 1149 if (Replace) 1150 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1151 return DAG.getZeroExtendInReg(NewOp, DL, OldVT); 1152 } 1153 1154 /// Promote the specified integer binary operation if the target indicates it is 1155 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1156 /// i32 since i16 instructions are longer. 1157 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1158 if (!LegalOperations) 1159 return SDValue(); 1160 1161 EVT VT = Op.getValueType(); 1162 if (VT.isVector() || !VT.isInteger()) 1163 return SDValue(); 1164 1165 // If operation type is 'undesirable', e.g. i16 on x86, consider 1166 // promoting it. 1167 unsigned Opc = Op.getOpcode(); 1168 if (TLI.isTypeDesirableForOp(Opc, VT)) 1169 return SDValue(); 1170 1171 EVT PVT = VT; 1172 // Consult target whether it is a good idea to promote this operation and 1173 // what's the right type to promote it to. 1174 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1175 assert(PVT != VT && "Don't know what type to promote to!"); 1176 1177 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1178 1179 bool Replace0 = false; 1180 SDValue N0 = Op.getOperand(0); 1181 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1182 1183 bool Replace1 = false; 1184 SDValue N1 = Op.getOperand(1); 1185 SDValue NN1 = PromoteOperand(N1, PVT, Replace1); 1186 SDLoc DL(Op); 1187 1188 SDValue RV = 1189 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1)); 1190 1191 // We are always replacing N0/N1's use in N and only need 1192 // additional replacements if there are additional uses. 1193 Replace0 &= !N0->hasOneUse(); 1194 Replace1 &= (N0 != N1) && !N1->hasOneUse(); 1195 1196 // Combine Op here so it is preserved past replacements. 1197 CombineTo(Op.getNode(), RV); 1198 1199 // If operands have a use ordering, make sure we deal with 1200 // predecessor first. 1201 if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) { 1202 std::swap(N0, N1); 1203 std::swap(NN0, NN1); 1204 } 1205 1206 if (Replace0) { 1207 AddToWorklist(NN0.getNode()); 1208 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1209 } 1210 if (Replace1) { 1211 AddToWorklist(NN1.getNode()); 1212 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1213 } 1214 return Op; 1215 } 1216 return SDValue(); 1217 } 1218 1219 /// Promote the specified integer shift operation if the target indicates it is 1220 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1221 /// i32 since i16 instructions are longer. 1222 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1223 if (!LegalOperations) 1224 return SDValue(); 1225 1226 EVT VT = Op.getValueType(); 1227 if (VT.isVector() || !VT.isInteger()) 1228 return SDValue(); 1229 1230 // If operation type is 'undesirable', e.g. i16 on x86, consider 1231 // promoting it. 1232 unsigned Opc = Op.getOpcode(); 1233 if (TLI.isTypeDesirableForOp(Opc, VT)) 1234 return SDValue(); 1235 1236 EVT PVT = VT; 1237 // Consult target whether it is a good idea to promote this operation and 1238 // what's the right type to promote it to. 1239 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1240 assert(PVT != VT && "Don't know what type to promote to!"); 1241 1242 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1243 1244 bool Replace = false; 1245 SDValue N0 = Op.getOperand(0); 1246 SDValue N1 = Op.getOperand(1); 1247 if (Opc == ISD::SRA) 1248 N0 = SExtPromoteOperand(N0, PVT); 1249 else if (Opc == ISD::SRL) 1250 N0 = ZExtPromoteOperand(N0, PVT); 1251 else 1252 N0 = PromoteOperand(N0, PVT, Replace); 1253 1254 if (!N0.getNode()) 1255 return SDValue(); 1256 1257 SDLoc DL(Op); 1258 SDValue RV = 1259 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1)); 1260 1261 AddToWorklist(N0.getNode()); 1262 if (Replace) 1263 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1264 1265 // Deal with Op being deleted. 1266 if (Op && Op.getOpcode() != ISD::DELETED_NODE) 1267 return RV; 1268 } 1269 return SDValue(); 1270 } 1271 1272 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1273 if (!LegalOperations) 1274 return SDValue(); 1275 1276 EVT VT = Op.getValueType(); 1277 if (VT.isVector() || !VT.isInteger()) 1278 return SDValue(); 1279 1280 // If operation type is 'undesirable', e.g. i16 on x86, consider 1281 // promoting it. 1282 unsigned Opc = Op.getOpcode(); 1283 if (TLI.isTypeDesirableForOp(Opc, VT)) 1284 return SDValue(); 1285 1286 EVT PVT = VT; 1287 // Consult target whether it is a good idea to promote this operation and 1288 // what's the right type to promote it to. 1289 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1290 assert(PVT != VT && "Don't know what type to promote to!"); 1291 // fold (aext (aext x)) -> (aext x) 1292 // fold (aext (zext x)) -> (zext x) 1293 // fold (aext (sext x)) -> (sext x) 1294 DEBUG(dbgs() << "\nPromoting "; 1295 Op.getNode()->dump(&DAG)); 1296 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1297 } 1298 return SDValue(); 1299 } 1300 1301 bool DAGCombiner::PromoteLoad(SDValue Op) { 1302 if (!LegalOperations) 1303 return false; 1304 1305 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1306 return false; 1307 1308 EVT VT = Op.getValueType(); 1309 if (VT.isVector() || !VT.isInteger()) 1310 return false; 1311 1312 // If operation type is 'undesirable', e.g. i16 on x86, consider 1313 // promoting it. 1314 unsigned Opc = Op.getOpcode(); 1315 if (TLI.isTypeDesirableForOp(Opc, VT)) 1316 return false; 1317 1318 EVT PVT = VT; 1319 // Consult target whether it is a good idea to promote this operation and 1320 // what's the right type to promote it to. 1321 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1322 assert(PVT != VT && "Don't know what type to promote to!"); 1323 1324 SDLoc DL(Op); 1325 SDNode *N = Op.getNode(); 1326 LoadSDNode *LD = cast<LoadSDNode>(N); 1327 EVT MemVT = LD->getMemoryVT(); 1328 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1329 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1330 : ISD::EXTLOAD) 1331 : LD->getExtensionType(); 1332 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT, 1333 LD->getChain(), LD->getBasePtr(), 1334 MemVT, LD->getMemOperand()); 1335 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD); 1336 1337 DEBUG(dbgs() << "\nPromoting "; 1338 N->dump(&DAG); 1339 dbgs() << "\nTo: "; 1340 Result.getNode()->dump(&DAG); 1341 dbgs() << '\n'); 1342 WorklistRemover DeadNodes(*this); 1343 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1344 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1345 deleteAndRecombine(N); 1346 AddToWorklist(Result.getNode()); 1347 return true; 1348 } 1349 return false; 1350 } 1351 1352 /// \brief Recursively delete a node which has no uses and any operands for 1353 /// which it is the only use. 1354 /// 1355 /// Note that this both deletes the nodes and removes them from the worklist. 1356 /// It also adds any nodes who have had a user deleted to the worklist as they 1357 /// may now have only one use and subject to other combines. 1358 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1359 if (!N->use_empty()) 1360 return false; 1361 1362 SmallSetVector<SDNode *, 16> Nodes; 1363 Nodes.insert(N); 1364 do { 1365 N = Nodes.pop_back_val(); 1366 if (!N) 1367 continue; 1368 1369 if (N->use_empty()) { 1370 for (const SDValue &ChildN : N->op_values()) 1371 Nodes.insert(ChildN.getNode()); 1372 1373 removeFromWorklist(N); 1374 DAG.DeleteNode(N); 1375 } else { 1376 AddToWorklist(N); 1377 } 1378 } while (!Nodes.empty()); 1379 return true; 1380 } 1381 1382 //===----------------------------------------------------------------------===// 1383 // Main DAG Combiner implementation 1384 //===----------------------------------------------------------------------===// 1385 1386 void DAGCombiner::Run(CombineLevel AtLevel) { 1387 // set the instance variables, so that the various visit routines may use it. 1388 Level = AtLevel; 1389 LegalOperations = Level >= AfterLegalizeVectorOps; 1390 LegalTypes = Level >= AfterLegalizeTypes; 1391 1392 // Add all the dag nodes to the worklist. 1393 for (SDNode &Node : DAG.allnodes()) 1394 AddToWorklist(&Node); 1395 1396 // Create a dummy node (which is not added to allnodes), that adds a reference 1397 // to the root node, preventing it from being deleted, and tracking any 1398 // changes of the root. 1399 HandleSDNode Dummy(DAG.getRoot()); 1400 1401 // While the worklist isn't empty, find a node and try to combine it. 1402 while (!WorklistMap.empty()) { 1403 SDNode *N; 1404 // The Worklist holds the SDNodes in order, but it may contain null entries. 1405 do { 1406 N = Worklist.pop_back_val(); 1407 } while (!N); 1408 1409 bool GoodWorklistEntry = WorklistMap.erase(N); 1410 (void)GoodWorklistEntry; 1411 assert(GoodWorklistEntry && 1412 "Found a worklist entry without a corresponding map entry!"); 1413 1414 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1415 // N is deleted from the DAG, since they too may now be dead or may have a 1416 // reduced number of uses, allowing other xforms. 1417 if (recursivelyDeleteUnusedNodes(N)) 1418 continue; 1419 1420 WorklistRemover DeadNodes(*this); 1421 1422 // If this combine is running after legalizing the DAG, re-legalize any 1423 // nodes pulled off the worklist. 1424 if (Level == AfterLegalizeDAG) { 1425 SmallSetVector<SDNode *, 16> UpdatedNodes; 1426 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1427 1428 for (SDNode *LN : UpdatedNodes) { 1429 AddToWorklist(LN); 1430 AddUsersToWorklist(LN); 1431 } 1432 if (!NIsValid) 1433 continue; 1434 } 1435 1436 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1437 1438 // Add any operands of the new node which have not yet been combined to the 1439 // worklist as well. Because the worklist uniques things already, this 1440 // won't repeatedly process the same operand. 1441 CombinedNodes.insert(N); 1442 for (const SDValue &ChildN : N->op_values()) 1443 if (!CombinedNodes.count(ChildN.getNode())) 1444 AddToWorklist(ChildN.getNode()); 1445 1446 SDValue RV = combine(N); 1447 1448 if (!RV.getNode()) 1449 continue; 1450 1451 ++NodesCombined; 1452 1453 // If we get back the same node we passed in, rather than a new node or 1454 // zero, we know that the node must have defined multiple values and 1455 // CombineTo was used. Since CombineTo takes care of the worklist 1456 // mechanics for us, we have no work to do in this case. 1457 if (RV.getNode() == N) 1458 continue; 1459 1460 assert(N->getOpcode() != ISD::DELETED_NODE && 1461 RV.getOpcode() != ISD::DELETED_NODE && 1462 "Node was deleted but visit returned new node!"); 1463 1464 DEBUG(dbgs() << " ... into: "; 1465 RV.getNode()->dump(&DAG)); 1466 1467 if (N->getNumValues() == RV.getNode()->getNumValues()) 1468 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1469 else { 1470 assert(N->getValueType(0) == RV.getValueType() && 1471 N->getNumValues() == 1 && "Type mismatch"); 1472 DAG.ReplaceAllUsesWith(N, &RV); 1473 } 1474 1475 // Push the new node and any users onto the worklist 1476 AddToWorklist(RV.getNode()); 1477 AddUsersToWorklist(RV.getNode()); 1478 1479 // Finally, if the node is now dead, remove it from the graph. The node 1480 // may not be dead if the replacement process recursively simplified to 1481 // something else needing this node. This will also take care of adding any 1482 // operands which have lost a user to the worklist. 1483 recursivelyDeleteUnusedNodes(N); 1484 } 1485 1486 // If the root changed (e.g. it was a dead load, update the root). 1487 DAG.setRoot(Dummy.getValue()); 1488 DAG.RemoveDeadNodes(); 1489 } 1490 1491 SDValue DAGCombiner::visit(SDNode *N) { 1492 switch (N->getOpcode()) { 1493 default: break; 1494 case ISD::TokenFactor: return visitTokenFactor(N); 1495 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1496 case ISD::ADD: return visitADD(N); 1497 case ISD::SUB: return visitSUB(N); 1498 case ISD::ADDC: return visitADDC(N); 1499 case ISD::UADDO: return visitUADDO(N); 1500 case ISD::SUBC: return visitSUBC(N); 1501 case ISD::USUBO: return visitUSUBO(N); 1502 case ISD::ADDE: return visitADDE(N); 1503 case ISD::ADDCARRY: return visitADDCARRY(N); 1504 case ISD::SUBE: return visitSUBE(N); 1505 case ISD::SUBCARRY: return visitSUBCARRY(N); 1506 case ISD::MUL: return visitMUL(N); 1507 case ISD::SDIV: return visitSDIV(N); 1508 case ISD::UDIV: return visitUDIV(N); 1509 case ISD::SREM: 1510 case ISD::UREM: return visitREM(N); 1511 case ISD::MULHU: return visitMULHU(N); 1512 case ISD::MULHS: return visitMULHS(N); 1513 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1514 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1515 case ISD::SMULO: return visitSMULO(N); 1516 case ISD::UMULO: return visitUMULO(N); 1517 case ISD::SMIN: 1518 case ISD::SMAX: 1519 case ISD::UMIN: 1520 case ISD::UMAX: return visitIMINMAX(N); 1521 case ISD::AND: return visitAND(N); 1522 case ISD::OR: return visitOR(N); 1523 case ISD::XOR: return visitXOR(N); 1524 case ISD::SHL: return visitSHL(N); 1525 case ISD::SRA: return visitSRA(N); 1526 case ISD::SRL: return visitSRL(N); 1527 case ISD::ROTR: 1528 case ISD::ROTL: return visitRotate(N); 1529 case ISD::ABS: return visitABS(N); 1530 case ISD::BSWAP: return visitBSWAP(N); 1531 case ISD::BITREVERSE: return visitBITREVERSE(N); 1532 case ISD::CTLZ: return visitCTLZ(N); 1533 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1534 case ISD::CTTZ: return visitCTTZ(N); 1535 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1536 case ISD::CTPOP: return visitCTPOP(N); 1537 case ISD::SELECT: return visitSELECT(N); 1538 case ISD::VSELECT: return visitVSELECT(N); 1539 case ISD::SELECT_CC: return visitSELECT_CC(N); 1540 case ISD::SETCC: return visitSETCC(N); 1541 case ISD::SETCCE: return visitSETCCE(N); 1542 case ISD::SETCCCARRY: return visitSETCCCARRY(N); 1543 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1544 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1545 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1546 case ISD::AssertSext: 1547 case ISD::AssertZext: return visitAssertExt(N); 1548 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1549 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1550 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1551 case ISD::TRUNCATE: return visitTRUNCATE(N); 1552 case ISD::BITCAST: return visitBITCAST(N); 1553 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1554 case ISD::FADD: return visitFADD(N); 1555 case ISD::FSUB: return visitFSUB(N); 1556 case ISD::FMUL: return visitFMUL(N); 1557 case ISD::FMA: return visitFMA(N); 1558 case ISD::FDIV: return visitFDIV(N); 1559 case ISD::FREM: return visitFREM(N); 1560 case ISD::FSQRT: return visitFSQRT(N); 1561 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1562 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1563 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1564 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1565 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1566 case ISD::FP_ROUND: return visitFP_ROUND(N); 1567 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1568 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1569 case ISD::FNEG: return visitFNEG(N); 1570 case ISD::FABS: return visitFABS(N); 1571 case ISD::FFLOOR: return visitFFLOOR(N); 1572 case ISD::FMINNUM: return visitFMINNUM(N); 1573 case ISD::FMAXNUM: return visitFMAXNUM(N); 1574 case ISD::FCEIL: return visitFCEIL(N); 1575 case ISD::FTRUNC: return visitFTRUNC(N); 1576 case ISD::BRCOND: return visitBRCOND(N); 1577 case ISD::BR_CC: return visitBR_CC(N); 1578 case ISD::LOAD: return visitLOAD(N); 1579 case ISD::STORE: return visitSTORE(N); 1580 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1581 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1582 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1583 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1584 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1585 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1586 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1587 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1588 case ISD::MGATHER: return visitMGATHER(N); 1589 case ISD::MLOAD: return visitMLOAD(N); 1590 case ISD::MSCATTER: return visitMSCATTER(N); 1591 case ISD::MSTORE: return visitMSTORE(N); 1592 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1593 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1594 } 1595 return SDValue(); 1596 } 1597 1598 SDValue DAGCombiner::combine(SDNode *N) { 1599 SDValue RV = visit(N); 1600 1601 // If nothing happened, try a target-specific DAG combine. 1602 if (!RV.getNode()) { 1603 assert(N->getOpcode() != ISD::DELETED_NODE && 1604 "Node was deleted but visit returned NULL!"); 1605 1606 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1607 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1608 1609 // Expose the DAG combiner to the target combiner impls. 1610 TargetLowering::DAGCombinerInfo 1611 DagCombineInfo(DAG, Level, false, this); 1612 1613 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1614 } 1615 } 1616 1617 // If nothing happened still, try promoting the operation. 1618 if (!RV.getNode()) { 1619 switch (N->getOpcode()) { 1620 default: break; 1621 case ISD::ADD: 1622 case ISD::SUB: 1623 case ISD::MUL: 1624 case ISD::AND: 1625 case ISD::OR: 1626 case ISD::XOR: 1627 RV = PromoteIntBinOp(SDValue(N, 0)); 1628 break; 1629 case ISD::SHL: 1630 case ISD::SRA: 1631 case ISD::SRL: 1632 RV = PromoteIntShiftOp(SDValue(N, 0)); 1633 break; 1634 case ISD::SIGN_EXTEND: 1635 case ISD::ZERO_EXTEND: 1636 case ISD::ANY_EXTEND: 1637 RV = PromoteExtend(SDValue(N, 0)); 1638 break; 1639 case ISD::LOAD: 1640 if (PromoteLoad(SDValue(N, 0))) 1641 RV = SDValue(N, 0); 1642 break; 1643 } 1644 } 1645 1646 // If N is a commutative binary node, try eliminate it if the commuted 1647 // version is already present in the DAG. 1648 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) && 1649 N->getNumValues() == 1) { 1650 SDValue N0 = N->getOperand(0); 1651 SDValue N1 = N->getOperand(1); 1652 1653 // Constant operands are canonicalized to RHS. 1654 if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) { 1655 SDValue Ops[] = {N1, N0}; 1656 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1657 N->getFlags()); 1658 if (CSENode) 1659 return SDValue(CSENode, 0); 1660 } 1661 } 1662 1663 return RV; 1664 } 1665 1666 /// Given a node, return its input chain if it has one, otherwise return a null 1667 /// sd operand. 1668 static SDValue getInputChainForNode(SDNode *N) { 1669 if (unsigned NumOps = N->getNumOperands()) { 1670 if (N->getOperand(0).getValueType() == MVT::Other) 1671 return N->getOperand(0); 1672 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1673 return N->getOperand(NumOps-1); 1674 for (unsigned i = 1; i < NumOps-1; ++i) 1675 if (N->getOperand(i).getValueType() == MVT::Other) 1676 return N->getOperand(i); 1677 } 1678 return SDValue(); 1679 } 1680 1681 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1682 // If N has two operands, where one has an input chain equal to the other, 1683 // the 'other' chain is redundant. 1684 if (N->getNumOperands() == 2) { 1685 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1686 return N->getOperand(0); 1687 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1688 return N->getOperand(1); 1689 } 1690 1691 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1692 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1693 SmallPtrSet<SDNode*, 16> SeenOps; 1694 bool Changed = false; // If we should replace this token factor. 1695 1696 // Start out with this token factor. 1697 TFs.push_back(N); 1698 1699 // Iterate through token factors. The TFs grows when new token factors are 1700 // encountered. 1701 for (unsigned i = 0; i < TFs.size(); ++i) { 1702 SDNode *TF = TFs[i]; 1703 1704 // Check each of the operands. 1705 for (const SDValue &Op : TF->op_values()) { 1706 switch (Op.getOpcode()) { 1707 case ISD::EntryToken: 1708 // Entry tokens don't need to be added to the list. They are 1709 // redundant. 1710 Changed = true; 1711 break; 1712 1713 case ISD::TokenFactor: 1714 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) { 1715 // Queue up for processing. 1716 TFs.push_back(Op.getNode()); 1717 // Clean up in case the token factor is removed. 1718 AddToWorklist(Op.getNode()); 1719 Changed = true; 1720 break; 1721 } 1722 LLVM_FALLTHROUGH; 1723 1724 default: 1725 // Only add if it isn't already in the list. 1726 if (SeenOps.insert(Op.getNode()).second) 1727 Ops.push_back(Op); 1728 else 1729 Changed = true; 1730 break; 1731 } 1732 } 1733 } 1734 1735 // Remove Nodes that are chained to another node in the list. Do so 1736 // by walking up chains breath-first stopping when we've seen 1737 // another operand. In general we must climb to the EntryNode, but we can exit 1738 // early if we find all remaining work is associated with just one operand as 1739 // no further pruning is possible. 1740 1741 // List of nodes to search through and original Ops from which they originate. 1742 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist; 1743 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op. 1744 SmallPtrSet<SDNode *, 16> SeenChains; 1745 bool DidPruneOps = false; 1746 1747 unsigned NumLeftToConsider = 0; 1748 for (const SDValue &Op : Ops) { 1749 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++)); 1750 OpWorkCount.push_back(1); 1751 } 1752 1753 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) { 1754 // If this is an Op, we can remove the op from the list. Remark any 1755 // search associated with it as from the current OpNumber. 1756 if (SeenOps.count(Op) != 0) { 1757 Changed = true; 1758 DidPruneOps = true; 1759 unsigned OrigOpNumber = 0; 1760 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op) 1761 OrigOpNumber++; 1762 assert((OrigOpNumber != Ops.size()) && 1763 "expected to find TokenFactor Operand"); 1764 // Re-mark worklist from OrigOpNumber to OpNumber 1765 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) { 1766 if (Worklist[i].second == OrigOpNumber) { 1767 Worklist[i].second = OpNumber; 1768 } 1769 } 1770 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber]; 1771 OpWorkCount[OrigOpNumber] = 0; 1772 NumLeftToConsider--; 1773 } 1774 // Add if it's a new chain 1775 if (SeenChains.insert(Op).second) { 1776 OpWorkCount[OpNumber]++; 1777 Worklist.push_back(std::make_pair(Op, OpNumber)); 1778 } 1779 }; 1780 1781 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) { 1782 // We need at least be consider at least 2 Ops to prune. 1783 if (NumLeftToConsider <= 1) 1784 break; 1785 auto CurNode = Worklist[i].first; 1786 auto CurOpNumber = Worklist[i].second; 1787 assert((OpWorkCount[CurOpNumber] > 0) && 1788 "Node should not appear in worklist"); 1789 switch (CurNode->getOpcode()) { 1790 case ISD::EntryToken: 1791 // Hitting EntryToken is the only way for the search to terminate without 1792 // hitting 1793 // another operand's search. Prevent us from marking this operand 1794 // considered. 1795 NumLeftToConsider++; 1796 break; 1797 case ISD::TokenFactor: 1798 for (const SDValue &Op : CurNode->op_values()) 1799 AddToWorklist(i, Op.getNode(), CurOpNumber); 1800 break; 1801 case ISD::CopyFromReg: 1802 case ISD::CopyToReg: 1803 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber); 1804 break; 1805 default: 1806 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode)) 1807 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber); 1808 break; 1809 } 1810 OpWorkCount[CurOpNumber]--; 1811 if (OpWorkCount[CurOpNumber] == 0) 1812 NumLeftToConsider--; 1813 } 1814 1815 // If we've changed things around then replace token factor. 1816 if (Changed) { 1817 SDValue Result; 1818 if (Ops.empty()) { 1819 // The entry token is the only possible outcome. 1820 Result = DAG.getEntryNode(); 1821 } else { 1822 if (DidPruneOps) { 1823 SmallVector<SDValue, 8> PrunedOps; 1824 // 1825 for (const SDValue &Op : Ops) { 1826 if (SeenChains.count(Op.getNode()) == 0) 1827 PrunedOps.push_back(Op); 1828 } 1829 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps); 1830 } else { 1831 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1832 } 1833 } 1834 return Result; 1835 } 1836 return SDValue(); 1837 } 1838 1839 /// MERGE_VALUES can always be eliminated. 1840 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1841 WorklistRemover DeadNodes(*this); 1842 // Replacing results may cause a different MERGE_VALUES to suddenly 1843 // be CSE'd with N, and carry its uses with it. Iterate until no 1844 // uses remain, to ensure that the node can be safely deleted. 1845 // First add the users of this node to the work list so that they 1846 // can be tried again once they have new operands. 1847 AddUsersToWorklist(N); 1848 do { 1849 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1850 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1851 } while (!N->use_empty()); 1852 deleteAndRecombine(N); 1853 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1854 } 1855 1856 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1857 /// ConstantSDNode pointer else nullptr. 1858 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1859 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1860 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1861 } 1862 1863 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) { 1864 auto BinOpcode = BO->getOpcode(); 1865 assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB || 1866 BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV || 1867 BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || 1868 BinOpcode == ISD::UREM || BinOpcode == ISD::AND || 1869 BinOpcode == ISD::OR || BinOpcode == ISD::XOR || 1870 BinOpcode == ISD::SHL || BinOpcode == ISD::SRL || 1871 BinOpcode == ISD::SRA || BinOpcode == ISD::FADD || 1872 BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || 1873 BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) && 1874 "Unexpected binary operator"); 1875 1876 // Bail out if any constants are opaque because we can't constant fold those. 1877 SDValue C1 = BO->getOperand(1); 1878 if (!isConstantOrConstantVector(C1, true) && 1879 !isConstantFPBuildVectorOrConstantFP(C1)) 1880 return SDValue(); 1881 1882 // Don't do this unless the old select is going away. We want to eliminate the 1883 // binary operator, not replace a binop with a select. 1884 // TODO: Handle ISD::SELECT_CC. 1885 SDValue Sel = BO->getOperand(0); 1886 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) 1887 return SDValue(); 1888 1889 SDValue CT = Sel.getOperand(1); 1890 if (!isConstantOrConstantVector(CT, true) && 1891 !isConstantFPBuildVectorOrConstantFP(CT)) 1892 return SDValue(); 1893 1894 SDValue CF = Sel.getOperand(2); 1895 if (!isConstantOrConstantVector(CF, true) && 1896 !isConstantFPBuildVectorOrConstantFP(CF)) 1897 return SDValue(); 1898 1899 // We have a select-of-constants followed by a binary operator with a 1900 // constant. Eliminate the binop by pulling the constant math into the select. 1901 // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1 1902 EVT VT = Sel.getValueType(); 1903 SDLoc DL(Sel); 1904 SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1); 1905 if (!NewCT.isUndef() && 1906 !isConstantOrConstantVector(NewCT, true) && 1907 !isConstantFPBuildVectorOrConstantFP(NewCT)) 1908 return SDValue(); 1909 1910 SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1); 1911 if (!NewCF.isUndef() && 1912 !isConstantOrConstantVector(NewCF, true) && 1913 !isConstantFPBuildVectorOrConstantFP(NewCF)) 1914 return SDValue(); 1915 1916 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF); 1917 } 1918 1919 SDValue DAGCombiner::visitADD(SDNode *N) { 1920 SDValue N0 = N->getOperand(0); 1921 SDValue N1 = N->getOperand(1); 1922 EVT VT = N0.getValueType(); 1923 SDLoc DL(N); 1924 1925 // fold vector ops 1926 if (VT.isVector()) { 1927 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1928 return FoldedVOp; 1929 1930 // fold (add x, 0) -> x, vector edition 1931 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1932 return N0; 1933 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1934 return N1; 1935 } 1936 1937 // fold (add x, undef) -> undef 1938 if (N0.isUndef()) 1939 return N0; 1940 1941 if (N1.isUndef()) 1942 return N1; 1943 1944 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 1945 // canonicalize constant to RHS 1946 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 1947 return DAG.getNode(ISD::ADD, DL, VT, N1, N0); 1948 // fold (add c1, c2) -> c1+c2 1949 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(), 1950 N1.getNode()); 1951 } 1952 1953 // fold (add x, 0) -> x 1954 if (isNullConstant(N1)) 1955 return N0; 1956 1957 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) { 1958 // fold ((c1-A)+c2) -> (c1+c2)-A 1959 if (N0.getOpcode() == ISD::SUB && 1960 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) { 1961 // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic. 1962 return DAG.getNode(ISD::SUB, DL, VT, 1963 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)), 1964 N0.getOperand(1)); 1965 } 1966 1967 // add (sext i1 X), 1 -> zext (not i1 X) 1968 // We don't transform this pattern: 1969 // add (zext i1 X), -1 -> sext (not i1 X) 1970 // because most (?) targets generate better code for the zext form. 1971 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() && 1972 isOneConstantOrOneSplatConstant(N1)) { 1973 SDValue X = N0.getOperand(0); 1974 if ((!LegalOperations || 1975 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) && 1976 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) && 1977 X.getScalarValueSizeInBits() == 1) { 1978 SDValue Not = DAG.getNOT(DL, X, X.getValueType()); 1979 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not); 1980 } 1981 } 1982 1983 // Undo the add -> or combine to merge constant offsets from a frame index. 1984 if (N0.getOpcode() == ISD::OR && 1985 isa<FrameIndexSDNode>(N0.getOperand(0)) && 1986 isa<ConstantSDNode>(N0.getOperand(1)) && 1987 DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) { 1988 SDValue Add0 = DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(1)); 1989 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0); 1990 } 1991 } 1992 1993 if (SDValue NewSel = foldBinOpIntoSelect(N)) 1994 return NewSel; 1995 1996 // reassociate add 1997 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1)) 1998 return RADD; 1999 2000 // fold ((0-A) + B) -> B-A 2001 if (N0.getOpcode() == ISD::SUB && 2002 isNullConstantOrNullSplatConstant(N0.getOperand(0))) 2003 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); 2004 2005 // fold (A + (0-B)) -> A-B 2006 if (N1.getOpcode() == ISD::SUB && 2007 isNullConstantOrNullSplatConstant(N1.getOperand(0))) 2008 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1)); 2009 2010 // fold (A+(B-A)) -> B 2011 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 2012 return N1.getOperand(0); 2013 2014 // fold ((B-A)+A) -> B 2015 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 2016 return N0.getOperand(0); 2017 2018 // fold (A+(B-(A+C))) to (B-C) 2019 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 2020 N0 == N1.getOperand(1).getOperand(0)) 2021 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2022 N1.getOperand(1).getOperand(1)); 2023 2024 // fold (A+(B-(C+A))) to (B-C) 2025 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 2026 N0 == N1.getOperand(1).getOperand(1)) 2027 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2028 N1.getOperand(1).getOperand(0)); 2029 2030 // fold (A+((B-A)+or-C)) to (B+or-C) 2031 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 2032 N1.getOperand(0).getOpcode() == ISD::SUB && 2033 N0 == N1.getOperand(0).getOperand(1)) 2034 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0), 2035 N1.getOperand(1)); 2036 2037 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 2038 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 2039 SDValue N00 = N0.getOperand(0); 2040 SDValue N01 = N0.getOperand(1); 2041 SDValue N10 = N1.getOperand(0); 2042 SDValue N11 = N1.getOperand(1); 2043 2044 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10)) 2045 return DAG.getNode(ISD::SUB, DL, VT, 2046 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 2047 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 2048 } 2049 2050 if (SimplifyDemandedBits(SDValue(N, 0))) 2051 return SDValue(N, 0); 2052 2053 // fold (a+b) -> (a|b) iff a and b share no bits. 2054 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 2055 DAG.haveNoCommonBitsSet(N0, N1)) 2056 return DAG.getNode(ISD::OR, DL, VT, N0, N1); 2057 2058 if (SDValue Combined = visitADDLike(N0, N1, N)) 2059 return Combined; 2060 2061 if (SDValue Combined = visitADDLike(N1, N0, N)) 2062 return Combined; 2063 2064 return SDValue(); 2065 } 2066 2067 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) { 2068 bool Masked = false; 2069 2070 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization. 2071 while (true) { 2072 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) { 2073 V = V.getOperand(0); 2074 continue; 2075 } 2076 2077 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) { 2078 Masked = true; 2079 V = V.getOperand(0); 2080 continue; 2081 } 2082 2083 break; 2084 } 2085 2086 // If this is not a carry, return. 2087 if (V.getResNo() != 1) 2088 return SDValue(); 2089 2090 if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY && 2091 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO) 2092 return SDValue(); 2093 2094 // If the result is masked, then no matter what kind of bool it is we can 2095 // return. If it isn't, then we need to make sure the bool type is either 0 or 2096 // 1 and not other values. 2097 if (Masked || 2098 TLI.getBooleanContents(V.getValueType()) == 2099 TargetLoweringBase::ZeroOrOneBooleanContent) 2100 return V; 2101 2102 return SDValue(); 2103 } 2104 2105 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) { 2106 EVT VT = N0.getValueType(); 2107 SDLoc DL(LocReference); 2108 2109 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 2110 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 2111 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0))) 2112 return DAG.getNode(ISD::SUB, DL, VT, N0, 2113 DAG.getNode(ISD::SHL, DL, VT, 2114 N1.getOperand(0).getOperand(1), 2115 N1.getOperand(1))); 2116 2117 if (N1.getOpcode() == ISD::AND) { 2118 SDValue AndOp0 = N1.getOperand(0); 2119 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 2120 unsigned DestBits = VT.getScalarSizeInBits(); 2121 2122 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 2123 // and similar xforms where the inner op is either ~0 or 0. 2124 if (NumSignBits == DestBits && 2125 isOneConstantOrOneSplatConstant(N1->getOperand(1))) 2126 return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0); 2127 } 2128 2129 // add (sext i1), X -> sub X, (zext i1) 2130 if (N0.getOpcode() == ISD::SIGN_EXTEND && 2131 N0.getOperand(0).getValueType() == MVT::i1 && 2132 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 2133 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 2134 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 2135 } 2136 2137 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 2138 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2139 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2140 if (TN->getVT() == MVT::i1) { 2141 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2142 DAG.getConstant(1, DL, VT)); 2143 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 2144 } 2145 } 2146 2147 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2148 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) && 2149 N1.getResNo() == 0) 2150 return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(), 2151 N0, N1.getOperand(0), N1.getOperand(2)); 2152 2153 // (add X, Carry) -> (addcarry X, 0, Carry) 2154 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2155 if (SDValue Carry = getAsCarry(TLI, N1)) 2156 return DAG.getNode(ISD::ADDCARRY, DL, 2157 DAG.getVTList(VT, Carry.getValueType()), N0, 2158 DAG.getConstant(0, DL, VT), Carry); 2159 2160 return SDValue(); 2161 } 2162 2163 SDValue DAGCombiner::visitADDC(SDNode *N) { 2164 SDValue N0 = N->getOperand(0); 2165 SDValue N1 = N->getOperand(1); 2166 EVT VT = N0.getValueType(); 2167 SDLoc DL(N); 2168 2169 // If the flag result is dead, turn this into an ADD. 2170 if (!N->hasAnyUseOfValue(1)) 2171 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2172 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2173 2174 // canonicalize constant to RHS. 2175 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2176 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2177 if (N0C && !N1C) 2178 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0); 2179 2180 // fold (addc x, 0) -> x + no carry out 2181 if (isNullConstant(N1)) 2182 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 2183 DL, MVT::Glue)); 2184 2185 // If it cannot overflow, transform into an add. 2186 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2187 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2188 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2189 2190 return SDValue(); 2191 } 2192 2193 SDValue DAGCombiner::visitUADDO(SDNode *N) { 2194 SDValue N0 = N->getOperand(0); 2195 SDValue N1 = N->getOperand(1); 2196 EVT VT = N0.getValueType(); 2197 if (VT.isVector()) 2198 return SDValue(); 2199 2200 EVT CarryVT = N->getValueType(1); 2201 SDLoc DL(N); 2202 2203 // If the flag result is dead, turn this into an ADD. 2204 if (!N->hasAnyUseOfValue(1)) 2205 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2206 DAG.getUNDEF(CarryVT)); 2207 2208 // canonicalize constant to RHS. 2209 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2210 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2211 if (N0C && !N1C) 2212 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0); 2213 2214 // fold (uaddo x, 0) -> x + no carry out 2215 if (isNullConstant(N1)) 2216 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2217 2218 // If it cannot overflow, transform into an add. 2219 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2220 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2221 DAG.getConstant(0, DL, CarryVT)); 2222 2223 if (SDValue Combined = visitUADDOLike(N0, N1, N)) 2224 return Combined; 2225 2226 if (SDValue Combined = visitUADDOLike(N1, N0, N)) 2227 return Combined; 2228 2229 return SDValue(); 2230 } 2231 2232 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) { 2233 auto VT = N0.getValueType(); 2234 2235 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2236 // If Y + 1 cannot overflow. 2237 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) { 2238 SDValue Y = N1.getOperand(0); 2239 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType()); 2240 if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never) 2241 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y, 2242 N1.getOperand(2)); 2243 } 2244 2245 // (uaddo X, Carry) -> (addcarry X, 0, Carry) 2246 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2247 if (SDValue Carry = getAsCarry(TLI, N1)) 2248 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, 2249 DAG.getConstant(0, SDLoc(N), VT), Carry); 2250 2251 return SDValue(); 2252 } 2253 2254 SDValue DAGCombiner::visitADDE(SDNode *N) { 2255 SDValue N0 = N->getOperand(0); 2256 SDValue N1 = N->getOperand(1); 2257 SDValue CarryIn = N->getOperand(2); 2258 2259 // canonicalize constant to RHS 2260 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2261 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2262 if (N0C && !N1C) 2263 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 2264 N1, N0, CarryIn); 2265 2266 // fold (adde x, y, false) -> (addc x, y) 2267 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2268 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 2269 2270 return SDValue(); 2271 } 2272 2273 SDValue DAGCombiner::visitADDCARRY(SDNode *N) { 2274 SDValue N0 = N->getOperand(0); 2275 SDValue N1 = N->getOperand(1); 2276 SDValue CarryIn = N->getOperand(2); 2277 SDLoc DL(N); 2278 2279 // canonicalize constant to RHS 2280 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2281 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2282 if (N0C && !N1C) 2283 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn); 2284 2285 // fold (addcarry x, y, false) -> (uaddo x, y) 2286 if (isNullConstant(CarryIn)) 2287 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1); 2288 2289 // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry. 2290 if (isNullConstant(N0) && isNullConstant(N1)) { 2291 EVT VT = N0.getValueType(); 2292 EVT CarryVT = CarryIn.getValueType(); 2293 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT); 2294 AddToWorklist(CarryExt.getNode()); 2295 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt, 2296 DAG.getConstant(1, DL, VT)), 2297 DAG.getConstant(0, DL, CarryVT)); 2298 } 2299 2300 if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N)) 2301 return Combined; 2302 2303 if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N)) 2304 return Combined; 2305 2306 return SDValue(); 2307 } 2308 2309 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, 2310 SDNode *N) { 2311 // Iff the flag result is dead: 2312 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry) 2313 if ((N0.getOpcode() == ISD::ADD || 2314 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) && 2315 isNullConstant(N1) && !N->hasAnyUseOfValue(1)) 2316 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), 2317 N0.getOperand(0), N0.getOperand(1), CarryIn); 2318 2319 /** 2320 * When one of the addcarry argument is itself a carry, we may be facing 2321 * a diamond carry propagation. In which case we try to transform the DAG 2322 * to ensure linear carry propagation if that is possible. 2323 * 2324 * We are trying to get: 2325 * (addcarry X, 0, (addcarry A, B, Z):Carry) 2326 */ 2327 if (auto Y = getAsCarry(TLI, N1)) { 2328 /** 2329 * (uaddo A, B) 2330 * / \ 2331 * Carry Sum 2332 * | \ 2333 * | (addcarry *, 0, Z) 2334 * | / 2335 * \ Carry 2336 * | / 2337 * (addcarry X, *, *) 2338 */ 2339 if (Y.getOpcode() == ISD::UADDO && 2340 CarryIn.getResNo() == 1 && 2341 CarryIn.getOpcode() == ISD::ADDCARRY && 2342 isNullConstant(CarryIn.getOperand(1)) && 2343 CarryIn.getOperand(0) == Y.getValue(0)) { 2344 auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(), 2345 Y.getOperand(0), Y.getOperand(1), 2346 CarryIn.getOperand(2)); 2347 AddToWorklist(NewY.getNode()); 2348 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, 2349 DAG.getConstant(0, SDLoc(N), N0.getValueType()), 2350 NewY.getValue(1)); 2351 } 2352 } 2353 2354 return SDValue(); 2355 } 2356 2357 // Since it may not be valid to emit a fold to zero for vector initializers 2358 // check if we can before folding. 2359 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 2360 SelectionDAG &DAG, bool LegalOperations, 2361 bool LegalTypes) { 2362 if (!VT.isVector()) 2363 return DAG.getConstant(0, DL, VT); 2364 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 2365 return DAG.getConstant(0, DL, VT); 2366 return SDValue(); 2367 } 2368 2369 SDValue DAGCombiner::visitSUB(SDNode *N) { 2370 SDValue N0 = N->getOperand(0); 2371 SDValue N1 = N->getOperand(1); 2372 EVT VT = N0.getValueType(); 2373 SDLoc DL(N); 2374 2375 // fold vector ops 2376 if (VT.isVector()) { 2377 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2378 return FoldedVOp; 2379 2380 // fold (sub x, 0) -> x, vector edition 2381 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2382 return N0; 2383 } 2384 2385 // fold (sub x, x) -> 0 2386 // FIXME: Refactor this and xor and other similar operations together. 2387 if (N0 == N1) 2388 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes); 2389 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2390 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 2391 // fold (sub c1, c2) -> c1-c2 2392 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(), 2393 N1.getNode()); 2394 } 2395 2396 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2397 return NewSel; 2398 2399 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2400 2401 // fold (sub x, c) -> (add x, -c) 2402 if (N1C) { 2403 return DAG.getNode(ISD::ADD, DL, VT, N0, 2404 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 2405 } 2406 2407 if (isNullConstantOrNullSplatConstant(N0)) { 2408 unsigned BitWidth = VT.getScalarSizeInBits(); 2409 // Right-shifting everything out but the sign bit followed by negation is 2410 // the same as flipping arithmetic/logical shift type without the negation: 2411 // -(X >>u 31) -> (X >>s 31) 2412 // -(X >>s 31) -> (X >>u 31) 2413 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) { 2414 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1)); 2415 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) { 2416 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA; 2417 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT)) 2418 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1)); 2419 } 2420 } 2421 2422 // 0 - X --> 0 if the sub is NUW. 2423 if (N->getFlags().hasNoUnsignedWrap()) 2424 return N0; 2425 2426 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) { 2427 // N1 is either 0 or the minimum signed value. If the sub is NSW, then 2428 // N1 must be 0 because negating the minimum signed value is undefined. 2429 if (N->getFlags().hasNoSignedWrap()) 2430 return N0; 2431 2432 // 0 - X --> X if X is 0 or the minimum signed value. 2433 return N1; 2434 } 2435 } 2436 2437 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 2438 if (isAllOnesConstantOrAllOnesSplatConstant(N0)) 2439 return DAG.getNode(ISD::XOR, DL, VT, N1, N0); 2440 2441 // fold A-(A-B) -> B 2442 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 2443 return N1.getOperand(1); 2444 2445 // fold (A+B)-A -> B 2446 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 2447 return N0.getOperand(1); 2448 2449 // fold (A+B)-B -> A 2450 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 2451 return N0.getOperand(0); 2452 2453 // fold C2-(A+C1) -> (C2-C1)-A 2454 if (N1.getOpcode() == ISD::ADD) { 2455 SDValue N11 = N1.getOperand(1); 2456 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) && 2457 isConstantOrConstantVector(N11, /* NoOpaques */ true)) { 2458 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11); 2459 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0)); 2460 } 2461 } 2462 2463 // fold ((A+(B+or-C))-B) -> A+or-C 2464 if (N0.getOpcode() == ISD::ADD && 2465 (N0.getOperand(1).getOpcode() == ISD::SUB || 2466 N0.getOperand(1).getOpcode() == ISD::ADD) && 2467 N0.getOperand(1).getOperand(0) == N1) 2468 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0), 2469 N0.getOperand(1).getOperand(1)); 2470 2471 // fold ((A+(C+B))-B) -> A+C 2472 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD && 2473 N0.getOperand(1).getOperand(1) == N1) 2474 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), 2475 N0.getOperand(1).getOperand(0)); 2476 2477 // fold ((A-(B-C))-C) -> A-B 2478 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB && 2479 N0.getOperand(1).getOperand(1) == N1) 2480 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), 2481 N0.getOperand(1).getOperand(0)); 2482 2483 // If either operand of a sub is undef, the result is undef 2484 if (N0.isUndef()) 2485 return N0; 2486 if (N1.isUndef()) 2487 return N1; 2488 2489 // If the relocation model supports it, consider symbol offsets. 2490 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 2491 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 2492 // fold (sub Sym, c) -> Sym-c 2493 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 2494 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 2495 GA->getOffset() - 2496 (uint64_t)N1C->getSExtValue()); 2497 // fold (sub Sym+c1, Sym+c2) -> c1-c2 2498 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 2499 if (GA->getGlobal() == GB->getGlobal()) 2500 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 2501 DL, VT); 2502 } 2503 2504 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 2505 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2506 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2507 if (TN->getVT() == MVT::i1) { 2508 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2509 DAG.getConstant(1, DL, VT)); 2510 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 2511 } 2512 } 2513 2514 return SDValue(); 2515 } 2516 2517 SDValue DAGCombiner::visitSUBC(SDNode *N) { 2518 SDValue N0 = N->getOperand(0); 2519 SDValue N1 = N->getOperand(1); 2520 EVT VT = N0.getValueType(); 2521 SDLoc DL(N); 2522 2523 // If the flag result is dead, turn this into an SUB. 2524 if (!N->hasAnyUseOfValue(1)) 2525 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2526 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2527 2528 // fold (subc x, x) -> 0 + no borrow 2529 if (N0 == N1) 2530 return CombineTo(N, DAG.getConstant(0, DL, VT), 2531 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2532 2533 // fold (subc x, 0) -> x + no borrow 2534 if (isNullConstant(N1)) 2535 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2536 2537 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2538 if (isAllOnesConstant(N0)) 2539 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2540 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2541 2542 return SDValue(); 2543 } 2544 2545 SDValue DAGCombiner::visitUSUBO(SDNode *N) { 2546 SDValue N0 = N->getOperand(0); 2547 SDValue N1 = N->getOperand(1); 2548 EVT VT = N0.getValueType(); 2549 if (VT.isVector()) 2550 return SDValue(); 2551 2552 EVT CarryVT = N->getValueType(1); 2553 SDLoc DL(N); 2554 2555 // If the flag result is dead, turn this into an SUB. 2556 if (!N->hasAnyUseOfValue(1)) 2557 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2558 DAG.getUNDEF(CarryVT)); 2559 2560 // fold (usubo x, x) -> 0 + no borrow 2561 if (N0 == N1) 2562 return CombineTo(N, DAG.getConstant(0, DL, VT), 2563 DAG.getConstant(0, DL, CarryVT)); 2564 2565 // fold (usubo x, 0) -> x + no borrow 2566 if (isNullConstant(N1)) 2567 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2568 2569 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2570 if (isAllOnesConstant(N0)) 2571 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2572 DAG.getConstant(0, DL, CarryVT)); 2573 2574 return SDValue(); 2575 } 2576 2577 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2578 SDValue N0 = N->getOperand(0); 2579 SDValue N1 = N->getOperand(1); 2580 SDValue CarryIn = N->getOperand(2); 2581 2582 // fold (sube x, y, false) -> (subc x, y) 2583 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2584 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2585 2586 return SDValue(); 2587 } 2588 2589 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) { 2590 SDValue N0 = N->getOperand(0); 2591 SDValue N1 = N->getOperand(1); 2592 SDValue CarryIn = N->getOperand(2); 2593 2594 // fold (subcarry x, y, false) -> (usubo x, y) 2595 if (isNullConstant(CarryIn)) 2596 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1); 2597 2598 return SDValue(); 2599 } 2600 2601 SDValue DAGCombiner::visitMUL(SDNode *N) { 2602 SDValue N0 = N->getOperand(0); 2603 SDValue N1 = N->getOperand(1); 2604 EVT VT = N0.getValueType(); 2605 2606 // fold (mul x, undef) -> 0 2607 if (N0.isUndef() || N1.isUndef()) 2608 return DAG.getConstant(0, SDLoc(N), VT); 2609 2610 bool N0IsConst = false; 2611 bool N1IsConst = false; 2612 bool N1IsOpaqueConst = false; 2613 bool N0IsOpaqueConst = false; 2614 APInt ConstValue0, ConstValue1; 2615 // fold vector ops 2616 if (VT.isVector()) { 2617 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2618 return FoldedVOp; 2619 2620 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0); 2621 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 2622 assert((!N0IsConst || 2623 ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) && 2624 "Splat APInt should be element width"); 2625 assert((!N1IsConst || 2626 ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) && 2627 "Splat APInt should be element width"); 2628 } else { 2629 N0IsConst = isa<ConstantSDNode>(N0); 2630 if (N0IsConst) { 2631 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2632 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2633 } 2634 N1IsConst = isa<ConstantSDNode>(N1); 2635 if (N1IsConst) { 2636 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2637 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2638 } 2639 } 2640 2641 // fold (mul c1, c2) -> c1*c2 2642 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2643 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2644 N0.getNode(), N1.getNode()); 2645 2646 // canonicalize constant to RHS (vector doesn't have to splat) 2647 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2648 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2649 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2650 // fold (mul x, 0) -> 0 2651 if (N1IsConst && ConstValue1.isNullValue()) 2652 return N1; 2653 // fold (mul x, 1) -> x 2654 if (N1IsConst && ConstValue1.isOneValue()) 2655 return N0; 2656 2657 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2658 return NewSel; 2659 2660 // fold (mul x, -1) -> 0-x 2661 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2662 SDLoc DL(N); 2663 return DAG.getNode(ISD::SUB, DL, VT, 2664 DAG.getConstant(0, DL, VT), N0); 2665 } 2666 // fold (mul x, (1 << c)) -> x << c 2667 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 2668 DAG.isKnownToBeAPowerOfTwo(N1) && 2669 (!VT.isVector() || Level <= AfterLegalizeVectorOps)) { 2670 SDLoc DL(N); 2671 SDValue LogBase2 = BuildLogBase2(N1, DL); 2672 AddToWorklist(LogBase2.getNode()); 2673 2674 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 2675 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 2676 AddToWorklist(Trunc.getNode()); 2677 return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc); 2678 } 2679 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2680 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) { 2681 unsigned Log2Val = (-ConstValue1).logBase2(); 2682 SDLoc DL(N); 2683 // FIXME: If the input is something that is easily negated (e.g. a 2684 // single-use add), we should put the negate there. 2685 return DAG.getNode(ISD::SUB, DL, VT, 2686 DAG.getConstant(0, DL, VT), 2687 DAG.getNode(ISD::SHL, DL, VT, N0, 2688 DAG.getConstant(Log2Val, DL, 2689 getShiftAmountTy(N0.getValueType())))); 2690 } 2691 2692 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2693 if (N0.getOpcode() == ISD::SHL && 2694 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 2695 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 2696 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 2697 if (isConstantOrConstantVector(C3)) 2698 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 2699 } 2700 2701 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2702 // use. 2703 { 2704 SDValue Sh(nullptr, 0), Y(nullptr, 0); 2705 2706 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2707 if (N0.getOpcode() == ISD::SHL && 2708 isConstantOrConstantVector(N0.getOperand(1)) && 2709 N0.getNode()->hasOneUse()) { 2710 Sh = N0; Y = N1; 2711 } else if (N1.getOpcode() == ISD::SHL && 2712 isConstantOrConstantVector(N1.getOperand(1)) && 2713 N1.getNode()->hasOneUse()) { 2714 Sh = N1; Y = N0; 2715 } 2716 2717 if (Sh.getNode()) { 2718 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 2719 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 2720 } 2721 } 2722 2723 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2724 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2725 N0.getOpcode() == ISD::ADD && 2726 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2727 isMulAddWithConstProfitable(N, N0, N1)) 2728 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2729 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2730 N0.getOperand(0), N1), 2731 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2732 N0.getOperand(1), N1)); 2733 2734 // reassociate mul 2735 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2736 return RMUL; 2737 2738 return SDValue(); 2739 } 2740 2741 /// Return true if divmod libcall is available. 2742 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2743 const TargetLowering &TLI) { 2744 RTLIB::Libcall LC; 2745 EVT NodeType = Node->getValueType(0); 2746 if (!NodeType.isSimple()) 2747 return false; 2748 switch (NodeType.getSimpleVT().SimpleTy) { 2749 default: return false; // No libcall for vector types. 2750 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2751 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2752 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2753 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2754 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2755 } 2756 2757 return TLI.getLibcallName(LC) != nullptr; 2758 } 2759 2760 /// Issue divrem if both quotient and remainder are needed. 2761 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2762 if (Node->use_empty()) 2763 return SDValue(); // This is a dead node, leave it alone. 2764 2765 unsigned Opcode = Node->getOpcode(); 2766 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2767 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2768 2769 // DivMod lib calls can still work on non-legal types if using lib-calls. 2770 EVT VT = Node->getValueType(0); 2771 if (VT.isVector() || !VT.isInteger()) 2772 return SDValue(); 2773 2774 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 2775 return SDValue(); 2776 2777 // If DIVREM is going to get expanded into a libcall, 2778 // but there is no libcall available, then don't combine. 2779 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2780 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2781 return SDValue(); 2782 2783 // If div is legal, it's better to do the normal expansion 2784 unsigned OtherOpcode = 0; 2785 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2786 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2787 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2788 return SDValue(); 2789 } else { 2790 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2791 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2792 return SDValue(); 2793 } 2794 2795 SDValue Op0 = Node->getOperand(0); 2796 SDValue Op1 = Node->getOperand(1); 2797 SDValue combined; 2798 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2799 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 2800 SDNode *User = *UI; 2801 if (User == Node || User->use_empty()) 2802 continue; 2803 // Convert the other matching node(s), too; 2804 // otherwise, the DIVREM may get target-legalized into something 2805 // target-specific that we won't be able to recognize. 2806 unsigned UserOpc = User->getOpcode(); 2807 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2808 User->getOperand(0) == Op0 && 2809 User->getOperand(1) == Op1) { 2810 if (!combined) { 2811 if (UserOpc == OtherOpcode) { 2812 SDVTList VTs = DAG.getVTList(VT, VT); 2813 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2814 } else if (UserOpc == DivRemOpc) { 2815 combined = SDValue(User, 0); 2816 } else { 2817 assert(UserOpc == Opcode); 2818 continue; 2819 } 2820 } 2821 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2822 CombineTo(User, combined); 2823 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2824 CombineTo(User, combined.getValue(1)); 2825 } 2826 } 2827 return combined; 2828 } 2829 2830 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) { 2831 SDValue N0 = N->getOperand(0); 2832 SDValue N1 = N->getOperand(1); 2833 EVT VT = N->getValueType(0); 2834 SDLoc DL(N); 2835 2836 if (DAG.isUndef(N->getOpcode(), {N0, N1})) 2837 return DAG.getUNDEF(VT); 2838 2839 // undef / X -> 0 2840 // undef % X -> 0 2841 if (N0.isUndef()) 2842 return DAG.getConstant(0, DL, VT); 2843 2844 return SDValue(); 2845 } 2846 2847 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2848 SDValue N0 = N->getOperand(0); 2849 SDValue N1 = N->getOperand(1); 2850 EVT VT = N->getValueType(0); 2851 2852 // fold vector ops 2853 if (VT.isVector()) 2854 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2855 return FoldedVOp; 2856 2857 SDLoc DL(N); 2858 2859 // fold (sdiv c1, c2) -> c1/c2 2860 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2861 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2862 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2863 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2864 // fold (sdiv X, 1) -> X 2865 if (N1C && N1C->isOne()) 2866 return N0; 2867 // fold (sdiv X, -1) -> 0-X 2868 if (N1C && N1C->isAllOnesValue()) 2869 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0); 2870 2871 if (SDValue V = simplifyDivRem(N, DAG)) 2872 return V; 2873 2874 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2875 return NewSel; 2876 2877 // If we know the sign bits of both operands are zero, strength reduce to a 2878 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2879 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2880 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2881 2882 // fold (sdiv X, pow2) -> simple ops after legalize 2883 // FIXME: We check for the exact bit here because the generic lowering gives 2884 // better results in that case. The target-specific lowering should learn how 2885 // to handle exact sdivs efficiently. 2886 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2887 !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() || 2888 (-N1C->getAPIntValue()).isPowerOf2())) { 2889 // Target-specific implementation of sdiv x, pow2. 2890 if (SDValue Res = BuildSDIVPow2(N)) 2891 return Res; 2892 2893 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2894 2895 // Splat the sign bit into the register 2896 SDValue SGN = 2897 DAG.getNode(ISD::SRA, DL, VT, N0, 2898 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2899 getShiftAmountTy(N0.getValueType()))); 2900 AddToWorklist(SGN.getNode()); 2901 2902 // Add (N0 < 0) ? abs2 - 1 : 0; 2903 SDValue SRL = 2904 DAG.getNode(ISD::SRL, DL, VT, SGN, 2905 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2906 getShiftAmountTy(SGN.getValueType()))); 2907 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2908 AddToWorklist(SRL.getNode()); 2909 AddToWorklist(ADD.getNode()); // Divide by pow2 2910 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2911 DAG.getConstant(lg2, DL, 2912 getShiftAmountTy(ADD.getValueType()))); 2913 2914 // If we're dividing by a positive value, we're done. Otherwise, we must 2915 // negate the result. 2916 if (N1C->getAPIntValue().isNonNegative()) 2917 return SRA; 2918 2919 AddToWorklist(SRA.getNode()); 2920 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2921 } 2922 2923 // If integer divide is expensive and we satisfy the requirements, emit an 2924 // alternate sequence. Targets may check function attributes for size/speed 2925 // trade-offs. 2926 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 2927 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2928 if (SDValue Op = BuildSDIV(N)) 2929 return Op; 2930 2931 // sdiv, srem -> sdivrem 2932 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 2933 // true. Otherwise, we break the simplification logic in visitREM(). 2934 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2935 if (SDValue DivRem = useDivRem(N)) 2936 return DivRem; 2937 2938 return SDValue(); 2939 } 2940 2941 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2942 SDValue N0 = N->getOperand(0); 2943 SDValue N1 = N->getOperand(1); 2944 EVT VT = N->getValueType(0); 2945 2946 // fold vector ops 2947 if (VT.isVector()) 2948 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2949 return FoldedVOp; 2950 2951 SDLoc DL(N); 2952 2953 // fold (udiv c1, c2) -> c1/c2 2954 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2955 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2956 if (N0C && N1C) 2957 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2958 N0C, N1C)) 2959 return Folded; 2960 2961 if (SDValue V = simplifyDivRem(N, DAG)) 2962 return V; 2963 2964 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2965 return NewSel; 2966 2967 // fold (udiv x, (1 << c)) -> x >>u c 2968 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 2969 DAG.isKnownToBeAPowerOfTwo(N1)) { 2970 SDValue LogBase2 = BuildLogBase2(N1, DL); 2971 AddToWorklist(LogBase2.getNode()); 2972 2973 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 2974 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 2975 AddToWorklist(Trunc.getNode()); 2976 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 2977 } 2978 2979 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2980 if (N1.getOpcode() == ISD::SHL) { 2981 SDValue N10 = N1.getOperand(0); 2982 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) && 2983 DAG.isKnownToBeAPowerOfTwo(N10)) { 2984 SDValue LogBase2 = BuildLogBase2(N10, DL); 2985 AddToWorklist(LogBase2.getNode()); 2986 2987 EVT ADDVT = N1.getOperand(1).getValueType(); 2988 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT); 2989 AddToWorklist(Trunc.getNode()); 2990 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc); 2991 AddToWorklist(Add.getNode()); 2992 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2993 } 2994 } 2995 2996 // fold (udiv x, c) -> alternate 2997 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 2998 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2999 if (SDValue Op = BuildUDIV(N)) 3000 return Op; 3001 3002 // sdiv, srem -> sdivrem 3003 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 3004 // true. Otherwise, we break the simplification logic in visitREM(). 3005 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 3006 if (SDValue DivRem = useDivRem(N)) 3007 return DivRem; 3008 3009 return SDValue(); 3010 } 3011 3012 // handles ISD::SREM and ISD::UREM 3013 SDValue DAGCombiner::visitREM(SDNode *N) { 3014 unsigned Opcode = N->getOpcode(); 3015 SDValue N0 = N->getOperand(0); 3016 SDValue N1 = N->getOperand(1); 3017 EVT VT = N->getValueType(0); 3018 bool isSigned = (Opcode == ISD::SREM); 3019 SDLoc DL(N); 3020 3021 // fold (rem c1, c2) -> c1%c2 3022 ConstantSDNode *N0C = isConstOrConstSplat(N0); 3023 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3024 if (N0C && N1C) 3025 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 3026 return Folded; 3027 3028 if (SDValue V = simplifyDivRem(N, DAG)) 3029 return V; 3030 3031 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3032 return NewSel; 3033 3034 if (isSigned) { 3035 // If we know the sign bits of both operands are zero, strength reduce to a 3036 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 3037 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 3038 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 3039 } else { 3040 SDValue NegOne = DAG.getAllOnesConstant(DL, VT); 3041 if (DAG.isKnownToBeAPowerOfTwo(N1)) { 3042 // fold (urem x, pow2) -> (and x, pow2-1) 3043 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 3044 AddToWorklist(Add.getNode()); 3045 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 3046 } 3047 if (N1.getOpcode() == ISD::SHL && 3048 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) { 3049 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 3050 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 3051 AddToWorklist(Add.getNode()); 3052 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 3053 } 3054 } 3055 3056 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3057 3058 // If X/C can be simplified by the division-by-constant logic, lower 3059 // X%C to the equivalent of X-X/C*C. 3060 // To avoid mangling nodes, this simplification requires that the combine() 3061 // call for the speculative DIV must not cause a DIVREM conversion. We guard 3062 // against this by skipping the simplification if isIntDivCheap(). When 3063 // div is not cheap, combine will not return a DIVREM. Regardless, 3064 // checking cheapness here makes sense since the simplification results in 3065 // fatter code. 3066 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 3067 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 3068 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 3069 AddToWorklist(Div.getNode()); 3070 SDValue OptimizedDiv = combine(Div.getNode()); 3071 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode() && 3072 OptimizedDiv.getOpcode() != ISD::UDIVREM && 3073 OptimizedDiv.getOpcode() != ISD::SDIVREM) { 3074 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 3075 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 3076 AddToWorklist(Mul.getNode()); 3077 return Sub; 3078 } 3079 } 3080 3081 // sdiv, srem -> sdivrem 3082 if (SDValue DivRem = useDivRem(N)) 3083 return DivRem.getValue(1); 3084 3085 return SDValue(); 3086 } 3087 3088 SDValue DAGCombiner::visitMULHS(SDNode *N) { 3089 SDValue N0 = N->getOperand(0); 3090 SDValue N1 = N->getOperand(1); 3091 EVT VT = N->getValueType(0); 3092 SDLoc DL(N); 3093 3094 if (VT.isVector()) { 3095 // fold (mulhs x, 0) -> 0 3096 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3097 return N1; 3098 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3099 return N0; 3100 } 3101 3102 // fold (mulhs x, 0) -> 0 3103 if (isNullConstant(N1)) 3104 return N1; 3105 // fold (mulhs x, 1) -> (sra x, size(x)-1) 3106 if (isOneConstant(N1)) 3107 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 3108 DAG.getConstant(N0.getValueSizeInBits() - 1, DL, 3109 getShiftAmountTy(N0.getValueType()))); 3110 3111 // fold (mulhs x, undef) -> 0 3112 if (N0.isUndef() || N1.isUndef()) 3113 return DAG.getConstant(0, DL, VT); 3114 3115 // If the type twice as wide is legal, transform the mulhs to a wider multiply 3116 // plus a shift. 3117 if (VT.isSimple() && !VT.isVector()) { 3118 MVT Simple = VT.getSimpleVT(); 3119 unsigned SimpleSize = Simple.getSizeInBits(); 3120 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3121 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3122 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 3123 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 3124 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 3125 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 3126 DAG.getConstant(SimpleSize, DL, 3127 getShiftAmountTy(N1.getValueType()))); 3128 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 3129 } 3130 } 3131 3132 return SDValue(); 3133 } 3134 3135 SDValue DAGCombiner::visitMULHU(SDNode *N) { 3136 SDValue N0 = N->getOperand(0); 3137 SDValue N1 = N->getOperand(1); 3138 EVT VT = N->getValueType(0); 3139 SDLoc DL(N); 3140 3141 if (VT.isVector()) { 3142 // fold (mulhu x, 0) -> 0 3143 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3144 return N1; 3145 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3146 return N0; 3147 } 3148 3149 // fold (mulhu x, 0) -> 0 3150 if (isNullConstant(N1)) 3151 return N1; 3152 // fold (mulhu x, 1) -> 0 3153 if (isOneConstant(N1)) 3154 return DAG.getConstant(0, DL, N0.getValueType()); 3155 // fold (mulhu x, undef) -> 0 3156 if (N0.isUndef() || N1.isUndef()) 3157 return DAG.getConstant(0, DL, VT); 3158 3159 // If the type twice as wide is legal, transform the mulhu to a wider multiply 3160 // plus a shift. 3161 if (VT.isSimple() && !VT.isVector()) { 3162 MVT Simple = VT.getSimpleVT(); 3163 unsigned SimpleSize = Simple.getSizeInBits(); 3164 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3165 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3166 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 3167 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 3168 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 3169 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 3170 DAG.getConstant(SimpleSize, DL, 3171 getShiftAmountTy(N1.getValueType()))); 3172 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 3173 } 3174 } 3175 3176 return SDValue(); 3177 } 3178 3179 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 3180 /// give the opcodes for the two computations that are being performed. Return 3181 /// true if a simplification was made. 3182 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 3183 unsigned HiOp) { 3184 // If the high half is not needed, just compute the low half. 3185 bool HiExists = N->hasAnyUseOfValue(1); 3186 if (!HiExists && 3187 (!LegalOperations || 3188 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 3189 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 3190 return CombineTo(N, Res, Res); 3191 } 3192 3193 // If the low half is not needed, just compute the high half. 3194 bool LoExists = N->hasAnyUseOfValue(0); 3195 if (!LoExists && 3196 (!LegalOperations || 3197 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 3198 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 3199 return CombineTo(N, Res, Res); 3200 } 3201 3202 // If both halves are used, return as it is. 3203 if (LoExists && HiExists) 3204 return SDValue(); 3205 3206 // If the two computed results can be simplified separately, separate them. 3207 if (LoExists) { 3208 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 3209 AddToWorklist(Lo.getNode()); 3210 SDValue LoOpt = combine(Lo.getNode()); 3211 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 3212 (!LegalOperations || 3213 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 3214 return CombineTo(N, LoOpt, LoOpt); 3215 } 3216 3217 if (HiExists) { 3218 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 3219 AddToWorklist(Hi.getNode()); 3220 SDValue HiOpt = combine(Hi.getNode()); 3221 if (HiOpt.getNode() && HiOpt != Hi && 3222 (!LegalOperations || 3223 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 3224 return CombineTo(N, HiOpt, HiOpt); 3225 } 3226 3227 return SDValue(); 3228 } 3229 3230 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 3231 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 3232 return Res; 3233 3234 EVT VT = N->getValueType(0); 3235 SDLoc DL(N); 3236 3237 // If the type is twice as wide is legal, transform the mulhu to a wider 3238 // multiply plus a shift. 3239 if (VT.isSimple() && !VT.isVector()) { 3240 MVT Simple = VT.getSimpleVT(); 3241 unsigned SimpleSize = Simple.getSizeInBits(); 3242 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3243 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3244 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 3245 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 3246 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3247 // Compute the high part as N1. 3248 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3249 DAG.getConstant(SimpleSize, DL, 3250 getShiftAmountTy(Lo.getValueType()))); 3251 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3252 // Compute the low part as N0. 3253 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3254 return CombineTo(N, Lo, Hi); 3255 } 3256 } 3257 3258 return SDValue(); 3259 } 3260 3261 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 3262 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 3263 return Res; 3264 3265 EVT VT = N->getValueType(0); 3266 SDLoc DL(N); 3267 3268 // If the type is twice as wide is legal, transform the mulhu to a wider 3269 // multiply plus a shift. 3270 if (VT.isSimple() && !VT.isVector()) { 3271 MVT Simple = VT.getSimpleVT(); 3272 unsigned SimpleSize = Simple.getSizeInBits(); 3273 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3274 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3275 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 3276 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 3277 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3278 // Compute the high part as N1. 3279 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3280 DAG.getConstant(SimpleSize, DL, 3281 getShiftAmountTy(Lo.getValueType()))); 3282 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3283 // Compute the low part as N0. 3284 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3285 return CombineTo(N, Lo, Hi); 3286 } 3287 } 3288 3289 return SDValue(); 3290 } 3291 3292 SDValue DAGCombiner::visitSMULO(SDNode *N) { 3293 // (smulo x, 2) -> (saddo x, x) 3294 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 3295 if (C2->getAPIntValue() == 2) 3296 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 3297 N->getOperand(0), N->getOperand(0)); 3298 3299 return SDValue(); 3300 } 3301 3302 SDValue DAGCombiner::visitUMULO(SDNode *N) { 3303 // (umulo x, 2) -> (uaddo x, x) 3304 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 3305 if (C2->getAPIntValue() == 2) 3306 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 3307 N->getOperand(0), N->getOperand(0)); 3308 3309 return SDValue(); 3310 } 3311 3312 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 3313 SDValue N0 = N->getOperand(0); 3314 SDValue N1 = N->getOperand(1); 3315 EVT VT = N0.getValueType(); 3316 3317 // fold vector ops 3318 if (VT.isVector()) 3319 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3320 return FoldedVOp; 3321 3322 // fold operation with constant operands. 3323 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3324 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 3325 if (N0C && N1C) 3326 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 3327 3328 // canonicalize constant to RHS 3329 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3330 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3331 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 3332 3333 // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX. 3334 // Only do this if the current op isn't legal and the flipped is. 3335 unsigned Opcode = N->getOpcode(); 3336 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3337 if (!TLI.isOperationLegal(Opcode, VT) && 3338 (N0.isUndef() || DAG.SignBitIsZero(N0)) && 3339 (N1.isUndef() || DAG.SignBitIsZero(N1))) { 3340 unsigned AltOpcode; 3341 switch (Opcode) { 3342 case ISD::SMIN: AltOpcode = ISD::UMIN; break; 3343 case ISD::SMAX: AltOpcode = ISD::UMAX; break; 3344 case ISD::UMIN: AltOpcode = ISD::SMIN; break; 3345 case ISD::UMAX: AltOpcode = ISD::SMAX; break; 3346 default: llvm_unreachable("Unknown MINMAX opcode"); 3347 } 3348 if (TLI.isOperationLegal(AltOpcode, VT)) 3349 return DAG.getNode(AltOpcode, SDLoc(N), VT, N0, N1); 3350 } 3351 3352 return SDValue(); 3353 } 3354 3355 /// If this is a binary operator with two operands of the same opcode, try to 3356 /// simplify it. 3357 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 3358 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 3359 EVT VT = N0.getValueType(); 3360 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 3361 3362 // Bail early if none of these transforms apply. 3363 if (N0.getNumOperands() == 0) return SDValue(); 3364 3365 // For each of OP in AND/OR/XOR: 3366 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 3367 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 3368 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 3369 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 3370 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 3371 // 3372 // do not sink logical op inside of a vector extend, since it may combine 3373 // into a vsetcc. 3374 EVT Op0VT = N0.getOperand(0).getValueType(); 3375 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 3376 N0.getOpcode() == ISD::SIGN_EXTEND || 3377 N0.getOpcode() == ISD::BSWAP || 3378 // Avoid infinite looping with PromoteIntBinOp. 3379 (N0.getOpcode() == ISD::ANY_EXTEND && 3380 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 3381 (N0.getOpcode() == ISD::TRUNCATE && 3382 (!TLI.isZExtFree(VT, Op0VT) || 3383 !TLI.isTruncateFree(Op0VT, VT)) && 3384 TLI.isTypeLegal(Op0VT))) && 3385 !VT.isVector() && 3386 Op0VT == N1.getOperand(0).getValueType() && 3387 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 3388 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 3389 N0.getOperand(0).getValueType(), 3390 N0.getOperand(0), N1.getOperand(0)); 3391 AddToWorklist(ORNode.getNode()); 3392 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 3393 } 3394 3395 // For each of OP in SHL/SRL/SRA/AND... 3396 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 3397 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 3398 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 3399 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 3400 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 3401 N0.getOperand(1) == N1.getOperand(1)) { 3402 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 3403 N0.getOperand(0).getValueType(), 3404 N0.getOperand(0), N1.getOperand(0)); 3405 AddToWorklist(ORNode.getNode()); 3406 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 3407 ORNode, N0.getOperand(1)); 3408 } 3409 3410 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 3411 // Only perform this optimization up until type legalization, before 3412 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 3413 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 3414 // we don't want to undo this promotion. 3415 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 3416 // on scalars. 3417 if ((N0.getOpcode() == ISD::BITCAST || 3418 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 3419 Level <= AfterLegalizeTypes) { 3420 SDValue In0 = N0.getOperand(0); 3421 SDValue In1 = N1.getOperand(0); 3422 EVT In0Ty = In0.getValueType(); 3423 EVT In1Ty = In1.getValueType(); 3424 SDLoc DL(N); 3425 // If both incoming values are integers, and the original types are the 3426 // same. 3427 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 3428 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 3429 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 3430 AddToWorklist(Op.getNode()); 3431 return BC; 3432 } 3433 } 3434 3435 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 3436 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 3437 // If both shuffles use the same mask, and both shuffle within a single 3438 // vector, then it is worthwhile to move the swizzle after the operation. 3439 // The type-legalizer generates this pattern when loading illegal 3440 // vector types from memory. In many cases this allows additional shuffle 3441 // optimizations. 3442 // There are other cases where moving the shuffle after the xor/and/or 3443 // is profitable even if shuffles don't perform a swizzle. 3444 // If both shuffles use the same mask, and both shuffles have the same first 3445 // or second operand, then it might still be profitable to move the shuffle 3446 // after the xor/and/or operation. 3447 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 3448 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 3449 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 3450 3451 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 3452 "Inputs to shuffles are not the same type"); 3453 3454 // Check that both shuffles use the same mask. The masks are known to be of 3455 // the same length because the result vector type is the same. 3456 // Check also that shuffles have only one use to avoid introducing extra 3457 // instructions. 3458 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 3459 SVN0->getMask().equals(SVN1->getMask())) { 3460 SDValue ShOp = N0->getOperand(1); 3461 3462 // Don't try to fold this node if it requires introducing a 3463 // build vector of all zeros that might be illegal at this stage. 3464 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3465 if (!LegalTypes) 3466 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3467 else 3468 ShOp = SDValue(); 3469 } 3470 3471 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 3472 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 3473 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 3474 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 3475 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3476 N0->getOperand(0), N1->getOperand(0)); 3477 AddToWorklist(NewNode.getNode()); 3478 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 3479 SVN0->getMask()); 3480 } 3481 3482 // Don't try to fold this node if it requires introducing a 3483 // build vector of all zeros that might be illegal at this stage. 3484 ShOp = N0->getOperand(0); 3485 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3486 if (!LegalTypes) 3487 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3488 else 3489 ShOp = SDValue(); 3490 } 3491 3492 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 3493 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 3494 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 3495 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 3496 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3497 N0->getOperand(1), N1->getOperand(1)); 3498 AddToWorklist(NewNode.getNode()); 3499 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 3500 SVN0->getMask()); 3501 } 3502 } 3503 } 3504 3505 return SDValue(); 3506 } 3507 3508 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient. 3509 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 3510 const SDLoc &DL) { 3511 SDValue LL, LR, RL, RR, N0CC, N1CC; 3512 if (!isSetCCEquivalent(N0, LL, LR, N0CC) || 3513 !isSetCCEquivalent(N1, RL, RR, N1CC)) 3514 return SDValue(); 3515 3516 assert(N0.getValueType() == N1.getValueType() && 3517 "Unexpected operand types for bitwise logic op"); 3518 assert(LL.getValueType() == LR.getValueType() && 3519 RL.getValueType() == RR.getValueType() && 3520 "Unexpected operand types for setcc"); 3521 3522 // If we're here post-legalization or the logic op type is not i1, the logic 3523 // op type must match a setcc result type. Also, all folds require new 3524 // operations on the left and right operands, so those types must match. 3525 EVT VT = N0.getValueType(); 3526 EVT OpVT = LL.getValueType(); 3527 if (LegalOperations || VT.getScalarType() != MVT::i1) 3528 if (VT != getSetCCResultType(OpVT)) 3529 return SDValue(); 3530 if (OpVT != RL.getValueType()) 3531 return SDValue(); 3532 3533 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get(); 3534 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get(); 3535 bool IsInteger = OpVT.isInteger(); 3536 if (LR == RR && CC0 == CC1 && IsInteger) { 3537 bool IsZero = isNullConstantOrNullSplatConstant(LR); 3538 bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR); 3539 3540 // All bits clear? 3541 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero; 3542 // All sign bits clear? 3543 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1; 3544 // Any bits set? 3545 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero; 3546 // Any sign bits set? 3547 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero; 3548 3549 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0) 3550 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1) 3551 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0) 3552 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0) 3553 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) { 3554 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL); 3555 AddToWorklist(Or.getNode()); 3556 return DAG.getSetCC(DL, VT, Or, LR, CC1); 3557 } 3558 3559 // All bits set? 3560 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1; 3561 // All sign bits set? 3562 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero; 3563 // Any bits clear? 3564 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1; 3565 // Any sign bits clear? 3566 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1; 3567 3568 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1) 3569 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0) 3570 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1) 3571 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1) 3572 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) { 3573 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL); 3574 AddToWorklist(And.getNode()); 3575 return DAG.getSetCC(DL, VT, And, LR, CC1); 3576 } 3577 } 3578 3579 // TODO: What is the 'or' equivalent of this fold? 3580 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2) 3581 if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 && 3582 IsInteger && CC0 == ISD::SETNE && 3583 ((isNullConstant(LR) && isAllOnesConstant(RR)) || 3584 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 3585 SDValue One = DAG.getConstant(1, DL, OpVT); 3586 SDValue Two = DAG.getConstant(2, DL, OpVT); 3587 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One); 3588 AddToWorklist(Add.getNode()); 3589 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE); 3590 } 3591 3592 // Try more general transforms if the predicates match and the only user of 3593 // the compares is the 'and' or 'or'. 3594 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 && 3595 N0.hasOneUse() && N1.hasOneUse()) { 3596 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0 3597 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0 3598 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) { 3599 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR); 3600 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR); 3601 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR); 3602 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3603 return DAG.getSetCC(DL, VT, Or, Zero, CC1); 3604 } 3605 } 3606 3607 // Canonicalize equivalent operands to LL == RL. 3608 if (LL == RR && LR == RL) { 3609 CC1 = ISD::getSetCCSwappedOperands(CC1); 3610 std::swap(RL, RR); 3611 } 3612 3613 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 3614 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 3615 if (LL == RL && LR == RR) { 3616 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger) 3617 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger); 3618 if (NewCC != ISD::SETCC_INVALID && 3619 (!LegalOperations || 3620 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) && 3621 TLI.isOperationLegal(ISD::SETCC, OpVT)))) 3622 return DAG.getSetCC(DL, VT, LL, LR, NewCC); 3623 } 3624 3625 return SDValue(); 3626 } 3627 3628 /// This contains all DAGCombine rules which reduce two values combined by 3629 /// an And operation to a single value. This makes them reusable in the context 3630 /// of visitSELECT(). Rules involving constants are not included as 3631 /// visitSELECT() already handles those cases. 3632 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) { 3633 EVT VT = N1.getValueType(); 3634 SDLoc DL(N); 3635 3636 // fold (and x, undef) -> 0 3637 if (N0.isUndef() || N1.isUndef()) 3638 return DAG.getConstant(0, DL, VT); 3639 3640 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL)) 3641 return V; 3642 3643 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 3644 VT.getSizeInBits() <= 64) { 3645 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3646 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 3647 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 3648 // immediate for an add, but it is legal if its top c2 bits are set, 3649 // transform the ADD so the immediate doesn't need to be materialized 3650 // in a register. 3651 APInt ADDC = ADDI->getAPIntValue(); 3652 APInt SRLC = SRLI->getAPIntValue(); 3653 if (ADDC.getMinSignedBits() <= 64 && 3654 SRLC.ult(VT.getSizeInBits()) && 3655 !TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3656 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3657 SRLC.getZExtValue()); 3658 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 3659 ADDC |= Mask; 3660 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3661 SDLoc DL0(N0); 3662 SDValue NewAdd = 3663 DAG.getNode(ISD::ADD, DL0, VT, 3664 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 3665 CombineTo(N0.getNode(), NewAdd); 3666 // Return N so it doesn't get rechecked! 3667 return SDValue(N, 0); 3668 } 3669 } 3670 } 3671 } 3672 } 3673 } 3674 3675 // Reduce bit extract of low half of an integer to the narrower type. 3676 // (and (srl i64:x, K), KMask) -> 3677 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 3678 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 3679 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 3680 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3681 unsigned Size = VT.getSizeInBits(); 3682 const APInt &AndMask = CAnd->getAPIntValue(); 3683 unsigned ShiftBits = CShift->getZExtValue(); 3684 3685 // Bail out, this node will probably disappear anyway. 3686 if (ShiftBits == 0) 3687 return SDValue(); 3688 3689 unsigned MaskBits = AndMask.countTrailingOnes(); 3690 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 3691 3692 if (AndMask.isMask() && 3693 // Required bits must not span the two halves of the integer and 3694 // must fit in the half size type. 3695 (ShiftBits + MaskBits <= Size / 2) && 3696 TLI.isNarrowingProfitable(VT, HalfVT) && 3697 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 3698 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 3699 TLI.isTruncateFree(VT, HalfVT) && 3700 TLI.isZExtFree(HalfVT, VT)) { 3701 // The isNarrowingProfitable is to avoid regressions on PPC and 3702 // AArch64 which match a few 64-bit bit insert / bit extract patterns 3703 // on downstream users of this. Those patterns could probably be 3704 // extended to handle extensions mixed in. 3705 3706 SDValue SL(N0); 3707 assert(MaskBits <= Size); 3708 3709 // Extracting the highest bit of the low half. 3710 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 3711 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 3712 N0.getOperand(0)); 3713 3714 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 3715 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 3716 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 3717 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 3718 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 3719 } 3720 } 3721 } 3722 } 3723 3724 return SDValue(); 3725 } 3726 3727 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 3728 EVT LoadResultTy, EVT &ExtVT) { 3729 if (!AndC->getAPIntValue().isMask()) 3730 return false; 3731 3732 unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes(); 3733 3734 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3735 EVT LoadedVT = LoadN->getMemoryVT(); 3736 3737 if (ExtVT == LoadedVT && 3738 (!LegalOperations || 3739 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 3740 // ZEXTLOAD will match without needing to change the size of the value being 3741 // loaded. 3742 return true; 3743 } 3744 3745 // Do not change the width of a volatile load. 3746 if (LoadN->isVolatile()) 3747 return false; 3748 3749 // Do not generate loads of non-round integer types since these can 3750 // be expensive (and would be wrong if the type is not byte sized). 3751 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 3752 return false; 3753 3754 if (LegalOperations && 3755 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 3756 return false; 3757 3758 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 3759 return false; 3760 3761 return true; 3762 } 3763 3764 bool DAGCombiner::isLegalNarrowLoad(LoadSDNode *LoadN, ISD::LoadExtType ExtType, 3765 EVT &ExtVT, unsigned ShAmt) { 3766 // Don't transform one with multiple uses, this would require adding a new 3767 // load. 3768 if (!SDValue(LoadN, 0).hasOneUse()) 3769 return false; 3770 3771 if (LegalOperations && 3772 !TLI.isLoadExtLegal(ExtType, LoadN->getValueType(0), ExtVT)) 3773 return false; 3774 3775 // Do not generate loads of non-round integer types since these can 3776 // be expensive (and would be wrong if the type is not byte sized). 3777 if (!ExtVT.isRound()) 3778 return false; 3779 3780 // Don't change the width of a volatile load. 3781 if (LoadN->isVolatile()) 3782 return false; 3783 3784 // Verify that we are actually reducing a load width here. 3785 if (LoadN->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits()) 3786 return false; 3787 3788 // For the transform to be legal, the load must produce only two values 3789 // (the value loaded and the chain). Don't transform a pre-increment 3790 // load, for example, which produces an extra value. Otherwise the 3791 // transformation is not equivalent, and the downstream logic to replace 3792 // uses gets things wrong. 3793 if (LoadN->getNumValues() > 2) 3794 return false; 3795 3796 // If the load that we're shrinking is an extload and we're not just 3797 // discarding the extension we can't simply shrink the load. Bail. 3798 // TODO: It would be possible to merge the extensions in some cases. 3799 if (LoadN->getExtensionType() != ISD::NON_EXTLOAD && 3800 LoadN->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 3801 return false; 3802 3803 if (!TLI.shouldReduceLoadWidth(LoadN, ExtType, ExtVT)) 3804 return false; 3805 3806 // It's not possible to generate a constant of extended or untyped type. 3807 EVT PtrType = LoadN->getOperand(1).getValueType(); 3808 if (PtrType == MVT::Untyped || PtrType.isExtended()) 3809 return false; 3810 3811 return true; 3812 } 3813 3814 bool DAGCombiner::SearchForAndLoads(SDNode *N, 3815 SmallPtrSetImpl<LoadSDNode*> &Loads, 3816 SmallPtrSetImpl<SDNode*> &NodesWithConsts, 3817 ConstantSDNode *Mask, 3818 SDNode *&NodeToMask) { 3819 // Recursively search for the operands, looking for loads which can be 3820 // narrowed. 3821 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i) { 3822 SDValue Op = N->getOperand(i); 3823 3824 if (Op.getValueType().isVector()) 3825 return false; 3826 3827 // Some constants may need fixing up later if they are too large. 3828 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3829 if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) && 3830 (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue()) 3831 NodesWithConsts.insert(N); 3832 continue; 3833 } 3834 3835 if (!Op.hasOneUse()) 3836 return false; 3837 3838 switch(Op.getOpcode()) { 3839 case ISD::LOAD: { 3840 auto *Load = cast<LoadSDNode>(Op); 3841 EVT ExtVT; 3842 if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) && 3843 isLegalNarrowLoad(Load, ISD::ZEXTLOAD, ExtVT)) { 3844 3845 // ZEXTLOAD is already small enough. 3846 if (Load->getExtensionType() == ISD::ZEXTLOAD && 3847 ExtVT.bitsGE(Load->getMemoryVT())) 3848 continue; 3849 3850 // Use LE to convert equal sized loads to zext. 3851 if (ExtVT.bitsLE(Load->getMemoryVT())) 3852 Loads.insert(Load); 3853 3854 continue; 3855 } 3856 return false; 3857 } 3858 case ISD::ZERO_EXTEND: 3859 case ISD::AssertZext: { 3860 unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes(); 3861 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3862 EVT VT = Op.getOpcode() == ISD::AssertZext ? 3863 cast<VTSDNode>(Op.getOperand(1))->getVT() : 3864 Op.getOperand(0).getValueType(); 3865 3866 // We can accept extending nodes if the mask is wider or an equal 3867 // width to the original type. 3868 if (ExtVT.bitsGE(VT)) 3869 continue; 3870 break; 3871 } 3872 case ISD::OR: 3873 case ISD::XOR: 3874 case ISD::AND: 3875 if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask, 3876 NodeToMask)) 3877 return false; 3878 continue; 3879 } 3880 3881 // Allow one node which will masked along with any loads found. 3882 if (NodeToMask) 3883 return false; 3884 NodeToMask = Op.getNode(); 3885 } 3886 return true; 3887 } 3888 3889 bool DAGCombiner::BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG) { 3890 auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1)); 3891 if (!Mask) 3892 return false; 3893 3894 if (!Mask->getAPIntValue().isMask()) 3895 return false; 3896 3897 // No need to do anything if the and directly uses a load. 3898 if (isa<LoadSDNode>(N->getOperand(0))) 3899 return false; 3900 3901 SmallPtrSet<LoadSDNode*, 8> Loads; 3902 SmallPtrSet<SDNode*, 2> NodesWithConsts; 3903 SDNode *FixupNode = nullptr; 3904 if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) { 3905 if (Loads.size() == 0) 3906 return false; 3907 3908 DEBUG(dbgs() << "Backwards propagate AND: "; N->dump()); 3909 SDValue MaskOp = N->getOperand(1); 3910 3911 // If it exists, fixup the single node we allow in the tree that needs 3912 // masking. 3913 if (FixupNode) { 3914 DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump()); 3915 SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode), 3916 FixupNode->getValueType(0), 3917 SDValue(FixupNode, 0), MaskOp); 3918 DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And); 3919 DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), 3920 MaskOp); 3921 } 3922 3923 // Narrow any constants that need it. 3924 for (auto *LogicN : NodesWithConsts) { 3925 SDValue Op0 = LogicN->getOperand(0); 3926 SDValue Op1 = LogicN->getOperand(1); 3927 3928 if (isa<ConstantSDNode>(Op0)) 3929 std::swap(Op0, Op1); 3930 3931 SDValue And = DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(), 3932 Op1, MaskOp); 3933 3934 DAG.UpdateNodeOperands(LogicN, Op0, And); 3935 } 3936 3937 // Create narrow loads. 3938 for (auto *Load : Loads) { 3939 DEBUG(dbgs() << "Propagate AND back to: "; Load->dump()); 3940 SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0), 3941 SDValue(Load, 0), MaskOp); 3942 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And); 3943 DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp); 3944 SDValue NewLoad = ReduceLoadWidth(And.getNode()); 3945 assert(NewLoad && 3946 "Shouldn't be masking the load if it can't be narrowed"); 3947 CombineTo(Load, NewLoad, NewLoad.getValue(1)); 3948 } 3949 DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode()); 3950 return true; 3951 } 3952 return false; 3953 } 3954 3955 SDValue DAGCombiner::visitAND(SDNode *N) { 3956 SDValue N0 = N->getOperand(0); 3957 SDValue N1 = N->getOperand(1); 3958 EVT VT = N1.getValueType(); 3959 3960 // x & x --> x 3961 if (N0 == N1) 3962 return N0; 3963 3964 // fold vector ops 3965 if (VT.isVector()) { 3966 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3967 return FoldedVOp; 3968 3969 // fold (and x, 0) -> 0, vector edition 3970 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3971 // do not return N0, because undef node may exist in N0 3972 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()), 3973 SDLoc(N), N0.getValueType()); 3974 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3975 // do not return N1, because undef node may exist in N1 3976 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()), 3977 SDLoc(N), N1.getValueType()); 3978 3979 // fold (and x, -1) -> x, vector edition 3980 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3981 return N1; 3982 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3983 return N0; 3984 } 3985 3986 // fold (and c1, c2) -> c1&c2 3987 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3988 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3989 if (N0C && N1C && !N1C->isOpaque()) 3990 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3991 // canonicalize constant to RHS 3992 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3993 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3994 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3995 // fold (and x, -1) -> x 3996 if (isAllOnesConstant(N1)) 3997 return N0; 3998 // if (and x, c) is known to be zero, return 0 3999 unsigned BitWidth = VT.getScalarSizeInBits(); 4000 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4001 APInt::getAllOnesValue(BitWidth))) 4002 return DAG.getConstant(0, SDLoc(N), VT); 4003 4004 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4005 return NewSel; 4006 4007 // reassociate and 4008 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 4009 return RAND; 4010 4011 // Try to convert a constant mask AND into a shuffle clear mask. 4012 if (VT.isVector()) 4013 if (SDValue Shuffle = XformToShuffleWithZero(N)) 4014 return Shuffle; 4015 4016 // fold (and (or x, C), D) -> D if (C & D) == D 4017 auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) { 4018 return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue()); 4019 }; 4020 if (N0.getOpcode() == ISD::OR && 4021 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset)) 4022 return N1; 4023 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 4024 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4025 SDValue N0Op0 = N0.getOperand(0); 4026 APInt Mask = ~N1C->getAPIntValue(); 4027 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits()); 4028 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 4029 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 4030 N0.getValueType(), N0Op0); 4031 4032 // Replace uses of the AND with uses of the Zero extend node. 4033 CombineTo(N, Zext); 4034 4035 // We actually want to replace all uses of the any_extend with the 4036 // zero_extend, to avoid duplicating things. This will later cause this 4037 // AND to be folded. 4038 CombineTo(N0.getNode(), Zext); 4039 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4040 } 4041 } 4042 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 4043 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 4044 // already be zero by virtue of the width of the base type of the load. 4045 // 4046 // the 'X' node here can either be nothing or an extract_vector_elt to catch 4047 // more cases. 4048 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 4049 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 4050 N0.getOperand(0).getOpcode() == ISD::LOAD && 4051 N0.getOperand(0).getResNo() == 0) || 4052 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 4053 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 4054 N0 : N0.getOperand(0) ); 4055 4056 // Get the constant (if applicable) the zero'th operand is being ANDed with. 4057 // This can be a pure constant or a vector splat, in which case we treat the 4058 // vector as a scalar and use the splat value. 4059 APInt Constant = APInt::getNullValue(1); 4060 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 4061 Constant = C->getAPIntValue(); 4062 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 4063 APInt SplatValue, SplatUndef; 4064 unsigned SplatBitSize; 4065 bool HasAnyUndefs; 4066 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 4067 SplatBitSize, HasAnyUndefs); 4068 if (IsSplat) { 4069 // Undef bits can contribute to a possible optimisation if set, so 4070 // set them. 4071 SplatValue |= SplatUndef; 4072 4073 // The splat value may be something like "0x00FFFFFF", which means 0 for 4074 // the first vector value and FF for the rest, repeating. We need a mask 4075 // that will apply equally to all members of the vector, so AND all the 4076 // lanes of the constant together. 4077 EVT VT = Vector->getValueType(0); 4078 unsigned BitWidth = VT.getScalarSizeInBits(); 4079 4080 // If the splat value has been compressed to a bitlength lower 4081 // than the size of the vector lane, we need to re-expand it to 4082 // the lane size. 4083 if (BitWidth > SplatBitSize) 4084 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 4085 SplatBitSize < BitWidth; 4086 SplatBitSize = SplatBitSize * 2) 4087 SplatValue |= SplatValue.shl(SplatBitSize); 4088 4089 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 4090 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 4091 if (SplatBitSize % BitWidth == 0) { 4092 Constant = APInt::getAllOnesValue(BitWidth); 4093 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 4094 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 4095 } 4096 } 4097 } 4098 4099 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 4100 // actually legal and isn't going to get expanded, else this is a false 4101 // optimisation. 4102 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 4103 Load->getValueType(0), 4104 Load->getMemoryVT()); 4105 4106 // Resize the constant to the same size as the original memory access before 4107 // extension. If it is still the AllOnesValue then this AND is completely 4108 // unneeded. 4109 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits()); 4110 4111 bool B; 4112 switch (Load->getExtensionType()) { 4113 default: B = false; break; 4114 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 4115 case ISD::ZEXTLOAD: 4116 case ISD::NON_EXTLOAD: B = true; break; 4117 } 4118 4119 if (B && Constant.isAllOnesValue()) { 4120 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 4121 // preserve semantics once we get rid of the AND. 4122 SDValue NewLoad(Load, 0); 4123 4124 // Fold the AND away. NewLoad may get replaced immediately. 4125 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 4126 4127 if (Load->getExtensionType() == ISD::EXTLOAD) { 4128 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 4129 Load->getValueType(0), SDLoc(Load), 4130 Load->getChain(), Load->getBasePtr(), 4131 Load->getOffset(), Load->getMemoryVT(), 4132 Load->getMemOperand()); 4133 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 4134 if (Load->getNumValues() == 3) { 4135 // PRE/POST_INC loads have 3 values. 4136 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 4137 NewLoad.getValue(2) }; 4138 CombineTo(Load, To, 3, true); 4139 } else { 4140 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 4141 } 4142 } 4143 4144 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4145 } 4146 } 4147 4148 // fold (and (load x), 255) -> (zextload x, i8) 4149 // fold (and (extload x, i16), 255) -> (zextload x, i8) 4150 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 4151 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD || 4152 (N0.getOpcode() == ISD::ANY_EXTEND && 4153 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 4154 if (SDValue Res = ReduceLoadWidth(N)) { 4155 LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND 4156 ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0); 4157 4158 AddToWorklist(N); 4159 CombineTo(LN0, Res, Res.getValue(1)); 4160 return SDValue(N, 0); 4161 } 4162 } 4163 4164 if (Level >= AfterLegalizeTypes) { 4165 // Attempt to propagate the AND back up to the leaves which, if they're 4166 // loads, can be combined to narrow loads and the AND node can be removed. 4167 // Perform after legalization so that extend nodes will already be 4168 // combined into the loads. 4169 if (BackwardsPropagateMask(N, DAG)) { 4170 return SDValue(N, 0); 4171 } 4172 } 4173 4174 if (SDValue Combined = visitANDLike(N0, N1, N)) 4175 return Combined; 4176 4177 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 4178 if (N0.getOpcode() == N1.getOpcode()) 4179 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4180 return Tmp; 4181 4182 // Masking the negated extension of a boolean is just the zero-extended 4183 // boolean: 4184 // and (sub 0, zext(bool X)), 1 --> zext(bool X) 4185 // and (sub 0, sext(bool X)), 1 --> zext(bool X) 4186 // 4187 // Note: the SimplifyDemandedBits fold below can make an information-losing 4188 // transform, and then we have no way to find this better fold. 4189 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) { 4190 if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) { 4191 SDValue SubRHS = N0.getOperand(1); 4192 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND && 4193 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 4194 return SubRHS; 4195 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND && 4196 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 4197 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0)); 4198 } 4199 } 4200 4201 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 4202 // fold (and (sra)) -> (and (srl)) when possible. 4203 if (SimplifyDemandedBits(SDValue(N, 0))) 4204 return SDValue(N, 0); 4205 4206 // fold (zext_inreg (extload x)) -> (zextload x) 4207 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 4208 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4209 EVT MemVT = LN0->getMemoryVT(); 4210 // If we zero all the possible extended bits, then we can turn this into 4211 // a zextload if we are running before legalize or the operation is legal. 4212 unsigned BitWidth = N1.getScalarValueSizeInBits(); 4213 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 4214 BitWidth - MemVT.getScalarSizeInBits())) && 4215 ((!LegalOperations && !LN0->isVolatile()) || 4216 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 4217 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 4218 LN0->getChain(), LN0->getBasePtr(), 4219 MemVT, LN0->getMemOperand()); 4220 AddToWorklist(N); 4221 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 4222 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4223 } 4224 } 4225 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 4226 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 4227 N0.hasOneUse()) { 4228 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4229 EVT MemVT = LN0->getMemoryVT(); 4230 // If we zero all the possible extended bits, then we can turn this into 4231 // a zextload if we are running before legalize or the operation is legal. 4232 unsigned BitWidth = N1.getScalarValueSizeInBits(); 4233 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 4234 BitWidth - MemVT.getScalarSizeInBits())) && 4235 ((!LegalOperations && !LN0->isVolatile()) || 4236 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 4237 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 4238 LN0->getChain(), LN0->getBasePtr(), 4239 MemVT, LN0->getMemOperand()); 4240 AddToWorklist(N); 4241 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 4242 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4243 } 4244 } 4245 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 4246 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 4247 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 4248 N0.getOperand(1), false)) 4249 return BSwap; 4250 } 4251 4252 return SDValue(); 4253 } 4254 4255 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 4256 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 4257 bool DemandHighBits) { 4258 if (!LegalOperations) 4259 return SDValue(); 4260 4261 EVT VT = N->getValueType(0); 4262 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 4263 return SDValue(); 4264 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 4265 return SDValue(); 4266 4267 // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff) 4268 bool LookPassAnd0 = false; 4269 bool LookPassAnd1 = false; 4270 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 4271 std::swap(N0, N1); 4272 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 4273 std::swap(N0, N1); 4274 if (N0.getOpcode() == ISD::AND) { 4275 if (!N0.getNode()->hasOneUse()) 4276 return SDValue(); 4277 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4278 // Also handle 0xffff since the LHS is guaranteed to have zeros there. 4279 // This is needed for X86. 4280 if (!N01C || (N01C->getZExtValue() != 0xFF00 && 4281 N01C->getZExtValue() != 0xFFFF)) 4282 return SDValue(); 4283 N0 = N0.getOperand(0); 4284 LookPassAnd0 = true; 4285 } 4286 4287 if (N1.getOpcode() == ISD::AND) { 4288 if (!N1.getNode()->hasOneUse()) 4289 return SDValue(); 4290 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 4291 if (!N11C || N11C->getZExtValue() != 0xFF) 4292 return SDValue(); 4293 N1 = N1.getOperand(0); 4294 LookPassAnd1 = true; 4295 } 4296 4297 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 4298 std::swap(N0, N1); 4299 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 4300 return SDValue(); 4301 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse()) 4302 return SDValue(); 4303 4304 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4305 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 4306 if (!N01C || !N11C) 4307 return SDValue(); 4308 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 4309 return SDValue(); 4310 4311 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 4312 SDValue N00 = N0->getOperand(0); 4313 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 4314 if (!N00.getNode()->hasOneUse()) 4315 return SDValue(); 4316 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 4317 if (!N001C || N001C->getZExtValue() != 0xFF) 4318 return SDValue(); 4319 N00 = N00.getOperand(0); 4320 LookPassAnd0 = true; 4321 } 4322 4323 SDValue N10 = N1->getOperand(0); 4324 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 4325 if (!N10.getNode()->hasOneUse()) 4326 return SDValue(); 4327 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 4328 // Also allow 0xFFFF since the bits will be shifted out. This is needed 4329 // for X86. 4330 if (!N101C || (N101C->getZExtValue() != 0xFF00 && 4331 N101C->getZExtValue() != 0xFFFF)) 4332 return SDValue(); 4333 N10 = N10.getOperand(0); 4334 LookPassAnd1 = true; 4335 } 4336 4337 if (N00 != N10) 4338 return SDValue(); 4339 4340 // Make sure everything beyond the low halfword gets set to zero since the SRL 4341 // 16 will clear the top bits. 4342 unsigned OpSizeInBits = VT.getSizeInBits(); 4343 if (DemandHighBits && OpSizeInBits > 16) { 4344 // If the left-shift isn't masked out then the only way this is a bswap is 4345 // if all bits beyond the low 8 are 0. In that case the entire pattern 4346 // reduces to a left shift anyway: leave it for other parts of the combiner. 4347 if (!LookPassAnd0) 4348 return SDValue(); 4349 4350 // However, if the right shift isn't masked out then it might be because 4351 // it's not needed. See if we can spot that too. 4352 if (!LookPassAnd1 && 4353 !DAG.MaskedValueIsZero( 4354 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 4355 return SDValue(); 4356 } 4357 4358 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 4359 if (OpSizeInBits > 16) { 4360 SDLoc DL(N); 4361 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 4362 DAG.getConstant(OpSizeInBits - 16, DL, 4363 getShiftAmountTy(VT))); 4364 } 4365 return Res; 4366 } 4367 4368 /// Return true if the specified node is an element that makes up a 32-bit 4369 /// packed halfword byteswap. 4370 /// ((x & 0x000000ff) << 8) | 4371 /// ((x & 0x0000ff00) >> 8) | 4372 /// ((x & 0x00ff0000) << 8) | 4373 /// ((x & 0xff000000) >> 8) 4374 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 4375 if (!N.getNode()->hasOneUse()) 4376 return false; 4377 4378 unsigned Opc = N.getOpcode(); 4379 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 4380 return false; 4381 4382 SDValue N0 = N.getOperand(0); 4383 unsigned Opc0 = N0.getOpcode(); 4384 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL) 4385 return false; 4386 4387 ConstantSDNode *N1C = nullptr; 4388 // SHL or SRL: look upstream for AND mask operand 4389 if (Opc == ISD::AND) 4390 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4391 else if (Opc0 == ISD::AND) 4392 N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4393 if (!N1C) 4394 return false; 4395 4396 unsigned MaskByteOffset; 4397 switch (N1C->getZExtValue()) { 4398 default: 4399 return false; 4400 case 0xFF: MaskByteOffset = 0; break; 4401 case 0xFF00: MaskByteOffset = 1; break; 4402 case 0xFFFF: 4403 // In case demanded bits didn't clear the bits that will be shifted out. 4404 // This is needed for X86. 4405 if (Opc == ISD::SRL || (Opc == ISD::AND && Opc0 == ISD::SHL)) { 4406 MaskByteOffset = 1; 4407 break; 4408 } 4409 return false; 4410 case 0xFF0000: MaskByteOffset = 2; break; 4411 case 0xFF000000: MaskByteOffset = 3; break; 4412 } 4413 4414 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 4415 if (Opc == ISD::AND) { 4416 if (MaskByteOffset == 0 || MaskByteOffset == 2) { 4417 // (x >> 8) & 0xff 4418 // (x >> 8) & 0xff0000 4419 if (Opc0 != ISD::SRL) 4420 return false; 4421 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4422 if (!C || C->getZExtValue() != 8) 4423 return false; 4424 } else { 4425 // (x << 8) & 0xff00 4426 // (x << 8) & 0xff000000 4427 if (Opc0 != ISD::SHL) 4428 return false; 4429 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4430 if (!C || C->getZExtValue() != 8) 4431 return false; 4432 } 4433 } else if (Opc == ISD::SHL) { 4434 // (x & 0xff) << 8 4435 // (x & 0xff0000) << 8 4436 if (MaskByteOffset != 0 && MaskByteOffset != 2) 4437 return false; 4438 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4439 if (!C || C->getZExtValue() != 8) 4440 return false; 4441 } else { // Opc == ISD::SRL 4442 // (x & 0xff00) >> 8 4443 // (x & 0xff000000) >> 8 4444 if (MaskByteOffset != 1 && MaskByteOffset != 3) 4445 return false; 4446 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4447 if (!C || C->getZExtValue() != 8) 4448 return false; 4449 } 4450 4451 if (Parts[MaskByteOffset]) 4452 return false; 4453 4454 Parts[MaskByteOffset] = N0.getOperand(0).getNode(); 4455 return true; 4456 } 4457 4458 /// Match a 32-bit packed halfword bswap. That is 4459 /// ((x & 0x000000ff) << 8) | 4460 /// ((x & 0x0000ff00) >> 8) | 4461 /// ((x & 0x00ff0000) << 8) | 4462 /// ((x & 0xff000000) >> 8) 4463 /// => (rotl (bswap x), 16) 4464 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 4465 if (!LegalOperations) 4466 return SDValue(); 4467 4468 EVT VT = N->getValueType(0); 4469 if (VT != MVT::i32) 4470 return SDValue(); 4471 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 4472 return SDValue(); 4473 4474 // Look for either 4475 // (or (or (and), (and)), (or (and), (and))) 4476 // (or (or (or (and), (and)), (and)), (and)) 4477 if (N0.getOpcode() != ISD::OR) 4478 return SDValue(); 4479 SDValue N00 = N0.getOperand(0); 4480 SDValue N01 = N0.getOperand(1); 4481 SDNode *Parts[4] = {}; 4482 4483 if (N1.getOpcode() == ISD::OR && 4484 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 4485 // (or (or (and), (and)), (or (and), (and))) 4486 if (!isBSwapHWordElement(N00, Parts)) 4487 return SDValue(); 4488 4489 if (!isBSwapHWordElement(N01, Parts)) 4490 return SDValue(); 4491 SDValue N10 = N1.getOperand(0); 4492 if (!isBSwapHWordElement(N10, Parts)) 4493 return SDValue(); 4494 SDValue N11 = N1.getOperand(1); 4495 if (!isBSwapHWordElement(N11, Parts)) 4496 return SDValue(); 4497 } else { 4498 // (or (or (or (and), (and)), (and)), (and)) 4499 if (!isBSwapHWordElement(N1, Parts)) 4500 return SDValue(); 4501 if (!isBSwapHWordElement(N01, Parts)) 4502 return SDValue(); 4503 if (N00.getOpcode() != ISD::OR) 4504 return SDValue(); 4505 SDValue N000 = N00.getOperand(0); 4506 if (!isBSwapHWordElement(N000, Parts)) 4507 return SDValue(); 4508 SDValue N001 = N00.getOperand(1); 4509 if (!isBSwapHWordElement(N001, Parts)) 4510 return SDValue(); 4511 } 4512 4513 // Make sure the parts are all coming from the same node. 4514 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 4515 return SDValue(); 4516 4517 SDLoc DL(N); 4518 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 4519 SDValue(Parts[0], 0)); 4520 4521 // Result of the bswap should be rotated by 16. If it's not legal, then 4522 // do (x << 16) | (x >> 16). 4523 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 4524 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 4525 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 4526 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 4527 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 4528 return DAG.getNode(ISD::OR, DL, VT, 4529 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 4530 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 4531 } 4532 4533 /// This contains all DAGCombine rules which reduce two values combined by 4534 /// an Or operation to a single value \see visitANDLike(). 4535 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) { 4536 EVT VT = N1.getValueType(); 4537 SDLoc DL(N); 4538 4539 // fold (or x, undef) -> -1 4540 if (!LegalOperations && (N0.isUndef() || N1.isUndef())) 4541 return DAG.getAllOnesConstant(DL, VT); 4542 4543 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL)) 4544 return V; 4545 4546 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 4547 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 4548 // Don't increase # computations. 4549 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 4550 // We can only do this xform if we know that bits from X that are set in C2 4551 // but not in C1 are already zero. Likewise for Y. 4552 if (const ConstantSDNode *N0O1C = 4553 getAsNonOpaqueConstant(N0.getOperand(1))) { 4554 if (const ConstantSDNode *N1O1C = 4555 getAsNonOpaqueConstant(N1.getOperand(1))) { 4556 // We can only do this xform if we know that bits from X that are set in 4557 // C2 but not in C1 are already zero. Likewise for Y. 4558 const APInt &LHSMask = N0O1C->getAPIntValue(); 4559 const APInt &RHSMask = N1O1C->getAPIntValue(); 4560 4561 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 4562 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 4563 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 4564 N0.getOperand(0), N1.getOperand(0)); 4565 return DAG.getNode(ISD::AND, DL, VT, X, 4566 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 4567 } 4568 } 4569 } 4570 } 4571 4572 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 4573 if (N0.getOpcode() == ISD::AND && 4574 N1.getOpcode() == ISD::AND && 4575 N0.getOperand(0) == N1.getOperand(0) && 4576 // Don't increase # computations. 4577 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 4578 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 4579 N0.getOperand(1), N1.getOperand(1)); 4580 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X); 4581 } 4582 4583 return SDValue(); 4584 } 4585 4586 SDValue DAGCombiner::visitOR(SDNode *N) { 4587 SDValue N0 = N->getOperand(0); 4588 SDValue N1 = N->getOperand(1); 4589 EVT VT = N1.getValueType(); 4590 4591 // x | x --> x 4592 if (N0 == N1) 4593 return N0; 4594 4595 // fold vector ops 4596 if (VT.isVector()) { 4597 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4598 return FoldedVOp; 4599 4600 // fold (or x, 0) -> x, vector edition 4601 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4602 return N1; 4603 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4604 return N0; 4605 4606 // fold (or x, -1) -> -1, vector edition 4607 if (ISD::isBuildVectorAllOnes(N0.getNode())) 4608 // do not return N0, because undef node may exist in N0 4609 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType()); 4610 if (ISD::isBuildVectorAllOnes(N1.getNode())) 4611 // do not return N1, because undef node may exist in N1 4612 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType()); 4613 4614 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 4615 // Do this only if the resulting shuffle is legal. 4616 if (isa<ShuffleVectorSDNode>(N0) && 4617 isa<ShuffleVectorSDNode>(N1) && 4618 // Avoid folding a node with illegal type. 4619 TLI.isTypeLegal(VT)) { 4620 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 4621 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 4622 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 4623 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 4624 // Ensure both shuffles have a zero input. 4625 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) { 4626 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 4627 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 4628 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 4629 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 4630 bool CanFold = true; 4631 int NumElts = VT.getVectorNumElements(); 4632 SmallVector<int, 4> Mask(NumElts); 4633 4634 for (int i = 0; i != NumElts; ++i) { 4635 int M0 = SV0->getMaskElt(i); 4636 int M1 = SV1->getMaskElt(i); 4637 4638 // Determine if either index is pointing to a zero vector. 4639 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 4640 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 4641 4642 // If one element is zero and the otherside is undef, keep undef. 4643 // This also handles the case that both are undef. 4644 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 4645 Mask[i] = -1; 4646 continue; 4647 } 4648 4649 // Make sure only one of the elements is zero. 4650 if (M0Zero == M1Zero) { 4651 CanFold = false; 4652 break; 4653 } 4654 4655 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 4656 4657 // We have a zero and non-zero element. If the non-zero came from 4658 // SV0 make the index a LHS index. If it came from SV1, make it 4659 // a RHS index. We need to mod by NumElts because we don't care 4660 // which operand it came from in the original shuffles. 4661 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 4662 } 4663 4664 if (CanFold) { 4665 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 4666 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 4667 4668 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 4669 if (!LegalMask) { 4670 std::swap(NewLHS, NewRHS); 4671 ShuffleVectorSDNode::commuteMask(Mask); 4672 LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 4673 } 4674 4675 if (LegalMask) 4676 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask); 4677 } 4678 } 4679 } 4680 } 4681 4682 // fold (or c1, c2) -> c1|c2 4683 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4684 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4685 if (N0C && N1C && !N1C->isOpaque()) 4686 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 4687 // canonicalize constant to RHS 4688 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4689 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4690 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 4691 // fold (or x, 0) -> x 4692 if (isNullConstant(N1)) 4693 return N0; 4694 // fold (or x, -1) -> -1 4695 if (isAllOnesConstant(N1)) 4696 return N1; 4697 4698 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4699 return NewSel; 4700 4701 // fold (or x, c) -> c iff (x & ~c) == 0 4702 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 4703 return N1; 4704 4705 if (SDValue Combined = visitORLike(N0, N1, N)) 4706 return Combined; 4707 4708 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 4709 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 4710 return BSwap; 4711 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 4712 return BSwap; 4713 4714 // reassociate or 4715 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 4716 return ROR; 4717 4718 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 4719 // iff (c1 & c2) != 0. 4720 auto MatchIntersect = [](ConstantSDNode *LHS, ConstantSDNode *RHS) { 4721 return LHS->getAPIntValue().intersects(RHS->getAPIntValue()); 4722 }; 4723 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4724 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect)) { 4725 if (SDValue COR = DAG.FoldConstantArithmetic( 4726 ISD::OR, SDLoc(N1), VT, N1.getNode(), N0.getOperand(1).getNode())) { 4727 SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1); 4728 AddToWorklist(IOR.getNode()); 4729 return DAG.getNode(ISD::AND, SDLoc(N), VT, COR, IOR); 4730 } 4731 } 4732 4733 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 4734 if (N0.getOpcode() == N1.getOpcode()) 4735 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4736 return Tmp; 4737 4738 // See if this is some rotate idiom. 4739 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 4740 return SDValue(Rot, 0); 4741 4742 if (SDValue Load = MatchLoadCombine(N)) 4743 return Load; 4744 4745 // Simplify the operands using demanded-bits information. 4746 if (SimplifyDemandedBits(SDValue(N, 0))) 4747 return SDValue(N, 0); 4748 4749 return SDValue(); 4750 } 4751 4752 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 4753 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 4754 if (Op.getOpcode() == ISD::AND) { 4755 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 4756 Mask = Op.getOperand(1); 4757 Op = Op.getOperand(0); 4758 } else { 4759 return false; 4760 } 4761 } 4762 4763 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 4764 Shift = Op; 4765 return true; 4766 } 4767 4768 return false; 4769 } 4770 4771 // Return true if we can prove that, whenever Neg and Pos are both in the 4772 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 4773 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 4774 // 4775 // (or (shift1 X, Neg), (shift2 X, Pos)) 4776 // 4777 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 4778 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 4779 // to consider shift amounts with defined behavior. 4780 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 4781 // If EltSize is a power of 2 then: 4782 // 4783 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 4784 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 4785 // 4786 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 4787 // for the stronger condition: 4788 // 4789 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 4790 // 4791 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 4792 // we can just replace Neg with Neg' for the rest of the function. 4793 // 4794 // In other cases we check for the even stronger condition: 4795 // 4796 // Neg == EltSize - Pos [B] 4797 // 4798 // for all Neg and Pos. Note that the (or ...) then invokes undefined 4799 // behavior if Pos == 0 (and consequently Neg == EltSize). 4800 // 4801 // We could actually use [A] whenever EltSize is a power of 2, but the 4802 // only extra cases that it would match are those uninteresting ones 4803 // where Neg and Pos are never in range at the same time. E.g. for 4804 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 4805 // as well as (sub 32, Pos), but: 4806 // 4807 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 4808 // 4809 // always invokes undefined behavior for 32-bit X. 4810 // 4811 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 4812 unsigned MaskLoBits = 0; 4813 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 4814 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 4815 if (NegC->getAPIntValue() == EltSize - 1) { 4816 Neg = Neg.getOperand(0); 4817 MaskLoBits = Log2_64(EltSize); 4818 } 4819 } 4820 } 4821 4822 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 4823 if (Neg.getOpcode() != ISD::SUB) 4824 return false; 4825 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 4826 if (!NegC) 4827 return false; 4828 SDValue NegOp1 = Neg.getOperand(1); 4829 4830 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 4831 // Pos'. The truncation is redundant for the purpose of the equality. 4832 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 4833 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4834 if (PosC->getAPIntValue() == EltSize - 1) 4835 Pos = Pos.getOperand(0); 4836 4837 // The condition we need is now: 4838 // 4839 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 4840 // 4841 // If NegOp1 == Pos then we need: 4842 // 4843 // EltSize & Mask == NegC & Mask 4844 // 4845 // (because "x & Mask" is a truncation and distributes through subtraction). 4846 APInt Width; 4847 if (Pos == NegOp1) 4848 Width = NegC->getAPIntValue(); 4849 4850 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 4851 // Then the condition we want to prove becomes: 4852 // 4853 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 4854 // 4855 // which, again because "x & Mask" is a truncation, becomes: 4856 // 4857 // NegC & Mask == (EltSize - PosC) & Mask 4858 // EltSize & Mask == (NegC + PosC) & Mask 4859 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 4860 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4861 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 4862 else 4863 return false; 4864 } else 4865 return false; 4866 4867 // Now we just need to check that EltSize & Mask == Width & Mask. 4868 if (MaskLoBits) 4869 // EltSize & Mask is 0 since Mask is EltSize - 1. 4870 return Width.getLoBits(MaskLoBits) == 0; 4871 return Width == EltSize; 4872 } 4873 4874 // A subroutine of MatchRotate used once we have found an OR of two opposite 4875 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 4876 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 4877 // former being preferred if supported. InnerPos and InnerNeg are Pos and 4878 // Neg with outer conversions stripped away. 4879 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 4880 SDValue Neg, SDValue InnerPos, 4881 SDValue InnerNeg, unsigned PosOpcode, 4882 unsigned NegOpcode, const SDLoc &DL) { 4883 // fold (or (shl x, (*ext y)), 4884 // (srl x, (*ext (sub 32, y)))) -> 4885 // (rotl x, y) or (rotr x, (sub 32, y)) 4886 // 4887 // fold (or (shl x, (*ext (sub 32, y))), 4888 // (srl x, (*ext y))) -> 4889 // (rotr x, y) or (rotl x, (sub 32, y)) 4890 EVT VT = Shifted.getValueType(); 4891 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 4892 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 4893 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 4894 HasPos ? Pos : Neg).getNode(); 4895 } 4896 4897 return nullptr; 4898 } 4899 4900 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 4901 // idioms for rotate, and if the target supports rotation instructions, generate 4902 // a rot[lr]. 4903 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 4904 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 4905 EVT VT = LHS.getValueType(); 4906 if (!TLI.isTypeLegal(VT)) return nullptr; 4907 4908 // The target must have at least one rotate flavor. 4909 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 4910 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 4911 if (!HasROTL && !HasROTR) return nullptr; 4912 4913 // Check for truncated rotate. 4914 if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE && 4915 LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) { 4916 assert(LHS.getValueType() == RHS.getValueType()); 4917 if (SDNode *Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) { 4918 return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(), 4919 SDValue(Rot, 0)).getNode(); 4920 } 4921 } 4922 4923 // Match "(X shl/srl V1) & V2" where V2 may not be present. 4924 SDValue LHSShift; // The shift. 4925 SDValue LHSMask; // AND value if any. 4926 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 4927 return nullptr; // Not part of a rotate. 4928 4929 SDValue RHSShift; // The shift. 4930 SDValue RHSMask; // AND value if any. 4931 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 4932 return nullptr; // Not part of a rotate. 4933 4934 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 4935 return nullptr; // Not shifting the same value. 4936 4937 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 4938 return nullptr; // Shifts must disagree. 4939 4940 // Canonicalize shl to left side in a shl/srl pair. 4941 if (RHSShift.getOpcode() == ISD::SHL) { 4942 std::swap(LHS, RHS); 4943 std::swap(LHSShift, RHSShift); 4944 std::swap(LHSMask, RHSMask); 4945 } 4946 4947 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4948 SDValue LHSShiftArg = LHSShift.getOperand(0); 4949 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4950 SDValue RHSShiftArg = RHSShift.getOperand(0); 4951 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4952 4953 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4954 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4955 auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS, 4956 ConstantSDNode *RHS) { 4957 return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits; 4958 }; 4959 if (ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) { 4960 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4961 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4962 4963 // If there is an AND of either shifted operand, apply it to the result. 4964 if (LHSMask.getNode() || RHSMask.getNode()) { 4965 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT); 4966 SDValue Mask = AllOnes; 4967 4968 if (LHSMask.getNode()) { 4969 SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt); 4970 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4971 DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits)); 4972 } 4973 if (RHSMask.getNode()) { 4974 SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt); 4975 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4976 DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits)); 4977 } 4978 4979 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4980 } 4981 4982 return Rot.getNode(); 4983 } 4984 4985 // If there is a mask here, and we have a variable shift, we can't be sure 4986 // that we're masking out the right stuff. 4987 if (LHSMask.getNode() || RHSMask.getNode()) 4988 return nullptr; 4989 4990 // If the shift amount is sign/zext/any-extended just peel it off. 4991 SDValue LExtOp0 = LHSShiftAmt; 4992 SDValue RExtOp0 = RHSShiftAmt; 4993 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4994 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4995 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4996 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4997 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4998 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4999 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 5000 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 5001 LExtOp0 = LHSShiftAmt.getOperand(0); 5002 RExtOp0 = RHSShiftAmt.getOperand(0); 5003 } 5004 5005 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 5006 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 5007 if (TryL) 5008 return TryL; 5009 5010 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 5011 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 5012 if (TryR) 5013 return TryR; 5014 5015 return nullptr; 5016 } 5017 5018 namespace { 5019 5020 /// Represents known origin of an individual byte in load combine pattern. The 5021 /// value of the byte is either constant zero or comes from memory. 5022 struct ByteProvider { 5023 // For constant zero providers Load is set to nullptr. For memory providers 5024 // Load represents the node which loads the byte from memory. 5025 // ByteOffset is the offset of the byte in the value produced by the load. 5026 LoadSDNode *Load = nullptr; 5027 unsigned ByteOffset = 0; 5028 5029 ByteProvider() = default; 5030 5031 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) { 5032 return ByteProvider(Load, ByteOffset); 5033 } 5034 5035 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); } 5036 5037 bool isConstantZero() const { return !Load; } 5038 bool isMemory() const { return Load; } 5039 5040 bool operator==(const ByteProvider &Other) const { 5041 return Other.Load == Load && Other.ByteOffset == ByteOffset; 5042 } 5043 5044 private: 5045 ByteProvider(LoadSDNode *Load, unsigned ByteOffset) 5046 : Load(Load), ByteOffset(ByteOffset) {} 5047 }; 5048 5049 } // end anonymous namespace 5050 5051 /// Recursively traverses the expression calculating the origin of the requested 5052 /// byte of the given value. Returns None if the provider can't be calculated. 5053 /// 5054 /// For all the values except the root of the expression verifies that the value 5055 /// has exactly one use and if it's not true return None. This way if the origin 5056 /// of the byte is returned it's guaranteed that the values which contribute to 5057 /// the byte are not used outside of this expression. 5058 /// 5059 /// Because the parts of the expression are not allowed to have more than one 5060 /// use this function iterates over trees, not DAGs. So it never visits the same 5061 /// node more than once. 5062 static const Optional<ByteProvider> 5063 calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth, 5064 bool Root = false) { 5065 // Typical i64 by i8 pattern requires recursion up to 8 calls depth 5066 if (Depth == 10) 5067 return None; 5068 5069 if (!Root && !Op.hasOneUse()) 5070 return None; 5071 5072 assert(Op.getValueType().isScalarInteger() && "can't handle other types"); 5073 unsigned BitWidth = Op.getValueSizeInBits(); 5074 if (BitWidth % 8 != 0) 5075 return None; 5076 unsigned ByteWidth = BitWidth / 8; 5077 assert(Index < ByteWidth && "invalid index requested"); 5078 (void) ByteWidth; 5079 5080 switch (Op.getOpcode()) { 5081 case ISD::OR: { 5082 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1); 5083 if (!LHS) 5084 return None; 5085 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1); 5086 if (!RHS) 5087 return None; 5088 5089 if (LHS->isConstantZero()) 5090 return RHS; 5091 if (RHS->isConstantZero()) 5092 return LHS; 5093 return None; 5094 } 5095 case ISD::SHL: { 5096 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 5097 if (!ShiftOp) 5098 return None; 5099 5100 uint64_t BitShift = ShiftOp->getZExtValue(); 5101 if (BitShift % 8 != 0) 5102 return None; 5103 uint64_t ByteShift = BitShift / 8; 5104 5105 return Index < ByteShift 5106 ? ByteProvider::getConstantZero() 5107 : calculateByteProvider(Op->getOperand(0), Index - ByteShift, 5108 Depth + 1); 5109 } 5110 case ISD::ANY_EXTEND: 5111 case ISD::SIGN_EXTEND: 5112 case ISD::ZERO_EXTEND: { 5113 SDValue NarrowOp = Op->getOperand(0); 5114 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits(); 5115 if (NarrowBitWidth % 8 != 0) 5116 return None; 5117 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 5118 5119 if (Index >= NarrowByteWidth) 5120 return Op.getOpcode() == ISD::ZERO_EXTEND 5121 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 5122 : None; 5123 return calculateByteProvider(NarrowOp, Index, Depth + 1); 5124 } 5125 case ISD::BSWAP: 5126 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1, 5127 Depth + 1); 5128 case ISD::LOAD: { 5129 auto L = cast<LoadSDNode>(Op.getNode()); 5130 if (L->isVolatile() || L->isIndexed()) 5131 return None; 5132 5133 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits(); 5134 if (NarrowBitWidth % 8 != 0) 5135 return None; 5136 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 5137 5138 if (Index >= NarrowByteWidth) 5139 return L->getExtensionType() == ISD::ZEXTLOAD 5140 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 5141 : None; 5142 return ByteProvider::getMemory(L, Index); 5143 } 5144 } 5145 5146 return None; 5147 } 5148 5149 /// Match a pattern where a wide type scalar value is loaded by several narrow 5150 /// loads and combined by shifts and ors. Fold it into a single load or a load 5151 /// and a BSWAP if the targets supports it. 5152 /// 5153 /// Assuming little endian target: 5154 /// i8 *a = ... 5155 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24) 5156 /// => 5157 /// i32 val = *((i32)a) 5158 /// 5159 /// i8 *a = ... 5160 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3] 5161 /// => 5162 /// i32 val = BSWAP(*((i32)a)) 5163 /// 5164 /// TODO: This rule matches complex patterns with OR node roots and doesn't 5165 /// interact well with the worklist mechanism. When a part of the pattern is 5166 /// updated (e.g. one of the loads) its direct users are put into the worklist, 5167 /// but the root node of the pattern which triggers the load combine is not 5168 /// necessarily a direct user of the changed node. For example, once the address 5169 /// of t28 load is reassociated load combine won't be triggered: 5170 /// t25: i32 = add t4, Constant:i32<2> 5171 /// t26: i64 = sign_extend t25 5172 /// t27: i64 = add t2, t26 5173 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64 5174 /// t29: i32 = zero_extend t28 5175 /// t32: i32 = shl t29, Constant:i8<8> 5176 /// t33: i32 = or t23, t32 5177 /// As a possible fix visitLoad can check if the load can be a part of a load 5178 /// combine pattern and add corresponding OR roots to the worklist. 5179 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) { 5180 assert(N->getOpcode() == ISD::OR && 5181 "Can only match load combining against OR nodes"); 5182 5183 // Handles simple types only 5184 EVT VT = N->getValueType(0); 5185 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 5186 return SDValue(); 5187 unsigned ByteWidth = VT.getSizeInBits() / 8; 5188 5189 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5190 // Before legalize we can introduce too wide illegal loads which will be later 5191 // split into legal sized loads. This enables us to combine i64 load by i8 5192 // patterns to a couple of i32 loads on 32 bit targets. 5193 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT)) 5194 return SDValue(); 5195 5196 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = []( 5197 unsigned BW, unsigned i) { return i; }; 5198 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = []( 5199 unsigned BW, unsigned i) { return BW - i - 1; }; 5200 5201 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian(); 5202 auto MemoryByteOffset = [&] (ByteProvider P) { 5203 assert(P.isMemory() && "Must be a memory byte provider"); 5204 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits(); 5205 assert(LoadBitWidth % 8 == 0 && 5206 "can only analyze providers for individual bytes not bit"); 5207 unsigned LoadByteWidth = LoadBitWidth / 8; 5208 return IsBigEndianTarget 5209 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset) 5210 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset); 5211 }; 5212 5213 Optional<BaseIndexOffset> Base; 5214 SDValue Chain; 5215 5216 SmallSet<LoadSDNode *, 8> Loads; 5217 Optional<ByteProvider> FirstByteProvider; 5218 int64_t FirstOffset = INT64_MAX; 5219 5220 // Check if all the bytes of the OR we are looking at are loaded from the same 5221 // base address. Collect bytes offsets from Base address in ByteOffsets. 5222 SmallVector<int64_t, 4> ByteOffsets(ByteWidth); 5223 for (unsigned i = 0; i < ByteWidth; i++) { 5224 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true); 5225 if (!P || !P->isMemory()) // All the bytes must be loaded from memory 5226 return SDValue(); 5227 5228 LoadSDNode *L = P->Load; 5229 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() && 5230 "Must be enforced by calculateByteProvider"); 5231 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset"); 5232 5233 // All loads must share the same chain 5234 SDValue LChain = L->getChain(); 5235 if (!Chain) 5236 Chain = LChain; 5237 else if (Chain != LChain) 5238 return SDValue(); 5239 5240 // Loads must share the same base address 5241 BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG); 5242 int64_t ByteOffsetFromBase = 0; 5243 if (!Base) 5244 Base = Ptr; 5245 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase)) 5246 return SDValue(); 5247 5248 // Calculate the offset of the current byte from the base address 5249 ByteOffsetFromBase += MemoryByteOffset(*P); 5250 ByteOffsets[i] = ByteOffsetFromBase; 5251 5252 // Remember the first byte load 5253 if (ByteOffsetFromBase < FirstOffset) { 5254 FirstByteProvider = P; 5255 FirstOffset = ByteOffsetFromBase; 5256 } 5257 5258 Loads.insert(L); 5259 } 5260 assert(!Loads.empty() && "All the bytes of the value must be loaded from " 5261 "memory, so there must be at least one load which produces the value"); 5262 assert(Base && "Base address of the accessed memory location must be set"); 5263 assert(FirstOffset != INT64_MAX && "First byte offset must be set"); 5264 5265 // Check if the bytes of the OR we are looking at match with either big or 5266 // little endian value load 5267 bool BigEndian = true, LittleEndian = true; 5268 for (unsigned i = 0; i < ByteWidth; i++) { 5269 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset; 5270 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i); 5271 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i); 5272 if (!BigEndian && !LittleEndian) 5273 return SDValue(); 5274 } 5275 assert((BigEndian != LittleEndian) && "should be either or"); 5276 assert(FirstByteProvider && "must be set"); 5277 5278 // Ensure that the first byte is loaded from zero offset of the first load. 5279 // So the combined value can be loaded from the first load address. 5280 if (MemoryByteOffset(*FirstByteProvider) != 0) 5281 return SDValue(); 5282 LoadSDNode *FirstLoad = FirstByteProvider->Load; 5283 5284 // The node we are looking at matches with the pattern, check if we can 5285 // replace it with a single load and bswap if needed. 5286 5287 // If the load needs byte swap check if the target supports it 5288 bool NeedsBswap = IsBigEndianTarget != BigEndian; 5289 5290 // Before legalize we can introduce illegal bswaps which will be later 5291 // converted to an explicit bswap sequence. This way we end up with a single 5292 // load and byte shuffling instead of several loads and byte shuffling. 5293 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT)) 5294 return SDValue(); 5295 5296 // Check that a load of the wide type is both allowed and fast on the target 5297 bool Fast = false; 5298 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), 5299 VT, FirstLoad->getAddressSpace(), 5300 FirstLoad->getAlignment(), &Fast); 5301 if (!Allowed || !Fast) 5302 return SDValue(); 5303 5304 SDValue NewLoad = 5305 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(), 5306 FirstLoad->getPointerInfo(), FirstLoad->getAlignment()); 5307 5308 // Transfer chain users from old loads to the new load. 5309 for (LoadSDNode *L : Loads) 5310 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1)); 5311 5312 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad; 5313 } 5314 5315 SDValue DAGCombiner::visitXOR(SDNode *N) { 5316 SDValue N0 = N->getOperand(0); 5317 SDValue N1 = N->getOperand(1); 5318 EVT VT = N0.getValueType(); 5319 5320 // fold vector ops 5321 if (VT.isVector()) { 5322 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5323 return FoldedVOp; 5324 5325 // fold (xor x, 0) -> x, vector edition 5326 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5327 return N1; 5328 if (ISD::isBuildVectorAllZeros(N1.getNode())) 5329 return N0; 5330 } 5331 5332 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 5333 if (N0.isUndef() && N1.isUndef()) 5334 return DAG.getConstant(0, SDLoc(N), VT); 5335 // fold (xor x, undef) -> undef 5336 if (N0.isUndef()) 5337 return N0; 5338 if (N1.isUndef()) 5339 return N1; 5340 // fold (xor c1, c2) -> c1^c2 5341 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5342 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 5343 if (N0C && N1C) 5344 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 5345 // canonicalize constant to RHS 5346 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 5347 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 5348 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 5349 // fold (xor x, 0) -> x 5350 if (isNullConstant(N1)) 5351 return N0; 5352 5353 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5354 return NewSel; 5355 5356 // reassociate xor 5357 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 5358 return RXOR; 5359 5360 // fold !(x cc y) -> (x !cc y) 5361 SDValue LHS, RHS, CC; 5362 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 5363 bool isInt = LHS.getValueType().isInteger(); 5364 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 5365 isInt); 5366 5367 if (!LegalOperations || 5368 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 5369 switch (N0.getOpcode()) { 5370 default: 5371 llvm_unreachable("Unhandled SetCC Equivalent!"); 5372 case ISD::SETCC: 5373 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC); 5374 case ISD::SELECT_CC: 5375 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2), 5376 N0.getOperand(3), NotCC); 5377 } 5378 } 5379 } 5380 5381 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 5382 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 5383 N0.getNode()->hasOneUse() && 5384 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 5385 SDValue V = N0.getOperand(0); 5386 SDLoc DL(N0); 5387 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 5388 DAG.getConstant(1, DL, V.getValueType())); 5389 AddToWorklist(V.getNode()); 5390 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 5391 } 5392 5393 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 5394 if (isOneConstant(N1) && VT == MVT::i1 && N0.hasOneUse() && 5395 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 5396 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5397 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 5398 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 5399 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 5400 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 5401 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 5402 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 5403 } 5404 } 5405 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 5406 if (isAllOnesConstant(N1) && N0.hasOneUse() && 5407 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 5408 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5409 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 5410 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 5411 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 5412 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 5413 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 5414 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 5415 } 5416 } 5417 // fold (xor (and x, y), y) -> (and (not x), y) 5418 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 5419 N0->getOperand(1) == N1) { 5420 SDValue X = N0->getOperand(0); 5421 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 5422 AddToWorklist(NotX.getNode()); 5423 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 5424 } 5425 5426 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X) 5427 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5428 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && 5429 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) && 5430 TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { 5431 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1))) 5432 if (C->getAPIntValue() == (OpSizeInBits - 1)) 5433 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0)); 5434 } 5435 5436 // fold (xor x, x) -> 0 5437 if (N0 == N1) 5438 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 5439 5440 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 5441 // Here is a concrete example of this equivalence: 5442 // i16 x == 14 5443 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 5444 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 5445 // 5446 // => 5447 // 5448 // i16 ~1 == 0b1111111111111110 5449 // i16 rol(~1, 14) == 0b1011111111111111 5450 // 5451 // Some additional tips to help conceptualize this transform: 5452 // - Try to see the operation as placing a single zero in a value of all ones. 5453 // - There exists no value for x which would allow the result to contain zero. 5454 // - Values of x larger than the bitwidth are undefined and do not require a 5455 // consistent result. 5456 // - Pushing the zero left requires shifting one bits in from the right. 5457 // A rotate left of ~1 is a nice way of achieving the desired result. 5458 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 5459 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 5460 SDLoc DL(N); 5461 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 5462 N0.getOperand(1)); 5463 } 5464 5465 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 5466 if (N0.getOpcode() == N1.getOpcode()) 5467 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 5468 return Tmp; 5469 5470 // Simplify the expression using non-local knowledge. 5471 if (SimplifyDemandedBits(SDValue(N, 0))) 5472 return SDValue(N, 0); 5473 5474 return SDValue(); 5475 } 5476 5477 /// Handle transforms common to the three shifts, when the shift amount is a 5478 /// constant. 5479 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 5480 SDNode *LHS = N->getOperand(0).getNode(); 5481 if (!LHS->hasOneUse()) return SDValue(); 5482 5483 // We want to pull some binops through shifts, so that we have (and (shift)) 5484 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 5485 // thing happens with address calculations, so it's important to canonicalize 5486 // it. 5487 bool HighBitSet = false; // Can we transform this if the high bit is set? 5488 5489 switch (LHS->getOpcode()) { 5490 default: return SDValue(); 5491 case ISD::OR: 5492 case ISD::XOR: 5493 HighBitSet = false; // We can only transform sra if the high bit is clear. 5494 break; 5495 case ISD::AND: 5496 HighBitSet = true; // We can only transform sra if the high bit is set. 5497 break; 5498 case ISD::ADD: 5499 if (N->getOpcode() != ISD::SHL) 5500 return SDValue(); // only shl(add) not sr[al](add). 5501 HighBitSet = false; // We can only transform sra if the high bit is clear. 5502 break; 5503 } 5504 5505 // We require the RHS of the binop to be a constant and not opaque as well. 5506 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 5507 if (!BinOpCst) return SDValue(); 5508 5509 // FIXME: disable this unless the input to the binop is a shift by a constant 5510 // or is copy/select.Enable this in other cases when figure out it's exactly profitable. 5511 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 5512 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL || 5513 BinOpLHSVal->getOpcode() == ISD::SRA || 5514 BinOpLHSVal->getOpcode() == ISD::SRL; 5515 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg || 5516 BinOpLHSVal->getOpcode() == ISD::SELECT; 5517 5518 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) && 5519 !isCopyOrSelect) 5520 return SDValue(); 5521 5522 if (isCopyOrSelect && N->hasOneUse()) 5523 return SDValue(); 5524 5525 EVT VT = N->getValueType(0); 5526 5527 // If this is a signed shift right, and the high bit is modified by the 5528 // logical operation, do not perform the transformation. The highBitSet 5529 // boolean indicates the value of the high bit of the constant which would 5530 // cause it to be modified for this operation. 5531 if (N->getOpcode() == ISD::SRA) { 5532 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 5533 if (BinOpRHSSignSet != HighBitSet) 5534 return SDValue(); 5535 } 5536 5537 if (!TLI.isDesirableToCommuteWithShift(LHS)) 5538 return SDValue(); 5539 5540 // Fold the constants, shifting the binop RHS by the shift amount. 5541 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 5542 N->getValueType(0), 5543 LHS->getOperand(1), N->getOperand(1)); 5544 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 5545 5546 // Create the new shift. 5547 SDValue NewShift = DAG.getNode(N->getOpcode(), 5548 SDLoc(LHS->getOperand(0)), 5549 VT, LHS->getOperand(0), N->getOperand(1)); 5550 5551 // Create the new binop. 5552 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 5553 } 5554 5555 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 5556 assert(N->getOpcode() == ISD::TRUNCATE); 5557 assert(N->getOperand(0).getOpcode() == ISD::AND); 5558 5559 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 5560 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 5561 SDValue N01 = N->getOperand(0).getOperand(1); 5562 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) { 5563 SDLoc DL(N); 5564 EVT TruncVT = N->getValueType(0); 5565 SDValue N00 = N->getOperand(0).getOperand(0); 5566 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00); 5567 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01); 5568 AddToWorklist(Trunc00.getNode()); 5569 AddToWorklist(Trunc01.getNode()); 5570 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01); 5571 } 5572 } 5573 5574 return SDValue(); 5575 } 5576 5577 SDValue DAGCombiner::visitRotate(SDNode *N) { 5578 SDLoc dl(N); 5579 SDValue N0 = N->getOperand(0); 5580 SDValue N1 = N->getOperand(1); 5581 EVT VT = N->getValueType(0); 5582 unsigned Bitsize = VT.getScalarSizeInBits(); 5583 5584 // fold (rot x, 0) -> x 5585 if (isNullConstantOrNullSplatConstant(N1)) 5586 return N0; 5587 5588 // fold (rot x, c) -> (rot x, c % BitSize) 5589 if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) { 5590 if (Cst->getAPIntValue().uge(Bitsize)) { 5591 uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize); 5592 return DAG.getNode(N->getOpcode(), dl, VT, N0, 5593 DAG.getConstant(RotAmt, dl, N1.getValueType())); 5594 } 5595 } 5596 5597 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 5598 if (N1.getOpcode() == ISD::TRUNCATE && 5599 N1.getOperand(0).getOpcode() == ISD::AND) { 5600 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5601 return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1); 5602 } 5603 5604 unsigned NextOp = N0.getOpcode(); 5605 // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize) 5606 if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) { 5607 SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1); 5608 SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)); 5609 if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) { 5610 EVT ShiftVT = C1->getValueType(0); 5611 bool SameSide = (N->getOpcode() == NextOp); 5612 unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB; 5613 if (SDValue CombinedShift = 5614 DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) { 5615 SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT); 5616 SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic( 5617 ISD::SREM, dl, ShiftVT, CombinedShift.getNode(), 5618 BitsizeC.getNode()); 5619 return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0), 5620 CombinedShiftNorm); 5621 } 5622 } 5623 } 5624 return SDValue(); 5625 } 5626 5627 SDValue DAGCombiner::visitSHL(SDNode *N) { 5628 SDValue N0 = N->getOperand(0); 5629 SDValue N1 = N->getOperand(1); 5630 EVT VT = N0.getValueType(); 5631 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5632 5633 // fold vector ops 5634 if (VT.isVector()) { 5635 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5636 return FoldedVOp; 5637 5638 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 5639 // If setcc produces all-one true value then: 5640 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 5641 if (N1CV && N1CV->isConstant()) { 5642 if (N0.getOpcode() == ISD::AND) { 5643 SDValue N00 = N0->getOperand(0); 5644 SDValue N01 = N0->getOperand(1); 5645 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 5646 5647 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 5648 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 5649 TargetLowering::ZeroOrNegativeOneBooleanContent) { 5650 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 5651 N01CV, N1CV)) 5652 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 5653 } 5654 } 5655 } 5656 } 5657 5658 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5659 5660 // fold (shl c1, c2) -> c1<<c2 5661 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5662 if (N0C && N1C && !N1C->isOpaque()) 5663 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 5664 // fold (shl 0, x) -> 0 5665 if (isNullConstantOrNullSplatConstant(N0)) 5666 return N0; 5667 // fold (shl x, c >= size(x)) -> undef 5668 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 5669 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 5670 return Val->getAPIntValue().uge(OpSizeInBits); 5671 }; 5672 if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig)) 5673 return DAG.getUNDEF(VT); 5674 // fold (shl x, 0) -> x 5675 if (N1C && N1C->isNullValue()) 5676 return N0; 5677 // fold (shl undef, x) -> 0 5678 if (N0.isUndef()) 5679 return DAG.getConstant(0, SDLoc(N), VT); 5680 5681 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5682 return NewSel; 5683 5684 // if (shl x, c) is known to be zero, return 0 5685 if (DAG.MaskedValueIsZero(SDValue(N, 0), 5686 APInt::getAllOnesValue(OpSizeInBits))) 5687 return DAG.getConstant(0, SDLoc(N), VT); 5688 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 5689 if (N1.getOpcode() == ISD::TRUNCATE && 5690 N1.getOperand(0).getOpcode() == ISD::AND) { 5691 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5692 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 5693 } 5694 5695 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5696 return SDValue(N, 0); 5697 5698 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 5699 if (N0.getOpcode() == ISD::SHL) { 5700 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 5701 ConstantSDNode *RHS) { 5702 APInt c1 = LHS->getAPIntValue(); 5703 APInt c2 = RHS->getAPIntValue(); 5704 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5705 return (c1 + c2).uge(OpSizeInBits); 5706 }; 5707 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 5708 return DAG.getConstant(0, SDLoc(N), VT); 5709 5710 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 5711 ConstantSDNode *RHS) { 5712 APInt c1 = LHS->getAPIntValue(); 5713 APInt c2 = RHS->getAPIntValue(); 5714 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5715 return (c1 + c2).ult(OpSizeInBits); 5716 }; 5717 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 5718 SDLoc DL(N); 5719 EVT ShiftVT = N1.getValueType(); 5720 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 5721 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum); 5722 } 5723 } 5724 5725 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 5726 // For this to be valid, the second form must not preserve any of the bits 5727 // that are shifted out by the inner shift in the first form. This means 5728 // the outer shift size must be >= the number of bits added by the ext. 5729 // As a corollary, we don't care what kind of ext it is. 5730 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 5731 N0.getOpcode() == ISD::ANY_EXTEND || 5732 N0.getOpcode() == ISD::SIGN_EXTEND) && 5733 N0.getOperand(0).getOpcode() == ISD::SHL) { 5734 SDValue N0Op0 = N0.getOperand(0); 5735 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5736 APInt c1 = N0Op0C1->getAPIntValue(); 5737 APInt c2 = N1C->getAPIntValue(); 5738 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5739 5740 EVT InnerShiftVT = N0Op0.getValueType(); 5741 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 5742 if (c2.uge(OpSizeInBits - InnerShiftSize)) { 5743 SDLoc DL(N0); 5744 APInt Sum = c1 + c2; 5745 if (Sum.uge(OpSizeInBits)) 5746 return DAG.getConstant(0, DL, VT); 5747 5748 return DAG.getNode( 5749 ISD::SHL, DL, VT, 5750 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)), 5751 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5752 } 5753 } 5754 } 5755 5756 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 5757 // Only fold this if the inner zext has no other uses to avoid increasing 5758 // the total number of instructions. 5759 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 5760 N0.getOperand(0).getOpcode() == ISD::SRL) { 5761 SDValue N0Op0 = N0.getOperand(0); 5762 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5763 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) { 5764 uint64_t c1 = N0Op0C1->getZExtValue(); 5765 uint64_t c2 = N1C->getZExtValue(); 5766 if (c1 == c2) { 5767 SDValue NewOp0 = N0.getOperand(0); 5768 EVT CountVT = NewOp0.getOperand(1).getValueType(); 5769 SDLoc DL(N); 5770 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 5771 NewOp0, 5772 DAG.getConstant(c2, DL, CountVT)); 5773 AddToWorklist(NewSHL.getNode()); 5774 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 5775 } 5776 } 5777 } 5778 } 5779 5780 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 5781 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 5782 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 5783 N0->getFlags().hasExact()) { 5784 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5785 uint64_t C1 = N0C1->getZExtValue(); 5786 uint64_t C2 = N1C->getZExtValue(); 5787 SDLoc DL(N); 5788 if (C1 <= C2) 5789 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5790 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 5791 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 5792 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 5793 } 5794 } 5795 5796 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 5797 // (and (srl x, (sub c1, c2), MASK) 5798 // Only fold this if the inner shift has no other uses -- if it does, folding 5799 // this will increase the total number of instructions. 5800 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5801 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5802 uint64_t c1 = N0C1->getZExtValue(); 5803 if (c1 < OpSizeInBits) { 5804 uint64_t c2 = N1C->getZExtValue(); 5805 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 5806 SDValue Shift; 5807 if (c2 > c1) { 5808 Mask <<= c2 - c1; 5809 SDLoc DL(N); 5810 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5811 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 5812 } else { 5813 Mask.lshrInPlace(c1 - c2); 5814 SDLoc DL(N); 5815 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 5816 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 5817 } 5818 SDLoc DL(N0); 5819 return DAG.getNode(ISD::AND, DL, VT, Shift, 5820 DAG.getConstant(Mask, DL, VT)); 5821 } 5822 } 5823 } 5824 5825 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 5826 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) && 5827 isConstantOrConstantVector(N1, /* No Opaques */ true)) { 5828 SDLoc DL(N); 5829 SDValue AllBits = DAG.getAllOnesConstant(DL, VT); 5830 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1); 5831 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask); 5832 } 5833 5834 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 5835 // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 5836 // Variant of version done on multiply, except mul by a power of 2 is turned 5837 // into a shift. 5838 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) && 5839 N0.getNode()->hasOneUse() && 5840 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5841 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5842 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 5843 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5844 AddToWorklist(Shl0.getNode()); 5845 AddToWorklist(Shl1.getNode()); 5846 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1); 5847 } 5848 5849 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 5850 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() && 5851 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5852 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5853 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5854 if (isConstantOrConstantVector(Shl)) 5855 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl); 5856 } 5857 5858 if (N1C && !N1C->isOpaque()) 5859 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 5860 return NewSHL; 5861 5862 return SDValue(); 5863 } 5864 5865 SDValue DAGCombiner::visitSRA(SDNode *N) { 5866 SDValue N0 = N->getOperand(0); 5867 SDValue N1 = N->getOperand(1); 5868 EVT VT = N0.getValueType(); 5869 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5870 5871 // Arithmetic shifting an all-sign-bit value is a no-op. 5872 // fold (sra 0, x) -> 0 5873 // fold (sra -1, x) -> -1 5874 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits) 5875 return N0; 5876 5877 // fold vector ops 5878 if (VT.isVector()) 5879 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5880 return FoldedVOp; 5881 5882 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5883 5884 // fold (sra c1, c2) -> (sra c1, c2) 5885 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5886 if (N0C && N1C && !N1C->isOpaque()) 5887 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 5888 // fold (sra x, c >= size(x)) -> undef 5889 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 5890 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 5891 return Val->getAPIntValue().uge(OpSizeInBits); 5892 }; 5893 if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig)) 5894 return DAG.getUNDEF(VT); 5895 // fold (sra x, 0) -> x 5896 if (N1C && N1C->isNullValue()) 5897 return N0; 5898 5899 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5900 return NewSel; 5901 5902 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 5903 // sext_inreg. 5904 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 5905 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 5906 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 5907 if (VT.isVector()) 5908 ExtVT = EVT::getVectorVT(*DAG.getContext(), 5909 ExtVT, VT.getVectorNumElements()); 5910 if ((!LegalOperations || 5911 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 5912 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5913 N0.getOperand(0), DAG.getValueType(ExtVT)); 5914 } 5915 5916 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 5917 if (N0.getOpcode() == ISD::SRA) { 5918 SDLoc DL(N); 5919 EVT ShiftVT = N1.getValueType(); 5920 5921 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 5922 ConstantSDNode *RHS) { 5923 APInt c1 = LHS->getAPIntValue(); 5924 APInt c2 = RHS->getAPIntValue(); 5925 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5926 return (c1 + c2).uge(OpSizeInBits); 5927 }; 5928 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 5929 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), 5930 DAG.getConstant(OpSizeInBits - 1, DL, ShiftVT)); 5931 5932 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 5933 ConstantSDNode *RHS) { 5934 APInt c1 = LHS->getAPIntValue(); 5935 APInt c2 = RHS->getAPIntValue(); 5936 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5937 return (c1 + c2).ult(OpSizeInBits); 5938 }; 5939 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 5940 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 5941 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), Sum); 5942 } 5943 } 5944 5945 // fold (sra (shl X, m), (sub result_size, n)) 5946 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 5947 // result_size - n != m. 5948 // If truncate is free for the target sext(shl) is likely to result in better 5949 // code. 5950 if (N0.getOpcode() == ISD::SHL && N1C) { 5951 // Get the two constanst of the shifts, CN0 = m, CN = n. 5952 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 5953 if (N01C) { 5954 LLVMContext &Ctx = *DAG.getContext(); 5955 // Determine what the truncate's result bitsize and type would be. 5956 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 5957 5958 if (VT.isVector()) 5959 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 5960 5961 // Determine the residual right-shift amount. 5962 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 5963 5964 // If the shift is not a no-op (in which case this should be just a sign 5965 // extend already), the truncated to type is legal, sign_extend is legal 5966 // on that type, and the truncate to that type is both legal and free, 5967 // perform the transform. 5968 if ((ShiftAmt > 0) && 5969 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 5970 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 5971 TLI.isTruncateFree(VT, TruncVT)) { 5972 SDLoc DL(N); 5973 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 5974 getShiftAmountTy(N0.getOperand(0).getValueType())); 5975 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 5976 N0.getOperand(0), Amt); 5977 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 5978 Shift); 5979 return DAG.getNode(ISD::SIGN_EXTEND, DL, 5980 N->getValueType(0), Trunc); 5981 } 5982 } 5983 } 5984 5985 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 5986 if (N1.getOpcode() == ISD::TRUNCATE && 5987 N1.getOperand(0).getOpcode() == ISD::AND) { 5988 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5989 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 5990 } 5991 5992 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 5993 // if c1 is equal to the number of bits the trunc removes 5994 if (N0.getOpcode() == ISD::TRUNCATE && 5995 (N0.getOperand(0).getOpcode() == ISD::SRL || 5996 N0.getOperand(0).getOpcode() == ISD::SRA) && 5997 N0.getOperand(0).hasOneUse() && 5998 N0.getOperand(0).getOperand(1).hasOneUse() && 5999 N1C) { 6000 SDValue N0Op0 = N0.getOperand(0); 6001 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 6002 unsigned LargeShiftVal = LargeShift->getZExtValue(); 6003 EVT LargeVT = N0Op0.getValueType(); 6004 6005 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 6006 SDLoc DL(N); 6007 SDValue Amt = 6008 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 6009 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 6010 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 6011 N0Op0.getOperand(0), Amt); 6012 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 6013 } 6014 } 6015 } 6016 6017 // Simplify, based on bits shifted out of the LHS. 6018 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 6019 return SDValue(N, 0); 6020 6021 // If the sign bit is known to be zero, switch this to a SRL. 6022 if (DAG.SignBitIsZero(N0)) 6023 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 6024 6025 if (N1C && !N1C->isOpaque()) 6026 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 6027 return NewSRA; 6028 6029 return SDValue(); 6030 } 6031 6032 SDValue DAGCombiner::visitSRL(SDNode *N) { 6033 SDValue N0 = N->getOperand(0); 6034 SDValue N1 = N->getOperand(1); 6035 EVT VT = N0.getValueType(); 6036 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 6037 6038 // fold vector ops 6039 if (VT.isVector()) 6040 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 6041 return FoldedVOp; 6042 6043 ConstantSDNode *N1C = isConstOrConstSplat(N1); 6044 6045 // fold (srl c1, c2) -> c1 >>u c2 6046 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 6047 if (N0C && N1C && !N1C->isOpaque()) 6048 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 6049 // fold (srl 0, x) -> 0 6050 if (isNullConstantOrNullSplatConstant(N0)) 6051 return N0; 6052 // fold (srl x, c >= size(x)) -> undef 6053 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 6054 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 6055 return Val->getAPIntValue().uge(OpSizeInBits); 6056 }; 6057 if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig)) 6058 return DAG.getUNDEF(VT); 6059 // fold (srl x, 0) -> x 6060 if (N1C && N1C->isNullValue()) 6061 return N0; 6062 6063 if (SDValue NewSel = foldBinOpIntoSelect(N)) 6064 return NewSel; 6065 6066 // if (srl x, c) is known to be zero, return 0 6067 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 6068 APInt::getAllOnesValue(OpSizeInBits))) 6069 return DAG.getConstant(0, SDLoc(N), VT); 6070 6071 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 6072 if (N0.getOpcode() == ISD::SRL) { 6073 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 6074 ConstantSDNode *RHS) { 6075 APInt c1 = LHS->getAPIntValue(); 6076 APInt c2 = RHS->getAPIntValue(); 6077 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6078 return (c1 + c2).uge(OpSizeInBits); 6079 }; 6080 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 6081 return DAG.getConstant(0, SDLoc(N), VT); 6082 6083 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 6084 ConstantSDNode *RHS) { 6085 APInt c1 = LHS->getAPIntValue(); 6086 APInt c2 = RHS->getAPIntValue(); 6087 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6088 return (c1 + c2).ult(OpSizeInBits); 6089 }; 6090 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 6091 SDLoc DL(N); 6092 EVT ShiftVT = N1.getValueType(); 6093 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 6094 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum); 6095 } 6096 } 6097 6098 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 6099 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 6100 N0.getOperand(0).getOpcode() == ISD::SRL) { 6101 if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) { 6102 uint64_t c1 = N001C->getZExtValue(); 6103 uint64_t c2 = N1C->getZExtValue(); 6104 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 6105 EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType(); 6106 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 6107 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 6108 if (c1 + OpSizeInBits == InnerShiftSize) { 6109 SDLoc DL(N0); 6110 if (c1 + c2 >= InnerShiftSize) 6111 return DAG.getConstant(0, DL, VT); 6112 return DAG.getNode(ISD::TRUNCATE, DL, VT, 6113 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 6114 N0.getOperand(0).getOperand(0), 6115 DAG.getConstant(c1 + c2, DL, 6116 ShiftCountVT))); 6117 } 6118 } 6119 } 6120 6121 // fold (srl (shl x, c), c) -> (and x, cst2) 6122 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 6123 isConstantOrConstantVector(N1, /* NoOpaques */ true)) { 6124 SDLoc DL(N); 6125 SDValue Mask = 6126 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1); 6127 AddToWorklist(Mask.getNode()); 6128 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask); 6129 } 6130 6131 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 6132 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 6133 // Shifting in all undef bits? 6134 EVT SmallVT = N0.getOperand(0).getValueType(); 6135 unsigned BitSize = SmallVT.getScalarSizeInBits(); 6136 if (N1C->getZExtValue() >= BitSize) 6137 return DAG.getUNDEF(VT); 6138 6139 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 6140 uint64_t ShiftAmt = N1C->getZExtValue(); 6141 SDLoc DL0(N0); 6142 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 6143 N0.getOperand(0), 6144 DAG.getConstant(ShiftAmt, DL0, 6145 getShiftAmountTy(SmallVT))); 6146 AddToWorklist(SmallShift.getNode()); 6147 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt); 6148 SDLoc DL(N); 6149 return DAG.getNode(ISD::AND, DL, VT, 6150 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 6151 DAG.getConstant(Mask, DL, VT)); 6152 } 6153 } 6154 6155 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 6156 // bit, which is unmodified by sra. 6157 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 6158 if (N0.getOpcode() == ISD::SRA) 6159 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 6160 } 6161 6162 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 6163 if (N1C && N0.getOpcode() == ISD::CTLZ && 6164 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 6165 KnownBits Known; 6166 DAG.computeKnownBits(N0.getOperand(0), Known); 6167 6168 // If any of the input bits are KnownOne, then the input couldn't be all 6169 // zeros, thus the result of the srl will always be zero. 6170 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 6171 6172 // If all of the bits input the to ctlz node are known to be zero, then 6173 // the result of the ctlz is "32" and the result of the shift is one. 6174 APInt UnknownBits = ~Known.Zero; 6175 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 6176 6177 // Otherwise, check to see if there is exactly one bit input to the ctlz. 6178 if (UnknownBits.isPowerOf2()) { 6179 // Okay, we know that only that the single bit specified by UnknownBits 6180 // could be set on input to the CTLZ node. If this bit is set, the SRL 6181 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 6182 // to an SRL/XOR pair, which is likely to simplify more. 6183 unsigned ShAmt = UnknownBits.countTrailingZeros(); 6184 SDValue Op = N0.getOperand(0); 6185 6186 if (ShAmt) { 6187 SDLoc DL(N0); 6188 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 6189 DAG.getConstant(ShAmt, DL, 6190 getShiftAmountTy(Op.getValueType()))); 6191 AddToWorklist(Op.getNode()); 6192 } 6193 6194 SDLoc DL(N); 6195 return DAG.getNode(ISD::XOR, DL, VT, 6196 Op, DAG.getConstant(1, DL, VT)); 6197 } 6198 } 6199 6200 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 6201 if (N1.getOpcode() == ISD::TRUNCATE && 6202 N1.getOperand(0).getOpcode() == ISD::AND) { 6203 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 6204 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 6205 } 6206 6207 // fold operands of srl based on knowledge that the low bits are not 6208 // demanded. 6209 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 6210 return SDValue(N, 0); 6211 6212 if (N1C && !N1C->isOpaque()) 6213 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 6214 return NewSRL; 6215 6216 // Attempt to convert a srl of a load into a narrower zero-extending load. 6217 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 6218 return NarrowLoad; 6219 6220 // Here is a common situation. We want to optimize: 6221 // 6222 // %a = ... 6223 // %b = and i32 %a, 2 6224 // %c = srl i32 %b, 1 6225 // brcond i32 %c ... 6226 // 6227 // into 6228 // 6229 // %a = ... 6230 // %b = and %a, 2 6231 // %c = setcc eq %b, 0 6232 // brcond %c ... 6233 // 6234 // However when after the source operand of SRL is optimized into AND, the SRL 6235 // itself may not be optimized further. Look for it and add the BRCOND into 6236 // the worklist. 6237 if (N->hasOneUse()) { 6238 SDNode *Use = *N->use_begin(); 6239 if (Use->getOpcode() == ISD::BRCOND) 6240 AddToWorklist(Use); 6241 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 6242 // Also look pass the truncate. 6243 Use = *Use->use_begin(); 6244 if (Use->getOpcode() == ISD::BRCOND) 6245 AddToWorklist(Use); 6246 } 6247 } 6248 6249 return SDValue(); 6250 } 6251 6252 SDValue DAGCombiner::visitABS(SDNode *N) { 6253 SDValue N0 = N->getOperand(0); 6254 EVT VT = N->getValueType(0); 6255 6256 // fold (abs c1) -> c2 6257 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6258 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0); 6259 // fold (abs (abs x)) -> (abs x) 6260 if (N0.getOpcode() == ISD::ABS) 6261 return N0; 6262 // fold (abs x) -> x iff not-negative 6263 if (DAG.SignBitIsZero(N0)) 6264 return N0; 6265 return SDValue(); 6266 } 6267 6268 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 6269 SDValue N0 = N->getOperand(0); 6270 EVT VT = N->getValueType(0); 6271 6272 // fold (bswap c1) -> c2 6273 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6274 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 6275 // fold (bswap (bswap x)) -> x 6276 if (N0.getOpcode() == ISD::BSWAP) 6277 return N0->getOperand(0); 6278 return SDValue(); 6279 } 6280 6281 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 6282 SDValue N0 = N->getOperand(0); 6283 EVT VT = N->getValueType(0); 6284 6285 // fold (bitreverse c1) -> c2 6286 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6287 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0); 6288 // fold (bitreverse (bitreverse x)) -> x 6289 if (N0.getOpcode() == ISD::BITREVERSE) 6290 return N0.getOperand(0); 6291 return SDValue(); 6292 } 6293 6294 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 6295 SDValue N0 = N->getOperand(0); 6296 EVT VT = N->getValueType(0); 6297 6298 // fold (ctlz c1) -> c2 6299 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6300 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 6301 6302 // If the value is known never to be zero, switch to the undef version. 6303 if (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ_ZERO_UNDEF, VT)) { 6304 if (DAG.isKnownNeverZero(N0)) 6305 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 6306 } 6307 6308 return SDValue(); 6309 } 6310 6311 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 6312 SDValue N0 = N->getOperand(0); 6313 EVT VT = N->getValueType(0); 6314 6315 // fold (ctlz_zero_undef c1) -> c2 6316 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6317 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 6318 return SDValue(); 6319 } 6320 6321 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 6322 SDValue N0 = N->getOperand(0); 6323 EVT VT = N->getValueType(0); 6324 6325 // fold (cttz c1) -> c2 6326 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6327 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 6328 6329 // If the value is known never to be zero, switch to the undef version. 6330 if (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ_ZERO_UNDEF, VT)) { 6331 if (DAG.isKnownNeverZero(N0)) 6332 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 6333 } 6334 6335 return SDValue(); 6336 } 6337 6338 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 6339 SDValue N0 = N->getOperand(0); 6340 EVT VT = N->getValueType(0); 6341 6342 // fold (cttz_zero_undef c1) -> c2 6343 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6344 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 6345 return SDValue(); 6346 } 6347 6348 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 6349 SDValue N0 = N->getOperand(0); 6350 EVT VT = N->getValueType(0); 6351 6352 // fold (ctpop c1) -> c2 6353 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6354 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 6355 return SDValue(); 6356 } 6357 6358 /// \brief Generate Min/Max node 6359 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 6360 SDValue RHS, SDValue True, SDValue False, 6361 ISD::CondCode CC, const TargetLowering &TLI, 6362 SelectionDAG &DAG) { 6363 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 6364 return SDValue(); 6365 6366 switch (CC) { 6367 case ISD::SETOLT: 6368 case ISD::SETOLE: 6369 case ISD::SETLT: 6370 case ISD::SETLE: 6371 case ISD::SETULT: 6372 case ISD::SETULE: { 6373 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 6374 if (TLI.isOperationLegal(Opcode, VT)) 6375 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 6376 return SDValue(); 6377 } 6378 case ISD::SETOGT: 6379 case ISD::SETOGE: 6380 case ISD::SETGT: 6381 case ISD::SETGE: 6382 case ISD::SETUGT: 6383 case ISD::SETUGE: { 6384 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 6385 if (TLI.isOperationLegal(Opcode, VT)) 6386 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 6387 return SDValue(); 6388 } 6389 default: 6390 return SDValue(); 6391 } 6392 } 6393 6394 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) { 6395 SDValue Cond = N->getOperand(0); 6396 SDValue N1 = N->getOperand(1); 6397 SDValue N2 = N->getOperand(2); 6398 EVT VT = N->getValueType(0); 6399 EVT CondVT = Cond.getValueType(); 6400 SDLoc DL(N); 6401 6402 if (!VT.isInteger()) 6403 return SDValue(); 6404 6405 auto *C1 = dyn_cast<ConstantSDNode>(N1); 6406 auto *C2 = dyn_cast<ConstantSDNode>(N2); 6407 if (!C1 || !C2) 6408 return SDValue(); 6409 6410 // Only do this before legalization to avoid conflicting with target-specific 6411 // transforms in the other direction (create a select from a zext/sext). There 6412 // is also a target-independent combine here in DAGCombiner in the other 6413 // direction for (select Cond, -1, 0) when the condition is not i1. 6414 if (CondVT == MVT::i1 && !LegalOperations) { 6415 if (C1->isNullValue() && C2->isOne()) { 6416 // select Cond, 0, 1 --> zext (!Cond) 6417 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 6418 if (VT != MVT::i1) 6419 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond); 6420 return NotCond; 6421 } 6422 if (C1->isNullValue() && C2->isAllOnesValue()) { 6423 // select Cond, 0, -1 --> sext (!Cond) 6424 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 6425 if (VT != MVT::i1) 6426 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond); 6427 return NotCond; 6428 } 6429 if (C1->isOne() && C2->isNullValue()) { 6430 // select Cond, 1, 0 --> zext (Cond) 6431 if (VT != MVT::i1) 6432 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 6433 return Cond; 6434 } 6435 if (C1->isAllOnesValue() && C2->isNullValue()) { 6436 // select Cond, -1, 0 --> sext (Cond) 6437 if (VT != MVT::i1) 6438 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 6439 return Cond; 6440 } 6441 6442 // For any constants that differ by 1, we can transform the select into an 6443 // extend and add. Use a target hook because some targets may prefer to 6444 // transform in the other direction. 6445 if (TLI.convertSelectOfConstantsToMath(VT)) { 6446 if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) { 6447 // select Cond, C1, C1-1 --> add (zext Cond), C1-1 6448 if (VT != MVT::i1) 6449 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 6450 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 6451 } 6452 if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) { 6453 // select Cond, C1, C1+1 --> add (sext Cond), C1+1 6454 if (VT != MVT::i1) 6455 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 6456 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 6457 } 6458 } 6459 6460 return SDValue(); 6461 } 6462 6463 // fold (select Cond, 0, 1) -> (xor Cond, 1) 6464 // We can't do this reliably if integer based booleans have different contents 6465 // to floating point based booleans. This is because we can't tell whether we 6466 // have an integer-based boolean or a floating-point-based boolean unless we 6467 // can find the SETCC that produced it and inspect its operands. This is 6468 // fairly easy if C is the SETCC node, but it can potentially be 6469 // undiscoverable (or not reasonably discoverable). For example, it could be 6470 // in another basic block or it could require searching a complicated 6471 // expression. 6472 if (CondVT.isInteger() && 6473 TLI.getBooleanContents(false, true) == 6474 TargetLowering::ZeroOrOneBooleanContent && 6475 TLI.getBooleanContents(false, false) == 6476 TargetLowering::ZeroOrOneBooleanContent && 6477 C1->isNullValue() && C2->isOne()) { 6478 SDValue NotCond = 6479 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT)); 6480 if (VT.bitsEq(CondVT)) 6481 return NotCond; 6482 return DAG.getZExtOrTrunc(NotCond, DL, VT); 6483 } 6484 6485 return SDValue(); 6486 } 6487 6488 SDValue DAGCombiner::visitSELECT(SDNode *N) { 6489 SDValue N0 = N->getOperand(0); 6490 SDValue N1 = N->getOperand(1); 6491 SDValue N2 = N->getOperand(2); 6492 EVT VT = N->getValueType(0); 6493 EVT VT0 = N0.getValueType(); 6494 SDLoc DL(N); 6495 6496 // fold (select C, X, X) -> X 6497 if (N1 == N2) 6498 return N1; 6499 6500 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 6501 // fold (select true, X, Y) -> X 6502 // fold (select false, X, Y) -> Y 6503 return !N0C->isNullValue() ? N1 : N2; 6504 } 6505 6506 // fold (select X, X, Y) -> (or X, Y) 6507 // fold (select X, 1, Y) -> (or C, Y) 6508 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 6509 return DAG.getNode(ISD::OR, DL, VT, N0, N2); 6510 6511 if (SDValue V = foldSelectOfConstants(N)) 6512 return V; 6513 6514 // fold (select C, 0, X) -> (and (not C), X) 6515 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 6516 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 6517 AddToWorklist(NOTNode.getNode()); 6518 return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2); 6519 } 6520 // fold (select C, X, 1) -> (or (not C), X) 6521 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 6522 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 6523 AddToWorklist(NOTNode.getNode()); 6524 return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1); 6525 } 6526 // fold (select X, Y, X) -> (and X, Y) 6527 // fold (select X, Y, 0) -> (and X, Y) 6528 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 6529 return DAG.getNode(ISD::AND, DL, VT, N0, N1); 6530 6531 // If we can fold this based on the true/false value, do so. 6532 if (SimplifySelectOps(N, N1, N2)) 6533 return SDValue(N, 0); // Don't revisit N. 6534 6535 if (VT0 == MVT::i1) { 6536 // The code in this block deals with the following 2 equivalences: 6537 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 6538 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 6539 // The target can specify its preferred form with the 6540 // shouldNormalizeToSelectSequence() callback. However we always transform 6541 // to the right anyway if we find the inner select exists in the DAG anyway 6542 // and we always transform to the left side if we know that we can further 6543 // optimize the combination of the conditions. 6544 bool normalizeToSequence = 6545 TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 6546 // select (and Cond0, Cond1), X, Y 6547 // -> select Cond0, (select Cond1, X, Y), Y 6548 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 6549 SDValue Cond0 = N0->getOperand(0); 6550 SDValue Cond1 = N0->getOperand(1); 6551 SDValue InnerSelect = 6552 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2); 6553 if (normalizeToSequence || !InnerSelect.use_empty()) 6554 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, 6555 InnerSelect, N2); 6556 } 6557 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 6558 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 6559 SDValue Cond0 = N0->getOperand(0); 6560 SDValue Cond1 = N0->getOperand(1); 6561 SDValue InnerSelect = 6562 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2); 6563 if (normalizeToSequence || !InnerSelect.use_empty()) 6564 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1, 6565 InnerSelect); 6566 } 6567 6568 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 6569 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 6570 SDValue N1_0 = N1->getOperand(0); 6571 SDValue N1_1 = N1->getOperand(1); 6572 SDValue N1_2 = N1->getOperand(2); 6573 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 6574 // Create the actual and node if we can generate good code for it. 6575 if (!normalizeToSequence) { 6576 SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0); 6577 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2); 6578 } 6579 // Otherwise see if we can optimize the "and" to a better pattern. 6580 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 6581 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1, 6582 N2); 6583 } 6584 } 6585 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 6586 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 6587 SDValue N2_0 = N2->getOperand(0); 6588 SDValue N2_1 = N2->getOperand(1); 6589 SDValue N2_2 = N2->getOperand(2); 6590 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 6591 // Create the actual or node if we can generate good code for it. 6592 if (!normalizeToSequence) { 6593 SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0); 6594 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2); 6595 } 6596 // Otherwise see if we can optimize to a better pattern. 6597 if (SDValue Combined = visitORLike(N0, N2_0, N)) 6598 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1, 6599 N2_2); 6600 } 6601 } 6602 } 6603 6604 // select (xor Cond, 1), X, Y -> select Cond, Y, X 6605 if (VT0 == MVT::i1) { 6606 if (N0->getOpcode() == ISD::XOR) { 6607 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) { 6608 SDValue Cond0 = N0->getOperand(0); 6609 if (C->isOne()) 6610 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N2, N1); 6611 } 6612 } 6613 } 6614 6615 // fold selects based on a setcc into other things, such as min/max/abs 6616 if (N0.getOpcode() == ISD::SETCC) { 6617 // select x, y (fcmp lt x, y) -> fminnum x, y 6618 // select x, y (fcmp gt x, y) -> fmaxnum x, y 6619 // 6620 // This is OK if we don't care about what happens if either operand is a 6621 // NaN. 6622 // 6623 6624 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 6625 // no signed zeros as well as no nans. 6626 const TargetOptions &Options = DAG.getTarget().Options; 6627 if (Options.UnsafeFPMath && VT.isFloatingPoint() && N0.hasOneUse() && 6628 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 6629 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6630 6631 if (SDValue FMinMax = combineMinNumMaxNum( 6632 DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG)) 6633 return FMinMax; 6634 } 6635 6636 if ((!LegalOperations && 6637 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 6638 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 6639 return DAG.getNode(ISD::SELECT_CC, DL, VT, N0.getOperand(0), 6640 N0.getOperand(1), N1, N2, N0.getOperand(2)); 6641 return SimplifySelect(DL, N0, N1, N2); 6642 } 6643 6644 return SDValue(); 6645 } 6646 6647 static 6648 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 6649 SDLoc DL(N); 6650 EVT LoVT, HiVT; 6651 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 6652 6653 // Split the inputs. 6654 SDValue Lo, Hi, LL, LH, RL, RH; 6655 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 6656 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 6657 6658 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 6659 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 6660 6661 return std::make_pair(Lo, Hi); 6662 } 6663 6664 // This function assumes all the vselect's arguments are CONCAT_VECTOR 6665 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 6666 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 6667 SDLoc DL(N); 6668 SDValue Cond = N->getOperand(0); 6669 SDValue LHS = N->getOperand(1); 6670 SDValue RHS = N->getOperand(2); 6671 EVT VT = N->getValueType(0); 6672 int NumElems = VT.getVectorNumElements(); 6673 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 6674 RHS.getOpcode() == ISD::CONCAT_VECTORS && 6675 Cond.getOpcode() == ISD::BUILD_VECTOR); 6676 6677 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 6678 // binary ones here. 6679 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 6680 return SDValue(); 6681 6682 // We're sure we have an even number of elements due to the 6683 // concat_vectors we have as arguments to vselect. 6684 // Skip BV elements until we find one that's not an UNDEF 6685 // After we find an UNDEF element, keep looping until we get to half the 6686 // length of the BV and see if all the non-undef nodes are the same. 6687 ConstantSDNode *BottomHalf = nullptr; 6688 for (int i = 0; i < NumElems / 2; ++i) { 6689 if (Cond->getOperand(i)->isUndef()) 6690 continue; 6691 6692 if (BottomHalf == nullptr) 6693 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 6694 else if (Cond->getOperand(i).getNode() != BottomHalf) 6695 return SDValue(); 6696 } 6697 6698 // Do the same for the second half of the BuildVector 6699 ConstantSDNode *TopHalf = nullptr; 6700 for (int i = NumElems / 2; i < NumElems; ++i) { 6701 if (Cond->getOperand(i)->isUndef()) 6702 continue; 6703 6704 if (TopHalf == nullptr) 6705 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 6706 else if (Cond->getOperand(i).getNode() != TopHalf) 6707 return SDValue(); 6708 } 6709 6710 assert(TopHalf && BottomHalf && 6711 "One half of the selector was all UNDEFs and the other was all the " 6712 "same value. This should have been addressed before this function."); 6713 return DAG.getNode( 6714 ISD::CONCAT_VECTORS, DL, VT, 6715 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 6716 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 6717 } 6718 6719 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 6720 if (Level >= AfterLegalizeTypes) 6721 return SDValue(); 6722 6723 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 6724 SDValue Mask = MSC->getMask(); 6725 SDValue Data = MSC->getValue(); 6726 SDLoc DL(N); 6727 6728 // If the MSCATTER data type requires splitting and the mask is provided by a 6729 // SETCC, then split both nodes and its operands before legalization. This 6730 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6731 // and enables future optimizations (e.g. min/max pattern matching on X86). 6732 if (Mask.getOpcode() != ISD::SETCC) 6733 return SDValue(); 6734 6735 // Check if any splitting is required. 6736 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 6737 TargetLowering::TypeSplitVector) 6738 return SDValue(); 6739 SDValue MaskLo, MaskHi, Lo, Hi; 6740 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6741 6742 EVT LoVT, HiVT; 6743 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 6744 6745 SDValue Chain = MSC->getChain(); 6746 6747 EVT MemoryVT = MSC->getMemoryVT(); 6748 unsigned Alignment = MSC->getOriginalAlignment(); 6749 6750 EVT LoMemVT, HiMemVT; 6751 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6752 6753 SDValue DataLo, DataHi; 6754 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6755 6756 SDValue Scale = MSC->getScale(); 6757 SDValue BasePtr = MSC->getBasePtr(); 6758 SDValue IndexLo, IndexHi; 6759 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 6760 6761 MachineMemOperand *MMO = DAG.getMachineFunction(). 6762 getMachineMemOperand(MSC->getPointerInfo(), 6763 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6764 Alignment, MSC->getAAInfo(), MSC->getRanges()); 6765 6766 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo, Scale }; 6767 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 6768 DL, OpsLo, MMO); 6769 6770 SDValue OpsHi[] = { Chain, DataHi, MaskHi, BasePtr, IndexHi, Scale }; 6771 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 6772 DL, OpsHi, MMO); 6773 6774 AddToWorklist(Lo.getNode()); 6775 AddToWorklist(Hi.getNode()); 6776 6777 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6778 } 6779 6780 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 6781 if (Level >= AfterLegalizeTypes) 6782 return SDValue(); 6783 6784 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 6785 SDValue Mask = MST->getMask(); 6786 SDValue Data = MST->getValue(); 6787 EVT VT = Data.getValueType(); 6788 SDLoc DL(N); 6789 6790 // If the MSTORE data type requires splitting and the mask is provided by a 6791 // SETCC, then split both nodes and its operands before legalization. This 6792 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6793 // and enables future optimizations (e.g. min/max pattern matching on X86). 6794 if (Mask.getOpcode() == ISD::SETCC) { 6795 // Check if any splitting is required. 6796 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6797 TargetLowering::TypeSplitVector) 6798 return SDValue(); 6799 6800 SDValue MaskLo, MaskHi, Lo, Hi; 6801 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6802 6803 SDValue Chain = MST->getChain(); 6804 SDValue Ptr = MST->getBasePtr(); 6805 6806 EVT MemoryVT = MST->getMemoryVT(); 6807 unsigned Alignment = MST->getOriginalAlignment(); 6808 6809 // if Alignment is equal to the vector size, 6810 // take the half of it for the second part 6811 unsigned SecondHalfAlignment = 6812 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment; 6813 6814 EVT LoMemVT, HiMemVT; 6815 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6816 6817 SDValue DataLo, DataHi; 6818 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6819 6820 MachineMemOperand *MMO = DAG.getMachineFunction(). 6821 getMachineMemOperand(MST->getPointerInfo(), 6822 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6823 Alignment, MST->getAAInfo(), MST->getRanges()); 6824 6825 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 6826 MST->isTruncatingStore(), 6827 MST->isCompressingStore()); 6828 6829 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6830 MST->isCompressingStore()); 6831 unsigned HiOffset = LoMemVT.getStoreSize(); 6832 6833 MMO = DAG.getMachineFunction().getMachineMemOperand( 6834 MST->getPointerInfo().getWithOffset(HiOffset), 6835 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), SecondHalfAlignment, 6836 MST->getAAInfo(), MST->getRanges()); 6837 6838 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 6839 MST->isTruncatingStore(), 6840 MST->isCompressingStore()); 6841 6842 AddToWorklist(Lo.getNode()); 6843 AddToWorklist(Hi.getNode()); 6844 6845 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6846 } 6847 return SDValue(); 6848 } 6849 6850 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 6851 if (Level >= AfterLegalizeTypes) 6852 return SDValue(); 6853 6854 MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N); 6855 SDValue Mask = MGT->getMask(); 6856 SDLoc DL(N); 6857 6858 // If the MGATHER result requires splitting and the mask is provided by a 6859 // SETCC, then split both nodes and its operands before legalization. This 6860 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6861 // and enables future optimizations (e.g. min/max pattern matching on X86). 6862 6863 if (Mask.getOpcode() != ISD::SETCC) 6864 return SDValue(); 6865 6866 EVT VT = N->getValueType(0); 6867 6868 // Check if any splitting is required. 6869 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6870 TargetLowering::TypeSplitVector) 6871 return SDValue(); 6872 6873 SDValue MaskLo, MaskHi, Lo, Hi; 6874 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6875 6876 SDValue Src0 = MGT->getValue(); 6877 SDValue Src0Lo, Src0Hi; 6878 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6879 6880 EVT LoVT, HiVT; 6881 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 6882 6883 SDValue Chain = MGT->getChain(); 6884 EVT MemoryVT = MGT->getMemoryVT(); 6885 unsigned Alignment = MGT->getOriginalAlignment(); 6886 6887 EVT LoMemVT, HiMemVT; 6888 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6889 6890 SDValue Scale = MGT->getScale(); 6891 SDValue BasePtr = MGT->getBasePtr(); 6892 SDValue Index = MGT->getIndex(); 6893 SDValue IndexLo, IndexHi; 6894 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 6895 6896 MachineMemOperand *MMO = DAG.getMachineFunction(). 6897 getMachineMemOperand(MGT->getPointerInfo(), 6898 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6899 Alignment, MGT->getAAInfo(), MGT->getRanges()); 6900 6901 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo, Scale }; 6902 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 6903 MMO); 6904 6905 SDValue OpsHi[] = { Chain, Src0Hi, MaskHi, BasePtr, IndexHi, Scale }; 6906 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 6907 MMO); 6908 6909 AddToWorklist(Lo.getNode()); 6910 AddToWorklist(Hi.getNode()); 6911 6912 // Build a factor node to remember that this load is independent of the 6913 // other one. 6914 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6915 Hi.getValue(1)); 6916 6917 // Legalized the chain result - switch anything that used the old chain to 6918 // use the new one. 6919 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 6920 6921 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6922 6923 SDValue RetOps[] = { GatherRes, Chain }; 6924 return DAG.getMergeValues(RetOps, DL); 6925 } 6926 6927 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 6928 if (Level >= AfterLegalizeTypes) 6929 return SDValue(); 6930 6931 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 6932 SDValue Mask = MLD->getMask(); 6933 SDLoc DL(N); 6934 6935 // If the MLOAD result requires splitting and the mask is provided by a 6936 // SETCC, then split both nodes and its operands before legalization. This 6937 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6938 // and enables future optimizations (e.g. min/max pattern matching on X86). 6939 if (Mask.getOpcode() == ISD::SETCC) { 6940 EVT VT = N->getValueType(0); 6941 6942 // Check if any splitting is required. 6943 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6944 TargetLowering::TypeSplitVector) 6945 return SDValue(); 6946 6947 SDValue MaskLo, MaskHi, Lo, Hi; 6948 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6949 6950 SDValue Src0 = MLD->getSrc0(); 6951 SDValue Src0Lo, Src0Hi; 6952 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6953 6954 EVT LoVT, HiVT; 6955 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 6956 6957 SDValue Chain = MLD->getChain(); 6958 SDValue Ptr = MLD->getBasePtr(); 6959 EVT MemoryVT = MLD->getMemoryVT(); 6960 unsigned Alignment = MLD->getOriginalAlignment(); 6961 6962 // if Alignment is equal to the vector size, 6963 // take the half of it for the second part 6964 unsigned SecondHalfAlignment = 6965 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 6966 Alignment/2 : Alignment; 6967 6968 EVT LoMemVT, HiMemVT; 6969 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6970 6971 MachineMemOperand *MMO = DAG.getMachineFunction(). 6972 getMachineMemOperand(MLD->getPointerInfo(), 6973 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6974 Alignment, MLD->getAAInfo(), MLD->getRanges()); 6975 6976 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 6977 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6978 6979 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6980 MLD->isExpandingLoad()); 6981 unsigned HiOffset = LoMemVT.getStoreSize(); 6982 6983 MMO = DAG.getMachineFunction().getMachineMemOperand( 6984 MLD->getPointerInfo().getWithOffset(HiOffset), 6985 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), SecondHalfAlignment, 6986 MLD->getAAInfo(), MLD->getRanges()); 6987 6988 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 6989 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6990 6991 AddToWorklist(Lo.getNode()); 6992 AddToWorklist(Hi.getNode()); 6993 6994 // Build a factor node to remember that this load is independent of the 6995 // other one. 6996 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6997 Hi.getValue(1)); 6998 6999 // Legalized the chain result - switch anything that used the old chain to 7000 // use the new one. 7001 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 7002 7003 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 7004 7005 SDValue RetOps[] = { LoadRes, Chain }; 7006 return DAG.getMergeValues(RetOps, DL); 7007 } 7008 return SDValue(); 7009 } 7010 7011 /// A vector select of 2 constant vectors can be simplified to math/logic to 7012 /// avoid a variable select instruction and possibly avoid constant loads. 7013 SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) { 7014 SDValue Cond = N->getOperand(0); 7015 SDValue N1 = N->getOperand(1); 7016 SDValue N2 = N->getOperand(2); 7017 EVT VT = N->getValueType(0); 7018 if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 || 7019 !TLI.convertSelectOfConstantsToMath(VT) || 7020 !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) || 7021 !ISD::isBuildVectorOfConstantSDNodes(N2.getNode())) 7022 return SDValue(); 7023 7024 // Check if we can use the condition value to increment/decrement a single 7025 // constant value. This simplifies a select to an add and removes a constant 7026 // load/materialization from the general case. 7027 bool AllAddOne = true; 7028 bool AllSubOne = true; 7029 unsigned Elts = VT.getVectorNumElements(); 7030 for (unsigned i = 0; i != Elts; ++i) { 7031 SDValue N1Elt = N1.getOperand(i); 7032 SDValue N2Elt = N2.getOperand(i); 7033 if (N1Elt.isUndef() || N2Elt.isUndef()) 7034 continue; 7035 7036 const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue(); 7037 const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue(); 7038 if (C1 != C2 + 1) 7039 AllAddOne = false; 7040 if (C1 != C2 - 1) 7041 AllSubOne = false; 7042 } 7043 7044 // Further simplifications for the extra-special cases where the constants are 7045 // all 0 or all -1 should be implemented as folds of these patterns. 7046 SDLoc DL(N); 7047 if (AllAddOne || AllSubOne) { 7048 // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C 7049 // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C 7050 auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND; 7051 SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond); 7052 return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2); 7053 } 7054 7055 // The general case for select-of-constants: 7056 // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2 7057 // ...but that only makes sense if a vselect is slower than 2 logic ops, so 7058 // leave that to a machine-specific pass. 7059 return SDValue(); 7060 } 7061 7062 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 7063 SDValue N0 = N->getOperand(0); 7064 SDValue N1 = N->getOperand(1); 7065 SDValue N2 = N->getOperand(2); 7066 SDLoc DL(N); 7067 7068 // fold (vselect C, X, X) -> X 7069 if (N1 == N2) 7070 return N1; 7071 7072 // Canonicalize integer abs. 7073 // vselect (setg[te] X, 0), X, -X -> 7074 // vselect (setgt X, -1), X, -X -> 7075 // vselect (setl[te] X, 0), -X, X -> 7076 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 7077 if (N0.getOpcode() == ISD::SETCC) { 7078 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 7079 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 7080 bool isAbs = false; 7081 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 7082 7083 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 7084 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 7085 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 7086 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 7087 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 7088 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 7089 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 7090 7091 if (isAbs) { 7092 EVT VT = LHS.getValueType(); 7093 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) 7094 return DAG.getNode(ISD::ABS, DL, VT, LHS); 7095 7096 SDValue Shift = DAG.getNode( 7097 ISD::SRA, DL, VT, LHS, 7098 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT)); 7099 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 7100 AddToWorklist(Shift.getNode()); 7101 AddToWorklist(Add.getNode()); 7102 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 7103 } 7104 } 7105 7106 if (SimplifySelectOps(N, N1, N2)) 7107 return SDValue(N, 0); // Don't revisit N. 7108 7109 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 7110 if (ISD::isBuildVectorAllOnes(N0.getNode())) 7111 return N1; 7112 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 7113 if (ISD::isBuildVectorAllZeros(N0.getNode())) 7114 return N2; 7115 7116 // The ConvertSelectToConcatVector function is assuming both the above 7117 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 7118 // and addressed. 7119 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 7120 N2.getOpcode() == ISD::CONCAT_VECTORS && 7121 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 7122 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 7123 return CV; 7124 } 7125 7126 if (SDValue V = foldVSelectOfConstants(N)) 7127 return V; 7128 7129 return SDValue(); 7130 } 7131 7132 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 7133 SDValue N0 = N->getOperand(0); 7134 SDValue N1 = N->getOperand(1); 7135 SDValue N2 = N->getOperand(2); 7136 SDValue N3 = N->getOperand(3); 7137 SDValue N4 = N->getOperand(4); 7138 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 7139 7140 // fold select_cc lhs, rhs, x, x, cc -> x 7141 if (N2 == N3) 7142 return N2; 7143 7144 // Determine if the condition we're dealing with is constant 7145 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 7146 CC, SDLoc(N), false)) { 7147 AddToWorklist(SCC.getNode()); 7148 7149 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 7150 if (!SCCC->isNullValue()) 7151 return N2; // cond always true -> true val 7152 else 7153 return N3; // cond always false -> false val 7154 } else if (SCC->isUndef()) { 7155 // When the condition is UNDEF, just return the first operand. This is 7156 // coherent the DAG creation, no setcc node is created in this case 7157 return N2; 7158 } else if (SCC.getOpcode() == ISD::SETCC) { 7159 // Fold to a simpler select_cc 7160 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 7161 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 7162 SCC.getOperand(2)); 7163 } 7164 } 7165 7166 // If we can fold this based on the true/false value, do so. 7167 if (SimplifySelectOps(N, N2, N3)) 7168 return SDValue(N, 0); // Don't revisit N. 7169 7170 // fold select_cc into other things, such as min/max/abs 7171 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 7172 } 7173 7174 SDValue DAGCombiner::visitSETCC(SDNode *N) { 7175 // setcc is very commonly used as an argument to brcond. This pattern 7176 // also lend itself to numerous combines and, as a result, it is desired 7177 // we keep the argument to a brcond as a setcc as much as possible. 7178 bool PreferSetCC = 7179 N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BRCOND; 7180 7181 SDValue Combined = SimplifySetCC( 7182 N->getValueType(0), N->getOperand(0), N->getOperand(1), 7183 cast<CondCodeSDNode>(N->getOperand(2))->get(), SDLoc(N), !PreferSetCC); 7184 7185 if (!Combined) 7186 return SDValue(); 7187 7188 // If we prefer to have a setcc, and we don't, we'll try our best to 7189 // recreate one using rebuildSetCC. 7190 if (PreferSetCC && Combined.getOpcode() != ISD::SETCC) { 7191 SDValue NewSetCC = rebuildSetCC(Combined); 7192 7193 // We don't have anything interesting to combine to. 7194 if (NewSetCC.getNode() == N) 7195 return SDValue(); 7196 7197 if (NewSetCC) 7198 return NewSetCC; 7199 } 7200 7201 return Combined; 7202 } 7203 7204 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 7205 SDValue LHS = N->getOperand(0); 7206 SDValue RHS = N->getOperand(1); 7207 SDValue Carry = N->getOperand(2); 7208 SDValue Cond = N->getOperand(3); 7209 7210 // If Carry is false, fold to a regular SETCC. 7211 if (Carry.getOpcode() == ISD::CARRY_FALSE) 7212 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 7213 7214 return SDValue(); 7215 } 7216 7217 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) { 7218 SDValue LHS = N->getOperand(0); 7219 SDValue RHS = N->getOperand(1); 7220 SDValue Carry = N->getOperand(2); 7221 SDValue Cond = N->getOperand(3); 7222 7223 // If Carry is false, fold to a regular SETCC. 7224 if (isNullConstant(Carry)) 7225 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 7226 7227 return SDValue(); 7228 } 7229 7230 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 7231 /// a build_vector of constants. 7232 /// This function is called by the DAGCombiner when visiting sext/zext/aext 7233 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 7234 /// Vector extends are not folded if operations are legal; this is to 7235 /// avoid introducing illegal build_vector dag nodes. 7236 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 7237 SelectionDAG &DAG, bool LegalTypes, 7238 bool LegalOperations) { 7239 unsigned Opcode = N->getOpcode(); 7240 SDValue N0 = N->getOperand(0); 7241 EVT VT = N->getValueType(0); 7242 7243 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 7244 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 7245 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 7246 && "Expected EXTEND dag node in input!"); 7247 7248 // fold (sext c1) -> c1 7249 // fold (zext c1) -> c1 7250 // fold (aext c1) -> c1 7251 if (isa<ConstantSDNode>(N0)) 7252 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 7253 7254 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 7255 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 7256 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 7257 EVT SVT = VT.getScalarType(); 7258 if (!(VT.isVector() && 7259 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 7260 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 7261 return nullptr; 7262 7263 // We can fold this node into a build_vector. 7264 unsigned VTBits = SVT.getSizeInBits(); 7265 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits(); 7266 SmallVector<SDValue, 8> Elts; 7267 unsigned NumElts = VT.getVectorNumElements(); 7268 SDLoc DL(N); 7269 7270 for (unsigned i=0; i != NumElts; ++i) { 7271 SDValue Op = N0->getOperand(i); 7272 if (Op->isUndef()) { 7273 Elts.push_back(DAG.getUNDEF(SVT)); 7274 continue; 7275 } 7276 7277 SDLoc DL(Op); 7278 // Get the constant value and if needed trunc it to the size of the type. 7279 // Nodes like build_vector might have constants wider than the scalar type. 7280 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 7281 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 7282 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 7283 else 7284 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 7285 } 7286 7287 return DAG.getBuildVector(VT, DL, Elts).getNode(); 7288 } 7289 7290 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 7291 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 7292 // transformation. Returns true if extension are possible and the above 7293 // mentioned transformation is profitable. 7294 static bool ExtendUsesToFormExtLoad(EVT VT, SDNode *N, SDValue N0, 7295 unsigned ExtOpc, 7296 SmallVectorImpl<SDNode *> &ExtendNodes, 7297 const TargetLowering &TLI) { 7298 bool HasCopyToRegUses = false; 7299 bool isTruncFree = TLI.isTruncateFree(VT, N0.getValueType()); 7300 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 7301 UE = N0.getNode()->use_end(); 7302 UI != UE; ++UI) { 7303 SDNode *User = *UI; 7304 if (User == N) 7305 continue; 7306 if (UI.getUse().getResNo() != N0.getResNo()) 7307 continue; 7308 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 7309 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 7310 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 7311 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 7312 // Sign bits will be lost after a zext. 7313 return false; 7314 bool Add = false; 7315 for (unsigned i = 0; i != 2; ++i) { 7316 SDValue UseOp = User->getOperand(i); 7317 if (UseOp == N0) 7318 continue; 7319 if (!isa<ConstantSDNode>(UseOp)) 7320 return false; 7321 Add = true; 7322 } 7323 if (Add) 7324 ExtendNodes.push_back(User); 7325 continue; 7326 } 7327 // If truncates aren't free and there are users we can't 7328 // extend, it isn't worthwhile. 7329 if (!isTruncFree) 7330 return false; 7331 // Remember if this value is live-out. 7332 if (User->getOpcode() == ISD::CopyToReg) 7333 HasCopyToRegUses = true; 7334 } 7335 7336 if (HasCopyToRegUses) { 7337 bool BothLiveOut = false; 7338 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 7339 UI != UE; ++UI) { 7340 SDUse &Use = UI.getUse(); 7341 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 7342 BothLiveOut = true; 7343 break; 7344 } 7345 } 7346 if (BothLiveOut) 7347 // Both unextended and extended values are live out. There had better be 7348 // a good reason for the transformation. 7349 return ExtendNodes.size(); 7350 } 7351 return true; 7352 } 7353 7354 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 7355 SDValue OrigLoad, SDValue ExtLoad, 7356 const SDLoc &DL, ISD::NodeType ExtType) { 7357 // Extend SetCC uses if necessary. 7358 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 7359 SDNode *SetCC = SetCCs[i]; 7360 SmallVector<SDValue, 4> Ops; 7361 7362 for (unsigned j = 0; j != 2; ++j) { 7363 SDValue SOp = SetCC->getOperand(j); 7364 if (SOp == OrigLoad) 7365 Ops.push_back(ExtLoad); 7366 else 7367 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 7368 } 7369 7370 Ops.push_back(SetCC->getOperand(2)); 7371 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 7372 } 7373 } 7374 7375 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 7376 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 7377 SDValue N0 = N->getOperand(0); 7378 EVT DstVT = N->getValueType(0); 7379 EVT SrcVT = N0.getValueType(); 7380 7381 assert((N->getOpcode() == ISD::SIGN_EXTEND || 7382 N->getOpcode() == ISD::ZERO_EXTEND) && 7383 "Unexpected node type (not an extend)!"); 7384 7385 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 7386 // For example, on a target with legal v4i32, but illegal v8i32, turn: 7387 // (v8i32 (sext (v8i16 (load x)))) 7388 // into: 7389 // (v8i32 (concat_vectors (v4i32 (sextload x)), 7390 // (v4i32 (sextload (x + 16))))) 7391 // Where uses of the original load, i.e.: 7392 // (v8i16 (load x)) 7393 // are replaced with: 7394 // (v8i16 (truncate 7395 // (v8i32 (concat_vectors (v4i32 (sextload x)), 7396 // (v4i32 (sextload (x + 16))))))) 7397 // 7398 // This combine is only applicable to illegal, but splittable, vectors. 7399 // All legal types, and illegal non-vector types, are handled elsewhere. 7400 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 7401 // 7402 if (N0->getOpcode() != ISD::LOAD) 7403 return SDValue(); 7404 7405 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7406 7407 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 7408 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 7409 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 7410 return SDValue(); 7411 7412 SmallVector<SDNode *, 4> SetCCs; 7413 if (!ExtendUsesToFormExtLoad(DstVT, N, N0, N->getOpcode(), SetCCs, TLI)) 7414 return SDValue(); 7415 7416 ISD::LoadExtType ExtType = 7417 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 7418 7419 // Try to split the vector types to get down to legal types. 7420 EVT SplitSrcVT = SrcVT; 7421 EVT SplitDstVT = DstVT; 7422 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 7423 SplitSrcVT.getVectorNumElements() > 1) { 7424 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 7425 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 7426 } 7427 7428 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 7429 return SDValue(); 7430 7431 SDLoc DL(N); 7432 const unsigned NumSplits = 7433 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 7434 const unsigned Stride = SplitSrcVT.getStoreSize(); 7435 SmallVector<SDValue, 4> Loads; 7436 SmallVector<SDValue, 4> Chains; 7437 7438 SDValue BasePtr = LN0->getBasePtr(); 7439 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 7440 const unsigned Offset = Idx * Stride; 7441 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 7442 7443 SDValue SplitLoad = DAG.getExtLoad( 7444 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 7445 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 7446 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 7447 7448 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 7449 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 7450 7451 Loads.push_back(SplitLoad.getValue(0)); 7452 Chains.push_back(SplitLoad.getValue(1)); 7453 } 7454 7455 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 7456 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 7457 7458 // Simplify TF. 7459 AddToWorklist(NewChain.getNode()); 7460 7461 CombineTo(N, NewValue); 7462 7463 // Replace uses of the original load (before extension) 7464 // with a truncate of the concatenated sextloaded vectors. 7465 SDValue Trunc = 7466 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 7467 ExtendSetCCUses(SetCCs, N0, NewValue, DL, 7468 (ISD::NodeType)N->getOpcode()); 7469 CombineTo(N0.getNode(), Trunc, NewChain); 7470 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7471 } 7472 7473 /// If we're narrowing or widening the result of a vector select and the final 7474 /// size is the same size as a setcc (compare) feeding the select, then try to 7475 /// apply the cast operation to the select's operands because matching vector 7476 /// sizes for a select condition and other operands should be more efficient. 7477 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) { 7478 unsigned CastOpcode = Cast->getOpcode(); 7479 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || 7480 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || 7481 CastOpcode == ISD::FP_ROUND) && 7482 "Unexpected opcode for vector select narrowing/widening"); 7483 7484 // We only do this transform before legal ops because the pattern may be 7485 // obfuscated by target-specific operations after legalization. Do not create 7486 // an illegal select op, however, because that may be difficult to lower. 7487 EVT VT = Cast->getValueType(0); 7488 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT)) 7489 return SDValue(); 7490 7491 SDValue VSel = Cast->getOperand(0); 7492 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() || 7493 VSel.getOperand(0).getOpcode() != ISD::SETCC) 7494 return SDValue(); 7495 7496 // Does the setcc have the same vector size as the casted select? 7497 SDValue SetCC = VSel.getOperand(0); 7498 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType()); 7499 if (SetCCVT.getSizeInBits() != VT.getSizeInBits()) 7500 return SDValue(); 7501 7502 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B) 7503 SDValue A = VSel.getOperand(1); 7504 SDValue B = VSel.getOperand(2); 7505 SDValue CastA, CastB; 7506 SDLoc DL(Cast); 7507 if (CastOpcode == ISD::FP_ROUND) { 7508 // FP_ROUND (fptrunc) has an extra flag operand to pass along. 7509 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1)); 7510 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1)); 7511 } else { 7512 CastA = DAG.getNode(CastOpcode, DL, VT, A); 7513 CastB = DAG.getNode(CastOpcode, DL, VT, B); 7514 } 7515 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB); 7516 } 7517 7518 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 7519 SDValue N0 = N->getOperand(0); 7520 EVT VT = N->getValueType(0); 7521 SDLoc DL(N); 7522 7523 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7524 LegalOperations)) 7525 return SDValue(Res, 0); 7526 7527 // fold (sext (sext x)) -> (sext x) 7528 // fold (sext (aext x)) -> (sext x) 7529 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 7530 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0)); 7531 7532 if (N0.getOpcode() == ISD::TRUNCATE) { 7533 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 7534 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 7535 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7536 SDNode *oye = N0.getOperand(0).getNode(); 7537 if (NarrowLoad.getNode() != N0.getNode()) { 7538 CombineTo(N0.getNode(), NarrowLoad); 7539 // CombineTo deleted the truncate, if needed, but not what's under it. 7540 AddToWorklist(oye); 7541 } 7542 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7543 } 7544 7545 // See if the value being truncated is already sign extended. If so, just 7546 // eliminate the trunc/sext pair. 7547 SDValue Op = N0.getOperand(0); 7548 unsigned OpBits = Op.getScalarValueSizeInBits(); 7549 unsigned MidBits = N0.getScalarValueSizeInBits(); 7550 unsigned DestBits = VT.getScalarSizeInBits(); 7551 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 7552 7553 if (OpBits == DestBits) { 7554 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 7555 // bits, it is already ready. 7556 if (NumSignBits > DestBits-MidBits) 7557 return Op; 7558 } else if (OpBits < DestBits) { 7559 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 7560 // bits, just sext from i32. 7561 if (NumSignBits > OpBits-MidBits) 7562 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op); 7563 } else { 7564 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 7565 // bits, just truncate to i32. 7566 if (NumSignBits > OpBits-MidBits) 7567 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 7568 } 7569 7570 // fold (sext (truncate x)) -> (sextinreg x). 7571 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 7572 N0.getValueType())) { 7573 if (OpBits < DestBits) 7574 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 7575 else if (OpBits > DestBits) 7576 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 7577 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op, 7578 DAG.getValueType(N0.getValueType())); 7579 } 7580 } 7581 7582 // fold (sext (load x)) -> (sext (truncate (sextload x))) 7583 // Only generate vector extloads when 1) they're legal, and 2) they are 7584 // deemed desirable by the target. 7585 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7586 ((!LegalOperations && !VT.isVector() && 7587 !cast<LoadSDNode>(N0)->isVolatile()) || 7588 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 7589 bool DoXform = true; 7590 SmallVector<SDNode*, 4> SetCCs; 7591 if (!N0.hasOneUse()) 7592 DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ISD::SIGN_EXTEND, SetCCs, 7593 TLI); 7594 if (VT.isVector()) 7595 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 7596 if (DoXform) { 7597 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7598 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 7599 LN0->getBasePtr(), N0.getValueType(), 7600 LN0->getMemOperand()); 7601 ExtendSetCCUses(SetCCs, N0, ExtLoad, DL, ISD::SIGN_EXTEND); 7602 // If the load value is used only by N, replace it via CombineTo N. 7603 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 7604 CombineTo(N, ExtLoad); 7605 if (NoReplaceTrunc) { 7606 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7607 } else { 7608 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7609 N0.getValueType(), ExtLoad); 7610 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 7611 } 7612 return SDValue(N, 0); 7613 } 7614 } 7615 7616 // fold (sext (load x)) to multiple smaller sextloads. 7617 // Only on illegal but splittable vectors. 7618 if (SDValue ExtLoad = CombineExtLoad(N)) 7619 return ExtLoad; 7620 7621 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 7622 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 7623 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 7624 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 7625 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7626 EVT MemVT = LN0->getMemoryVT(); 7627 if ((!LegalOperations && !LN0->isVolatile()) || 7628 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 7629 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 7630 LN0->getBasePtr(), MemVT, 7631 LN0->getMemOperand()); 7632 CombineTo(N, ExtLoad); 7633 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7634 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7635 } 7636 } 7637 7638 // fold (sext (and/or/xor (load x), cst)) -> 7639 // (and/or/xor (sextload x), (sext cst)) 7640 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 7641 N0.getOpcode() == ISD::XOR) && 7642 isa<LoadSDNode>(N0.getOperand(0)) && 7643 N0.getOperand(1).getOpcode() == ISD::Constant && 7644 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 7645 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0)); 7646 EVT MemVT = LN00->getMemoryVT(); 7647 if (TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT) && 7648 LN00->getExtensionType() != ISD::ZEXTLOAD && LN00->isUnindexed()) { 7649 SmallVector<SDNode*, 4> SetCCs; 7650 bool DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0), 7651 ISD::SIGN_EXTEND, SetCCs, TLI); 7652 if (DoXform) { 7653 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN00), VT, 7654 LN00->getChain(), LN00->getBasePtr(), 7655 LN00->getMemoryVT(), 7656 LN00->getMemOperand()); 7657 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7658 Mask = Mask.sext(VT.getSizeInBits()); 7659 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 7660 ExtLoad, DAG.getConstant(Mask, DL, VT)); 7661 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, DL, 7662 ISD::SIGN_EXTEND); 7663 bool NoReplaceTruncAnd = !N0.hasOneUse(); 7664 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse(); 7665 CombineTo(N, And); 7666 // If N0 has multiple uses, change other uses as well. 7667 if (NoReplaceTruncAnd) { 7668 SDValue TruncAnd = 7669 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 7670 CombineTo(N0.getNode(), TruncAnd); 7671 } 7672 if (NoReplaceTrunc) { 7673 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1)); 7674 } else { 7675 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00), 7676 LN00->getValueType(0), ExtLoad); 7677 CombineTo(LN00, Trunc, ExtLoad.getValue(1)); 7678 } 7679 return SDValue(N,0); // Return N so it doesn't get rechecked! 7680 } 7681 } 7682 } 7683 7684 if (N0.getOpcode() == ISD::SETCC) { 7685 SDValue N00 = N0.getOperand(0); 7686 SDValue N01 = N0.getOperand(1); 7687 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 7688 EVT N00VT = N0.getOperand(0).getValueType(); 7689 7690 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 7691 // Only do this before legalize for now. 7692 if (VT.isVector() && !LegalOperations && 7693 TLI.getBooleanContents(N00VT) == 7694 TargetLowering::ZeroOrNegativeOneBooleanContent) { 7695 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 7696 // of the same size as the compared operands. Only optimize sext(setcc()) 7697 // if this is the case. 7698 EVT SVT = getSetCCResultType(N00VT); 7699 7700 // We know that the # elements of the results is the same as the 7701 // # elements of the compare (and the # elements of the compare result 7702 // for that matter). Check to see that they are the same size. If so, 7703 // we know that the element size of the sext'd result matches the 7704 // element size of the compare operands. 7705 if (VT.getSizeInBits() == SVT.getSizeInBits()) 7706 return DAG.getSetCC(DL, VT, N00, N01, CC); 7707 7708 // If the desired elements are smaller or larger than the source 7709 // elements, we can use a matching integer vector type and then 7710 // truncate/sign extend. 7711 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger(); 7712 if (SVT == MatchingVecType) { 7713 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC); 7714 return DAG.getSExtOrTrunc(VsetCC, DL, VT); 7715 } 7716 } 7717 7718 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 7719 // Here, T can be 1 or -1, depending on the type of the setcc and 7720 // getBooleanContents(). 7721 unsigned SetCCWidth = N0.getScalarValueSizeInBits(); 7722 7723 // To determine the "true" side of the select, we need to know the high bit 7724 // of the value returned by the setcc if it evaluates to true. 7725 // If the type of the setcc is i1, then the true case of the select is just 7726 // sext(i1 1), that is, -1. 7727 // If the type of the setcc is larger (say, i8) then the value of the high 7728 // bit depends on getBooleanContents(), so ask TLI for a real "true" value 7729 // of the appropriate width. 7730 SDValue ExtTrueVal = (SetCCWidth == 1) 7731 ? DAG.getAllOnesConstant(DL, VT) 7732 : DAG.getBoolConstant(true, DL, VT, N00VT); 7733 SDValue Zero = DAG.getConstant(0, DL, VT); 7734 if (SDValue SCC = 7735 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true)) 7736 return SCC; 7737 7738 if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) { 7739 EVT SetCCVT = getSetCCResultType(N00VT); 7740 // Don't do this transform for i1 because there's a select transform 7741 // that would reverse it. 7742 // TODO: We should not do this transform at all without a target hook 7743 // because a sext is likely cheaper than a select? 7744 if (SetCCVT.getScalarSizeInBits() != 1 && 7745 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) { 7746 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC); 7747 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero); 7748 } 7749 } 7750 } 7751 7752 // fold (sext x) -> (zext x) if the sign bit is known zero. 7753 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 7754 DAG.SignBitIsZero(N0)) 7755 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0); 7756 7757 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 7758 return NewVSel; 7759 7760 return SDValue(); 7761 } 7762 7763 // isTruncateOf - If N is a truncate of some other value, return true, record 7764 // the value being truncated in Op and which of Op's bits are zero/one in Known. 7765 // This function computes KnownBits to avoid a duplicated call to 7766 // computeKnownBits in the caller. 7767 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 7768 KnownBits &Known) { 7769 if (N->getOpcode() == ISD::TRUNCATE) { 7770 Op = N->getOperand(0); 7771 DAG.computeKnownBits(Op, Known); 7772 return true; 7773 } 7774 7775 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 7776 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 7777 return false; 7778 7779 SDValue Op0 = N->getOperand(0); 7780 SDValue Op1 = N->getOperand(1); 7781 assert(Op0.getValueType() == Op1.getValueType()); 7782 7783 if (isNullConstant(Op0)) 7784 Op = Op1; 7785 else if (isNullConstant(Op1)) 7786 Op = Op0; 7787 else 7788 return false; 7789 7790 DAG.computeKnownBits(Op, Known); 7791 7792 if (!(Known.Zero | 1).isAllOnesValue()) 7793 return false; 7794 7795 return true; 7796 } 7797 7798 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 7799 SDValue N0 = N->getOperand(0); 7800 EVT VT = N->getValueType(0); 7801 7802 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7803 LegalOperations)) 7804 return SDValue(Res, 0); 7805 7806 // fold (zext (zext x)) -> (zext x) 7807 // fold (zext (aext x)) -> (zext x) 7808 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 7809 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 7810 N0.getOperand(0)); 7811 7812 // fold (zext (truncate x)) -> (zext x) or 7813 // (zext (truncate x)) -> (truncate x) 7814 // This is valid when the truncated bits of x are already zero. 7815 // FIXME: We should extend this to work for vectors too. 7816 SDValue Op; 7817 KnownBits Known; 7818 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) { 7819 APInt TruncatedBits = 7820 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 7821 APInt(Op.getValueSizeInBits(), 0) : 7822 APInt::getBitsSet(Op.getValueSizeInBits(), 7823 N0.getValueSizeInBits(), 7824 std::min(Op.getValueSizeInBits(), 7825 VT.getSizeInBits())); 7826 if (TruncatedBits.isSubsetOf(Known.Zero)) 7827 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 7828 } 7829 7830 // fold (zext (truncate x)) -> (and x, mask) 7831 if (N0.getOpcode() == ISD::TRUNCATE) { 7832 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 7833 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 7834 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7835 SDNode *oye = N0.getOperand(0).getNode(); 7836 if (NarrowLoad.getNode() != N0.getNode()) { 7837 CombineTo(N0.getNode(), NarrowLoad); 7838 // CombineTo deleted the truncate, if needed, but not what's under it. 7839 AddToWorklist(oye); 7840 } 7841 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7842 } 7843 7844 EVT SrcVT = N0.getOperand(0).getValueType(); 7845 EVT MinVT = N0.getValueType(); 7846 7847 // Try to mask before the extension to avoid having to generate a larger mask, 7848 // possibly over several sub-vectors. 7849 if (SrcVT.bitsLT(VT) && VT.isVector()) { 7850 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 7851 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 7852 SDValue Op = N0.getOperand(0); 7853 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 7854 AddToWorklist(Op.getNode()); 7855 SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 7856 // Transfer the debug info; the new node is equivalent to N0. 7857 DAG.transferDbgValues(N0, ZExtOrTrunc); 7858 return ZExtOrTrunc; 7859 } 7860 } 7861 7862 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 7863 SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 7864 AddToWorklist(Op.getNode()); 7865 SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 7866 // We may safely transfer the debug info describing the truncate node over 7867 // to the equivalent and operation. 7868 DAG.transferDbgValues(N0, And); 7869 return And; 7870 } 7871 } 7872 7873 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 7874 // if either of the casts is not free. 7875 if (N0.getOpcode() == ISD::AND && 7876 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 7877 N0.getOperand(1).getOpcode() == ISD::Constant && 7878 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 7879 N0.getValueType()) || 7880 !TLI.isZExtFree(N0.getValueType(), VT))) { 7881 SDValue X = N0.getOperand(0).getOperand(0); 7882 X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT); 7883 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7884 Mask = Mask.zext(VT.getSizeInBits()); 7885 SDLoc DL(N); 7886 return DAG.getNode(ISD::AND, DL, VT, 7887 X, DAG.getConstant(Mask, DL, VT)); 7888 } 7889 7890 // fold (zext (load x)) -> (zext (truncate (zextload x))) 7891 // Only generate vector extloads when 1) they're legal, and 2) they are 7892 // deemed desirable by the target. 7893 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7894 ((!LegalOperations && !VT.isVector() && 7895 !cast<LoadSDNode>(N0)->isVolatile()) || 7896 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 7897 bool DoXform = true; 7898 SmallVector<SDNode*, 4> SetCCs; 7899 if (!N0.hasOneUse()) 7900 DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ISD::ZERO_EXTEND, SetCCs, 7901 TLI); 7902 if (VT.isVector()) 7903 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 7904 if (DoXform) { 7905 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7906 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 7907 LN0->getChain(), 7908 LN0->getBasePtr(), N0.getValueType(), 7909 LN0->getMemOperand()); 7910 7911 ExtendSetCCUses(SetCCs, N0, ExtLoad, SDLoc(N), ISD::ZERO_EXTEND); 7912 // If the load value is used only by N, replace it via CombineTo N. 7913 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 7914 CombineTo(N, ExtLoad); 7915 if (NoReplaceTrunc) { 7916 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7917 } else { 7918 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7919 N0.getValueType(), ExtLoad); 7920 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 7921 } 7922 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7923 } 7924 } 7925 7926 // fold (zext (load x)) to multiple smaller zextloads. 7927 // Only on illegal but splittable vectors. 7928 if (SDValue ExtLoad = CombineExtLoad(N)) 7929 return ExtLoad; 7930 7931 // fold (zext (and/or/xor (load x), cst)) -> 7932 // (and/or/xor (zextload x), (zext cst)) 7933 // Unless (and (load x) cst) will match as a zextload already and has 7934 // additional users. 7935 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 7936 N0.getOpcode() == ISD::XOR) && 7937 isa<LoadSDNode>(N0.getOperand(0)) && 7938 N0.getOperand(1).getOpcode() == ISD::Constant && 7939 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 7940 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0)); 7941 EVT MemVT = LN00->getMemoryVT(); 7942 if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) && 7943 LN00->getExtensionType() != ISD::SEXTLOAD && LN00->isUnindexed()) { 7944 bool DoXform = true; 7945 SmallVector<SDNode*, 4> SetCCs; 7946 if (!N0.hasOneUse()) { 7947 if (N0.getOpcode() == ISD::AND) { 7948 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 7949 EVT LoadResultTy = AndC->getValueType(0); 7950 EVT ExtVT; 7951 if (isAndLoadExtLoad(AndC, LN00, LoadResultTy, ExtVT)) 7952 DoXform = false; 7953 } 7954 } 7955 if (DoXform) 7956 DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0), 7957 ISD::ZERO_EXTEND, SetCCs, TLI); 7958 if (DoXform) { 7959 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN00), VT, 7960 LN00->getChain(), LN00->getBasePtr(), 7961 LN00->getMemoryVT(), 7962 LN00->getMemOperand()); 7963 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7964 Mask = Mask.zext(VT.getSizeInBits()); 7965 SDLoc DL(N); 7966 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 7967 ExtLoad, DAG.getConstant(Mask, DL, VT)); 7968 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, DL, 7969 ISD::ZERO_EXTEND); 7970 bool NoReplaceTruncAnd = !N0.hasOneUse(); 7971 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse(); 7972 CombineTo(N, And); 7973 // If N0 has multiple uses, change other uses as well. 7974 if (NoReplaceTruncAnd) { 7975 SDValue TruncAnd = 7976 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 7977 CombineTo(N0.getNode(), TruncAnd); 7978 } 7979 if (NoReplaceTrunc) { 7980 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1)); 7981 } else { 7982 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00), 7983 LN00->getValueType(0), ExtLoad); 7984 CombineTo(LN00, Trunc, ExtLoad.getValue(1)); 7985 } 7986 return SDValue(N,0); // Return N so it doesn't get rechecked! 7987 } 7988 } 7989 } 7990 7991 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 7992 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 7993 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 7994 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 7995 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7996 EVT MemVT = LN0->getMemoryVT(); 7997 if ((!LegalOperations && !LN0->isVolatile()) || 7998 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 7999 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 8000 LN0->getChain(), 8001 LN0->getBasePtr(), MemVT, 8002 LN0->getMemOperand()); 8003 CombineTo(N, ExtLoad); 8004 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 8005 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8006 } 8007 } 8008 8009 if (N0.getOpcode() == ISD::SETCC) { 8010 // Only do this before legalize for now. 8011 if (!LegalOperations && VT.isVector() && 8012 N0.getValueType().getVectorElementType() == MVT::i1) { 8013 EVT N00VT = N0.getOperand(0).getValueType(); 8014 if (getSetCCResultType(N00VT) == N0.getValueType()) 8015 return SDValue(); 8016 8017 // We know that the # elements of the results is the same as the # 8018 // elements of the compare (and the # elements of the compare result for 8019 // that matter). Check to see that they are the same size. If so, we know 8020 // that the element size of the sext'd result matches the element size of 8021 // the compare operands. 8022 SDLoc DL(N); 8023 SDValue VecOnes = DAG.getConstant(1, DL, VT); 8024 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 8025 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 8026 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 8027 N0.getOperand(1), N0.getOperand(2)); 8028 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes); 8029 } 8030 8031 // If the desired elements are smaller or larger than the source 8032 // elements we can use a matching integer vector type and then 8033 // truncate/sign extend. 8034 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); 8035 SDValue VsetCC = 8036 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 8037 N0.getOperand(1), N0.getOperand(2)); 8038 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT), 8039 VecOnes); 8040 } 8041 8042 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 8043 SDLoc DL(N); 8044 if (SDValue SCC = SimplifySelectCC( 8045 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 8046 DAG.getConstant(0, DL, VT), 8047 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 8048 return SCC; 8049 } 8050 8051 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 8052 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 8053 isa<ConstantSDNode>(N0.getOperand(1)) && 8054 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 8055 N0.hasOneUse()) { 8056 SDValue ShAmt = N0.getOperand(1); 8057 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 8058 if (N0.getOpcode() == ISD::SHL) { 8059 SDValue InnerZExt = N0.getOperand(0); 8060 // If the original shl may be shifting out bits, do not perform this 8061 // transformation. 8062 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() - 8063 InnerZExt.getOperand(0).getValueSizeInBits(); 8064 if (ShAmtVal > KnownZeroBits) 8065 return SDValue(); 8066 } 8067 8068 SDLoc DL(N); 8069 8070 // Ensure that the shift amount is wide enough for the shifted value. 8071 if (VT.getSizeInBits() >= 256) 8072 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 8073 8074 return DAG.getNode(N0.getOpcode(), DL, VT, 8075 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 8076 ShAmt); 8077 } 8078 8079 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 8080 return NewVSel; 8081 8082 return SDValue(); 8083 } 8084 8085 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 8086 SDValue N0 = N->getOperand(0); 8087 EVT VT = N->getValueType(0); 8088 8089 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8090 LegalOperations)) 8091 return SDValue(Res, 0); 8092 8093 // fold (aext (aext x)) -> (aext x) 8094 // fold (aext (zext x)) -> (zext x) 8095 // fold (aext (sext x)) -> (sext x) 8096 if (N0.getOpcode() == ISD::ANY_EXTEND || 8097 N0.getOpcode() == ISD::ZERO_EXTEND || 8098 N0.getOpcode() == ISD::SIGN_EXTEND) 8099 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 8100 8101 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 8102 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 8103 if (N0.getOpcode() == ISD::TRUNCATE) { 8104 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 8105 SDNode *oye = N0.getOperand(0).getNode(); 8106 if (NarrowLoad.getNode() != N0.getNode()) { 8107 CombineTo(N0.getNode(), NarrowLoad); 8108 // CombineTo deleted the truncate, if needed, but not what's under it. 8109 AddToWorklist(oye); 8110 } 8111 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8112 } 8113 } 8114 8115 // fold (aext (truncate x)) 8116 if (N0.getOpcode() == ISD::TRUNCATE) 8117 return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 8118 8119 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 8120 // if the trunc is not free. 8121 if (N0.getOpcode() == ISD::AND && 8122 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 8123 N0.getOperand(1).getOpcode() == ISD::Constant && 8124 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 8125 N0.getValueType())) { 8126 SDLoc DL(N); 8127 SDValue X = N0.getOperand(0).getOperand(0); 8128 X = DAG.getAnyExtOrTrunc(X, DL, VT); 8129 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 8130 Mask = Mask.zext(VT.getSizeInBits()); 8131 return DAG.getNode(ISD::AND, DL, VT, 8132 X, DAG.getConstant(Mask, DL, VT)); 8133 } 8134 8135 // fold (aext (load x)) -> (aext (truncate (extload x))) 8136 // None of the supported targets knows how to perform load and any_ext 8137 // on vectors in one instruction. We only perform this transformation on 8138 // scalars. 8139 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 8140 ISD::isUNINDEXEDLoad(N0.getNode()) && 8141 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 8142 bool DoXform = true; 8143 SmallVector<SDNode*, 4> SetCCs; 8144 if (!N0.hasOneUse()) 8145 DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ISD::ANY_EXTEND, SetCCs, 8146 TLI); 8147 if (DoXform) { 8148 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8149 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 8150 LN0->getChain(), 8151 LN0->getBasePtr(), N0.getValueType(), 8152 LN0->getMemOperand()); 8153 ExtendSetCCUses(SetCCs, N0, ExtLoad, SDLoc(N), 8154 ISD::ANY_EXTEND); 8155 // If the load value is used only by N, replace it via CombineTo N. 8156 bool NoReplaceTrunc = N0.hasOneUse(); 8157 CombineTo(N, ExtLoad); 8158 if (NoReplaceTrunc) { 8159 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 8160 } else { 8161 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 8162 N0.getValueType(), ExtLoad); 8163 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 8164 } 8165 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8166 } 8167 } 8168 8169 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 8170 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 8171 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 8172 if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.getNode()) && 8173 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 8174 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8175 ISD::LoadExtType ExtType = LN0->getExtensionType(); 8176 EVT MemVT = LN0->getMemoryVT(); 8177 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 8178 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 8179 VT, LN0->getChain(), LN0->getBasePtr(), 8180 MemVT, LN0->getMemOperand()); 8181 CombineTo(N, ExtLoad); 8182 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 8183 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8184 } 8185 } 8186 8187 if (N0.getOpcode() == ISD::SETCC) { 8188 // For vectors: 8189 // aext(setcc) -> vsetcc 8190 // aext(setcc) -> truncate(vsetcc) 8191 // aext(setcc) -> aext(vsetcc) 8192 // Only do this before legalize for now. 8193 if (VT.isVector() && !LegalOperations) { 8194 EVT N00VT = N0.getOperand(0).getValueType(); 8195 if (getSetCCResultType(N00VT) == N0.getValueType()) 8196 return SDValue(); 8197 8198 // We know that the # elements of the results is the same as the 8199 // # elements of the compare (and the # elements of the compare result 8200 // for that matter). Check to see that they are the same size. If so, 8201 // we know that the element size of the sext'd result matches the 8202 // element size of the compare operands. 8203 if (VT.getSizeInBits() == N00VT.getSizeInBits()) 8204 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 8205 N0.getOperand(1), 8206 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 8207 // If the desired elements are smaller or larger than the source 8208 // elements we can use a matching integer vector type and then 8209 // truncate/any extend 8210 else { 8211 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); 8212 SDValue VsetCC = 8213 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 8214 N0.getOperand(1), 8215 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 8216 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 8217 } 8218 } 8219 8220 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 8221 SDLoc DL(N); 8222 if (SDValue SCC = SimplifySelectCC( 8223 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 8224 DAG.getConstant(0, DL, VT), 8225 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 8226 return SCC; 8227 } 8228 8229 return SDValue(); 8230 } 8231 8232 SDValue DAGCombiner::visitAssertExt(SDNode *N) { 8233 unsigned Opcode = N->getOpcode(); 8234 SDValue N0 = N->getOperand(0); 8235 SDValue N1 = N->getOperand(1); 8236 EVT AssertVT = cast<VTSDNode>(N1)->getVT(); 8237 8238 // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt) 8239 if (N0.getOpcode() == Opcode && 8240 AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT()) 8241 return N0; 8242 8243 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && 8244 N0.getOperand(0).getOpcode() == Opcode) { 8245 // We have an assert, truncate, assert sandwich. Make one stronger assert 8246 // by asserting on the smallest asserted type to the larger source type. 8247 // This eliminates the later assert: 8248 // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN 8249 // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN 8250 SDValue BigA = N0.getOperand(0); 8251 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT(); 8252 assert(BigA_AssertVT.bitsLE(N0.getValueType()) && 8253 "Asserting zero/sign-extended bits to a type larger than the " 8254 "truncated destination does not provide information"); 8255 8256 SDLoc DL(N); 8257 EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT; 8258 SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT); 8259 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(), 8260 BigA.getOperand(0), MinAssertVTVal); 8261 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert); 8262 } 8263 8264 return SDValue(); 8265 } 8266 8267 /// If the result of a wider load is shifted to right of N bits and then 8268 /// truncated to a narrower type and where N is a multiple of number of bits of 8269 /// the narrower type, transform it to a narrower load from address + N / num of 8270 /// bits of new type. Also narrow the load if the result is masked with an AND 8271 /// to effectively produce a smaller type. If the result is to be extended, also 8272 /// fold the extension to form a extending load. 8273 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 8274 unsigned Opc = N->getOpcode(); 8275 8276 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 8277 SDValue N0 = N->getOperand(0); 8278 EVT VT = N->getValueType(0); 8279 EVT ExtVT = VT; 8280 8281 // This transformation isn't valid for vector loads. 8282 if (VT.isVector()) 8283 return SDValue(); 8284 8285 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 8286 // extended to VT. 8287 if (Opc == ISD::SIGN_EXTEND_INREG) { 8288 ExtType = ISD::SEXTLOAD; 8289 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8290 } else if (Opc == ISD::SRL) { 8291 // Another special-case: SRL is basically zero-extending a narrower value, 8292 // or it maybe shifting a higher subword, half or byte into the lowest 8293 // bits. 8294 ExtType = ISD::ZEXTLOAD; 8295 N0 = SDValue(N, 0); 8296 8297 auto *LN0 = dyn_cast<LoadSDNode>(N0.getOperand(0)); 8298 auto *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8299 if (!N01 || !LN0) 8300 return SDValue(); 8301 8302 uint64_t ShiftAmt = N01->getZExtValue(); 8303 uint64_t MemoryWidth = LN0->getMemoryVT().getSizeInBits(); 8304 if (LN0->getExtensionType() != ISD::SEXTLOAD && MemoryWidth > ShiftAmt) 8305 ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShiftAmt); 8306 else 8307 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 8308 VT.getSizeInBits() - ShiftAmt); 8309 } else if (Opc == ISD::AND) { 8310 // An AND with a constant mask is the same as a truncate + zero-extend. 8311 auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8312 if (!AndC || !AndC->getAPIntValue().isMask()) 8313 return SDValue(); 8314 8315 unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes(); 8316 ExtType = ISD::ZEXTLOAD; 8317 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 8318 } 8319 8320 unsigned ShAmt = 0; 8321 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 8322 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 8323 ShAmt = N01->getZExtValue(); 8324 unsigned EVTBits = ExtVT.getSizeInBits(); 8325 // Is the shift amount a multiple of size of VT? 8326 if ((ShAmt & (EVTBits-1)) == 0) { 8327 N0 = N0.getOperand(0); 8328 // Is the load width a multiple of size of VT? 8329 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0) 8330 return SDValue(); 8331 } 8332 8333 // At this point, we must have a load or else we can't do the transform. 8334 if (!isa<LoadSDNode>(N0)) return SDValue(); 8335 8336 // Because a SRL must be assumed to *need* to zero-extend the high bits 8337 // (as opposed to anyext the high bits), we can't combine the zextload 8338 // lowering of SRL and an sextload. 8339 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 8340 return SDValue(); 8341 8342 // If the shift amount is larger than the input type then we're not 8343 // accessing any of the loaded bytes. If the load was a zextload/extload 8344 // then the result of the shift+trunc is zero/undef (handled elsewhere). 8345 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 8346 return SDValue(); 8347 } 8348 } 8349 8350 // If the load is shifted left (and the result isn't shifted back right), 8351 // we can fold the truncate through the shift. 8352 unsigned ShLeftAmt = 0; 8353 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 8354 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 8355 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 8356 ShLeftAmt = N01->getZExtValue(); 8357 N0 = N0.getOperand(0); 8358 } 8359 } 8360 8361 // If we haven't found a load, we can't narrow it. 8362 if (!isa<LoadSDNode>(N0)) 8363 return SDValue(); 8364 8365 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8366 if (!isLegalNarrowLoad(LN0, ExtType, ExtVT, ShAmt)) 8367 return SDValue(); 8368 8369 // For big endian targets, we need to adjust the offset to the pointer to 8370 // load the correct bytes. 8371 if (DAG.getDataLayout().isBigEndian()) { 8372 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 8373 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 8374 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 8375 } 8376 8377 EVT PtrType = N0.getOperand(1).getValueType(); 8378 uint64_t PtrOff = ShAmt / 8; 8379 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 8380 SDLoc DL(LN0); 8381 // The original load itself didn't wrap, so an offset within it doesn't. 8382 SDNodeFlags Flags; 8383 Flags.setNoUnsignedWrap(true); 8384 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 8385 PtrType, LN0->getBasePtr(), 8386 DAG.getConstant(PtrOff, DL, PtrType), 8387 Flags); 8388 AddToWorklist(NewPtr.getNode()); 8389 8390 SDValue Load; 8391 if (ExtType == ISD::NON_EXTLOAD) 8392 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 8393 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 8394 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8395 else 8396 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr, 8397 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 8398 NewAlign, LN0->getMemOperand()->getFlags(), 8399 LN0->getAAInfo()); 8400 8401 // Replace the old load's chain with the new load's chain. 8402 WorklistRemover DeadNodes(*this); 8403 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 8404 8405 // Shift the result left, if we've swallowed a left shift. 8406 SDValue Result = Load; 8407 if (ShLeftAmt != 0) { 8408 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 8409 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 8410 ShImmTy = VT; 8411 // If the shift amount is as large as the result size (but, presumably, 8412 // no larger than the source) then the useful bits of the result are 8413 // zero; we can't simply return the shortened shift, because the result 8414 // of that operation is undefined. 8415 SDLoc DL(N0); 8416 if (ShLeftAmt >= VT.getSizeInBits()) 8417 Result = DAG.getConstant(0, DL, VT); 8418 else 8419 Result = DAG.getNode(ISD::SHL, DL, VT, 8420 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 8421 } 8422 8423 // Return the new loaded value. 8424 return Result; 8425 } 8426 8427 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 8428 SDValue N0 = N->getOperand(0); 8429 SDValue N1 = N->getOperand(1); 8430 EVT VT = N->getValueType(0); 8431 EVT EVT = cast<VTSDNode>(N1)->getVT(); 8432 unsigned VTBits = VT.getScalarSizeInBits(); 8433 unsigned EVTBits = EVT.getScalarSizeInBits(); 8434 8435 if (N0.isUndef()) 8436 return DAG.getUNDEF(VT); 8437 8438 // fold (sext_in_reg c1) -> c1 8439 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 8440 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 8441 8442 // If the input is already sign extended, just drop the extension. 8443 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 8444 return N0; 8445 8446 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 8447 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 8448 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 8449 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 8450 N0.getOperand(0), N1); 8451 8452 // fold (sext_in_reg (sext x)) -> (sext x) 8453 // fold (sext_in_reg (aext x)) -> (sext x) 8454 // if x is small enough. 8455 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 8456 SDValue N00 = N0.getOperand(0); 8457 if (N00.getScalarValueSizeInBits() <= EVTBits && 8458 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 8459 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 8460 } 8461 8462 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_inreg x) 8463 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG || 8464 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG || 8465 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) && 8466 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) { 8467 if (!LegalOperations || 8468 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT)) 8469 return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT); 8470 } 8471 8472 // fold (sext_in_reg (zext x)) -> (sext x) 8473 // iff we are extending the source sign bit. 8474 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 8475 SDValue N00 = N0.getOperand(0); 8476 if (N00.getScalarValueSizeInBits() == EVTBits && 8477 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 8478 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 8479 } 8480 8481 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 8482 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1))) 8483 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType()); 8484 8485 // fold operands of sext_in_reg based on knowledge that the top bits are not 8486 // demanded. 8487 if (SimplifyDemandedBits(SDValue(N, 0))) 8488 return SDValue(N, 0); 8489 8490 // fold (sext_in_reg (load x)) -> (smaller sextload x) 8491 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 8492 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 8493 return NarrowLoad; 8494 8495 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 8496 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 8497 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 8498 if (N0.getOpcode() == ISD::SRL) { 8499 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 8500 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 8501 // We can turn this into an SRA iff the input to the SRL is already sign 8502 // extended enough. 8503 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 8504 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 8505 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 8506 N0.getOperand(0), N0.getOperand(1)); 8507 } 8508 } 8509 8510 // fold (sext_inreg (extload x)) -> (sextload x) 8511 // If sextload is not supported by target, we can only do the combine when 8512 // load has one use. Doing otherwise can block folding the extload with other 8513 // extends that the target does support. 8514 if (ISD::isEXTLoad(N0.getNode()) && 8515 ISD::isUNINDEXEDLoad(N0.getNode()) && 8516 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 8517 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile() && 8518 N0.hasOneUse()) || 8519 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 8520 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8521 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 8522 LN0->getChain(), 8523 LN0->getBasePtr(), EVT, 8524 LN0->getMemOperand()); 8525 CombineTo(N, ExtLoad); 8526 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 8527 AddToWorklist(ExtLoad.getNode()); 8528 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8529 } 8530 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 8531 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 8532 N0.hasOneUse() && 8533 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 8534 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 8535 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 8536 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8537 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 8538 LN0->getChain(), 8539 LN0->getBasePtr(), EVT, 8540 LN0->getMemOperand()); 8541 CombineTo(N, ExtLoad); 8542 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 8543 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8544 } 8545 8546 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 8547 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 8548 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 8549 N0.getOperand(1), false)) 8550 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 8551 BSwap, N1); 8552 } 8553 8554 return SDValue(); 8555 } 8556 8557 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 8558 SDValue N0 = N->getOperand(0); 8559 EVT VT = N->getValueType(0); 8560 8561 if (N0.isUndef()) 8562 return DAG.getUNDEF(VT); 8563 8564 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8565 LegalOperations)) 8566 return SDValue(Res, 0); 8567 8568 return SDValue(); 8569 } 8570 8571 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 8572 SDValue N0 = N->getOperand(0); 8573 EVT VT = N->getValueType(0); 8574 8575 if (N0.isUndef()) 8576 return DAG.getUNDEF(VT); 8577 8578 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8579 LegalOperations)) 8580 return SDValue(Res, 0); 8581 8582 return SDValue(); 8583 } 8584 8585 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 8586 SDValue N0 = N->getOperand(0); 8587 EVT VT = N->getValueType(0); 8588 bool isLE = DAG.getDataLayout().isLittleEndian(); 8589 8590 // noop truncate 8591 if (N0.getValueType() == N->getValueType(0)) 8592 return N0; 8593 8594 // fold (truncate (truncate x)) -> (truncate x) 8595 if (N0.getOpcode() == ISD::TRUNCATE) 8596 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 8597 8598 // fold (truncate c1) -> c1 8599 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 8600 SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 8601 if (C.getNode() != N) 8602 return C; 8603 } 8604 8605 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 8606 if (N0.getOpcode() == ISD::ZERO_EXTEND || 8607 N0.getOpcode() == ISD::SIGN_EXTEND || 8608 N0.getOpcode() == ISD::ANY_EXTEND) { 8609 // if the source is smaller than the dest, we still need an extend. 8610 if (N0.getOperand(0).getValueType().bitsLT(VT)) 8611 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 8612 // if the source is larger than the dest, than we just need the truncate. 8613 if (N0.getOperand(0).getValueType().bitsGT(VT)) 8614 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 8615 // if the source and dest are the same type, we can drop both the extend 8616 // and the truncate. 8617 return N0.getOperand(0); 8618 } 8619 8620 // If this is anyext(trunc), don't fold it, allow ourselves to be folded. 8621 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND)) 8622 return SDValue(); 8623 8624 // Fold extract-and-trunc into a narrow extract. For example: 8625 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 8626 // i32 y = TRUNCATE(i64 x) 8627 // -- becomes -- 8628 // v16i8 b = BITCAST (v2i64 val) 8629 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 8630 // 8631 // Note: We only run this optimization after type legalization (which often 8632 // creates this pattern) and before operation legalization after which 8633 // we need to be more careful about the vector instructions that we generate. 8634 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 8635 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 8636 EVT VecTy = N0.getOperand(0).getValueType(); 8637 EVT ExTy = N0.getValueType(); 8638 EVT TrTy = N->getValueType(0); 8639 8640 unsigned NumElem = VecTy.getVectorNumElements(); 8641 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 8642 8643 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 8644 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 8645 8646 SDValue EltNo = N0->getOperand(1); 8647 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 8648 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 8649 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 8650 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 8651 8652 SDLoc DL(N); 8653 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 8654 DAG.getBitcast(NVT, N0.getOperand(0)), 8655 DAG.getConstant(Index, DL, IndexTy)); 8656 } 8657 } 8658 8659 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 8660 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) { 8661 EVT SrcVT = N0.getValueType(); 8662 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 8663 TLI.isTruncateFree(SrcVT, VT)) { 8664 SDLoc SL(N0); 8665 SDValue Cond = N0.getOperand(0); 8666 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 8667 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 8668 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 8669 } 8670 } 8671 8672 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits() 8673 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 8674 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 8675 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 8676 SDValue Amt = N0.getOperand(1); 8677 KnownBits Known; 8678 DAG.computeKnownBits(Amt, Known); 8679 unsigned Size = VT.getScalarSizeInBits(); 8680 if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) { 8681 SDLoc SL(N); 8682 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 8683 8684 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 8685 if (AmtVT != Amt.getValueType()) { 8686 Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT); 8687 AddToWorklist(Amt.getNode()); 8688 } 8689 return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt); 8690 } 8691 } 8692 8693 // Fold a series of buildvector, bitcast, and truncate if possible. 8694 // For example fold 8695 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 8696 // (2xi32 (buildvector x, y)). 8697 if (Level == AfterLegalizeVectorOps && VT.isVector() && 8698 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 8699 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 8700 N0.getOperand(0).hasOneUse()) { 8701 SDValue BuildVect = N0.getOperand(0); 8702 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 8703 EVT TruncVecEltTy = VT.getVectorElementType(); 8704 8705 // Check that the element types match. 8706 if (BuildVectEltTy == TruncVecEltTy) { 8707 // Now we only need to compute the offset of the truncated elements. 8708 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 8709 unsigned TruncVecNumElts = VT.getVectorNumElements(); 8710 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 8711 8712 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 8713 "Invalid number of elements"); 8714 8715 SmallVector<SDValue, 8> Opnds; 8716 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 8717 Opnds.push_back(BuildVect.getOperand(i)); 8718 8719 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 8720 } 8721 } 8722 8723 // See if we can simplify the input to this truncate through knowledge that 8724 // only the low bits are being used. 8725 // For example "trunc (or (shl x, 8), y)" // -> trunc y 8726 // Currently we only perform this optimization on scalars because vectors 8727 // may have different active low bits. 8728 if (!VT.isVector()) { 8729 APInt Mask = 8730 APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits()); 8731 if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask)) 8732 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 8733 } 8734 8735 // fold (truncate (load x)) -> (smaller load x) 8736 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 8737 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 8738 if (SDValue Reduced = ReduceLoadWidth(N)) 8739 return Reduced; 8740 8741 // Handle the case where the load remains an extending load even 8742 // after truncation. 8743 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 8744 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8745 if (!LN0->isVolatile() && 8746 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 8747 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 8748 VT, LN0->getChain(), LN0->getBasePtr(), 8749 LN0->getMemoryVT(), 8750 LN0->getMemOperand()); 8751 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 8752 return NewLoad; 8753 } 8754 } 8755 } 8756 8757 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 8758 // where ... are all 'undef'. 8759 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 8760 SmallVector<EVT, 8> VTs; 8761 SDValue V; 8762 unsigned Idx = 0; 8763 unsigned NumDefs = 0; 8764 8765 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 8766 SDValue X = N0.getOperand(i); 8767 if (!X.isUndef()) { 8768 V = X; 8769 Idx = i; 8770 NumDefs++; 8771 } 8772 // Stop if more than one members are non-undef. 8773 if (NumDefs > 1) 8774 break; 8775 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 8776 VT.getVectorElementType(), 8777 X.getValueType().getVectorNumElements())); 8778 } 8779 8780 if (NumDefs == 0) 8781 return DAG.getUNDEF(VT); 8782 8783 if (NumDefs == 1) { 8784 assert(V.getNode() && "The single defined operand is empty!"); 8785 SmallVector<SDValue, 8> Opnds; 8786 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 8787 if (i != Idx) { 8788 Opnds.push_back(DAG.getUNDEF(VTs[i])); 8789 continue; 8790 } 8791 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 8792 AddToWorklist(NV.getNode()); 8793 Opnds.push_back(NV); 8794 } 8795 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 8796 } 8797 } 8798 8799 // Fold truncate of a bitcast of a vector to an extract of the low vector 8800 // element. 8801 // 8802 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx 8803 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 8804 SDValue VecSrc = N0.getOperand(0); 8805 EVT SrcVT = VecSrc.getValueType(); 8806 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 8807 (!LegalOperations || 8808 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 8809 SDLoc SL(N); 8810 8811 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 8812 unsigned Idx = isLE ? 0 : SrcVT.getVectorNumElements() - 1; 8813 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 8814 VecSrc, DAG.getConstant(Idx, SL, IdxVT)); 8815 } 8816 } 8817 8818 // Simplify the operands using demanded-bits information. 8819 if (!VT.isVector() && 8820 SimplifyDemandedBits(SDValue(N, 0))) 8821 return SDValue(N, 0); 8822 8823 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry) 8824 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry) 8825 // When the adde's carry is not used. 8826 if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) && 8827 N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) && 8828 (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) { 8829 SDLoc SL(N); 8830 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 8831 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 8832 auto VTs = DAG.getVTList(VT, N0->getValueType(1)); 8833 return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2)); 8834 } 8835 8836 // fold (truncate (extract_subvector(ext x))) -> 8837 // (extract_subvector x) 8838 // TODO: This can be generalized to cover cases where the truncate and extract 8839 // do not fully cancel each other out. 8840 if (!LegalTypes && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 8841 SDValue N00 = N0.getOperand(0); 8842 if (N00.getOpcode() == ISD::SIGN_EXTEND || 8843 N00.getOpcode() == ISD::ZERO_EXTEND || 8844 N00.getOpcode() == ISD::ANY_EXTEND) { 8845 if (N00.getOperand(0)->getValueType(0).getVectorElementType() == 8846 VT.getVectorElementType()) 8847 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N0->getOperand(0)), VT, 8848 N00.getOperand(0), N0.getOperand(1)); 8849 } 8850 } 8851 8852 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 8853 return NewVSel; 8854 8855 return SDValue(); 8856 } 8857 8858 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 8859 SDValue Elt = N->getOperand(i); 8860 if (Elt.getOpcode() != ISD::MERGE_VALUES) 8861 return Elt.getNode(); 8862 return Elt.getOperand(Elt.getResNo()).getNode(); 8863 } 8864 8865 /// build_pair (load, load) -> load 8866 /// if load locations are consecutive. 8867 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 8868 assert(N->getOpcode() == ISD::BUILD_PAIR); 8869 8870 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 8871 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 8872 8873 // A BUILD_PAIR is always having the least significant part in elt 0 and the 8874 // most significant part in elt 1. So when combining into one large load, we 8875 // need to consider the endianness. 8876 if (DAG.getDataLayout().isBigEndian()) 8877 std::swap(LD1, LD2); 8878 8879 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 8880 LD1->getAddressSpace() != LD2->getAddressSpace()) 8881 return SDValue(); 8882 EVT LD1VT = LD1->getValueType(0); 8883 unsigned LD1Bytes = LD1VT.getStoreSize(); 8884 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 8885 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 8886 unsigned Align = LD1->getAlignment(); 8887 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 8888 VT.getTypeForEVT(*DAG.getContext())); 8889 8890 if (NewAlign <= Align && 8891 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 8892 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 8893 LD1->getPointerInfo(), Align); 8894 } 8895 8896 return SDValue(); 8897 } 8898 8899 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 8900 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 8901 // and Lo parts; on big-endian machines it doesn't. 8902 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 8903 } 8904 8905 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 8906 const TargetLowering &TLI) { 8907 // If this is not a bitcast to an FP type or if the target doesn't have 8908 // IEEE754-compliant FP logic, we're done. 8909 EVT VT = N->getValueType(0); 8910 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 8911 return SDValue(); 8912 8913 // TODO: Use splat values for the constant-checking below and remove this 8914 // restriction. 8915 SDValue N0 = N->getOperand(0); 8916 EVT SourceVT = N0.getValueType(); 8917 if (SourceVT.isVector()) 8918 return SDValue(); 8919 8920 unsigned FPOpcode; 8921 APInt SignMask; 8922 switch (N0.getOpcode()) { 8923 case ISD::AND: 8924 FPOpcode = ISD::FABS; 8925 SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits()); 8926 break; 8927 case ISD::XOR: 8928 FPOpcode = ISD::FNEG; 8929 SignMask = APInt::getSignMask(SourceVT.getSizeInBits()); 8930 break; 8931 // TODO: ISD::OR --> ISD::FNABS? 8932 default: 8933 return SDValue(); 8934 } 8935 8936 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 8937 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 8938 SDValue LogicOp0 = N0.getOperand(0); 8939 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8940 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 8941 LogicOp0.getOpcode() == ISD::BITCAST && 8942 LogicOp0->getOperand(0).getValueType() == VT) 8943 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0)); 8944 8945 return SDValue(); 8946 } 8947 8948 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 8949 SDValue N0 = N->getOperand(0); 8950 EVT VT = N->getValueType(0); 8951 8952 if (N0.isUndef()) 8953 return DAG.getUNDEF(VT); 8954 8955 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 8956 // Only do this before legalize, since afterward the target may be depending 8957 // on the bitconvert. 8958 // First check to see if this is all constant. 8959 if (!LegalTypes && 8960 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 8961 VT.isVector()) { 8962 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 8963 8964 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 8965 assert(!DestEltVT.isVector() && 8966 "Element type of vector ValueType must not be vector!"); 8967 if (isSimple) 8968 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 8969 } 8970 8971 // If the input is a constant, let getNode fold it. 8972 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 8973 // If we can't allow illegal operations, we need to check that this is just 8974 // a fp -> int or int -> conversion and that the resulting operation will 8975 // be legal. 8976 if (!LegalOperations || 8977 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 8978 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 8979 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 8980 TLI.isOperationLegal(ISD::Constant, VT))) 8981 return DAG.getBitcast(VT, N0); 8982 } 8983 8984 // (conv (conv x, t1), t2) -> (conv x, t2) 8985 if (N0.getOpcode() == ISD::BITCAST) 8986 return DAG.getBitcast(VT, N0.getOperand(0)); 8987 8988 // fold (conv (load x)) -> (load (conv*)x) 8989 // If the resultant load doesn't need a higher alignment than the original! 8990 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8991 // Do not change the width of a volatile load. 8992 !cast<LoadSDNode>(N0)->isVolatile() && 8993 // Do not remove the cast if the types differ in endian layout. 8994 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 8995 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 8996 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 8997 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 8998 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8999 unsigned OrigAlign = LN0->getAlignment(); 9000 9001 bool Fast = false; 9002 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 9003 LN0->getAddressSpace(), OrigAlign, &Fast) && 9004 Fast) { 9005 SDValue Load = 9006 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 9007 LN0->getPointerInfo(), OrigAlign, 9008 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 9009 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 9010 return Load; 9011 } 9012 } 9013 9014 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 9015 return V; 9016 9017 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 9018 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 9019 // 9020 // For ppc_fp128: 9021 // fold (bitcast (fneg x)) -> 9022 // flipbit = signbit 9023 // (xor (bitcast x) (build_pair flipbit, flipbit)) 9024 // 9025 // fold (bitcast (fabs x)) -> 9026 // flipbit = (and (extract_element (bitcast x), 0), signbit) 9027 // (xor (bitcast x) (build_pair flipbit, flipbit)) 9028 // This often reduces constant pool loads. 9029 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 9030 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 9031 N0.getNode()->hasOneUse() && VT.isInteger() && 9032 !VT.isVector() && !N0.getValueType().isVector()) { 9033 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 9034 AddToWorklist(NewConv.getNode()); 9035 9036 SDLoc DL(N); 9037 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 9038 assert(VT.getSizeInBits() == 128); 9039 SDValue SignBit = DAG.getConstant( 9040 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 9041 SDValue FlipBit; 9042 if (N0.getOpcode() == ISD::FNEG) { 9043 FlipBit = SignBit; 9044 AddToWorklist(FlipBit.getNode()); 9045 } else { 9046 assert(N0.getOpcode() == ISD::FABS); 9047 SDValue Hi = 9048 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 9049 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 9050 SDLoc(NewConv))); 9051 AddToWorklist(Hi.getNode()); 9052 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 9053 AddToWorklist(FlipBit.getNode()); 9054 } 9055 SDValue FlipBits = 9056 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 9057 AddToWorklist(FlipBits.getNode()); 9058 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 9059 } 9060 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 9061 if (N0.getOpcode() == ISD::FNEG) 9062 return DAG.getNode(ISD::XOR, DL, VT, 9063 NewConv, DAG.getConstant(SignBit, DL, VT)); 9064 assert(N0.getOpcode() == ISD::FABS); 9065 return DAG.getNode(ISD::AND, DL, VT, 9066 NewConv, DAG.getConstant(~SignBit, DL, VT)); 9067 } 9068 9069 // fold (bitconvert (fcopysign cst, x)) -> 9070 // (or (and (bitconvert x), sign), (and cst, (not sign))) 9071 // Note that we don't handle (copysign x, cst) because this can always be 9072 // folded to an fneg or fabs. 9073 // 9074 // For ppc_fp128: 9075 // fold (bitcast (fcopysign cst, x)) -> 9076 // flipbit = (and (extract_element 9077 // (xor (bitcast cst), (bitcast x)), 0), 9078 // signbit) 9079 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 9080 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 9081 isa<ConstantFPSDNode>(N0.getOperand(0)) && 9082 VT.isInteger() && !VT.isVector()) { 9083 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits(); 9084 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 9085 if (isTypeLegal(IntXVT)) { 9086 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 9087 AddToWorklist(X.getNode()); 9088 9089 // If X has a different width than the result/lhs, sext it or truncate it. 9090 unsigned VTWidth = VT.getSizeInBits(); 9091 if (OrigXWidth < VTWidth) { 9092 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 9093 AddToWorklist(X.getNode()); 9094 } else if (OrigXWidth > VTWidth) { 9095 // To get the sign bit in the right place, we have to shift it right 9096 // before truncating. 9097 SDLoc DL(X); 9098 X = DAG.getNode(ISD::SRL, DL, 9099 X.getValueType(), X, 9100 DAG.getConstant(OrigXWidth-VTWidth, DL, 9101 X.getValueType())); 9102 AddToWorklist(X.getNode()); 9103 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 9104 AddToWorklist(X.getNode()); 9105 } 9106 9107 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 9108 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2); 9109 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 9110 AddToWorklist(Cst.getNode()); 9111 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 9112 AddToWorklist(X.getNode()); 9113 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 9114 AddToWorklist(XorResult.getNode()); 9115 SDValue XorResult64 = DAG.getNode( 9116 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 9117 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 9118 SDLoc(XorResult))); 9119 AddToWorklist(XorResult64.getNode()); 9120 SDValue FlipBit = 9121 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 9122 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 9123 AddToWorklist(FlipBit.getNode()); 9124 SDValue FlipBits = 9125 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 9126 AddToWorklist(FlipBits.getNode()); 9127 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 9128 } 9129 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 9130 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 9131 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 9132 AddToWorklist(X.getNode()); 9133 9134 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 9135 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 9136 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 9137 AddToWorklist(Cst.getNode()); 9138 9139 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 9140 } 9141 } 9142 9143 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 9144 if (N0.getOpcode() == ISD::BUILD_PAIR) 9145 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 9146 return CombineLD; 9147 9148 // Remove double bitcasts from shuffles - this is often a legacy of 9149 // XformToShuffleWithZero being used to combine bitmaskings (of 9150 // float vectors bitcast to integer vectors) into shuffles. 9151 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 9152 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 9153 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 9154 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 9155 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 9156 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 9157 9158 // If operands are a bitcast, peek through if it casts the original VT. 9159 // If operands are a constant, just bitcast back to original VT. 9160 auto PeekThroughBitcast = [&](SDValue Op) { 9161 if (Op.getOpcode() == ISD::BITCAST && 9162 Op.getOperand(0).getValueType() == VT) 9163 return SDValue(Op.getOperand(0)); 9164 if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 9165 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 9166 return DAG.getBitcast(VT, Op); 9167 return SDValue(); 9168 }; 9169 9170 // FIXME: If either input vector is bitcast, try to convert the shuffle to 9171 // the result type of this bitcast. This would eliminate at least one 9172 // bitcast. See the transform in InstCombine. 9173 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 9174 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 9175 if (!(SV0 && SV1)) 9176 return SDValue(); 9177 9178 int MaskScale = 9179 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 9180 SmallVector<int, 8> NewMask; 9181 for (int M : SVN->getMask()) 9182 for (int i = 0; i != MaskScale; ++i) 9183 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 9184 9185 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 9186 if (!LegalMask) { 9187 std::swap(SV0, SV1); 9188 ShuffleVectorSDNode::commuteMask(NewMask); 9189 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 9190 } 9191 9192 if (LegalMask) 9193 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 9194 } 9195 9196 return SDValue(); 9197 } 9198 9199 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 9200 EVT VT = N->getValueType(0); 9201 return CombineConsecutiveLoads(N, VT); 9202 } 9203 9204 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 9205 /// operands. DstEltVT indicates the destination element value type. 9206 SDValue DAGCombiner:: 9207 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 9208 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 9209 9210 // If this is already the right type, we're done. 9211 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 9212 9213 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 9214 unsigned DstBitSize = DstEltVT.getSizeInBits(); 9215 9216 // If this is a conversion of N elements of one type to N elements of another 9217 // type, convert each element. This handles FP<->INT cases. 9218 if (SrcBitSize == DstBitSize) { 9219 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 9220 BV->getValueType(0).getVectorNumElements()); 9221 9222 // Due to the FP element handling below calling this routine recursively, 9223 // we can end up with a scalar-to-vector node here. 9224 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 9225 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 9226 DAG.getBitcast(DstEltVT, BV->getOperand(0))); 9227 9228 SmallVector<SDValue, 8> Ops; 9229 for (SDValue Op : BV->op_values()) { 9230 // If the vector element type is not legal, the BUILD_VECTOR operands 9231 // are promoted and implicitly truncated. Make that explicit here. 9232 if (Op.getValueType() != SrcEltVT) 9233 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 9234 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 9235 AddToWorklist(Ops.back().getNode()); 9236 } 9237 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 9238 } 9239 9240 // Otherwise, we're growing or shrinking the elements. To avoid having to 9241 // handle annoying details of growing/shrinking FP values, we convert them to 9242 // int first. 9243 if (SrcEltVT.isFloatingPoint()) { 9244 // Convert the input float vector to a int vector where the elements are the 9245 // same sizes. 9246 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 9247 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 9248 SrcEltVT = IntVT; 9249 } 9250 9251 // Now we know the input is an integer vector. If the output is a FP type, 9252 // convert to integer first, then to FP of the right size. 9253 if (DstEltVT.isFloatingPoint()) { 9254 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 9255 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 9256 9257 // Next, convert to FP elements of the same size. 9258 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 9259 } 9260 9261 SDLoc DL(BV); 9262 9263 // Okay, we know the src/dst types are both integers of differing types. 9264 // Handling growing first. 9265 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 9266 if (SrcBitSize < DstBitSize) { 9267 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 9268 9269 SmallVector<SDValue, 8> Ops; 9270 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 9271 i += NumInputsPerOutput) { 9272 bool isLE = DAG.getDataLayout().isLittleEndian(); 9273 APInt NewBits = APInt(DstBitSize, 0); 9274 bool EltIsUndef = true; 9275 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 9276 // Shift the previously computed bits over. 9277 NewBits <<= SrcBitSize; 9278 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 9279 if (Op.isUndef()) continue; 9280 EltIsUndef = false; 9281 9282 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 9283 zextOrTrunc(SrcBitSize).zext(DstBitSize); 9284 } 9285 9286 if (EltIsUndef) 9287 Ops.push_back(DAG.getUNDEF(DstEltVT)); 9288 else 9289 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 9290 } 9291 9292 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 9293 return DAG.getBuildVector(VT, DL, Ops); 9294 } 9295 9296 // Finally, this must be the case where we are shrinking elements: each input 9297 // turns into multiple outputs. 9298 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 9299 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 9300 NumOutputsPerInput*BV->getNumOperands()); 9301 SmallVector<SDValue, 8> Ops; 9302 9303 for (const SDValue &Op : BV->op_values()) { 9304 if (Op.isUndef()) { 9305 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 9306 continue; 9307 } 9308 9309 APInt OpVal = cast<ConstantSDNode>(Op)-> 9310 getAPIntValue().zextOrTrunc(SrcBitSize); 9311 9312 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 9313 APInt ThisVal = OpVal.trunc(DstBitSize); 9314 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 9315 OpVal.lshrInPlace(DstBitSize); 9316 } 9317 9318 // For big endian targets, swap the order of the pieces of each element. 9319 if (DAG.getDataLayout().isBigEndian()) 9320 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 9321 } 9322 9323 return DAG.getBuildVector(VT, DL, Ops); 9324 } 9325 9326 static bool isContractable(SDNode *N) { 9327 SDNodeFlags F = N->getFlags(); 9328 return F.hasAllowContract() || F.hasUnsafeAlgebra(); 9329 } 9330 9331 /// Try to perform FMA combining on a given FADD node. 9332 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 9333 SDValue N0 = N->getOperand(0); 9334 SDValue N1 = N->getOperand(1); 9335 EVT VT = N->getValueType(0); 9336 SDLoc SL(N); 9337 9338 const TargetOptions &Options = DAG.getTarget().Options; 9339 9340 // Floating-point multiply-add with intermediate rounding. 9341 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9342 9343 // Floating-point multiply-add without intermediate rounding. 9344 bool HasFMA = 9345 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9346 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9347 9348 // No valid opcode, do not combine. 9349 if (!HasFMAD && !HasFMA) 9350 return SDValue(); 9351 9352 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 9353 Options.UnsafeFPMath || HasFMAD); 9354 // If the addition is not contractable, do not combine. 9355 if (!AllowFusionGlobally && !isContractable(N)) 9356 return SDValue(); 9357 9358 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 9359 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 9360 return SDValue(); 9361 9362 // Always prefer FMAD to FMA for precision. 9363 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9364 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9365 9366 // Is the node an FMUL and contractable either due to global flags or 9367 // SDNodeFlags. 9368 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 9369 if (N.getOpcode() != ISD::FMUL) 9370 return false; 9371 return AllowFusionGlobally || isContractable(N.getNode()); 9372 }; 9373 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 9374 // prefer to fold the multiply with fewer uses. 9375 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) { 9376 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 9377 std::swap(N0, N1); 9378 } 9379 9380 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 9381 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 9382 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9383 N0.getOperand(0), N0.getOperand(1), N1); 9384 } 9385 9386 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 9387 // Note: Commutes FADD operands. 9388 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) { 9389 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9390 N1.getOperand(0), N1.getOperand(1), N0); 9391 } 9392 9393 // Look through FP_EXTEND nodes to do more combining. 9394 9395 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 9396 if (N0.getOpcode() == ISD::FP_EXTEND) { 9397 SDValue N00 = N0.getOperand(0); 9398 if (isContractableFMUL(N00) && 9399 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 9400 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9401 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9402 N00.getOperand(0)), 9403 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9404 N00.getOperand(1)), N1); 9405 } 9406 } 9407 9408 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 9409 // Note: Commutes FADD operands. 9410 if (N1.getOpcode() == ISD::FP_EXTEND) { 9411 SDValue N10 = N1.getOperand(0); 9412 if (isContractableFMUL(N10) && 9413 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 9414 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9415 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9416 N10.getOperand(0)), 9417 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9418 N10.getOperand(1)), N0); 9419 } 9420 } 9421 9422 // More folding opportunities when target permits. 9423 if (Aggressive) { 9424 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 9425 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9426 // are currently only supported on binary nodes. 9427 if (Options.UnsafeFPMath && 9428 N0.getOpcode() == PreferredFusedOpcode && 9429 N0.getOperand(2).getOpcode() == ISD::FMUL && 9430 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) { 9431 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9432 N0.getOperand(0), N0.getOperand(1), 9433 DAG.getNode(PreferredFusedOpcode, SL, VT, 9434 N0.getOperand(2).getOperand(0), 9435 N0.getOperand(2).getOperand(1), 9436 N1)); 9437 } 9438 9439 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 9440 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9441 // are currently only supported on binary nodes. 9442 if (Options.UnsafeFPMath && 9443 N1->getOpcode() == PreferredFusedOpcode && 9444 N1.getOperand(2).getOpcode() == ISD::FMUL && 9445 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) { 9446 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9447 N1.getOperand(0), N1.getOperand(1), 9448 DAG.getNode(PreferredFusedOpcode, SL, VT, 9449 N1.getOperand(2).getOperand(0), 9450 N1.getOperand(2).getOperand(1), 9451 N0)); 9452 } 9453 9454 9455 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 9456 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 9457 auto FoldFAddFMAFPExtFMul = [&] ( 9458 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 9459 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 9460 DAG.getNode(PreferredFusedOpcode, SL, VT, 9461 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 9462 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 9463 Z)); 9464 }; 9465 if (N0.getOpcode() == PreferredFusedOpcode) { 9466 SDValue N02 = N0.getOperand(2); 9467 if (N02.getOpcode() == ISD::FP_EXTEND) { 9468 SDValue N020 = N02.getOperand(0); 9469 if (isContractableFMUL(N020) && 9470 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) { 9471 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 9472 N020.getOperand(0), N020.getOperand(1), 9473 N1); 9474 } 9475 } 9476 } 9477 9478 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 9479 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 9480 // FIXME: This turns two single-precision and one double-precision 9481 // operation into two double-precision operations, which might not be 9482 // interesting for all targets, especially GPUs. 9483 auto FoldFAddFPExtFMAFMul = [&] ( 9484 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 9485 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9486 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 9487 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 9488 DAG.getNode(PreferredFusedOpcode, SL, VT, 9489 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 9490 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 9491 Z)); 9492 }; 9493 if (N0.getOpcode() == ISD::FP_EXTEND) { 9494 SDValue N00 = N0.getOperand(0); 9495 if (N00.getOpcode() == PreferredFusedOpcode) { 9496 SDValue N002 = N00.getOperand(2); 9497 if (isContractableFMUL(N002) && 9498 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 9499 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 9500 N002.getOperand(0), N002.getOperand(1), 9501 N1); 9502 } 9503 } 9504 } 9505 9506 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 9507 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 9508 if (N1.getOpcode() == PreferredFusedOpcode) { 9509 SDValue N12 = N1.getOperand(2); 9510 if (N12.getOpcode() == ISD::FP_EXTEND) { 9511 SDValue N120 = N12.getOperand(0); 9512 if (isContractableFMUL(N120) && 9513 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) { 9514 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 9515 N120.getOperand(0), N120.getOperand(1), 9516 N0); 9517 } 9518 } 9519 } 9520 9521 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 9522 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 9523 // FIXME: This turns two single-precision and one double-precision 9524 // operation into two double-precision operations, which might not be 9525 // interesting for all targets, especially GPUs. 9526 if (N1.getOpcode() == ISD::FP_EXTEND) { 9527 SDValue N10 = N1.getOperand(0); 9528 if (N10.getOpcode() == PreferredFusedOpcode) { 9529 SDValue N102 = N10.getOperand(2); 9530 if (isContractableFMUL(N102) && 9531 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 9532 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 9533 N102.getOperand(0), N102.getOperand(1), 9534 N0); 9535 } 9536 } 9537 } 9538 } 9539 9540 return SDValue(); 9541 } 9542 9543 /// Try to perform FMA combining on a given FSUB node. 9544 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 9545 SDValue N0 = N->getOperand(0); 9546 SDValue N1 = N->getOperand(1); 9547 EVT VT = N->getValueType(0); 9548 SDLoc SL(N); 9549 9550 const TargetOptions &Options = DAG.getTarget().Options; 9551 // Floating-point multiply-add with intermediate rounding. 9552 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9553 9554 // Floating-point multiply-add without intermediate rounding. 9555 bool HasFMA = 9556 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9557 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9558 9559 // No valid opcode, do not combine. 9560 if (!HasFMAD && !HasFMA) 9561 return SDValue(); 9562 9563 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 9564 Options.UnsafeFPMath || HasFMAD); 9565 // If the subtraction is not contractable, do not combine. 9566 if (!AllowFusionGlobally && !isContractable(N)) 9567 return SDValue(); 9568 9569 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 9570 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 9571 return SDValue(); 9572 9573 // Always prefer FMAD to FMA for precision. 9574 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9575 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9576 9577 // Is the node an FMUL and contractable either due to global flags or 9578 // SDNodeFlags. 9579 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 9580 if (N.getOpcode() != ISD::FMUL) 9581 return false; 9582 return AllowFusionGlobally || isContractable(N.getNode()); 9583 }; 9584 9585 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 9586 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 9587 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9588 N0.getOperand(0), N0.getOperand(1), 9589 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9590 } 9591 9592 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 9593 // Note: Commutes FSUB operands. 9594 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) 9595 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9596 DAG.getNode(ISD::FNEG, SL, VT, 9597 N1.getOperand(0)), 9598 N1.getOperand(1), N0); 9599 9600 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 9601 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) && 9602 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 9603 SDValue N00 = N0.getOperand(0).getOperand(0); 9604 SDValue N01 = N0.getOperand(0).getOperand(1); 9605 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9606 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 9607 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9608 } 9609 9610 // Look through FP_EXTEND nodes to do more combining. 9611 9612 // fold (fsub (fpext (fmul x, y)), z) 9613 // -> (fma (fpext x), (fpext y), (fneg z)) 9614 if (N0.getOpcode() == ISD::FP_EXTEND) { 9615 SDValue N00 = N0.getOperand(0); 9616 if (isContractableFMUL(N00) && 9617 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 9618 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9619 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9620 N00.getOperand(0)), 9621 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9622 N00.getOperand(1)), 9623 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9624 } 9625 } 9626 9627 // fold (fsub x, (fpext (fmul y, z))) 9628 // -> (fma (fneg (fpext y)), (fpext z), x) 9629 // Note: Commutes FSUB operands. 9630 if (N1.getOpcode() == ISD::FP_EXTEND) { 9631 SDValue N10 = N1.getOperand(0); 9632 if (isContractableFMUL(N10) && 9633 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 9634 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9635 DAG.getNode(ISD::FNEG, SL, VT, 9636 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9637 N10.getOperand(0))), 9638 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9639 N10.getOperand(1)), 9640 N0); 9641 } 9642 } 9643 9644 // fold (fsub (fpext (fneg (fmul, x, y))), z) 9645 // -> (fneg (fma (fpext x), (fpext y), z)) 9646 // Note: This could be removed with appropriate canonicalization of the 9647 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 9648 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 9649 // from implementing the canonicalization in visitFSUB. 9650 if (N0.getOpcode() == ISD::FP_EXTEND) { 9651 SDValue N00 = N0.getOperand(0); 9652 if (N00.getOpcode() == ISD::FNEG) { 9653 SDValue N000 = N00.getOperand(0); 9654 if (isContractableFMUL(N000) && 9655 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 9656 return DAG.getNode(ISD::FNEG, SL, VT, 9657 DAG.getNode(PreferredFusedOpcode, SL, VT, 9658 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9659 N000.getOperand(0)), 9660 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9661 N000.getOperand(1)), 9662 N1)); 9663 } 9664 } 9665 } 9666 9667 // fold (fsub (fneg (fpext (fmul, x, y))), z) 9668 // -> (fneg (fma (fpext x)), (fpext y), z) 9669 // Note: This could be removed with appropriate canonicalization of the 9670 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 9671 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 9672 // from implementing the canonicalization in visitFSUB. 9673 if (N0.getOpcode() == ISD::FNEG) { 9674 SDValue N00 = N0.getOperand(0); 9675 if (N00.getOpcode() == ISD::FP_EXTEND) { 9676 SDValue N000 = N00.getOperand(0); 9677 if (isContractableFMUL(N000) && 9678 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N000.getValueType())) { 9679 return DAG.getNode(ISD::FNEG, SL, VT, 9680 DAG.getNode(PreferredFusedOpcode, SL, VT, 9681 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9682 N000.getOperand(0)), 9683 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9684 N000.getOperand(1)), 9685 N1)); 9686 } 9687 } 9688 } 9689 9690 // More folding opportunities when target permits. 9691 if (Aggressive) { 9692 // fold (fsub (fma x, y, (fmul u, v)), z) 9693 // -> (fma x, y (fma u, v, (fneg z))) 9694 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9695 // are currently only supported on binary nodes. 9696 if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode && 9697 isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() && 9698 N0.getOperand(2)->hasOneUse()) { 9699 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9700 N0.getOperand(0), N0.getOperand(1), 9701 DAG.getNode(PreferredFusedOpcode, SL, VT, 9702 N0.getOperand(2).getOperand(0), 9703 N0.getOperand(2).getOperand(1), 9704 DAG.getNode(ISD::FNEG, SL, VT, 9705 N1))); 9706 } 9707 9708 // fold (fsub x, (fma y, z, (fmul u, v))) 9709 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 9710 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9711 // are currently only supported on binary nodes. 9712 if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode && 9713 isContractableFMUL(N1.getOperand(2))) { 9714 SDValue N20 = N1.getOperand(2).getOperand(0); 9715 SDValue N21 = N1.getOperand(2).getOperand(1); 9716 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9717 DAG.getNode(ISD::FNEG, SL, VT, 9718 N1.getOperand(0)), 9719 N1.getOperand(1), 9720 DAG.getNode(PreferredFusedOpcode, SL, VT, 9721 DAG.getNode(ISD::FNEG, SL, VT, N20), 9722 9723 N21, N0)); 9724 } 9725 9726 9727 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 9728 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 9729 if (N0.getOpcode() == PreferredFusedOpcode) { 9730 SDValue N02 = N0.getOperand(2); 9731 if (N02.getOpcode() == ISD::FP_EXTEND) { 9732 SDValue N020 = N02.getOperand(0); 9733 if (isContractableFMUL(N020) && 9734 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) { 9735 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9736 N0.getOperand(0), N0.getOperand(1), 9737 DAG.getNode(PreferredFusedOpcode, SL, VT, 9738 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9739 N020.getOperand(0)), 9740 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9741 N020.getOperand(1)), 9742 DAG.getNode(ISD::FNEG, SL, VT, 9743 N1))); 9744 } 9745 } 9746 } 9747 9748 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 9749 // -> (fma (fpext x), (fpext y), 9750 // (fma (fpext u), (fpext v), (fneg z))) 9751 // FIXME: This turns two single-precision and one double-precision 9752 // operation into two double-precision operations, which might not be 9753 // interesting for all targets, especially GPUs. 9754 if (N0.getOpcode() == ISD::FP_EXTEND) { 9755 SDValue N00 = N0.getOperand(0); 9756 if (N00.getOpcode() == PreferredFusedOpcode) { 9757 SDValue N002 = N00.getOperand(2); 9758 if (isContractableFMUL(N002) && 9759 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 9760 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9761 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9762 N00.getOperand(0)), 9763 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9764 N00.getOperand(1)), 9765 DAG.getNode(PreferredFusedOpcode, SL, VT, 9766 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9767 N002.getOperand(0)), 9768 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9769 N002.getOperand(1)), 9770 DAG.getNode(ISD::FNEG, SL, VT, 9771 N1))); 9772 } 9773 } 9774 } 9775 9776 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 9777 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 9778 if (N1.getOpcode() == PreferredFusedOpcode && 9779 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 9780 SDValue N120 = N1.getOperand(2).getOperand(0); 9781 if (isContractableFMUL(N120) && 9782 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) { 9783 SDValue N1200 = N120.getOperand(0); 9784 SDValue N1201 = N120.getOperand(1); 9785 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9786 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 9787 N1.getOperand(1), 9788 DAG.getNode(PreferredFusedOpcode, SL, VT, 9789 DAG.getNode(ISD::FNEG, SL, VT, 9790 DAG.getNode(ISD::FP_EXTEND, SL, 9791 VT, N1200)), 9792 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9793 N1201), 9794 N0)); 9795 } 9796 } 9797 9798 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 9799 // -> (fma (fneg (fpext y)), (fpext z), 9800 // (fma (fneg (fpext u)), (fpext v), x)) 9801 // FIXME: This turns two single-precision and one double-precision 9802 // operation into two double-precision operations, which might not be 9803 // interesting for all targets, especially GPUs. 9804 if (N1.getOpcode() == ISD::FP_EXTEND && 9805 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 9806 SDValue CvtSrc = N1.getOperand(0); 9807 SDValue N100 = CvtSrc.getOperand(0); 9808 SDValue N101 = CvtSrc.getOperand(1); 9809 SDValue N102 = CvtSrc.getOperand(2); 9810 if (isContractableFMUL(N102) && 9811 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, CvtSrc.getValueType())) { 9812 SDValue N1020 = N102.getOperand(0); 9813 SDValue N1021 = N102.getOperand(1); 9814 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9815 DAG.getNode(ISD::FNEG, SL, VT, 9816 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9817 N100)), 9818 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 9819 DAG.getNode(PreferredFusedOpcode, SL, VT, 9820 DAG.getNode(ISD::FNEG, SL, VT, 9821 DAG.getNode(ISD::FP_EXTEND, SL, 9822 VT, N1020)), 9823 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9824 N1021), 9825 N0)); 9826 } 9827 } 9828 } 9829 9830 return SDValue(); 9831 } 9832 9833 /// Try to perform FMA combining on a given FMUL node based on the distributive 9834 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions, 9835 /// subtraction instead of addition). 9836 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) { 9837 SDValue N0 = N->getOperand(0); 9838 SDValue N1 = N->getOperand(1); 9839 EVT VT = N->getValueType(0); 9840 SDLoc SL(N); 9841 9842 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 9843 9844 const TargetOptions &Options = DAG.getTarget().Options; 9845 9846 // The transforms below are incorrect when x == 0 and y == inf, because the 9847 // intermediate multiplication produces a nan. 9848 if (!Options.NoInfsFPMath) 9849 return SDValue(); 9850 9851 // Floating-point multiply-add without intermediate rounding. 9852 bool HasFMA = 9853 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 9854 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9855 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9856 9857 // Floating-point multiply-add with intermediate rounding. This can result 9858 // in a less precise result due to the changed rounding order. 9859 bool HasFMAD = Options.UnsafeFPMath && 9860 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9861 9862 // No valid opcode, do not combine. 9863 if (!HasFMAD && !HasFMA) 9864 return SDValue(); 9865 9866 // Always prefer FMAD to FMA for precision. 9867 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9868 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9869 9870 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 9871 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 9872 auto FuseFADD = [&](SDValue X, SDValue Y) { 9873 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 9874 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 9875 if (XC1 && XC1->isExactlyValue(+1.0)) 9876 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 9877 if (XC1 && XC1->isExactlyValue(-1.0)) 9878 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 9879 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9880 } 9881 return SDValue(); 9882 }; 9883 9884 if (SDValue FMA = FuseFADD(N0, N1)) 9885 return FMA; 9886 if (SDValue FMA = FuseFADD(N1, N0)) 9887 return FMA; 9888 9889 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 9890 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 9891 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 9892 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 9893 auto FuseFSUB = [&](SDValue X, SDValue Y) { 9894 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 9895 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 9896 if (XC0 && XC0->isExactlyValue(+1.0)) 9897 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9898 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 9899 Y); 9900 if (XC0 && XC0->isExactlyValue(-1.0)) 9901 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9902 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 9903 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9904 9905 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 9906 if (XC1 && XC1->isExactlyValue(+1.0)) 9907 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 9908 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9909 if (XC1 && XC1->isExactlyValue(-1.0)) 9910 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 9911 } 9912 return SDValue(); 9913 }; 9914 9915 if (SDValue FMA = FuseFSUB(N0, N1)) 9916 return FMA; 9917 if (SDValue FMA = FuseFSUB(N1, N0)) 9918 return FMA; 9919 9920 return SDValue(); 9921 } 9922 9923 static bool isFMulNegTwo(SDValue &N) { 9924 if (N.getOpcode() != ISD::FMUL) 9925 return false; 9926 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1))) 9927 return CFP->isExactlyValue(-2.0); 9928 return false; 9929 } 9930 9931 SDValue DAGCombiner::visitFADD(SDNode *N) { 9932 SDValue N0 = N->getOperand(0); 9933 SDValue N1 = N->getOperand(1); 9934 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 9935 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 9936 EVT VT = N->getValueType(0); 9937 SDLoc DL(N); 9938 const TargetOptions &Options = DAG.getTarget().Options; 9939 const SDNodeFlags Flags = N->getFlags(); 9940 9941 // fold vector ops 9942 if (VT.isVector()) 9943 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9944 return FoldedVOp; 9945 9946 // fold (fadd c1, c2) -> c1 + c2 9947 if (N0CFP && N1CFP) 9948 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 9949 9950 // canonicalize constant to RHS 9951 if (N0CFP && !N1CFP) 9952 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 9953 9954 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9955 return NewSel; 9956 9957 // fold (fadd A, (fneg B)) -> (fsub A, B) 9958 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 9959 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 9960 return DAG.getNode(ISD::FSUB, DL, VT, N0, 9961 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 9962 9963 // fold (fadd (fneg A), B) -> (fsub B, A) 9964 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 9965 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 9966 return DAG.getNode(ISD::FSUB, DL, VT, N1, 9967 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 9968 9969 // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B)) 9970 // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B)) 9971 if ((isFMulNegTwo(N0) && N0.hasOneUse()) || 9972 (isFMulNegTwo(N1) && N1.hasOneUse())) { 9973 bool N1IsFMul = isFMulNegTwo(N1); 9974 SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0); 9975 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags); 9976 return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags); 9977 } 9978 9979 // FIXME: Auto-upgrade the target/function-level option. 9980 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) { 9981 // fold (fadd A, 0) -> A 9982 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 9983 if (N1C->isZero()) 9984 return N0; 9985 } 9986 9987 // If 'unsafe math' is enabled, fold lots of things. 9988 if (Options.UnsafeFPMath) { 9989 // No FP constant should be created after legalization as Instruction 9990 // Selection pass has a hard time dealing with FP constants. 9991 bool AllowNewConst = (Level < AfterLegalizeDAG); 9992 9993 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 9994 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 9995 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 9996 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 9997 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 9998 Flags), 9999 Flags); 10000 10001 // If allowed, fold (fadd (fneg x), x) -> 0.0 10002 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 10003 return DAG.getConstantFP(0.0, DL, VT); 10004 10005 // If allowed, fold (fadd x, (fneg x)) -> 0.0 10006 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 10007 return DAG.getConstantFP(0.0, DL, VT); 10008 10009 // We can fold chains of FADD's of the same value into multiplications. 10010 // This transform is not safe in general because we are reducing the number 10011 // of rounding steps. 10012 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 10013 if (N0.getOpcode() == ISD::FMUL) { 10014 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 10015 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 10016 10017 // (fadd (fmul x, c), x) -> (fmul x, c+1) 10018 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 10019 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 10020 DAG.getConstantFP(1.0, DL, VT), Flags); 10021 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 10022 } 10023 10024 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 10025 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 10026 N1.getOperand(0) == N1.getOperand(1) && 10027 N0.getOperand(0) == N1.getOperand(0)) { 10028 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 10029 DAG.getConstantFP(2.0, DL, VT), Flags); 10030 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 10031 } 10032 } 10033 10034 if (N1.getOpcode() == ISD::FMUL) { 10035 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 10036 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 10037 10038 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 10039 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 10040 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 10041 DAG.getConstantFP(1.0, DL, VT), Flags); 10042 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 10043 } 10044 10045 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 10046 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 10047 N0.getOperand(0) == N0.getOperand(1) && 10048 N1.getOperand(0) == N0.getOperand(0)) { 10049 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 10050 DAG.getConstantFP(2.0, DL, VT), Flags); 10051 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 10052 } 10053 } 10054 10055 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 10056 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 10057 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 10058 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 10059 (N0.getOperand(0) == N1)) { 10060 return DAG.getNode(ISD::FMUL, DL, VT, 10061 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 10062 } 10063 } 10064 10065 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 10066 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 10067 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 10068 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 10069 N1.getOperand(0) == N0) { 10070 return DAG.getNode(ISD::FMUL, DL, VT, 10071 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 10072 } 10073 } 10074 10075 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 10076 if (AllowNewConst && 10077 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 10078 N0.getOperand(0) == N0.getOperand(1) && 10079 N1.getOperand(0) == N1.getOperand(1) && 10080 N0.getOperand(0) == N1.getOperand(0)) { 10081 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 10082 DAG.getConstantFP(4.0, DL, VT), Flags); 10083 } 10084 } 10085 } // enable-unsafe-fp-math 10086 10087 // FADD -> FMA combines: 10088 if (SDValue Fused = visitFADDForFMACombine(N)) { 10089 AddToWorklist(Fused.getNode()); 10090 return Fused; 10091 } 10092 return SDValue(); 10093 } 10094 10095 SDValue DAGCombiner::visitFSUB(SDNode *N) { 10096 SDValue N0 = N->getOperand(0); 10097 SDValue N1 = N->getOperand(1); 10098 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10099 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10100 EVT VT = N->getValueType(0); 10101 SDLoc DL(N); 10102 const TargetOptions &Options = DAG.getTarget().Options; 10103 const SDNodeFlags Flags = N->getFlags(); 10104 10105 // fold vector ops 10106 if (VT.isVector()) 10107 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 10108 return FoldedVOp; 10109 10110 // fold (fsub c1, c2) -> c1-c2 10111 if (N0CFP && N1CFP) 10112 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags); 10113 10114 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10115 return NewSel; 10116 10117 // fold (fsub A, (fneg B)) -> (fadd A, B) 10118 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 10119 return DAG.getNode(ISD::FADD, DL, VT, N0, 10120 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 10121 10122 // FIXME: Auto-upgrade the target/function-level option. 10123 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) { 10124 // (fsub 0, B) -> -B 10125 if (N0CFP && N0CFP->isZero()) { 10126 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 10127 return GetNegatedExpression(N1, DAG, LegalOperations); 10128 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 10129 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags); 10130 } 10131 } 10132 10133 // If 'unsafe math' is enabled, fold lots of things. 10134 if (Options.UnsafeFPMath) { 10135 // (fsub A, 0) -> A 10136 if (N1CFP && N1CFP->isZero()) 10137 return N0; 10138 10139 // (fsub x, x) -> 0.0 10140 if (N0 == N1) 10141 return DAG.getConstantFP(0.0f, DL, VT); 10142 10143 // (fsub x, (fadd x, y)) -> (fneg y) 10144 // (fsub x, (fadd y, x)) -> (fneg y) 10145 if (N1.getOpcode() == ISD::FADD) { 10146 SDValue N10 = N1->getOperand(0); 10147 SDValue N11 = N1->getOperand(1); 10148 10149 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 10150 return GetNegatedExpression(N11, DAG, LegalOperations); 10151 10152 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 10153 return GetNegatedExpression(N10, DAG, LegalOperations); 10154 } 10155 } 10156 10157 // FSUB -> FMA combines: 10158 if (SDValue Fused = visitFSUBForFMACombine(N)) { 10159 AddToWorklist(Fused.getNode()); 10160 return Fused; 10161 } 10162 10163 return SDValue(); 10164 } 10165 10166 SDValue DAGCombiner::visitFMUL(SDNode *N) { 10167 SDValue N0 = N->getOperand(0); 10168 SDValue N1 = N->getOperand(1); 10169 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10170 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10171 EVT VT = N->getValueType(0); 10172 SDLoc DL(N); 10173 const TargetOptions &Options = DAG.getTarget().Options; 10174 const SDNodeFlags Flags = N->getFlags(); 10175 10176 // fold vector ops 10177 if (VT.isVector()) { 10178 // This just handles C1 * C2 for vectors. Other vector folds are below. 10179 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 10180 return FoldedVOp; 10181 } 10182 10183 // fold (fmul c1, c2) -> c1*c2 10184 if (N0CFP && N1CFP) 10185 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 10186 10187 // canonicalize constant to RHS 10188 if (isConstantFPBuildVectorOrConstantFP(N0) && 10189 !isConstantFPBuildVectorOrConstantFP(N1)) 10190 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 10191 10192 // fold (fmul A, 1.0) -> A 10193 if (N1CFP && N1CFP->isExactlyValue(1.0)) 10194 return N0; 10195 10196 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10197 return NewSel; 10198 10199 if (Options.UnsafeFPMath) { 10200 // fold (fmul A, 0) -> 0 10201 if (N1CFP && N1CFP->isZero()) 10202 return N1; 10203 10204 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 10205 if (N0.getOpcode() == ISD::FMUL) { 10206 // Fold scalars or any vector constants (not just splats). 10207 // This fold is done in general by InstCombine, but extra fmul insts 10208 // may have been generated during lowering. 10209 SDValue N00 = N0.getOperand(0); 10210 SDValue N01 = N0.getOperand(1); 10211 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 10212 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 10213 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 10214 10215 // Check 1: Make sure that the first operand of the inner multiply is NOT 10216 // a constant. Otherwise, we may induce infinite looping. 10217 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 10218 // Check 2: Make sure that the second operand of the inner multiply and 10219 // the second operand of the outer multiply are constants. 10220 if ((N1CFP && isConstOrConstSplatFP(N01)) || 10221 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 10222 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 10223 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 10224 } 10225 } 10226 } 10227 10228 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 10229 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 10230 // during an early run of DAGCombiner can prevent folding with fmuls 10231 // inserted during lowering. 10232 if (N0.getOpcode() == ISD::FADD && 10233 (N0.getOperand(0) == N0.getOperand(1)) && 10234 N0.hasOneUse()) { 10235 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 10236 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 10237 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 10238 } 10239 } 10240 10241 // fold (fmul X, 2.0) -> (fadd X, X) 10242 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 10243 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 10244 10245 // fold (fmul X, -1.0) -> (fneg X) 10246 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 10247 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 10248 return DAG.getNode(ISD::FNEG, DL, VT, N0); 10249 10250 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 10251 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 10252 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 10253 // Both can be negated for free, check to see if at least one is cheaper 10254 // negated. 10255 if (LHSNeg == 2 || RHSNeg == 2) 10256 return DAG.getNode(ISD::FMUL, DL, VT, 10257 GetNegatedExpression(N0, DAG, LegalOperations), 10258 GetNegatedExpression(N1, DAG, LegalOperations), 10259 Flags); 10260 } 10261 } 10262 10263 // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X)) 10264 // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X) 10265 if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() && 10266 (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) && 10267 TLI.isOperationLegal(ISD::FABS, VT)) { 10268 SDValue Select = N0, X = N1; 10269 if (Select.getOpcode() != ISD::SELECT) 10270 std::swap(Select, X); 10271 10272 SDValue Cond = Select.getOperand(0); 10273 auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1)); 10274 auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2)); 10275 10276 if (TrueOpnd && FalseOpnd && 10277 Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X && 10278 isa<ConstantFPSDNode>(Cond.getOperand(1)) && 10279 cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) { 10280 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 10281 switch (CC) { 10282 default: break; 10283 case ISD::SETOLT: 10284 case ISD::SETULT: 10285 case ISD::SETOLE: 10286 case ISD::SETULE: 10287 case ISD::SETLT: 10288 case ISD::SETLE: 10289 std::swap(TrueOpnd, FalseOpnd); 10290 LLVM_FALLTHROUGH; 10291 case ISD::SETOGT: 10292 case ISD::SETUGT: 10293 case ISD::SETOGE: 10294 case ISD::SETUGE: 10295 case ISD::SETGT: 10296 case ISD::SETGE: 10297 if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) && 10298 TLI.isOperationLegal(ISD::FNEG, VT)) 10299 return DAG.getNode(ISD::FNEG, DL, VT, 10300 DAG.getNode(ISD::FABS, DL, VT, X)); 10301 if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0)) 10302 return DAG.getNode(ISD::FABS, DL, VT, X); 10303 10304 break; 10305 } 10306 } 10307 } 10308 10309 // FMUL -> FMA combines: 10310 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) { 10311 AddToWorklist(Fused.getNode()); 10312 return Fused; 10313 } 10314 10315 return SDValue(); 10316 } 10317 10318 SDValue DAGCombiner::visitFMA(SDNode *N) { 10319 SDValue N0 = N->getOperand(0); 10320 SDValue N1 = N->getOperand(1); 10321 SDValue N2 = N->getOperand(2); 10322 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10323 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10324 EVT VT = N->getValueType(0); 10325 SDLoc DL(N); 10326 const TargetOptions &Options = DAG.getTarget().Options; 10327 10328 // Constant fold FMA. 10329 if (isa<ConstantFPSDNode>(N0) && 10330 isa<ConstantFPSDNode>(N1) && 10331 isa<ConstantFPSDNode>(N2)) { 10332 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2); 10333 } 10334 10335 if (Options.UnsafeFPMath) { 10336 if (N0CFP && N0CFP->isZero()) 10337 return N2; 10338 if (N1CFP && N1CFP->isZero()) 10339 return N2; 10340 } 10341 // TODO: The FMA node should have flags that propagate to these nodes. 10342 if (N0CFP && N0CFP->isExactlyValue(1.0)) 10343 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 10344 if (N1CFP && N1CFP->isExactlyValue(1.0)) 10345 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 10346 10347 // Canonicalize (fma c, x, y) -> (fma x, c, y) 10348 if (isConstantFPBuildVectorOrConstantFP(N0) && 10349 !isConstantFPBuildVectorOrConstantFP(N1)) 10350 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 10351 10352 // TODO: FMA nodes should have flags that propagate to the created nodes. 10353 // For now, create a Flags object for use with all unsafe math transforms. 10354 SDNodeFlags Flags; 10355 Flags.setUnsafeAlgebra(true); 10356 10357 if (Options.UnsafeFPMath) { 10358 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 10359 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 10360 isConstantFPBuildVectorOrConstantFP(N1) && 10361 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 10362 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10363 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1), 10364 Flags), Flags); 10365 } 10366 10367 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 10368 if (N0.getOpcode() == ISD::FMUL && 10369 isConstantFPBuildVectorOrConstantFP(N1) && 10370 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 10371 return DAG.getNode(ISD::FMA, DL, VT, 10372 N0.getOperand(0), 10373 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1), 10374 Flags), 10375 N2); 10376 } 10377 } 10378 10379 // (fma x, 1, y) -> (fadd x, y) 10380 // (fma x, -1, y) -> (fadd (fneg x), y) 10381 if (N1CFP) { 10382 if (N1CFP->isExactlyValue(1.0)) 10383 // TODO: The FMA node should have flags that propagate to this node. 10384 return DAG.getNode(ISD::FADD, DL, VT, N0, N2); 10385 10386 if (N1CFP->isExactlyValue(-1.0) && 10387 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 10388 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0); 10389 AddToWorklist(RHSNeg.getNode()); 10390 // TODO: The FMA node should have flags that propagate to this node. 10391 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg); 10392 } 10393 10394 // fma (fneg x), K, y -> fma x -K, y 10395 if (N0.getOpcode() == ISD::FNEG && 10396 (TLI.isOperationLegal(ISD::ConstantFP, VT) || 10397 (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT)))) { 10398 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0), 10399 DAG.getNode(ISD::FNEG, DL, VT, N1, Flags), N2); 10400 } 10401 } 10402 10403 if (Options.UnsafeFPMath) { 10404 // (fma x, c, x) -> (fmul x, (c+1)) 10405 if (N1CFP && N0 == N2) { 10406 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10407 DAG.getNode(ISD::FADD, DL, VT, N1, 10408 DAG.getConstantFP(1.0, DL, VT), Flags), 10409 Flags); 10410 } 10411 10412 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 10413 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 10414 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10415 DAG.getNode(ISD::FADD, DL, VT, N1, 10416 DAG.getConstantFP(-1.0, DL, VT), Flags), 10417 Flags); 10418 } 10419 } 10420 10421 return SDValue(); 10422 } 10423 10424 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10425 // reciprocal. 10426 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 10427 // Notice that this is not always beneficial. One reason is different targets 10428 // may have different costs for FDIV and FMUL, so sometimes the cost of two 10429 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 10430 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 10431 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 10432 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 10433 const SDNodeFlags Flags = N->getFlags(); 10434 if (!UnsafeMath && !Flags.hasAllowReciprocal()) 10435 return SDValue(); 10436 10437 // Skip if current node is a reciprocal. 10438 SDValue N0 = N->getOperand(0); 10439 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10440 if (N0CFP && N0CFP->isExactlyValue(1.0)) 10441 return SDValue(); 10442 10443 // Exit early if the target does not want this transform or if there can't 10444 // possibly be enough uses of the divisor to make the transform worthwhile. 10445 SDValue N1 = N->getOperand(1); 10446 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 10447 if (!MinUses || N1->use_size() < MinUses) 10448 return SDValue(); 10449 10450 // Find all FDIV users of the same divisor. 10451 // Use a set because duplicates may be present in the user list. 10452 SetVector<SDNode *> Users; 10453 for (auto *U : N1->uses()) { 10454 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 10455 // This division is eligible for optimization only if global unsafe math 10456 // is enabled or if this division allows reciprocal formation. 10457 if (UnsafeMath || U->getFlags().hasAllowReciprocal()) 10458 Users.insert(U); 10459 } 10460 } 10461 10462 // Now that we have the actual number of divisor uses, make sure it meets 10463 // the minimum threshold specified by the target. 10464 if (Users.size() < MinUses) 10465 return SDValue(); 10466 10467 EVT VT = N->getValueType(0); 10468 SDLoc DL(N); 10469 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 10470 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 10471 10472 // Dividend / Divisor -> Dividend * Reciprocal 10473 for (auto *U : Users) { 10474 SDValue Dividend = U->getOperand(0); 10475 if (Dividend != FPOne) { 10476 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 10477 Reciprocal, Flags); 10478 CombineTo(U, NewNode); 10479 } else if (U != Reciprocal.getNode()) { 10480 // In the absence of fast-math-flags, this user node is always the 10481 // same node as Reciprocal, but with FMF they may be different nodes. 10482 CombineTo(U, Reciprocal); 10483 } 10484 } 10485 return SDValue(N, 0); // N was replaced. 10486 } 10487 10488 SDValue DAGCombiner::visitFDIV(SDNode *N) { 10489 SDValue N0 = N->getOperand(0); 10490 SDValue N1 = N->getOperand(1); 10491 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10492 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10493 EVT VT = N->getValueType(0); 10494 SDLoc DL(N); 10495 const TargetOptions &Options = DAG.getTarget().Options; 10496 SDNodeFlags Flags = N->getFlags(); 10497 10498 // fold vector ops 10499 if (VT.isVector()) 10500 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 10501 return FoldedVOp; 10502 10503 // fold (fdiv c1, c2) -> c1/c2 10504 if (N0CFP && N1CFP) 10505 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 10506 10507 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10508 return NewSel; 10509 10510 if (Options.UnsafeFPMath) { 10511 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 10512 if (N1CFP) { 10513 // Compute the reciprocal 1.0 / c2. 10514 const APFloat &N1APF = N1CFP->getValueAPF(); 10515 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 10516 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 10517 // Only do the transform if the reciprocal is a legal fp immediate that 10518 // isn't too nasty (eg NaN, denormal, ...). 10519 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 10520 (!LegalOperations || 10521 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 10522 // backend)... we should handle this gracefully after Legalize. 10523 // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) || 10524 TLI.isOperationLegal(ISD::ConstantFP, VT) || 10525 TLI.isFPImmLegal(Recip, VT))) 10526 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10527 DAG.getConstantFP(Recip, DL, VT), Flags); 10528 } 10529 10530 // If this FDIV is part of a reciprocal square root, it may be folded 10531 // into a target-specific square root estimate instruction. 10532 if (N1.getOpcode() == ISD::FSQRT) { 10533 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) { 10534 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10535 } 10536 } else if (N1.getOpcode() == ISD::FP_EXTEND && 10537 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10538 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 10539 Flags)) { 10540 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 10541 AddToWorklist(RV.getNode()); 10542 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10543 } 10544 } else if (N1.getOpcode() == ISD::FP_ROUND && 10545 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10546 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 10547 Flags)) { 10548 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 10549 AddToWorklist(RV.getNode()); 10550 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10551 } 10552 } else if (N1.getOpcode() == ISD::FMUL) { 10553 // Look through an FMUL. Even though this won't remove the FDIV directly, 10554 // it's still worthwhile to get rid of the FSQRT if possible. 10555 SDValue SqrtOp; 10556 SDValue OtherOp; 10557 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10558 SqrtOp = N1.getOperand(0); 10559 OtherOp = N1.getOperand(1); 10560 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 10561 SqrtOp = N1.getOperand(1); 10562 OtherOp = N1.getOperand(0); 10563 } 10564 if (SqrtOp.getNode()) { 10565 // We found a FSQRT, so try to make this fold: 10566 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 10567 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 10568 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 10569 AddToWorklist(RV.getNode()); 10570 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10571 } 10572 } 10573 } 10574 10575 // Fold into a reciprocal estimate and multiply instead of a real divide. 10576 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 10577 AddToWorklist(RV.getNode()); 10578 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10579 } 10580 } 10581 10582 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 10583 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 10584 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 10585 // Both can be negated for free, check to see if at least one is cheaper 10586 // negated. 10587 if (LHSNeg == 2 || RHSNeg == 2) 10588 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 10589 GetNegatedExpression(N0, DAG, LegalOperations), 10590 GetNegatedExpression(N1, DAG, LegalOperations), 10591 Flags); 10592 } 10593 } 10594 10595 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 10596 return CombineRepeatedDivisors; 10597 10598 return SDValue(); 10599 } 10600 10601 SDValue DAGCombiner::visitFREM(SDNode *N) { 10602 SDValue N0 = N->getOperand(0); 10603 SDValue N1 = N->getOperand(1); 10604 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10605 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10606 EVT VT = N->getValueType(0); 10607 10608 // fold (frem c1, c2) -> fmod(c1,c2) 10609 if (N0CFP && N1CFP) 10610 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags()); 10611 10612 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10613 return NewSel; 10614 10615 return SDValue(); 10616 } 10617 10618 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 10619 if (!DAG.getTarget().Options.UnsafeFPMath) 10620 return SDValue(); 10621 10622 SDValue N0 = N->getOperand(0); 10623 if (TLI.isFsqrtCheap(N0, DAG)) 10624 return SDValue(); 10625 10626 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 10627 // For now, create a Flags object for use with all unsafe math transforms. 10628 SDNodeFlags Flags; 10629 Flags.setUnsafeAlgebra(true); 10630 return buildSqrtEstimate(N0, Flags); 10631 } 10632 10633 /// copysign(x, fp_extend(y)) -> copysign(x, y) 10634 /// copysign(x, fp_round(y)) -> copysign(x, y) 10635 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 10636 SDValue N1 = N->getOperand(1); 10637 if ((N1.getOpcode() == ISD::FP_EXTEND || 10638 N1.getOpcode() == ISD::FP_ROUND)) { 10639 // Do not optimize out type conversion of f128 type yet. 10640 // For some targets like x86_64, configuration is changed to keep one f128 10641 // value in one SSE register, but instruction selection cannot handle 10642 // FCOPYSIGN on SSE registers yet. 10643 EVT N1VT = N1->getValueType(0); 10644 EVT N1Op0VT = N1->getOperand(0).getValueType(); 10645 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 10646 } 10647 return false; 10648 } 10649 10650 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 10651 SDValue N0 = N->getOperand(0); 10652 SDValue N1 = N->getOperand(1); 10653 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10654 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10655 EVT VT = N->getValueType(0); 10656 10657 if (N0CFP && N1CFP) // Constant fold 10658 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 10659 10660 if (N1CFP) { 10661 const APFloat &V = N1CFP->getValueAPF(); 10662 // copysign(x, c1) -> fabs(x) iff ispos(c1) 10663 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 10664 if (!V.isNegative()) { 10665 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 10666 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10667 } else { 10668 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 10669 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 10670 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 10671 } 10672 } 10673 10674 // copysign(fabs(x), y) -> copysign(x, y) 10675 // copysign(fneg(x), y) -> copysign(x, y) 10676 // copysign(copysign(x,z), y) -> copysign(x, y) 10677 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 10678 N0.getOpcode() == ISD::FCOPYSIGN) 10679 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1); 10680 10681 // copysign(x, abs(y)) -> abs(x) 10682 if (N1.getOpcode() == ISD::FABS) 10683 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10684 10685 // copysign(x, copysign(y,z)) -> copysign(x, z) 10686 if (N1.getOpcode() == ISD::FCOPYSIGN) 10687 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1)); 10688 10689 // copysign(x, fp_extend(y)) -> copysign(x, y) 10690 // copysign(x, fp_round(y)) -> copysign(x, y) 10691 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 10692 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0)); 10693 10694 return SDValue(); 10695 } 10696 10697 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 10698 SDValue N0 = N->getOperand(0); 10699 EVT VT = N->getValueType(0); 10700 EVT OpVT = N0.getValueType(); 10701 10702 // fold (sint_to_fp c1) -> c1fp 10703 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 10704 // ...but only if the target supports immediate floating-point values 10705 (!LegalOperations || 10706 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) 10707 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 10708 10709 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 10710 // but UINT_TO_FP is legal on this target, try to convert. 10711 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 10712 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 10713 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 10714 if (DAG.SignBitIsZero(N0)) 10715 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 10716 } 10717 10718 // The next optimizations are desirable only if SELECT_CC can be lowered. 10719 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 10720 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 10721 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 10722 !VT.isVector() && 10723 (!LegalOperations || 10724 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 10725 SDLoc DL(N); 10726 SDValue Ops[] = 10727 { N0.getOperand(0), N0.getOperand(1), 10728 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10729 N0.getOperand(2) }; 10730 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10731 } 10732 10733 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 10734 // (select_cc x, y, 1.0, 0.0,, cc) 10735 if (N0.getOpcode() == ISD::ZERO_EXTEND && 10736 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 10737 (!LegalOperations || 10738 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 10739 SDLoc DL(N); 10740 SDValue Ops[] = 10741 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 10742 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10743 N0.getOperand(0).getOperand(2) }; 10744 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10745 } 10746 } 10747 10748 return SDValue(); 10749 } 10750 10751 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 10752 SDValue N0 = N->getOperand(0); 10753 EVT VT = N->getValueType(0); 10754 EVT OpVT = N0.getValueType(); 10755 10756 // fold (uint_to_fp c1) -> c1fp 10757 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 10758 // ...but only if the target supports immediate floating-point values 10759 (!LegalOperations || 10760 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) 10761 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 10762 10763 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 10764 // but SINT_TO_FP is legal on this target, try to convert. 10765 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 10766 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 10767 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 10768 if (DAG.SignBitIsZero(N0)) 10769 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 10770 } 10771 10772 // The next optimizations are desirable only if SELECT_CC can be lowered. 10773 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 10774 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 10775 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 10776 (!LegalOperations || 10777 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 10778 SDLoc DL(N); 10779 SDValue Ops[] = 10780 { N0.getOperand(0), N0.getOperand(1), 10781 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10782 N0.getOperand(2) }; 10783 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10784 } 10785 } 10786 10787 return SDValue(); 10788 } 10789 10790 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 10791 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 10792 SDValue N0 = N->getOperand(0); 10793 EVT VT = N->getValueType(0); 10794 10795 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 10796 return SDValue(); 10797 10798 SDValue Src = N0.getOperand(0); 10799 EVT SrcVT = Src.getValueType(); 10800 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 10801 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 10802 10803 // We can safely assume the conversion won't overflow the output range, 10804 // because (for example) (uint8_t)18293.f is undefined behavior. 10805 10806 // Since we can assume the conversion won't overflow, our decision as to 10807 // whether the input will fit in the float should depend on the minimum 10808 // of the input range and output range. 10809 10810 // This means this is also safe for a signed input and unsigned output, since 10811 // a negative input would lead to undefined behavior. 10812 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 10813 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 10814 unsigned ActualSize = std::min(InputSize, OutputSize); 10815 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 10816 10817 // We can only fold away the float conversion if the input range can be 10818 // represented exactly in the float range. 10819 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 10820 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 10821 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 10822 : ISD::ZERO_EXTEND; 10823 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 10824 } 10825 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 10826 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 10827 return DAG.getBitcast(VT, Src); 10828 } 10829 return SDValue(); 10830 } 10831 10832 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 10833 SDValue N0 = N->getOperand(0); 10834 EVT VT = N->getValueType(0); 10835 10836 // fold (fp_to_sint c1fp) -> c1 10837 if (isConstantFPBuildVectorOrConstantFP(N0)) 10838 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 10839 10840 return FoldIntToFPToInt(N, DAG); 10841 } 10842 10843 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 10844 SDValue N0 = N->getOperand(0); 10845 EVT VT = N->getValueType(0); 10846 10847 // fold (fp_to_uint c1fp) -> c1 10848 if (isConstantFPBuildVectorOrConstantFP(N0)) 10849 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 10850 10851 return FoldIntToFPToInt(N, DAG); 10852 } 10853 10854 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 10855 SDValue N0 = N->getOperand(0); 10856 SDValue N1 = N->getOperand(1); 10857 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10858 EVT VT = N->getValueType(0); 10859 10860 // fold (fp_round c1fp) -> c1fp 10861 if (N0CFP) 10862 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 10863 10864 // fold (fp_round (fp_extend x)) -> x 10865 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 10866 return N0.getOperand(0); 10867 10868 // fold (fp_round (fp_round x)) -> (fp_round x) 10869 if (N0.getOpcode() == ISD::FP_ROUND) { 10870 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 10871 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1; 10872 10873 // Skip this folding if it results in an fp_round from f80 to f16. 10874 // 10875 // f80 to f16 always generates an expensive (and as yet, unimplemented) 10876 // libcall to __truncxfhf2 instead of selecting native f16 conversion 10877 // instructions from f32 or f64. Moreover, the first (value-preserving) 10878 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 10879 // x86. 10880 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 10881 return SDValue(); 10882 10883 // If the first fp_round isn't a value preserving truncation, it might 10884 // introduce a tie in the second fp_round, that wouldn't occur in the 10885 // single-step fp_round we want to fold to. 10886 // In other words, double rounding isn't the same as rounding. 10887 // Also, this is a value preserving truncation iff both fp_round's are. 10888 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 10889 SDLoc DL(N); 10890 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 10891 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 10892 } 10893 } 10894 10895 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 10896 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 10897 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 10898 N0.getOperand(0), N1); 10899 AddToWorklist(Tmp.getNode()); 10900 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 10901 Tmp, N0.getOperand(1)); 10902 } 10903 10904 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 10905 return NewVSel; 10906 10907 return SDValue(); 10908 } 10909 10910 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 10911 SDValue N0 = N->getOperand(0); 10912 EVT VT = N->getValueType(0); 10913 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 10914 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10915 10916 // fold (fp_round_inreg c1fp) -> c1fp 10917 if (N0CFP && isTypeLegal(EVT)) { 10918 SDLoc DL(N); 10919 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 10920 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 10921 } 10922 10923 return SDValue(); 10924 } 10925 10926 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 10927 SDValue N0 = N->getOperand(0); 10928 EVT VT = N->getValueType(0); 10929 10930 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 10931 if (N->hasOneUse() && 10932 N->use_begin()->getOpcode() == ISD::FP_ROUND) 10933 return SDValue(); 10934 10935 // fold (fp_extend c1fp) -> c1fp 10936 if (isConstantFPBuildVectorOrConstantFP(N0)) 10937 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 10938 10939 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 10940 if (N0.getOpcode() == ISD::FP16_TO_FP && 10941 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 10942 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 10943 10944 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 10945 // value of X. 10946 if (N0.getOpcode() == ISD::FP_ROUND 10947 && N0.getConstantOperandVal(1) == 1) { 10948 SDValue In = N0.getOperand(0); 10949 if (In.getValueType() == VT) return In; 10950 if (VT.bitsLT(In.getValueType())) 10951 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 10952 In, N0.getOperand(1)); 10953 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 10954 } 10955 10956 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 10957 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10958 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 10959 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10960 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 10961 LN0->getChain(), 10962 LN0->getBasePtr(), N0.getValueType(), 10963 LN0->getMemOperand()); 10964 CombineTo(N, ExtLoad); 10965 CombineTo(N0.getNode(), 10966 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 10967 N0.getValueType(), ExtLoad, 10968 DAG.getIntPtrConstant(1, SDLoc(N0))), 10969 ExtLoad.getValue(1)); 10970 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10971 } 10972 10973 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 10974 return NewVSel; 10975 10976 return SDValue(); 10977 } 10978 10979 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 10980 SDValue N0 = N->getOperand(0); 10981 EVT VT = N->getValueType(0); 10982 10983 // fold (fceil c1) -> fceil(c1) 10984 if (isConstantFPBuildVectorOrConstantFP(N0)) 10985 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 10986 10987 return SDValue(); 10988 } 10989 10990 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 10991 SDValue N0 = N->getOperand(0); 10992 EVT VT = N->getValueType(0); 10993 10994 // fold (ftrunc c1) -> ftrunc(c1) 10995 if (isConstantFPBuildVectorOrConstantFP(N0)) 10996 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 10997 10998 // fold ftrunc (known rounded int x) -> x 10999 // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is 11000 // likely to be generated to extract integer from a rounded floating value. 11001 switch (N0.getOpcode()) { 11002 default: break; 11003 case ISD::FRINT: 11004 case ISD::FTRUNC: 11005 case ISD::FNEARBYINT: 11006 case ISD::FFLOOR: 11007 case ISD::FCEIL: 11008 return N0; 11009 } 11010 11011 return SDValue(); 11012 } 11013 11014 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 11015 SDValue N0 = N->getOperand(0); 11016 EVT VT = N->getValueType(0); 11017 11018 // fold (ffloor c1) -> ffloor(c1) 11019 if (isConstantFPBuildVectorOrConstantFP(N0)) 11020 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 11021 11022 return SDValue(); 11023 } 11024 11025 // FIXME: FNEG and FABS have a lot in common; refactor. 11026 SDValue DAGCombiner::visitFNEG(SDNode *N) { 11027 SDValue N0 = N->getOperand(0); 11028 EVT VT = N->getValueType(0); 11029 11030 // Constant fold FNEG. 11031 if (isConstantFPBuildVectorOrConstantFP(N0)) 11032 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 11033 11034 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 11035 &DAG.getTarget().Options)) 11036 return GetNegatedExpression(N0, DAG, LegalOperations); 11037 11038 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 11039 // constant pool values. 11040 if (!TLI.isFNegFree(VT) && 11041 N0.getOpcode() == ISD::BITCAST && 11042 N0.getNode()->hasOneUse()) { 11043 SDValue Int = N0.getOperand(0); 11044 EVT IntVT = Int.getValueType(); 11045 if (IntVT.isInteger() && !IntVT.isVector()) { 11046 APInt SignMask; 11047 if (N0.getValueType().isVector()) { 11048 // For a vector, get a mask such as 0x80... per scalar element 11049 // and splat it. 11050 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits()); 11051 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 11052 } else { 11053 // For a scalar, just generate 0x80... 11054 SignMask = APInt::getSignMask(IntVT.getSizeInBits()); 11055 } 11056 SDLoc DL0(N0); 11057 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 11058 DAG.getConstant(SignMask, DL0, IntVT)); 11059 AddToWorklist(Int.getNode()); 11060 return DAG.getBitcast(VT, Int); 11061 } 11062 } 11063 11064 // (fneg (fmul c, x)) -> (fmul -c, x) 11065 if (N0.getOpcode() == ISD::FMUL && 11066 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 11067 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 11068 if (CFP1) { 11069 APFloat CVal = CFP1->getValueAPF(); 11070 CVal.changeSign(); 11071 if (Level >= AfterLegalizeDAG && 11072 (TLI.isFPImmLegal(CVal, VT) || 11073 TLI.isOperationLegal(ISD::ConstantFP, VT))) 11074 return DAG.getNode( 11075 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 11076 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)), 11077 N0->getFlags()); 11078 } 11079 } 11080 11081 return SDValue(); 11082 } 11083 11084 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 11085 SDValue N0 = N->getOperand(0); 11086 SDValue N1 = N->getOperand(1); 11087 EVT VT = N->getValueType(0); 11088 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 11089 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 11090 11091 if (N0CFP && N1CFP) { 11092 const APFloat &C0 = N0CFP->getValueAPF(); 11093 const APFloat &C1 = N1CFP->getValueAPF(); 11094 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 11095 } 11096 11097 // Canonicalize to constant on RHS. 11098 if (isConstantFPBuildVectorOrConstantFP(N0) && 11099 !isConstantFPBuildVectorOrConstantFP(N1)) 11100 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 11101 11102 return SDValue(); 11103 } 11104 11105 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 11106 SDValue N0 = N->getOperand(0); 11107 SDValue N1 = N->getOperand(1); 11108 EVT VT = N->getValueType(0); 11109 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 11110 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 11111 11112 if (N0CFP && N1CFP) { 11113 const APFloat &C0 = N0CFP->getValueAPF(); 11114 const APFloat &C1 = N1CFP->getValueAPF(); 11115 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 11116 } 11117 11118 // Canonicalize to constant on RHS. 11119 if (isConstantFPBuildVectorOrConstantFP(N0) && 11120 !isConstantFPBuildVectorOrConstantFP(N1)) 11121 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 11122 11123 return SDValue(); 11124 } 11125 11126 SDValue DAGCombiner::visitFABS(SDNode *N) { 11127 SDValue N0 = N->getOperand(0); 11128 EVT VT = N->getValueType(0); 11129 11130 // fold (fabs c1) -> fabs(c1) 11131 if (isConstantFPBuildVectorOrConstantFP(N0)) 11132 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 11133 11134 // fold (fabs (fabs x)) -> (fabs x) 11135 if (N0.getOpcode() == ISD::FABS) 11136 return N->getOperand(0); 11137 11138 // fold (fabs (fneg x)) -> (fabs x) 11139 // fold (fabs (fcopysign x, y)) -> (fabs x) 11140 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 11141 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 11142 11143 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 11144 // constant pool values. 11145 if (!TLI.isFAbsFree(VT) && 11146 N0.getOpcode() == ISD::BITCAST && 11147 N0.getNode()->hasOneUse()) { 11148 SDValue Int = N0.getOperand(0); 11149 EVT IntVT = Int.getValueType(); 11150 if (IntVT.isInteger() && !IntVT.isVector()) { 11151 APInt SignMask; 11152 if (N0.getValueType().isVector()) { 11153 // For a vector, get a mask such as 0x7f... per scalar element 11154 // and splat it. 11155 SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits()); 11156 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 11157 } else { 11158 // For a scalar, just generate 0x7f... 11159 SignMask = ~APInt::getSignMask(IntVT.getSizeInBits()); 11160 } 11161 SDLoc DL(N0); 11162 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 11163 DAG.getConstant(SignMask, DL, IntVT)); 11164 AddToWorklist(Int.getNode()); 11165 return DAG.getBitcast(N->getValueType(0), Int); 11166 } 11167 } 11168 11169 return SDValue(); 11170 } 11171 11172 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 11173 SDValue Chain = N->getOperand(0); 11174 SDValue N1 = N->getOperand(1); 11175 SDValue N2 = N->getOperand(2); 11176 11177 // If N is a constant we could fold this into a fallthrough or unconditional 11178 // branch. However that doesn't happen very often in normal code, because 11179 // Instcombine/SimplifyCFG should have handled the available opportunities. 11180 // If we did this folding here, it would be necessary to update the 11181 // MachineBasicBlock CFG, which is awkward. 11182 11183 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 11184 // on the target. 11185 if (N1.getOpcode() == ISD::SETCC && 11186 TLI.isOperationLegalOrCustom(ISD::BR_CC, 11187 N1.getOperand(0).getValueType())) { 11188 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 11189 Chain, N1.getOperand(2), 11190 N1.getOperand(0), N1.getOperand(1), N2); 11191 } 11192 11193 if (N1.hasOneUse()) { 11194 if (SDValue NewN1 = rebuildSetCC(N1)) 11195 return DAG.getNode(ISD::BRCOND, SDLoc(N), MVT::Other, Chain, NewN1, N2); 11196 } 11197 11198 return SDValue(); 11199 } 11200 11201 SDValue DAGCombiner::rebuildSetCC(SDValue N) { 11202 if (N.getOpcode() == ISD::SRL || 11203 (N.getOpcode() == ISD::TRUNCATE && 11204 (N.getOperand(0).hasOneUse() && 11205 N.getOperand(0).getOpcode() == ISD::SRL))) { 11206 // Look pass the truncate. 11207 if (N.getOpcode() == ISD::TRUNCATE) 11208 N = N.getOperand(0); 11209 11210 // Match this pattern so that we can generate simpler code: 11211 // 11212 // %a = ... 11213 // %b = and i32 %a, 2 11214 // %c = srl i32 %b, 1 11215 // brcond i32 %c ... 11216 // 11217 // into 11218 // 11219 // %a = ... 11220 // %b = and i32 %a, 2 11221 // %c = setcc eq %b, 0 11222 // brcond %c ... 11223 // 11224 // This applies only when the AND constant value has one bit set and the 11225 // SRL constant is equal to the log2 of the AND constant. The back-end is 11226 // smart enough to convert the result into a TEST/JMP sequence. 11227 SDValue Op0 = N.getOperand(0); 11228 SDValue Op1 = N.getOperand(1); 11229 11230 if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::Constant) { 11231 SDValue AndOp1 = Op0.getOperand(1); 11232 11233 if (AndOp1.getOpcode() == ISD::Constant) { 11234 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 11235 11236 if (AndConst.isPowerOf2() && 11237 cast<ConstantSDNode>(Op1)->getAPIntValue() == AndConst.logBase2()) { 11238 SDLoc DL(N); 11239 return DAG.getSetCC(DL, getSetCCResultType(Op0.getValueType()), 11240 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 11241 ISD::SETNE); 11242 } 11243 } 11244 } 11245 } 11246 11247 // Transform br(xor(x, y)) -> br(x != y) 11248 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 11249 if (N.getOpcode() == ISD::XOR) { 11250 SDNode *TheXor = N.getNode(); 11251 11252 // Avoid missing important xor optimizations. 11253 while (SDValue Tmp = visitXOR(TheXor)) { 11254 // We don't have a XOR anymore, bail. 11255 if (Tmp.getOpcode() != ISD::XOR) 11256 return Tmp; 11257 11258 TheXor = Tmp.getNode(); 11259 } 11260 11261 SDValue Op0 = TheXor->getOperand(0); 11262 SDValue Op1 = TheXor->getOperand(1); 11263 11264 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 11265 bool Equal = false; 11266 if (isOneConstant(Op0) && Op0.hasOneUse() && 11267 Op0.getOpcode() == ISD::XOR) { 11268 TheXor = Op0.getNode(); 11269 Equal = true; 11270 } 11271 11272 EVT SetCCVT = N.getValueType(); 11273 if (LegalTypes) 11274 SetCCVT = getSetCCResultType(SetCCVT); 11275 // Replace the uses of XOR with SETCC 11276 return DAG.getSetCC(SDLoc(TheXor), SetCCVT, Op0, Op1, 11277 Equal ? ISD::SETEQ : ISD::SETNE); 11278 } 11279 } 11280 11281 return SDValue(); 11282 } 11283 11284 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 11285 // 11286 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 11287 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 11288 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 11289 11290 // If N is a constant we could fold this into a fallthrough or unconditional 11291 // branch. However that doesn't happen very often in normal code, because 11292 // Instcombine/SimplifyCFG should have handled the available opportunities. 11293 // If we did this folding here, it would be necessary to update the 11294 // MachineBasicBlock CFG, which is awkward. 11295 11296 // Use SimplifySetCC to simplify SETCC's. 11297 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 11298 CondLHS, CondRHS, CC->get(), SDLoc(N), 11299 false); 11300 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 11301 11302 // fold to a simpler setcc 11303 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 11304 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 11305 N->getOperand(0), Simp.getOperand(2), 11306 Simp.getOperand(0), Simp.getOperand(1), 11307 N->getOperand(4)); 11308 11309 return SDValue(); 11310 } 11311 11312 /// Return true if 'Use' is a load or a store that uses N as its base pointer 11313 /// and that N may be folded in the load / store addressing mode. 11314 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 11315 SelectionDAG &DAG, 11316 const TargetLowering &TLI) { 11317 EVT VT; 11318 unsigned AS; 11319 11320 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 11321 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 11322 return false; 11323 VT = LD->getMemoryVT(); 11324 AS = LD->getAddressSpace(); 11325 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 11326 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 11327 return false; 11328 VT = ST->getMemoryVT(); 11329 AS = ST->getAddressSpace(); 11330 } else 11331 return false; 11332 11333 TargetLowering::AddrMode AM; 11334 if (N->getOpcode() == ISD::ADD) { 11335 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11336 if (Offset) 11337 // [reg +/- imm] 11338 AM.BaseOffs = Offset->getSExtValue(); 11339 else 11340 // [reg +/- reg] 11341 AM.Scale = 1; 11342 } else if (N->getOpcode() == ISD::SUB) { 11343 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11344 if (Offset) 11345 // [reg +/- imm] 11346 AM.BaseOffs = -Offset->getSExtValue(); 11347 else 11348 // [reg +/- reg] 11349 AM.Scale = 1; 11350 } else 11351 return false; 11352 11353 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 11354 VT.getTypeForEVT(*DAG.getContext()), AS); 11355 } 11356 11357 /// Try turning a load/store into a pre-indexed load/store when the base 11358 /// pointer is an add or subtract and it has other uses besides the load/store. 11359 /// After the transformation, the new indexed load/store has effectively folded 11360 /// the add/subtract in and all of its other uses are redirected to the 11361 /// new load/store. 11362 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 11363 if (Level < AfterLegalizeDAG) 11364 return false; 11365 11366 bool isLoad = true; 11367 SDValue Ptr; 11368 EVT VT; 11369 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11370 if (LD->isIndexed()) 11371 return false; 11372 VT = LD->getMemoryVT(); 11373 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 11374 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 11375 return false; 11376 Ptr = LD->getBasePtr(); 11377 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11378 if (ST->isIndexed()) 11379 return false; 11380 VT = ST->getMemoryVT(); 11381 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 11382 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 11383 return false; 11384 Ptr = ST->getBasePtr(); 11385 isLoad = false; 11386 } else { 11387 return false; 11388 } 11389 11390 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 11391 // out. There is no reason to make this a preinc/predec. 11392 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 11393 Ptr.getNode()->hasOneUse()) 11394 return false; 11395 11396 // Ask the target to do addressing mode selection. 11397 SDValue BasePtr; 11398 SDValue Offset; 11399 ISD::MemIndexedMode AM = ISD::UNINDEXED; 11400 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 11401 return false; 11402 11403 // Backends without true r+i pre-indexed forms may need to pass a 11404 // constant base with a variable offset so that constant coercion 11405 // will work with the patterns in canonical form. 11406 bool Swapped = false; 11407 if (isa<ConstantSDNode>(BasePtr)) { 11408 std::swap(BasePtr, Offset); 11409 Swapped = true; 11410 } 11411 11412 // Don't create a indexed load / store with zero offset. 11413 if (isNullConstant(Offset)) 11414 return false; 11415 11416 // Try turning it into a pre-indexed load / store except when: 11417 // 1) The new base ptr is a frame index. 11418 // 2) If N is a store and the new base ptr is either the same as or is a 11419 // predecessor of the value being stored. 11420 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 11421 // that would create a cycle. 11422 // 4) All uses are load / store ops that use it as old base ptr. 11423 11424 // Check #1. Preinc'ing a frame index would require copying the stack pointer 11425 // (plus the implicit offset) to a register to preinc anyway. 11426 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 11427 return false; 11428 11429 // Check #2. 11430 if (!isLoad) { 11431 SDValue Val = cast<StoreSDNode>(N)->getValue(); 11432 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 11433 return false; 11434 } 11435 11436 // Caches for hasPredecessorHelper. 11437 SmallPtrSet<const SDNode *, 32> Visited; 11438 SmallVector<const SDNode *, 16> Worklist; 11439 Worklist.push_back(N); 11440 11441 // If the offset is a constant, there may be other adds of constants that 11442 // can be folded with this one. We should do this to avoid having to keep 11443 // a copy of the original base pointer. 11444 SmallVector<SDNode *, 16> OtherUses; 11445 if (isa<ConstantSDNode>(Offset)) 11446 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 11447 UE = BasePtr.getNode()->use_end(); 11448 UI != UE; ++UI) { 11449 SDUse &Use = UI.getUse(); 11450 // Skip the use that is Ptr and uses of other results from BasePtr's 11451 // node (important for nodes that return multiple results). 11452 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 11453 continue; 11454 11455 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 11456 continue; 11457 11458 if (Use.getUser()->getOpcode() != ISD::ADD && 11459 Use.getUser()->getOpcode() != ISD::SUB) { 11460 OtherUses.clear(); 11461 break; 11462 } 11463 11464 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 11465 if (!isa<ConstantSDNode>(Op1)) { 11466 OtherUses.clear(); 11467 break; 11468 } 11469 11470 // FIXME: In some cases, we can be smarter about this. 11471 if (Op1.getValueType() != Offset.getValueType()) { 11472 OtherUses.clear(); 11473 break; 11474 } 11475 11476 OtherUses.push_back(Use.getUser()); 11477 } 11478 11479 if (Swapped) 11480 std::swap(BasePtr, Offset); 11481 11482 // Now check for #3 and #4. 11483 bool RealUse = false; 11484 11485 for (SDNode *Use : Ptr.getNode()->uses()) { 11486 if (Use == N) 11487 continue; 11488 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 11489 return false; 11490 11491 // If Ptr may be folded in addressing mode of other use, then it's 11492 // not profitable to do this transformation. 11493 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 11494 RealUse = true; 11495 } 11496 11497 if (!RealUse) 11498 return false; 11499 11500 SDValue Result; 11501 if (isLoad) 11502 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 11503 BasePtr, Offset, AM); 11504 else 11505 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 11506 BasePtr, Offset, AM); 11507 ++PreIndexedNodes; 11508 ++NodesCombined; 11509 DEBUG(dbgs() << "\nReplacing.4 "; 11510 N->dump(&DAG); 11511 dbgs() << "\nWith: "; 11512 Result.getNode()->dump(&DAG); 11513 dbgs() << '\n'); 11514 WorklistRemover DeadNodes(*this); 11515 if (isLoad) { 11516 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 11517 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 11518 } else { 11519 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 11520 } 11521 11522 // Finally, since the node is now dead, remove it from the graph. 11523 deleteAndRecombine(N); 11524 11525 if (Swapped) 11526 std::swap(BasePtr, Offset); 11527 11528 // Replace other uses of BasePtr that can be updated to use Ptr 11529 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 11530 unsigned OffsetIdx = 1; 11531 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 11532 OffsetIdx = 0; 11533 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 11534 BasePtr.getNode() && "Expected BasePtr operand"); 11535 11536 // We need to replace ptr0 in the following expression: 11537 // x0 * offset0 + y0 * ptr0 = t0 11538 // knowing that 11539 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 11540 // 11541 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 11542 // indexed load/store and the expression that needs to be re-written. 11543 // 11544 // Therefore, we have: 11545 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 11546 11547 ConstantSDNode *CN = 11548 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 11549 int X0, X1, Y0, Y1; 11550 const APInt &Offset0 = CN->getAPIntValue(); 11551 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 11552 11553 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 11554 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 11555 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 11556 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 11557 11558 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 11559 11560 APInt CNV = Offset0; 11561 if (X0 < 0) CNV = -CNV; 11562 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 11563 else CNV = CNV - Offset1; 11564 11565 SDLoc DL(OtherUses[i]); 11566 11567 // We can now generate the new expression. 11568 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 11569 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 11570 11571 SDValue NewUse = DAG.getNode(Opcode, 11572 DL, 11573 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 11574 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 11575 deleteAndRecombine(OtherUses[i]); 11576 } 11577 11578 // Replace the uses of Ptr with uses of the updated base value. 11579 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 11580 deleteAndRecombine(Ptr.getNode()); 11581 AddToWorklist(Result.getNode()); 11582 11583 return true; 11584 } 11585 11586 /// Try to combine a load/store with a add/sub of the base pointer node into a 11587 /// post-indexed load/store. The transformation folded the add/subtract into the 11588 /// new indexed load/store effectively and all of its uses are redirected to the 11589 /// new load/store. 11590 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 11591 if (Level < AfterLegalizeDAG) 11592 return false; 11593 11594 bool isLoad = true; 11595 SDValue Ptr; 11596 EVT VT; 11597 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11598 if (LD->isIndexed()) 11599 return false; 11600 VT = LD->getMemoryVT(); 11601 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 11602 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 11603 return false; 11604 Ptr = LD->getBasePtr(); 11605 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11606 if (ST->isIndexed()) 11607 return false; 11608 VT = ST->getMemoryVT(); 11609 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 11610 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 11611 return false; 11612 Ptr = ST->getBasePtr(); 11613 isLoad = false; 11614 } else { 11615 return false; 11616 } 11617 11618 if (Ptr.getNode()->hasOneUse()) 11619 return false; 11620 11621 for (SDNode *Op : Ptr.getNode()->uses()) { 11622 if (Op == N || 11623 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 11624 continue; 11625 11626 SDValue BasePtr; 11627 SDValue Offset; 11628 ISD::MemIndexedMode AM = ISD::UNINDEXED; 11629 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 11630 // Don't create a indexed load / store with zero offset. 11631 if (isNullConstant(Offset)) 11632 continue; 11633 11634 // Try turning it into a post-indexed load / store except when 11635 // 1) All uses are load / store ops that use it as base ptr (and 11636 // it may be folded as addressing mmode). 11637 // 2) Op must be independent of N, i.e. Op is neither a predecessor 11638 // nor a successor of N. Otherwise, if Op is folded that would 11639 // create a cycle. 11640 11641 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 11642 continue; 11643 11644 // Check for #1. 11645 bool TryNext = false; 11646 for (SDNode *Use : BasePtr.getNode()->uses()) { 11647 if (Use == Ptr.getNode()) 11648 continue; 11649 11650 // If all the uses are load / store addresses, then don't do the 11651 // transformation. 11652 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 11653 bool RealUse = false; 11654 for (SDNode *UseUse : Use->uses()) { 11655 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 11656 RealUse = true; 11657 } 11658 11659 if (!RealUse) { 11660 TryNext = true; 11661 break; 11662 } 11663 } 11664 } 11665 11666 if (TryNext) 11667 continue; 11668 11669 // Check for #2 11670 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 11671 SDValue Result = isLoad 11672 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 11673 BasePtr, Offset, AM) 11674 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 11675 BasePtr, Offset, AM); 11676 ++PostIndexedNodes; 11677 ++NodesCombined; 11678 DEBUG(dbgs() << "\nReplacing.5 "; 11679 N->dump(&DAG); 11680 dbgs() << "\nWith: "; 11681 Result.getNode()->dump(&DAG); 11682 dbgs() << '\n'); 11683 WorklistRemover DeadNodes(*this); 11684 if (isLoad) { 11685 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 11686 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 11687 } else { 11688 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 11689 } 11690 11691 // Finally, since the node is now dead, remove it from the graph. 11692 deleteAndRecombine(N); 11693 11694 // Replace the uses of Use with uses of the updated base value. 11695 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 11696 Result.getValue(isLoad ? 1 : 0)); 11697 deleteAndRecombine(Op); 11698 return true; 11699 } 11700 } 11701 } 11702 11703 return false; 11704 } 11705 11706 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 11707 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 11708 ISD::MemIndexedMode AM = LD->getAddressingMode(); 11709 assert(AM != ISD::UNINDEXED); 11710 SDValue BP = LD->getOperand(1); 11711 SDValue Inc = LD->getOperand(2); 11712 11713 // Some backends use TargetConstants for load offsets, but don't expect 11714 // TargetConstants in general ADD nodes. We can convert these constants into 11715 // regular Constants (if the constant is not opaque). 11716 assert((Inc.getOpcode() != ISD::TargetConstant || 11717 !cast<ConstantSDNode>(Inc)->isOpaque()) && 11718 "Cannot split out indexing using opaque target constants"); 11719 if (Inc.getOpcode() == ISD::TargetConstant) { 11720 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 11721 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 11722 ConstInc->getValueType(0)); 11723 } 11724 11725 unsigned Opc = 11726 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 11727 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 11728 } 11729 11730 SDValue DAGCombiner::visitLOAD(SDNode *N) { 11731 LoadSDNode *LD = cast<LoadSDNode>(N); 11732 SDValue Chain = LD->getChain(); 11733 SDValue Ptr = LD->getBasePtr(); 11734 11735 // If load is not volatile and there are no uses of the loaded value (and 11736 // the updated indexed value in case of indexed loads), change uses of the 11737 // chain value into uses of the chain input (i.e. delete the dead load). 11738 if (!LD->isVolatile()) { 11739 if (N->getValueType(1) == MVT::Other) { 11740 // Unindexed loads. 11741 if (!N->hasAnyUseOfValue(0)) { 11742 // It's not safe to use the two value CombineTo variant here. e.g. 11743 // v1, chain2 = load chain1, loc 11744 // v2, chain3 = load chain2, loc 11745 // v3 = add v2, c 11746 // Now we replace use of chain2 with chain1. This makes the second load 11747 // isomorphic to the one we are deleting, and thus makes this load live. 11748 DEBUG(dbgs() << "\nReplacing.6 "; 11749 N->dump(&DAG); 11750 dbgs() << "\nWith chain: "; 11751 Chain.getNode()->dump(&DAG); 11752 dbgs() << "\n"); 11753 WorklistRemover DeadNodes(*this); 11754 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 11755 AddUsersToWorklist(Chain.getNode()); 11756 if (N->use_empty()) 11757 deleteAndRecombine(N); 11758 11759 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11760 } 11761 } else { 11762 // Indexed loads. 11763 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 11764 11765 // If this load has an opaque TargetConstant offset, then we cannot split 11766 // the indexing into an add/sub directly (that TargetConstant may not be 11767 // valid for a different type of node, and we cannot convert an opaque 11768 // target constant into a regular constant). 11769 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 11770 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 11771 11772 if (!N->hasAnyUseOfValue(0) && 11773 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 11774 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 11775 SDValue Index; 11776 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 11777 Index = SplitIndexingFromLoad(LD); 11778 // Try to fold the base pointer arithmetic into subsequent loads and 11779 // stores. 11780 AddUsersToWorklist(N); 11781 } else 11782 Index = DAG.getUNDEF(N->getValueType(1)); 11783 DEBUG(dbgs() << "\nReplacing.7 "; 11784 N->dump(&DAG); 11785 dbgs() << "\nWith: "; 11786 Undef.getNode()->dump(&DAG); 11787 dbgs() << " and 2 other values\n"); 11788 WorklistRemover DeadNodes(*this); 11789 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 11790 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 11791 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 11792 deleteAndRecombine(N); 11793 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11794 } 11795 } 11796 } 11797 11798 // If this load is directly stored, replace the load value with the stored 11799 // value. 11800 // TODO: Handle store large -> read small portion. 11801 // TODO: Handle TRUNCSTORE/LOADEXT 11802 if (OptLevel != CodeGenOpt::None && 11803 ISD::isNormalLoad(N) && !LD->isVolatile()) { 11804 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 11805 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 11806 if (PrevST->getBasePtr() == Ptr && 11807 PrevST->getValue().getValueType() == N->getValueType(0)) 11808 return CombineTo(N, PrevST->getOperand(1), Chain); 11809 } 11810 } 11811 11812 // Try to infer better alignment information than the load already has. 11813 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 11814 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 11815 if (Align > LD->getMemOperand()->getBaseAlignment()) { 11816 SDValue NewLoad = DAG.getExtLoad( 11817 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 11818 LD->getPointerInfo(), LD->getMemoryVT(), Align, 11819 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 11820 if (NewLoad.getNode() != N) 11821 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 11822 } 11823 } 11824 } 11825 11826 if (LD->isUnindexed()) { 11827 // Walk up chain skipping non-aliasing memory nodes. 11828 SDValue BetterChain = FindBetterChain(N, Chain); 11829 11830 // If there is a better chain. 11831 if (Chain != BetterChain) { 11832 SDValue ReplLoad; 11833 11834 // Replace the chain to void dependency. 11835 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 11836 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 11837 BetterChain, Ptr, LD->getMemOperand()); 11838 } else { 11839 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 11840 LD->getValueType(0), 11841 BetterChain, Ptr, LD->getMemoryVT(), 11842 LD->getMemOperand()); 11843 } 11844 11845 // Create token factor to keep old chain connected. 11846 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 11847 MVT::Other, Chain, ReplLoad.getValue(1)); 11848 11849 // Replace uses with load result and token factor 11850 return CombineTo(N, ReplLoad.getValue(0), Token); 11851 } 11852 } 11853 11854 // Try transforming N to an indexed load. 11855 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 11856 return SDValue(N, 0); 11857 11858 // Try to slice up N to more direct loads if the slices are mapped to 11859 // different register banks or pairing can take place. 11860 if (SliceUpLoad(N)) 11861 return SDValue(N, 0); 11862 11863 return SDValue(); 11864 } 11865 11866 namespace { 11867 11868 /// \brief Helper structure used to slice a load in smaller loads. 11869 /// Basically a slice is obtained from the following sequence: 11870 /// Origin = load Ty1, Base 11871 /// Shift = srl Ty1 Origin, CstTy Amount 11872 /// Inst = trunc Shift to Ty2 11873 /// 11874 /// Then, it will be rewritten into: 11875 /// Slice = load SliceTy, Base + SliceOffset 11876 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 11877 /// 11878 /// SliceTy is deduced from the number of bits that are actually used to 11879 /// build Inst. 11880 struct LoadedSlice { 11881 /// \brief Helper structure used to compute the cost of a slice. 11882 struct Cost { 11883 /// Are we optimizing for code size. 11884 bool ForCodeSize; 11885 11886 /// Various cost. 11887 unsigned Loads = 0; 11888 unsigned Truncates = 0; 11889 unsigned CrossRegisterBanksCopies = 0; 11890 unsigned ZExts = 0; 11891 unsigned Shift = 0; 11892 11893 Cost(bool ForCodeSize = false) : ForCodeSize(ForCodeSize) {} 11894 11895 /// \brief Get the cost of one isolated slice. 11896 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 11897 : ForCodeSize(ForCodeSize), Loads(1) { 11898 EVT TruncType = LS.Inst->getValueType(0); 11899 EVT LoadedType = LS.getLoadedType(); 11900 if (TruncType != LoadedType && 11901 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 11902 ZExts = 1; 11903 } 11904 11905 /// \brief Account for slicing gain in the current cost. 11906 /// Slicing provide a few gains like removing a shift or a 11907 /// truncate. This method allows to grow the cost of the original 11908 /// load with the gain from this slice. 11909 void addSliceGain(const LoadedSlice &LS) { 11910 // Each slice saves a truncate. 11911 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 11912 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 11913 LS.Inst->getValueType(0))) 11914 ++Truncates; 11915 // If there is a shift amount, this slice gets rid of it. 11916 if (LS.Shift) 11917 ++Shift; 11918 // If this slice can merge a cross register bank copy, account for it. 11919 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 11920 ++CrossRegisterBanksCopies; 11921 } 11922 11923 Cost &operator+=(const Cost &RHS) { 11924 Loads += RHS.Loads; 11925 Truncates += RHS.Truncates; 11926 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 11927 ZExts += RHS.ZExts; 11928 Shift += RHS.Shift; 11929 return *this; 11930 } 11931 11932 bool operator==(const Cost &RHS) const { 11933 return Loads == RHS.Loads && Truncates == RHS.Truncates && 11934 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 11935 ZExts == RHS.ZExts && Shift == RHS.Shift; 11936 } 11937 11938 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 11939 11940 bool operator<(const Cost &RHS) const { 11941 // Assume cross register banks copies are as expensive as loads. 11942 // FIXME: Do we want some more target hooks? 11943 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 11944 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 11945 // Unless we are optimizing for code size, consider the 11946 // expensive operation first. 11947 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 11948 return ExpensiveOpsLHS < ExpensiveOpsRHS; 11949 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 11950 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 11951 } 11952 11953 bool operator>(const Cost &RHS) const { return RHS < *this; } 11954 11955 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 11956 11957 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 11958 }; 11959 11960 // The last instruction that represent the slice. This should be a 11961 // truncate instruction. 11962 SDNode *Inst; 11963 11964 // The original load instruction. 11965 LoadSDNode *Origin; 11966 11967 // The right shift amount in bits from the original load. 11968 unsigned Shift; 11969 11970 // The DAG from which Origin came from. 11971 // This is used to get some contextual information about legal types, etc. 11972 SelectionDAG *DAG; 11973 11974 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 11975 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 11976 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 11977 11978 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 11979 /// \return Result is \p BitWidth and has used bits set to 1 and 11980 /// not used bits set to 0. 11981 APInt getUsedBits() const { 11982 // Reproduce the trunc(lshr) sequence: 11983 // - Start from the truncated value. 11984 // - Zero extend to the desired bit width. 11985 // - Shift left. 11986 assert(Origin && "No original load to compare against."); 11987 unsigned BitWidth = Origin->getValueSizeInBits(0); 11988 assert(Inst && "This slice is not bound to an instruction"); 11989 assert(Inst->getValueSizeInBits(0) <= BitWidth && 11990 "Extracted slice is bigger than the whole type!"); 11991 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 11992 UsedBits.setAllBits(); 11993 UsedBits = UsedBits.zext(BitWidth); 11994 UsedBits <<= Shift; 11995 return UsedBits; 11996 } 11997 11998 /// \brief Get the size of the slice to be loaded in bytes. 11999 unsigned getLoadedSize() const { 12000 unsigned SliceSize = getUsedBits().countPopulation(); 12001 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 12002 return SliceSize / 8; 12003 } 12004 12005 /// \brief Get the type that will be loaded for this slice. 12006 /// Note: This may not be the final type for the slice. 12007 EVT getLoadedType() const { 12008 assert(DAG && "Missing context"); 12009 LLVMContext &Ctxt = *DAG->getContext(); 12010 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 12011 } 12012 12013 /// \brief Get the alignment of the load used for this slice. 12014 unsigned getAlignment() const { 12015 unsigned Alignment = Origin->getAlignment(); 12016 unsigned Offset = getOffsetFromBase(); 12017 if (Offset != 0) 12018 Alignment = MinAlign(Alignment, Alignment + Offset); 12019 return Alignment; 12020 } 12021 12022 /// \brief Check if this slice can be rewritten with legal operations. 12023 bool isLegal() const { 12024 // An invalid slice is not legal. 12025 if (!Origin || !Inst || !DAG) 12026 return false; 12027 12028 // Offsets are for indexed load only, we do not handle that. 12029 if (!Origin->getOffset().isUndef()) 12030 return false; 12031 12032 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 12033 12034 // Check that the type is legal. 12035 EVT SliceType = getLoadedType(); 12036 if (!TLI.isTypeLegal(SliceType)) 12037 return false; 12038 12039 // Check that the load is legal for this type. 12040 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 12041 return false; 12042 12043 // Check that the offset can be computed. 12044 // 1. Check its type. 12045 EVT PtrType = Origin->getBasePtr().getValueType(); 12046 if (PtrType == MVT::Untyped || PtrType.isExtended()) 12047 return false; 12048 12049 // 2. Check that it fits in the immediate. 12050 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 12051 return false; 12052 12053 // 3. Check that the computation is legal. 12054 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 12055 return false; 12056 12057 // Check that the zext is legal if it needs one. 12058 EVT TruncateType = Inst->getValueType(0); 12059 if (TruncateType != SliceType && 12060 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 12061 return false; 12062 12063 return true; 12064 } 12065 12066 /// \brief Get the offset in bytes of this slice in the original chunk of 12067 /// bits. 12068 /// \pre DAG != nullptr. 12069 uint64_t getOffsetFromBase() const { 12070 assert(DAG && "Missing context."); 12071 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 12072 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 12073 uint64_t Offset = Shift / 8; 12074 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 12075 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 12076 "The size of the original loaded type is not a multiple of a" 12077 " byte."); 12078 // If Offset is bigger than TySizeInBytes, it means we are loading all 12079 // zeros. This should have been optimized before in the process. 12080 assert(TySizeInBytes > Offset && 12081 "Invalid shift amount for given loaded size"); 12082 if (IsBigEndian) 12083 Offset = TySizeInBytes - Offset - getLoadedSize(); 12084 return Offset; 12085 } 12086 12087 /// \brief Generate the sequence of instructions to load the slice 12088 /// represented by this object and redirect the uses of this slice to 12089 /// this new sequence of instructions. 12090 /// \pre this->Inst && this->Origin are valid Instructions and this 12091 /// object passed the legal check: LoadedSlice::isLegal returned true. 12092 /// \return The last instruction of the sequence used to load the slice. 12093 SDValue loadSlice() const { 12094 assert(Inst && Origin && "Unable to replace a non-existing slice."); 12095 const SDValue &OldBaseAddr = Origin->getBasePtr(); 12096 SDValue BaseAddr = OldBaseAddr; 12097 // Get the offset in that chunk of bytes w.r.t. the endianness. 12098 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 12099 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 12100 if (Offset) { 12101 // BaseAddr = BaseAddr + Offset. 12102 EVT ArithType = BaseAddr.getValueType(); 12103 SDLoc DL(Origin); 12104 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 12105 DAG->getConstant(Offset, DL, ArithType)); 12106 } 12107 12108 // Create the type of the loaded slice according to its size. 12109 EVT SliceType = getLoadedType(); 12110 12111 // Create the load for the slice. 12112 SDValue LastInst = 12113 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 12114 Origin->getPointerInfo().getWithOffset(Offset), 12115 getAlignment(), Origin->getMemOperand()->getFlags()); 12116 // If the final type is not the same as the loaded type, this means that 12117 // we have to pad with zero. Create a zero extend for that. 12118 EVT FinalType = Inst->getValueType(0); 12119 if (SliceType != FinalType) 12120 LastInst = 12121 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 12122 return LastInst; 12123 } 12124 12125 /// \brief Check if this slice can be merged with an expensive cross register 12126 /// bank copy. E.g., 12127 /// i = load i32 12128 /// f = bitcast i32 i to float 12129 bool canMergeExpensiveCrossRegisterBankCopy() const { 12130 if (!Inst || !Inst->hasOneUse()) 12131 return false; 12132 SDNode *Use = *Inst->use_begin(); 12133 if (Use->getOpcode() != ISD::BITCAST) 12134 return false; 12135 assert(DAG && "Missing context"); 12136 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 12137 EVT ResVT = Use->getValueType(0); 12138 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 12139 const TargetRegisterClass *ArgRC = 12140 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 12141 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 12142 return false; 12143 12144 // At this point, we know that we perform a cross-register-bank copy. 12145 // Check if it is expensive. 12146 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 12147 // Assume bitcasts are cheap, unless both register classes do not 12148 // explicitly share a common sub class. 12149 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 12150 return false; 12151 12152 // Check if it will be merged with the load. 12153 // 1. Check the alignment constraint. 12154 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 12155 ResVT.getTypeForEVT(*DAG->getContext())); 12156 12157 if (RequiredAlignment > getAlignment()) 12158 return false; 12159 12160 // 2. Check that the load is a legal operation for that type. 12161 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 12162 return false; 12163 12164 // 3. Check that we do not have a zext in the way. 12165 if (Inst->getValueType(0) != getLoadedType()) 12166 return false; 12167 12168 return true; 12169 } 12170 }; 12171 12172 } // end anonymous namespace 12173 12174 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 12175 /// \p UsedBits looks like 0..0 1..1 0..0. 12176 static bool areUsedBitsDense(const APInt &UsedBits) { 12177 // If all the bits are one, this is dense! 12178 if (UsedBits.isAllOnesValue()) 12179 return true; 12180 12181 // Get rid of the unused bits on the right. 12182 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 12183 // Get rid of the unused bits on the left. 12184 if (NarrowedUsedBits.countLeadingZeros()) 12185 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 12186 // Check that the chunk of bits is completely used. 12187 return NarrowedUsedBits.isAllOnesValue(); 12188 } 12189 12190 /// \brief Check whether or not \p First and \p Second are next to each other 12191 /// in memory. This means that there is no hole between the bits loaded 12192 /// by \p First and the bits loaded by \p Second. 12193 static bool areSlicesNextToEachOther(const LoadedSlice &First, 12194 const LoadedSlice &Second) { 12195 assert(First.Origin == Second.Origin && First.Origin && 12196 "Unable to match different memory origins."); 12197 APInt UsedBits = First.getUsedBits(); 12198 assert((UsedBits & Second.getUsedBits()) == 0 && 12199 "Slices are not supposed to overlap."); 12200 UsedBits |= Second.getUsedBits(); 12201 return areUsedBitsDense(UsedBits); 12202 } 12203 12204 /// \brief Adjust the \p GlobalLSCost according to the target 12205 /// paring capabilities and the layout of the slices. 12206 /// \pre \p GlobalLSCost should account for at least as many loads as 12207 /// there is in the slices in \p LoadedSlices. 12208 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 12209 LoadedSlice::Cost &GlobalLSCost) { 12210 unsigned NumberOfSlices = LoadedSlices.size(); 12211 // If there is less than 2 elements, no pairing is possible. 12212 if (NumberOfSlices < 2) 12213 return; 12214 12215 // Sort the slices so that elements that are likely to be next to each 12216 // other in memory are next to each other in the list. 12217 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 12218 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 12219 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 12220 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 12221 }); 12222 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 12223 // First (resp. Second) is the first (resp. Second) potentially candidate 12224 // to be placed in a paired load. 12225 const LoadedSlice *First = nullptr; 12226 const LoadedSlice *Second = nullptr; 12227 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 12228 // Set the beginning of the pair. 12229 First = Second) { 12230 Second = &LoadedSlices[CurrSlice]; 12231 12232 // If First is NULL, it means we start a new pair. 12233 // Get to the next slice. 12234 if (!First) 12235 continue; 12236 12237 EVT LoadedType = First->getLoadedType(); 12238 12239 // If the types of the slices are different, we cannot pair them. 12240 if (LoadedType != Second->getLoadedType()) 12241 continue; 12242 12243 // Check if the target supplies paired loads for this type. 12244 unsigned RequiredAlignment = 0; 12245 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 12246 // move to the next pair, this type is hopeless. 12247 Second = nullptr; 12248 continue; 12249 } 12250 // Check if we meet the alignment requirement. 12251 if (RequiredAlignment > First->getAlignment()) 12252 continue; 12253 12254 // Check that both loads are next to each other in memory. 12255 if (!areSlicesNextToEachOther(*First, *Second)) 12256 continue; 12257 12258 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 12259 --GlobalLSCost.Loads; 12260 // Move to the next pair. 12261 Second = nullptr; 12262 } 12263 } 12264 12265 /// \brief Check the profitability of all involved LoadedSlice. 12266 /// Currently, it is considered profitable if there is exactly two 12267 /// involved slices (1) which are (2) next to each other in memory, and 12268 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 12269 /// 12270 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 12271 /// the elements themselves. 12272 /// 12273 /// FIXME: When the cost model will be mature enough, we can relax 12274 /// constraints (1) and (2). 12275 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 12276 const APInt &UsedBits, bool ForCodeSize) { 12277 unsigned NumberOfSlices = LoadedSlices.size(); 12278 if (StressLoadSlicing) 12279 return NumberOfSlices > 1; 12280 12281 // Check (1). 12282 if (NumberOfSlices != 2) 12283 return false; 12284 12285 // Check (2). 12286 if (!areUsedBitsDense(UsedBits)) 12287 return false; 12288 12289 // Check (3). 12290 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 12291 // The original code has one big load. 12292 OrigCost.Loads = 1; 12293 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 12294 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 12295 // Accumulate the cost of all the slices. 12296 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 12297 GlobalSlicingCost += SliceCost; 12298 12299 // Account as cost in the original configuration the gain obtained 12300 // with the current slices. 12301 OrigCost.addSliceGain(LS); 12302 } 12303 12304 // If the target supports paired load, adjust the cost accordingly. 12305 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 12306 return OrigCost > GlobalSlicingCost; 12307 } 12308 12309 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 12310 /// operations, split it in the various pieces being extracted. 12311 /// 12312 /// This sort of thing is introduced by SROA. 12313 /// This slicing takes care not to insert overlapping loads. 12314 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 12315 bool DAGCombiner::SliceUpLoad(SDNode *N) { 12316 if (Level < AfterLegalizeDAG) 12317 return false; 12318 12319 LoadSDNode *LD = cast<LoadSDNode>(N); 12320 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 12321 !LD->getValueType(0).isInteger()) 12322 return false; 12323 12324 // Keep track of already used bits to detect overlapping values. 12325 // In that case, we will just abort the transformation. 12326 APInt UsedBits(LD->getValueSizeInBits(0), 0); 12327 12328 SmallVector<LoadedSlice, 4> LoadedSlices; 12329 12330 // Check if this load is used as several smaller chunks of bits. 12331 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 12332 // of computation for each trunc. 12333 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 12334 UI != UIEnd; ++UI) { 12335 // Skip the uses of the chain. 12336 if (UI.getUse().getResNo() != 0) 12337 continue; 12338 12339 SDNode *User = *UI; 12340 unsigned Shift = 0; 12341 12342 // Check if this is a trunc(lshr). 12343 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 12344 isa<ConstantSDNode>(User->getOperand(1))) { 12345 Shift = User->getConstantOperandVal(1); 12346 User = *User->use_begin(); 12347 } 12348 12349 // At this point, User is a Truncate, iff we encountered, trunc or 12350 // trunc(lshr). 12351 if (User->getOpcode() != ISD::TRUNCATE) 12352 return false; 12353 12354 // The width of the type must be a power of 2 and greater than 8-bits. 12355 // Otherwise the load cannot be represented in LLVM IR. 12356 // Moreover, if we shifted with a non-8-bits multiple, the slice 12357 // will be across several bytes. We do not support that. 12358 unsigned Width = User->getValueSizeInBits(0); 12359 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 12360 return false; 12361 12362 // Build the slice for this chain of computations. 12363 LoadedSlice LS(User, LD, Shift, &DAG); 12364 APInt CurrentUsedBits = LS.getUsedBits(); 12365 12366 // Check if this slice overlaps with another. 12367 if ((CurrentUsedBits & UsedBits) != 0) 12368 return false; 12369 // Update the bits used globally. 12370 UsedBits |= CurrentUsedBits; 12371 12372 // Check if the new slice would be legal. 12373 if (!LS.isLegal()) 12374 return false; 12375 12376 // Record the slice. 12377 LoadedSlices.push_back(LS); 12378 } 12379 12380 // Abort slicing if it does not seem to be profitable. 12381 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 12382 return false; 12383 12384 ++SlicedLoads; 12385 12386 // Rewrite each chain to use an independent load. 12387 // By construction, each chain can be represented by a unique load. 12388 12389 // Prepare the argument for the new token factor for all the slices. 12390 SmallVector<SDValue, 8> ArgChains; 12391 for (SmallVectorImpl<LoadedSlice>::const_iterator 12392 LSIt = LoadedSlices.begin(), 12393 LSItEnd = LoadedSlices.end(); 12394 LSIt != LSItEnd; ++LSIt) { 12395 SDValue SliceInst = LSIt->loadSlice(); 12396 CombineTo(LSIt->Inst, SliceInst, true); 12397 if (SliceInst.getOpcode() != ISD::LOAD) 12398 SliceInst = SliceInst.getOperand(0); 12399 assert(SliceInst->getOpcode() == ISD::LOAD && 12400 "It takes more than a zext to get to the loaded slice!!"); 12401 ArgChains.push_back(SliceInst.getValue(1)); 12402 } 12403 12404 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 12405 ArgChains); 12406 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 12407 AddToWorklist(Chain.getNode()); 12408 return true; 12409 } 12410 12411 /// Check to see if V is (and load (ptr), imm), where the load is having 12412 /// specific bytes cleared out. If so, return the byte size being masked out 12413 /// and the shift amount. 12414 static std::pair<unsigned, unsigned> 12415 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 12416 std::pair<unsigned, unsigned> Result(0, 0); 12417 12418 // Check for the structure we're looking for. 12419 if (V->getOpcode() != ISD::AND || 12420 !isa<ConstantSDNode>(V->getOperand(1)) || 12421 !ISD::isNormalLoad(V->getOperand(0).getNode())) 12422 return Result; 12423 12424 // Check the chain and pointer. 12425 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 12426 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 12427 12428 // The store should be chained directly to the load or be an operand of a 12429 // tokenfactor. 12430 if (LD == Chain.getNode()) 12431 ; // ok. 12432 else if (Chain->getOpcode() != ISD::TokenFactor) 12433 return Result; // Fail. 12434 else { 12435 bool isOk = false; 12436 for (const SDValue &ChainOp : Chain->op_values()) 12437 if (ChainOp.getNode() == LD) { 12438 isOk = true; 12439 break; 12440 } 12441 if (!isOk) return Result; 12442 } 12443 12444 // This only handles simple types. 12445 if (V.getValueType() != MVT::i16 && 12446 V.getValueType() != MVT::i32 && 12447 V.getValueType() != MVT::i64) 12448 return Result; 12449 12450 // Check the constant mask. Invert it so that the bits being masked out are 12451 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 12452 // follow the sign bit for uniformity. 12453 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 12454 unsigned NotMaskLZ = countLeadingZeros(NotMask); 12455 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 12456 unsigned NotMaskTZ = countTrailingZeros(NotMask); 12457 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 12458 if (NotMaskLZ == 64) return Result; // All zero mask. 12459 12460 // See if we have a continuous run of bits. If so, we have 0*1+0* 12461 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 12462 return Result; 12463 12464 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 12465 if (V.getValueType() != MVT::i64 && NotMaskLZ) 12466 NotMaskLZ -= 64-V.getValueSizeInBits(); 12467 12468 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 12469 switch (MaskedBytes) { 12470 case 1: 12471 case 2: 12472 case 4: break; 12473 default: return Result; // All one mask, or 5-byte mask. 12474 } 12475 12476 // Verify that the first bit starts at a multiple of mask so that the access 12477 // is aligned the same as the access width. 12478 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 12479 12480 Result.first = MaskedBytes; 12481 Result.second = NotMaskTZ/8; 12482 return Result; 12483 } 12484 12485 /// Check to see if IVal is something that provides a value as specified by 12486 /// MaskInfo. If so, replace the specified store with a narrower store of 12487 /// truncated IVal. 12488 static SDNode * 12489 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 12490 SDValue IVal, StoreSDNode *St, 12491 DAGCombiner *DC) { 12492 unsigned NumBytes = MaskInfo.first; 12493 unsigned ByteShift = MaskInfo.second; 12494 SelectionDAG &DAG = DC->getDAG(); 12495 12496 // Check to see if IVal is all zeros in the part being masked in by the 'or' 12497 // that uses this. If not, this is not a replacement. 12498 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 12499 ByteShift*8, (ByteShift+NumBytes)*8); 12500 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 12501 12502 // Check that it is legal on the target to do this. It is legal if the new 12503 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 12504 // legalization. 12505 MVT VT = MVT::getIntegerVT(NumBytes*8); 12506 if (!DC->isTypeLegal(VT)) 12507 return nullptr; 12508 12509 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 12510 // shifted by ByteShift and truncated down to NumBytes. 12511 if (ByteShift) { 12512 SDLoc DL(IVal); 12513 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 12514 DAG.getConstant(ByteShift*8, DL, 12515 DC->getShiftAmountTy(IVal.getValueType()))); 12516 } 12517 12518 // Figure out the offset for the store and the alignment of the access. 12519 unsigned StOffset; 12520 unsigned NewAlign = St->getAlignment(); 12521 12522 if (DAG.getDataLayout().isLittleEndian()) 12523 StOffset = ByteShift; 12524 else 12525 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 12526 12527 SDValue Ptr = St->getBasePtr(); 12528 if (StOffset) { 12529 SDLoc DL(IVal); 12530 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 12531 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 12532 NewAlign = MinAlign(NewAlign, StOffset); 12533 } 12534 12535 // Truncate down to the new size. 12536 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 12537 12538 ++OpsNarrowed; 12539 return DAG 12540 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 12541 St->getPointerInfo().getWithOffset(StOffset), NewAlign) 12542 .getNode(); 12543 } 12544 12545 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 12546 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 12547 /// narrowing the load and store if it would end up being a win for performance 12548 /// or code size. 12549 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 12550 StoreSDNode *ST = cast<StoreSDNode>(N); 12551 if (ST->isVolatile()) 12552 return SDValue(); 12553 12554 SDValue Chain = ST->getChain(); 12555 SDValue Value = ST->getValue(); 12556 SDValue Ptr = ST->getBasePtr(); 12557 EVT VT = Value.getValueType(); 12558 12559 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 12560 return SDValue(); 12561 12562 unsigned Opc = Value.getOpcode(); 12563 12564 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 12565 // is a byte mask indicating a consecutive number of bytes, check to see if 12566 // Y is known to provide just those bytes. If so, we try to replace the 12567 // load + replace + store sequence with a single (narrower) store, which makes 12568 // the load dead. 12569 if (Opc == ISD::OR) { 12570 std::pair<unsigned, unsigned> MaskedLoad; 12571 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 12572 if (MaskedLoad.first) 12573 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 12574 Value.getOperand(1), ST,this)) 12575 return SDValue(NewST, 0); 12576 12577 // Or is commutative, so try swapping X and Y. 12578 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 12579 if (MaskedLoad.first) 12580 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 12581 Value.getOperand(0), ST,this)) 12582 return SDValue(NewST, 0); 12583 } 12584 12585 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 12586 Value.getOperand(1).getOpcode() != ISD::Constant) 12587 return SDValue(); 12588 12589 SDValue N0 = Value.getOperand(0); 12590 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 12591 Chain == SDValue(N0.getNode(), 1)) { 12592 LoadSDNode *LD = cast<LoadSDNode>(N0); 12593 if (LD->getBasePtr() != Ptr || 12594 LD->getPointerInfo().getAddrSpace() != 12595 ST->getPointerInfo().getAddrSpace()) 12596 return SDValue(); 12597 12598 // Find the type to narrow it the load / op / store to. 12599 SDValue N1 = Value.getOperand(1); 12600 unsigned BitWidth = N1.getValueSizeInBits(); 12601 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 12602 if (Opc == ISD::AND) 12603 Imm ^= APInt::getAllOnesValue(BitWidth); 12604 if (Imm == 0 || Imm.isAllOnesValue()) 12605 return SDValue(); 12606 unsigned ShAmt = Imm.countTrailingZeros(); 12607 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 12608 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 12609 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 12610 // The narrowing should be profitable, the load/store operation should be 12611 // legal (or custom) and the store size should be equal to the NewVT width. 12612 while (NewBW < BitWidth && 12613 (NewVT.getStoreSizeInBits() != NewBW || 12614 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 12615 !TLI.isNarrowingProfitable(VT, NewVT))) { 12616 NewBW = NextPowerOf2(NewBW); 12617 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 12618 } 12619 if (NewBW >= BitWidth) 12620 return SDValue(); 12621 12622 // If the lsb changed does not start at the type bitwidth boundary, 12623 // start at the previous one. 12624 if (ShAmt % NewBW) 12625 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 12626 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 12627 std::min(BitWidth, ShAmt + NewBW)); 12628 if ((Imm & Mask) == Imm) { 12629 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 12630 if (Opc == ISD::AND) 12631 NewImm ^= APInt::getAllOnesValue(NewBW); 12632 uint64_t PtrOff = ShAmt / 8; 12633 // For big endian targets, we need to adjust the offset to the pointer to 12634 // load the correct bytes. 12635 if (DAG.getDataLayout().isBigEndian()) 12636 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 12637 12638 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 12639 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 12640 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 12641 return SDValue(); 12642 12643 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 12644 Ptr.getValueType(), Ptr, 12645 DAG.getConstant(PtrOff, SDLoc(LD), 12646 Ptr.getValueType())); 12647 SDValue NewLD = 12648 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 12649 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 12650 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 12651 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 12652 DAG.getConstant(NewImm, SDLoc(Value), 12653 NewVT)); 12654 SDValue NewST = 12655 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 12656 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 12657 12658 AddToWorklist(NewPtr.getNode()); 12659 AddToWorklist(NewLD.getNode()); 12660 AddToWorklist(NewVal.getNode()); 12661 WorklistRemover DeadNodes(*this); 12662 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 12663 ++OpsNarrowed; 12664 return NewST; 12665 } 12666 } 12667 12668 return SDValue(); 12669 } 12670 12671 /// For a given floating point load / store pair, if the load value isn't used 12672 /// by any other operations, then consider transforming the pair to integer 12673 /// load / store operations if the target deems the transformation profitable. 12674 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 12675 StoreSDNode *ST = cast<StoreSDNode>(N); 12676 SDValue Chain = ST->getChain(); 12677 SDValue Value = ST->getValue(); 12678 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 12679 Value.hasOneUse() && 12680 Chain == SDValue(Value.getNode(), 1)) { 12681 LoadSDNode *LD = cast<LoadSDNode>(Value); 12682 EVT VT = LD->getMemoryVT(); 12683 if (!VT.isFloatingPoint() || 12684 VT != ST->getMemoryVT() || 12685 LD->isNonTemporal() || 12686 ST->isNonTemporal() || 12687 LD->getPointerInfo().getAddrSpace() != 0 || 12688 ST->getPointerInfo().getAddrSpace() != 0) 12689 return SDValue(); 12690 12691 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 12692 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 12693 !TLI.isOperationLegal(ISD::STORE, IntVT) || 12694 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 12695 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 12696 return SDValue(); 12697 12698 unsigned LDAlign = LD->getAlignment(); 12699 unsigned STAlign = ST->getAlignment(); 12700 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 12701 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 12702 if (LDAlign < ABIAlign || STAlign < ABIAlign) 12703 return SDValue(); 12704 12705 SDValue NewLD = 12706 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 12707 LD->getPointerInfo(), LDAlign); 12708 12709 SDValue NewST = 12710 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(), 12711 ST->getPointerInfo(), STAlign); 12712 12713 AddToWorklist(NewLD.getNode()); 12714 AddToWorklist(NewST.getNode()); 12715 WorklistRemover DeadNodes(*this); 12716 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 12717 ++LdStFP2Int; 12718 return NewST; 12719 } 12720 12721 return SDValue(); 12722 } 12723 12724 // This is a helper function for visitMUL to check the profitability 12725 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 12726 // MulNode is the original multiply, AddNode is (add x, c1), 12727 // and ConstNode is c2. 12728 // 12729 // If the (add x, c1) has multiple uses, we could increase 12730 // the number of adds if we make this transformation. 12731 // It would only be worth doing this if we can remove a 12732 // multiply in the process. Check for that here. 12733 // To illustrate: 12734 // (A + c1) * c3 12735 // (A + c2) * c3 12736 // We're checking for cases where we have common "c3 * A" expressions. 12737 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 12738 SDValue &AddNode, 12739 SDValue &ConstNode) { 12740 APInt Val; 12741 12742 // If the add only has one use, this would be OK to do. 12743 if (AddNode.getNode()->hasOneUse()) 12744 return true; 12745 12746 // Walk all the users of the constant with which we're multiplying. 12747 for (SDNode *Use : ConstNode->uses()) { 12748 if (Use == MulNode) // This use is the one we're on right now. Skip it. 12749 continue; 12750 12751 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 12752 SDNode *OtherOp; 12753 SDNode *MulVar = AddNode.getOperand(0).getNode(); 12754 12755 // OtherOp is what we're multiplying against the constant. 12756 if (Use->getOperand(0) == ConstNode) 12757 OtherOp = Use->getOperand(1).getNode(); 12758 else 12759 OtherOp = Use->getOperand(0).getNode(); 12760 12761 // Check to see if multiply is with the same operand of our "add". 12762 // 12763 // ConstNode = CONST 12764 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 12765 // ... 12766 // AddNode = (A + c1) <-- MulVar is A. 12767 // = AddNode * ConstNode <-- current visiting instruction. 12768 // 12769 // If we make this transformation, we will have a common 12770 // multiply (ConstNode * A) that we can save. 12771 if (OtherOp == MulVar) 12772 return true; 12773 12774 // Now check to see if a future expansion will give us a common 12775 // multiply. 12776 // 12777 // ConstNode = CONST 12778 // AddNode = (A + c1) 12779 // ... = AddNode * ConstNode <-- current visiting instruction. 12780 // ... 12781 // OtherOp = (A + c2) 12782 // Use = OtherOp * ConstNode <-- visiting Use. 12783 // 12784 // If we make this transformation, we will have a common 12785 // multiply (CONST * A) after we also do the same transformation 12786 // to the "t2" instruction. 12787 if (OtherOp->getOpcode() == ISD::ADD && 12788 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 12789 OtherOp->getOperand(0).getNode() == MulVar) 12790 return true; 12791 } 12792 } 12793 12794 // Didn't find a case where this would be profitable. 12795 return false; 12796 } 12797 12798 static SDValue peekThroughBitcast(SDValue V) { 12799 while (V.getOpcode() == ISD::BITCAST) 12800 V = V.getOperand(0); 12801 return V; 12802 } 12803 12804 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 12805 unsigned NumStores) { 12806 SmallVector<SDValue, 8> Chains; 12807 SmallPtrSet<const SDNode *, 8> Visited; 12808 SDLoc StoreDL(StoreNodes[0].MemNode); 12809 12810 for (unsigned i = 0; i < NumStores; ++i) { 12811 Visited.insert(StoreNodes[i].MemNode); 12812 } 12813 12814 // don't include nodes that are children 12815 for (unsigned i = 0; i < NumStores; ++i) { 12816 if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0) 12817 Chains.push_back(StoreNodes[i].MemNode->getChain()); 12818 } 12819 12820 assert(Chains.size() > 0 && "Chain should have generated a chain"); 12821 return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains); 12822 } 12823 12824 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 12825 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores, 12826 bool IsConstantSrc, bool UseVector, bool UseTrunc) { 12827 // Make sure we have something to merge. 12828 if (NumStores < 2) 12829 return false; 12830 12831 // The latest Node in the DAG. 12832 SDLoc DL(StoreNodes[0].MemNode); 12833 12834 int64_t ElementSizeBits = MemVT.getStoreSizeInBits(); 12835 unsigned SizeInBits = NumStores * ElementSizeBits; 12836 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 12837 12838 EVT StoreTy; 12839 if (UseVector) { 12840 unsigned Elts = NumStores * NumMemElts; 12841 // Get the type for the merged vector store. 12842 StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 12843 } else 12844 StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 12845 12846 SDValue StoredVal; 12847 if (UseVector) { 12848 if (IsConstantSrc) { 12849 SmallVector<SDValue, 8> BuildVector; 12850 for (unsigned I = 0; I != NumStores; ++I) { 12851 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode); 12852 SDValue Val = St->getValue(); 12853 // If constant is of the wrong type, convert it now. 12854 if (MemVT != Val.getValueType()) { 12855 Val = peekThroughBitcast(Val); 12856 // Deal with constants of wrong size. 12857 if (ElementSizeBits != Val.getValueSizeInBits()) { 12858 EVT IntMemVT = 12859 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 12860 if (isa<ConstantFPSDNode>(Val)) { 12861 // Not clear how to truncate FP values. 12862 return false; 12863 } else if (auto *C = dyn_cast<ConstantSDNode>(Val)) 12864 Val = DAG.getConstant(C->getAPIntValue() 12865 .zextOrTrunc(Val.getValueSizeInBits()) 12866 .zextOrTrunc(ElementSizeBits), 12867 SDLoc(C), IntMemVT); 12868 } 12869 // Make sure correctly size type is the correct type. 12870 Val = DAG.getBitcast(MemVT, Val); 12871 } 12872 BuildVector.push_back(Val); 12873 } 12874 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS 12875 : ISD::BUILD_VECTOR, 12876 DL, StoreTy, BuildVector); 12877 } else { 12878 SmallVector<SDValue, 8> Ops; 12879 for (unsigned i = 0; i < NumStores; ++i) { 12880 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12881 SDValue Val = peekThroughBitcast(St->getValue()); 12882 // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of 12883 // type MemVT. If the underlying value is not the correct 12884 // type, but it is an extraction of an appropriate vector we 12885 // can recast Val to be of the correct type. This may require 12886 // converting between EXTRACT_VECTOR_ELT and 12887 // EXTRACT_SUBVECTOR. 12888 if ((MemVT != Val.getValueType()) && 12889 (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12890 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) { 12891 SDValue Vec = Val.getOperand(0); 12892 EVT MemVTScalarTy = MemVT.getScalarType(); 12893 // We may need to add a bitcast here to get types to line up. 12894 if (MemVTScalarTy != Vec.getValueType()) { 12895 unsigned Elts = Vec.getValueType().getSizeInBits() / 12896 MemVTScalarTy.getSizeInBits(); 12897 EVT NewVecTy = 12898 EVT::getVectorVT(*DAG.getContext(), MemVTScalarTy, Elts); 12899 Vec = DAG.getBitcast(NewVecTy, Vec); 12900 } 12901 auto OpC = (MemVT.isVector()) ? ISD::EXTRACT_SUBVECTOR 12902 : ISD::EXTRACT_VECTOR_ELT; 12903 Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Val.getOperand(1)); 12904 } 12905 Ops.push_back(Val); 12906 } 12907 12908 // Build the extracted vector elements back into a vector. 12909 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS 12910 : ISD::BUILD_VECTOR, 12911 DL, StoreTy, Ops); 12912 } 12913 } else { 12914 // We should always use a vector store when merging extracted vector 12915 // elements, so this path implies a store of constants. 12916 assert(IsConstantSrc && "Merged vector elements should use vector store"); 12917 12918 APInt StoreInt(SizeInBits, 0); 12919 12920 // Construct a single integer constant which is made of the smaller 12921 // constant inputs. 12922 bool IsLE = DAG.getDataLayout().isLittleEndian(); 12923 for (unsigned i = 0; i < NumStores; ++i) { 12924 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 12925 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 12926 12927 SDValue Val = St->getValue(); 12928 Val = peekThroughBitcast(Val); 12929 StoreInt <<= ElementSizeBits; 12930 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 12931 StoreInt |= C->getAPIntValue() 12932 .zextOrTrunc(ElementSizeBits) 12933 .zextOrTrunc(SizeInBits); 12934 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 12935 StoreInt |= C->getValueAPF() 12936 .bitcastToAPInt() 12937 .zextOrTrunc(ElementSizeBits) 12938 .zextOrTrunc(SizeInBits); 12939 // If fp truncation is necessary give up for now. 12940 if (MemVT.getSizeInBits() != ElementSizeBits) 12941 return false; 12942 } else { 12943 llvm_unreachable("Invalid constant element type"); 12944 } 12945 } 12946 12947 // Create the new Load and Store operations. 12948 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 12949 } 12950 12951 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12952 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores); 12953 12954 // make sure we use trunc store if it's necessary to be legal. 12955 SDValue NewStore; 12956 if (!UseTrunc) { 12957 NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(), 12958 FirstInChain->getPointerInfo(), 12959 FirstInChain->getAlignment()); 12960 } else { // Must be realized as a trunc store 12961 EVT LegalizedStoredValueTy = 12962 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 12963 unsigned LegalizedStoreSize = LegalizedStoredValueTy.getSizeInBits(); 12964 ConstantSDNode *C = cast<ConstantSDNode>(StoredVal); 12965 SDValue ExtendedStoreVal = 12966 DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL, 12967 LegalizedStoredValueTy); 12968 NewStore = DAG.getTruncStore( 12969 NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(), 12970 FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/, 12971 FirstInChain->getAlignment(), 12972 FirstInChain->getMemOperand()->getFlags()); 12973 } 12974 12975 // Replace all merged stores with the new store. 12976 for (unsigned i = 0; i < NumStores; ++i) 12977 CombineTo(StoreNodes[i].MemNode, NewStore); 12978 12979 AddToWorklist(NewChain.getNode()); 12980 return true; 12981 } 12982 12983 void DAGCombiner::getStoreMergeCandidates( 12984 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) { 12985 // This holds the base pointer, index, and the offset in bytes from the base 12986 // pointer. 12987 BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); 12988 EVT MemVT = St->getMemoryVT(); 12989 12990 SDValue Val = peekThroughBitcast(St->getValue()); 12991 // We must have a base and an offset. 12992 if (!BasePtr.getBase().getNode()) 12993 return; 12994 12995 // Do not handle stores to undef base pointers. 12996 if (BasePtr.getBase().isUndef()) 12997 return; 12998 12999 bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val); 13000 bool IsExtractVecSrc = (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 13001 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR); 13002 bool IsLoadSrc = isa<LoadSDNode>(Val); 13003 BaseIndexOffset LBasePtr; 13004 // Match on loadbaseptr if relevant. 13005 EVT LoadVT; 13006 if (IsLoadSrc) { 13007 auto *Ld = cast<LoadSDNode>(Val); 13008 LBasePtr = BaseIndexOffset::match(Ld, DAG); 13009 LoadVT = Ld->getMemoryVT(); 13010 // Load and store should be the same type. 13011 if (MemVT != LoadVT) 13012 return; 13013 } 13014 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr, 13015 int64_t &Offset) -> bool { 13016 if (Other->isVolatile() || Other->isIndexed()) 13017 return false; 13018 SDValue Val = peekThroughBitcast(Other->getValue()); 13019 // Allow merging constants of different types as integers. 13020 bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT()) 13021 : Other->getMemoryVT() != MemVT; 13022 if (IsLoadSrc) { 13023 if (NoTypeMatch) 13024 return false; 13025 // The Load's Base Ptr must also match 13026 if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Val)) { 13027 auto LPtr = BaseIndexOffset::match(OtherLd, DAG); 13028 if (LoadVT != OtherLd->getMemoryVT()) 13029 return false; 13030 if (!(LBasePtr.equalBaseIndex(LPtr, DAG))) 13031 return false; 13032 } else 13033 return false; 13034 } 13035 if (IsConstantSrc) { 13036 if (NoTypeMatch) 13037 return false; 13038 if (!(isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val))) 13039 return false; 13040 } 13041 if (IsExtractVecSrc) { 13042 // Do not merge truncated stores here. 13043 if (Other->isTruncatingStore()) 13044 return false; 13045 if (!MemVT.bitsEq(Val.getValueType())) 13046 return false; 13047 if (Val.getOpcode() != ISD::EXTRACT_VECTOR_ELT && 13048 Val.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13049 return false; 13050 } 13051 Ptr = BaseIndexOffset::match(Other, DAG); 13052 return (BasePtr.equalBaseIndex(Ptr, DAG, Offset)); 13053 }; 13054 13055 // We looking for a root node which is an ancestor to all mergable 13056 // stores. We search up through a load, to our root and then down 13057 // through all children. For instance we will find Store{1,2,3} if 13058 // St is Store1, Store2. or Store3 where the root is not a load 13059 // which always true for nonvolatile ops. TODO: Expand 13060 // the search to find all valid candidates through multiple layers of loads. 13061 // 13062 // Root 13063 // |-------|-------| 13064 // Load Load Store3 13065 // | | 13066 // Store1 Store2 13067 // 13068 // FIXME: We should be able to climb and 13069 // descend TokenFactors to find candidates as well. 13070 13071 SDNode *RootNode = (St->getChain()).getNode(); 13072 13073 if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) { 13074 RootNode = Ldn->getChain().getNode(); 13075 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 13076 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain 13077 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2) 13078 if (I2.getOperandNo() == 0) 13079 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) { 13080 BaseIndexOffset Ptr; 13081 int64_t PtrDiff; 13082 if (CandidateMatch(OtherST, Ptr, PtrDiff)) 13083 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff)); 13084 } 13085 } else 13086 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 13087 if (I.getOperandNo() == 0) 13088 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 13089 BaseIndexOffset Ptr; 13090 int64_t PtrDiff; 13091 if (CandidateMatch(OtherST, Ptr, PtrDiff)) 13092 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff)); 13093 } 13094 } 13095 13096 // We need to check that merging these stores does not cause a loop in 13097 // the DAG. Any store candidate may depend on another candidate 13098 // indirectly through its operand (we already consider dependencies 13099 // through the chain). Check in parallel by searching up from 13100 // non-chain operands of candidates. 13101 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 13102 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) { 13103 // FIXME: We should be able to truncate a full search of 13104 // predecessors by doing a BFS and keeping tabs the originating 13105 // stores from which worklist nodes come from in a similar way to 13106 // TokenFactor simplfication. 13107 13108 SmallPtrSet<const SDNode *, 16> Visited; 13109 SmallVector<const SDNode *, 8> Worklist; 13110 unsigned int Max = 8192; 13111 // Search Ops of store candidates. 13112 for (unsigned i = 0; i < NumStores; ++i) { 13113 SDNode *n = StoreNodes[i].MemNode; 13114 // Potential loops may happen only through non-chain operands 13115 for (unsigned j = 1; j < n->getNumOperands(); ++j) 13116 Worklist.push_back(n->getOperand(j).getNode()); 13117 } 13118 // Search through DAG. We can stop early if we find a store node. 13119 for (unsigned i = 0; i < NumStores; ++i) 13120 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist, 13121 Max)) 13122 return false; 13123 return true; 13124 } 13125 13126 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) { 13127 if (OptLevel == CodeGenOpt::None) 13128 return false; 13129 13130 EVT MemVT = St->getMemoryVT(); 13131 int64_t ElementSizeBytes = MemVT.getStoreSize(); 13132 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 13133 13134 if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits) 13135 return false; 13136 13137 bool NoVectors = DAG.getMachineFunction().getFunction().hasFnAttribute( 13138 Attribute::NoImplicitFloat); 13139 13140 // This function cannot currently deal with non-byte-sized memory sizes. 13141 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 13142 return false; 13143 13144 if (!MemVT.isSimple()) 13145 return false; 13146 13147 // Perform an early exit check. Do not bother looking at stored values that 13148 // are not constants, loads, or extracted vector elements. 13149 SDValue StoredVal = peekThroughBitcast(St->getValue()); 13150 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 13151 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 13152 isa<ConstantFPSDNode>(StoredVal); 13153 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 13154 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 13155 13156 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 13157 return false; 13158 13159 SmallVector<MemOpLink, 8> StoreNodes; 13160 // Find potential store merge candidates by searching through chain sub-DAG 13161 getStoreMergeCandidates(St, StoreNodes); 13162 13163 // Check if there is anything to merge. 13164 if (StoreNodes.size() < 2) 13165 return false; 13166 13167 // Sort the memory operands according to their distance from the 13168 // base pointer. 13169 std::sort(StoreNodes.begin(), StoreNodes.end(), 13170 [](MemOpLink LHS, MemOpLink RHS) { 13171 return LHS.OffsetFromBase < RHS.OffsetFromBase; 13172 }); 13173 13174 // Store Merge attempts to merge the lowest stores. This generally 13175 // works out as if successful, as the remaining stores are checked 13176 // after the first collection of stores is merged. However, in the 13177 // case that a non-mergeable store is found first, e.g., {p[-2], 13178 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent 13179 // mergeable cases. To prevent this, we prune such stores from the 13180 // front of StoreNodes here. 13181 13182 bool RV = false; 13183 while (StoreNodes.size() > 1) { 13184 unsigned StartIdx = 0; 13185 while ((StartIdx + 1 < StoreNodes.size()) && 13186 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes != 13187 StoreNodes[StartIdx + 1].OffsetFromBase) 13188 ++StartIdx; 13189 13190 // Bail if we don't have enough candidates to merge. 13191 if (StartIdx + 1 >= StoreNodes.size()) 13192 return RV; 13193 13194 if (StartIdx) 13195 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx); 13196 13197 // Scan the memory operations on the chain and find the first 13198 // non-consecutive store memory address. 13199 unsigned NumConsecutiveStores = 1; 13200 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 13201 // Check that the addresses are consecutive starting from the second 13202 // element in the list of stores. 13203 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) { 13204 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 13205 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 13206 break; 13207 NumConsecutiveStores = i + 1; 13208 } 13209 13210 if (NumConsecutiveStores < 2) { 13211 StoreNodes.erase(StoreNodes.begin(), 13212 StoreNodes.begin() + NumConsecutiveStores); 13213 continue; 13214 } 13215 13216 // Check that we can merge these candidates without causing a cycle 13217 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, 13218 NumConsecutiveStores)) { 13219 StoreNodes.erase(StoreNodes.begin(), 13220 StoreNodes.begin() + NumConsecutiveStores); 13221 continue; 13222 } 13223 13224 // The node with the lowest store address. 13225 LLVMContext &Context = *DAG.getContext(); 13226 const DataLayout &DL = DAG.getDataLayout(); 13227 13228 // Store the constants into memory as one consecutive store. 13229 if (IsConstantSrc) { 13230 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 13231 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 13232 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 13233 unsigned LastLegalType = 1; 13234 unsigned LastLegalVectorType = 1; 13235 bool LastIntegerTrunc = false; 13236 bool NonZero = false; 13237 unsigned FirstZeroAfterNonZero = NumConsecutiveStores; 13238 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 13239 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode); 13240 SDValue StoredVal = ST->getValue(); 13241 bool IsElementZero = false; 13242 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) 13243 IsElementZero = C->isNullValue(); 13244 else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) 13245 IsElementZero = C->getConstantFPValue()->isNullValue(); 13246 if (IsElementZero) { 13247 if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores) 13248 FirstZeroAfterNonZero = i; 13249 } 13250 NonZero |= !IsElementZero; 13251 13252 // Find a legal type for the constant store. 13253 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 13254 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 13255 bool IsFast = false; 13256 if (TLI.isTypeLegal(StoreTy) && 13257 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 13258 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13259 FirstStoreAlign, &IsFast) && 13260 IsFast) { 13261 LastIntegerTrunc = false; 13262 LastLegalType = i + 1; 13263 // Or check whether a truncstore is legal. 13264 } else if (TLI.getTypeAction(Context, StoreTy) == 13265 TargetLowering::TypePromoteInteger) { 13266 EVT LegalizedStoredValueTy = 13267 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 13268 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 13269 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) && 13270 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13271 FirstStoreAlign, &IsFast) && 13272 IsFast) { 13273 LastIntegerTrunc = true; 13274 LastLegalType = i + 1; 13275 } 13276 } 13277 13278 // We only use vectors if the constant is known to be zero or the target 13279 // allows it and the function is not marked with the noimplicitfloat 13280 // attribute. 13281 if ((!NonZero || 13282 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) && 13283 !NoVectors) { 13284 // Find a legal type for the vector store. 13285 unsigned Elts = (i + 1) * NumMemElts; 13286 EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 13287 if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) && 13288 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && 13289 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 13290 FirstStoreAlign, &IsFast) && 13291 IsFast) 13292 LastLegalVectorType = i + 1; 13293 } 13294 } 13295 13296 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 13297 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType; 13298 13299 // Check if we found a legal integer type that creates a meaningful merge. 13300 if (NumElem < 2) { 13301 // We know that candidate stores are in order and of correct 13302 // shape. While there is no mergeable sequence from the 13303 // beginning one may start later in the sequence. The only 13304 // reason a merge of size N could have failed where another of 13305 // the same size would not have, is if the alignment has 13306 // improved or we've dropped a non-zero value. Drop as many 13307 // candidates as we can here. 13308 unsigned NumSkip = 1; 13309 while ( 13310 (NumSkip < NumConsecutiveStores) && 13311 (NumSkip < FirstZeroAfterNonZero) && 13312 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) { 13313 NumSkip++; 13314 } 13315 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 13316 continue; 13317 } 13318 13319 bool Merged = MergeStoresOfConstantsOrVecElts( 13320 StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc); 13321 RV |= Merged; 13322 13323 // Remove merged stores for next iteration. 13324 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 13325 continue; 13326 } 13327 13328 // When extracting multiple vector elements, try to store them 13329 // in one vector store rather than a sequence of scalar stores. 13330 if (IsExtractVecSrc) { 13331 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 13332 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 13333 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 13334 unsigned NumStoresToMerge = 1; 13335 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 13336 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 13337 SDValue StVal = peekThroughBitcast(St->getValue()); 13338 // This restriction could be loosened. 13339 // Bail out if any stored values are not elements extracted from a 13340 // vector. It should be possible to handle mixed sources, but load 13341 // sources need more careful handling (see the block of code below that 13342 // handles consecutive loads). 13343 if (StVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT && 13344 StVal.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13345 return RV; 13346 13347 // Find a legal type for the vector store. 13348 unsigned Elts = (i + 1) * NumMemElts; 13349 EVT Ty = 13350 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 13351 bool IsFast; 13352 if (TLI.isTypeLegal(Ty) && 13353 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && 13354 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 13355 FirstStoreAlign, &IsFast) && 13356 IsFast) 13357 NumStoresToMerge = i + 1; 13358 } 13359 13360 // Check if we found a legal integer type that creates a meaningful merge. 13361 if (NumStoresToMerge < 2) { 13362 // We know that candidate stores are in order and of correct 13363 // shape. While there is no mergeable sequence from the 13364 // beginning one may start later in the sequence. The only 13365 // reason a merge of size N could have failed where another of 13366 // the same size would not have, is if the alignment has 13367 // improved. Drop as many candidates as we can here. 13368 unsigned NumSkip = 1; 13369 while ((NumSkip < NumConsecutiveStores) && 13370 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 13371 NumSkip++; 13372 13373 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 13374 continue; 13375 } 13376 13377 bool Merged = MergeStoresOfConstantsOrVecElts( 13378 StoreNodes, MemVT, NumStoresToMerge, false, true, false); 13379 if (!Merged) { 13380 StoreNodes.erase(StoreNodes.begin(), 13381 StoreNodes.begin() + NumStoresToMerge); 13382 continue; 13383 } 13384 // Remove merged stores for next iteration. 13385 StoreNodes.erase(StoreNodes.begin(), 13386 StoreNodes.begin() + NumStoresToMerge); 13387 RV = true; 13388 continue; 13389 } 13390 13391 // Below we handle the case of multiple consecutive stores that 13392 // come from multiple consecutive loads. We merge them into a single 13393 // wide load and a single wide store. 13394 13395 // Look for load nodes which are used by the stored values. 13396 SmallVector<MemOpLink, 8> LoadNodes; 13397 13398 // Find acceptable loads. Loads need to have the same chain (token factor), 13399 // must not be zext, volatile, indexed, and they must be consecutive. 13400 BaseIndexOffset LdBasePtr; 13401 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 13402 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 13403 SDValue Val = peekThroughBitcast(St->getValue()); 13404 LoadSDNode *Ld = dyn_cast<LoadSDNode>(Val); 13405 if (!Ld) 13406 break; 13407 13408 // Loads must only have one use. 13409 if (!Ld->hasNUsesOfValue(1, 0)) 13410 break; 13411 13412 // The memory operands must not be volatile. 13413 if (Ld->isVolatile() || Ld->isIndexed()) 13414 break; 13415 13416 // The stored memory type must be the same. 13417 if (Ld->getMemoryVT() != MemVT) 13418 break; 13419 13420 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld, DAG); 13421 // If this is not the first ptr that we check. 13422 int64_t LdOffset = 0; 13423 if (LdBasePtr.getBase().getNode()) { 13424 // The base ptr must be the same. 13425 if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset)) 13426 break; 13427 } else { 13428 // Check that all other base pointers are the same as this one. 13429 LdBasePtr = LdPtr; 13430 } 13431 13432 // We found a potential memory operand to merge. 13433 LoadNodes.push_back(MemOpLink(Ld, LdOffset)); 13434 } 13435 13436 if (LoadNodes.size() < 2) { 13437 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1); 13438 continue; 13439 } 13440 13441 // If we have load/store pair instructions and we only have two values, 13442 // don't bother merging. 13443 unsigned RequiredAlignment; 13444 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 13445 StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) { 13446 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2); 13447 continue; 13448 } 13449 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 13450 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 13451 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 13452 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 13453 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 13454 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 13455 13456 // Scan the memory operations on the chain and find the first 13457 // non-consecutive load memory address. These variables hold the index in 13458 // the store node array. 13459 unsigned LastConsecutiveLoad = 1; 13460 // This variable refers to the size and not index in the array. 13461 unsigned LastLegalVectorType = 1; 13462 unsigned LastLegalIntegerType = 1; 13463 bool isDereferenceable = true; 13464 bool DoIntegerTruncate = false; 13465 StartAddress = LoadNodes[0].OffsetFromBase; 13466 SDValue FirstChain = FirstLoad->getChain(); 13467 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 13468 // All loads must share the same chain. 13469 if (LoadNodes[i].MemNode->getChain() != FirstChain) 13470 break; 13471 13472 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 13473 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 13474 break; 13475 LastConsecutiveLoad = i; 13476 13477 if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable()) 13478 isDereferenceable = false; 13479 13480 // Find a legal type for the vector store. 13481 unsigned Elts = (i + 1) * NumMemElts; 13482 EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 13483 13484 bool IsFastSt, IsFastLd; 13485 if (TLI.isTypeLegal(StoreTy) && 13486 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 13487 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13488 FirstStoreAlign, &IsFastSt) && 13489 IsFastSt && 13490 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 13491 FirstLoadAlign, &IsFastLd) && 13492 IsFastLd) { 13493 LastLegalVectorType = i + 1; 13494 } 13495 13496 // Find a legal type for the integer store. 13497 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 13498 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 13499 if (TLI.isTypeLegal(StoreTy) && 13500 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 13501 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13502 FirstStoreAlign, &IsFastSt) && 13503 IsFastSt && 13504 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 13505 FirstLoadAlign, &IsFastLd) && 13506 IsFastLd) { 13507 LastLegalIntegerType = i + 1; 13508 DoIntegerTruncate = false; 13509 // Or check whether a truncstore and extload is legal. 13510 } else if (TLI.getTypeAction(Context, StoreTy) == 13511 TargetLowering::TypePromoteInteger) { 13512 EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy); 13513 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 13514 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) && 13515 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, 13516 StoreTy) && 13517 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, 13518 StoreTy) && 13519 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 13520 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13521 FirstStoreAlign, &IsFastSt) && 13522 IsFastSt && 13523 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 13524 FirstLoadAlign, &IsFastLd) && 13525 IsFastLd) { 13526 LastLegalIntegerType = i + 1; 13527 DoIntegerTruncate = true; 13528 } 13529 } 13530 } 13531 13532 // Only use vector types if the vector type is larger than the integer type. 13533 // If they are the same, use integers. 13534 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 13535 unsigned LastLegalType = 13536 std::max(LastLegalVectorType, LastLegalIntegerType); 13537 13538 // We add +1 here because the LastXXX variables refer to location while 13539 // the NumElem refers to array/index size. 13540 unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1); 13541 NumElem = std::min(LastLegalType, NumElem); 13542 13543 if (NumElem < 2) { 13544 // We know that candidate stores are in order and of correct 13545 // shape. While there is no mergeable sequence from the 13546 // beginning one may start later in the sequence. The only 13547 // reason a merge of size N could have failed where another of 13548 // the same size would not have is if the alignment or either 13549 // the load or store has improved. Drop as many candidates as we 13550 // can here. 13551 unsigned NumSkip = 1; 13552 while ((NumSkip < LoadNodes.size()) && 13553 (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) && 13554 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 13555 NumSkip++; 13556 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 13557 continue; 13558 } 13559 13560 // Find if it is better to use vectors or integers to load and store 13561 // to memory. 13562 EVT JointMemOpVT; 13563 if (UseVectorTy) { 13564 // Find a legal type for the vector store. 13565 unsigned Elts = NumElem * NumMemElts; 13566 JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 13567 } else { 13568 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 13569 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 13570 } 13571 13572 SDLoc LoadDL(LoadNodes[0].MemNode); 13573 SDLoc StoreDL(StoreNodes[0].MemNode); 13574 13575 // The merged loads are required to have the same incoming chain, so 13576 // using the first's chain is acceptable. 13577 13578 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem); 13579 AddToWorklist(NewStoreChain.getNode()); 13580 13581 MachineMemOperand::Flags MMOFlags = isDereferenceable ? 13582 MachineMemOperand::MODereferenceable: 13583 MachineMemOperand::MONone; 13584 13585 SDValue NewLoad, NewStore; 13586 if (UseVectorTy || !DoIntegerTruncate) { 13587 NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(), 13588 FirstLoad->getBasePtr(), 13589 FirstLoad->getPointerInfo(), FirstLoadAlign, 13590 MMOFlags); 13591 NewStore = DAG.getStore(NewStoreChain, StoreDL, NewLoad, 13592 FirstInChain->getBasePtr(), 13593 FirstInChain->getPointerInfo(), FirstStoreAlign); 13594 } else { // This must be the truncstore/extload case 13595 EVT ExtendedTy = 13596 TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT); 13597 NewLoad = 13598 DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, FirstLoad->getChain(), 13599 FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(), 13600 JointMemOpVT, FirstLoadAlign, MMOFlags); 13601 NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad, 13602 FirstInChain->getBasePtr(), 13603 FirstInChain->getPointerInfo(), JointMemOpVT, 13604 FirstInChain->getAlignment(), 13605 FirstInChain->getMemOperand()->getFlags()); 13606 } 13607 13608 // Transfer chain users from old loads to the new load. 13609 for (unsigned i = 0; i < NumElem; ++i) { 13610 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 13611 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 13612 SDValue(NewLoad.getNode(), 1)); 13613 } 13614 13615 // Replace the all stores with the new store. Recursively remove 13616 // corresponding value if its no longer used. 13617 for (unsigned i = 0; i < NumElem; ++i) { 13618 SDValue Val = StoreNodes[i].MemNode->getOperand(1); 13619 CombineTo(StoreNodes[i].MemNode, NewStore); 13620 if (Val.getNode()->use_empty()) 13621 recursivelyDeleteUnusedNodes(Val.getNode()); 13622 } 13623 13624 RV = true; 13625 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 13626 } 13627 return RV; 13628 } 13629 13630 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 13631 SDLoc SL(ST); 13632 SDValue ReplStore; 13633 13634 // Replace the chain to avoid dependency. 13635 if (ST->isTruncatingStore()) { 13636 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 13637 ST->getBasePtr(), ST->getMemoryVT(), 13638 ST->getMemOperand()); 13639 } else { 13640 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 13641 ST->getMemOperand()); 13642 } 13643 13644 // Create token to keep both nodes around. 13645 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 13646 MVT::Other, ST->getChain(), ReplStore); 13647 13648 // Make sure the new and old chains are cleaned up. 13649 AddToWorklist(Token.getNode()); 13650 13651 // Don't add users to work list. 13652 return CombineTo(ST, Token, false); 13653 } 13654 13655 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 13656 SDValue Value = ST->getValue(); 13657 if (Value.getOpcode() == ISD::TargetConstantFP) 13658 return SDValue(); 13659 13660 SDLoc DL(ST); 13661 13662 SDValue Chain = ST->getChain(); 13663 SDValue Ptr = ST->getBasePtr(); 13664 13665 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 13666 13667 // NOTE: If the original store is volatile, this transform must not increase 13668 // the number of stores. For example, on x86-32 an f64 can be stored in one 13669 // processor operation but an i64 (which is not legal) requires two. So the 13670 // transform should not be done in this case. 13671 13672 SDValue Tmp; 13673 switch (CFP->getSimpleValueType(0).SimpleTy) { 13674 default: 13675 llvm_unreachable("Unknown FP type"); 13676 case MVT::f16: // We don't do this for these yet. 13677 case MVT::f80: 13678 case MVT::f128: 13679 case MVT::ppcf128: 13680 return SDValue(); 13681 case MVT::f32: 13682 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 13683 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 13684 ; 13685 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 13686 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 13687 MVT::i32); 13688 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 13689 } 13690 13691 return SDValue(); 13692 case MVT::f64: 13693 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 13694 !ST->isVolatile()) || 13695 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 13696 ; 13697 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 13698 getZExtValue(), SDLoc(CFP), MVT::i64); 13699 return DAG.getStore(Chain, DL, Tmp, 13700 Ptr, ST->getMemOperand()); 13701 } 13702 13703 if (!ST->isVolatile() && 13704 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 13705 // Many FP stores are not made apparent until after legalize, e.g. for 13706 // argument passing. Since this is so common, custom legalize the 13707 // 64-bit integer store into two 32-bit stores. 13708 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 13709 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 13710 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 13711 if (DAG.getDataLayout().isBigEndian()) 13712 std::swap(Lo, Hi); 13713 13714 unsigned Alignment = ST->getAlignment(); 13715 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 13716 AAMDNodes AAInfo = ST->getAAInfo(); 13717 13718 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 13719 ST->getAlignment(), MMOFlags, AAInfo); 13720 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 13721 DAG.getConstant(4, DL, Ptr.getValueType())); 13722 Alignment = MinAlign(Alignment, 4U); 13723 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 13724 ST->getPointerInfo().getWithOffset(4), 13725 Alignment, MMOFlags, AAInfo); 13726 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 13727 St0, St1); 13728 } 13729 13730 return SDValue(); 13731 } 13732 } 13733 13734 SDValue DAGCombiner::visitSTORE(SDNode *N) { 13735 StoreSDNode *ST = cast<StoreSDNode>(N); 13736 SDValue Chain = ST->getChain(); 13737 SDValue Value = ST->getValue(); 13738 SDValue Ptr = ST->getBasePtr(); 13739 13740 // If this is a store of a bit convert, store the input value if the 13741 // resultant store does not need a higher alignment than the original. 13742 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 13743 ST->isUnindexed()) { 13744 EVT SVT = Value.getOperand(0).getValueType(); 13745 if (((!LegalOperations && !ST->isVolatile()) || 13746 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) && 13747 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 13748 unsigned OrigAlign = ST->getAlignment(); 13749 bool Fast = false; 13750 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 13751 ST->getAddressSpace(), OrigAlign, &Fast) && 13752 Fast) { 13753 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 13754 ST->getPointerInfo(), OrigAlign, 13755 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 13756 } 13757 } 13758 } 13759 13760 // Turn 'store undef, Ptr' -> nothing. 13761 if (Value.isUndef() && ST->isUnindexed()) 13762 return Chain; 13763 13764 // Try to infer better alignment information than the store already has. 13765 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 13766 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 13767 if (Align > ST->getAlignment()) { 13768 SDValue NewStore = 13769 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 13770 ST->getMemoryVT(), Align, 13771 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 13772 if (NewStore.getNode() != N) 13773 return CombineTo(ST, NewStore, true); 13774 } 13775 } 13776 } 13777 13778 // Try transforming a pair floating point load / store ops to integer 13779 // load / store ops. 13780 if (SDValue NewST = TransformFPLoadStorePair(N)) 13781 return NewST; 13782 13783 if (ST->isUnindexed()) { 13784 // Walk up chain skipping non-aliasing memory nodes, on this store and any 13785 // adjacent stores. 13786 if (findBetterNeighborChains(ST)) { 13787 // replaceStoreChain uses CombineTo, which handled all of the worklist 13788 // manipulation. Return the original node to not do anything else. 13789 return SDValue(ST, 0); 13790 } 13791 Chain = ST->getChain(); 13792 } 13793 13794 // FIXME: is there such a thing as a truncating indexed store? 13795 if (ST->isTruncatingStore() && ST->isUnindexed() && 13796 Value.getValueType().isInteger()) { 13797 // See if we can simplify the input to this truncstore with knowledge that 13798 // only the low bits are being used. For example: 13799 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 13800 SDValue Shorter = DAG.GetDemandedBits( 13801 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 13802 ST->getMemoryVT().getScalarSizeInBits())); 13803 AddToWorklist(Value.getNode()); 13804 if (Shorter.getNode()) 13805 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 13806 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 13807 13808 // Otherwise, see if we can simplify the operation with 13809 // SimplifyDemandedBits, which only works if the value has a single use. 13810 if (SimplifyDemandedBits( 13811 Value, 13812 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 13813 ST->getMemoryVT().getScalarSizeInBits()))) { 13814 // Re-visit the store if anything changed and the store hasn't been merged 13815 // with another node (N is deleted) SimplifyDemandedBits will add Value's 13816 // node back to the worklist if necessary, but we also need to re-visit 13817 // the Store node itself. 13818 if (N->getOpcode() != ISD::DELETED_NODE) 13819 AddToWorklist(N); 13820 return SDValue(N, 0); 13821 } 13822 } 13823 13824 // If this is a load followed by a store to the same location, then the store 13825 // is dead/noop. 13826 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 13827 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 13828 ST->isUnindexed() && !ST->isVolatile() && 13829 // There can't be any side effects between the load and store, such as 13830 // a call or store. 13831 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 13832 // The store is dead, remove it. 13833 return Chain; 13834 } 13835 } 13836 13837 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 13838 if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() && 13839 !ST1->isVolatile() && ST1->getBasePtr() == Ptr && 13840 ST->getMemoryVT() == ST1->getMemoryVT()) { 13841 // If this is a store followed by a store with the same value to the same 13842 // location, then the store is dead/noop. 13843 if (ST1->getValue() == Value) { 13844 // The store is dead, remove it. 13845 return Chain; 13846 } 13847 13848 // If this is a store who's preceeding store to the same location 13849 // and no one other node is chained to that store we can effectively 13850 // drop the store. Do not remove stores to undef as they may be used as 13851 // data sinks. 13852 if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() && 13853 !ST1->getBasePtr().isUndef()) { 13854 // ST1 is fully overwritten and can be elided. Combine with it's chain 13855 // value. 13856 CombineTo(ST1, ST1->getChain()); 13857 return SDValue(); 13858 } 13859 } 13860 } 13861 13862 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 13863 // truncating store. We can do this even if this is already a truncstore. 13864 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 13865 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 13866 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 13867 ST->getMemoryVT())) { 13868 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 13869 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 13870 } 13871 13872 // Always perform this optimization before types are legal. If the target 13873 // prefers, also try this after legalization to catch stores that were created 13874 // by intrinsics or other nodes. 13875 if (!LegalTypes || (TLI.mergeStoresAfterLegalization())) { 13876 while (true) { 13877 // There can be multiple store sequences on the same chain. 13878 // Keep trying to merge store sequences until we are unable to do so 13879 // or until we merge the last store on the chain. 13880 bool Changed = MergeConsecutiveStores(ST); 13881 if (!Changed) break; 13882 // Return N as merge only uses CombineTo and no worklist clean 13883 // up is necessary. 13884 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N)) 13885 return SDValue(N, 0); 13886 } 13887 } 13888 13889 // Try transforming N to an indexed store. 13890 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 13891 return SDValue(N, 0); 13892 13893 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 13894 // 13895 // Make sure to do this only after attempting to merge stores in order to 13896 // avoid changing the types of some subset of stores due to visit order, 13897 // preventing their merging. 13898 if (isa<ConstantFPSDNode>(ST->getValue())) { 13899 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 13900 return NewSt; 13901 } 13902 13903 if (SDValue NewSt = splitMergedValStore(ST)) 13904 return NewSt; 13905 13906 return ReduceLoadOpStoreWidth(N); 13907 } 13908 13909 /// For the instruction sequence of store below, F and I values 13910 /// are bundled together as an i64 value before being stored into memory. 13911 /// Sometimes it is more efficent to generate separate stores for F and I, 13912 /// which can remove the bitwise instructions or sink them to colder places. 13913 /// 13914 /// (store (or (zext (bitcast F to i32) to i64), 13915 /// (shl (zext I to i64), 32)), addr) --> 13916 /// (store F, addr) and (store I, addr+4) 13917 /// 13918 /// Similarly, splitting for other merged store can also be beneficial, like: 13919 /// For pair of {i32, i32}, i64 store --> two i32 stores. 13920 /// For pair of {i32, i16}, i64 store --> two i32 stores. 13921 /// For pair of {i16, i16}, i32 store --> two i16 stores. 13922 /// For pair of {i16, i8}, i32 store --> two i16 stores. 13923 /// For pair of {i8, i8}, i16 store --> two i8 stores. 13924 /// 13925 /// We allow each target to determine specifically which kind of splitting is 13926 /// supported. 13927 /// 13928 /// The store patterns are commonly seen from the simple code snippet below 13929 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 13930 /// void goo(const std::pair<int, float> &); 13931 /// hoo() { 13932 /// ... 13933 /// goo(std::make_pair(tmp, ftmp)); 13934 /// ... 13935 /// } 13936 /// 13937 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) { 13938 if (OptLevel == CodeGenOpt::None) 13939 return SDValue(); 13940 13941 SDValue Val = ST->getValue(); 13942 SDLoc DL(ST); 13943 13944 // Match OR operand. 13945 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR) 13946 return SDValue(); 13947 13948 // Match SHL operand and get Lower and Higher parts of Val. 13949 SDValue Op1 = Val.getOperand(0); 13950 SDValue Op2 = Val.getOperand(1); 13951 SDValue Lo, Hi; 13952 if (Op1.getOpcode() != ISD::SHL) { 13953 std::swap(Op1, Op2); 13954 if (Op1.getOpcode() != ISD::SHL) 13955 return SDValue(); 13956 } 13957 Lo = Op2; 13958 Hi = Op1.getOperand(0); 13959 if (!Op1.hasOneUse()) 13960 return SDValue(); 13961 13962 // Match shift amount to HalfValBitSize. 13963 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2; 13964 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1)); 13965 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize) 13966 return SDValue(); 13967 13968 // Lo and Hi are zero-extended from int with size less equal than 32 13969 // to i64. 13970 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() || 13971 !Lo.getOperand(0).getValueType().isScalarInteger() || 13972 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize || 13973 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() || 13974 !Hi.getOperand(0).getValueType().isScalarInteger() || 13975 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize) 13976 return SDValue(); 13977 13978 // Use the EVT of low and high parts before bitcast as the input 13979 // of target query. 13980 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST) 13981 ? Lo.getOperand(0).getValueType() 13982 : Lo.getValueType(); 13983 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST) 13984 ? Hi.getOperand(0).getValueType() 13985 : Hi.getValueType(); 13986 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) 13987 return SDValue(); 13988 13989 // Start to split store. 13990 unsigned Alignment = ST->getAlignment(); 13991 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 13992 AAMDNodes AAInfo = ST->getAAInfo(); 13993 13994 // Change the sizes of Lo and Hi's value types to HalfValBitSize. 13995 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize); 13996 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0)); 13997 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0)); 13998 13999 SDValue Chain = ST->getChain(); 14000 SDValue Ptr = ST->getBasePtr(); 14001 // Lower value store. 14002 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 14003 ST->getAlignment(), MMOFlags, AAInfo); 14004 Ptr = 14005 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 14006 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType())); 14007 // Higher value store. 14008 SDValue St1 = 14009 DAG.getStore(St0, DL, Hi, Ptr, 14010 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8), 14011 Alignment / 2, MMOFlags, AAInfo); 14012 return St1; 14013 } 14014 14015 /// Convert a disguised subvector insertion into a shuffle: 14016 /// insert_vector_elt V, (bitcast X from vector type), IdxC --> 14017 /// bitcast(shuffle (bitcast V), (extended X), Mask) 14018 /// Note: We do not use an insert_subvector node because that requires a legal 14019 /// subvector type. 14020 SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) { 14021 SDValue InsertVal = N->getOperand(1); 14022 if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() || 14023 !InsertVal.getOperand(0).getValueType().isVector()) 14024 return SDValue(); 14025 14026 SDValue SubVec = InsertVal.getOperand(0); 14027 SDValue DestVec = N->getOperand(0); 14028 EVT SubVecVT = SubVec.getValueType(); 14029 EVT VT = DestVec.getValueType(); 14030 unsigned NumSrcElts = SubVecVT.getVectorNumElements(); 14031 unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits(); 14032 unsigned NumMaskVals = ExtendRatio * NumSrcElts; 14033 14034 // Step 1: Create a shuffle mask that implements this insert operation. The 14035 // vector that we are inserting into will be operand 0 of the shuffle, so 14036 // those elements are just 'i'. The inserted subvector is in the first 14037 // positions of operand 1 of the shuffle. Example: 14038 // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7} 14039 SmallVector<int, 16> Mask(NumMaskVals); 14040 for (unsigned i = 0; i != NumMaskVals; ++i) { 14041 if (i / NumSrcElts == InsIndex) 14042 Mask[i] = (i % NumSrcElts) + NumMaskVals; 14043 else 14044 Mask[i] = i; 14045 } 14046 14047 // Bail out if the target can not handle the shuffle we want to create. 14048 EVT SubVecEltVT = SubVecVT.getVectorElementType(); 14049 EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals); 14050 if (!TLI.isShuffleMaskLegal(Mask, ShufVT)) 14051 return SDValue(); 14052 14053 // Step 2: Create a wide vector from the inserted source vector by appending 14054 // undefined elements. This is the same size as our destination vector. 14055 SDLoc DL(N); 14056 SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT)); 14057 ConcatOps[0] = SubVec; 14058 SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps); 14059 14060 // Step 3: Shuffle in the padded subvector. 14061 SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec); 14062 SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask); 14063 AddToWorklist(PaddedSubV.getNode()); 14064 AddToWorklist(DestVecBC.getNode()); 14065 AddToWorklist(Shuf.getNode()); 14066 return DAG.getBitcast(VT, Shuf); 14067 } 14068 14069 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 14070 SDValue InVec = N->getOperand(0); 14071 SDValue InVal = N->getOperand(1); 14072 SDValue EltNo = N->getOperand(2); 14073 SDLoc DL(N); 14074 14075 // If the inserted element is an UNDEF, just use the input vector. 14076 if (InVal.isUndef()) 14077 return InVec; 14078 14079 EVT VT = InVec.getValueType(); 14080 14081 // Remove redundant insertions: 14082 // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x 14083 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 14084 InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1)) 14085 return InVec; 14086 14087 // We must know which element is being inserted for folds below here. 14088 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo); 14089 if (!IndexC) 14090 return SDValue(); 14091 unsigned Elt = IndexC->getZExtValue(); 14092 14093 if (SDValue Shuf = combineInsertEltToShuffle(N, Elt)) 14094 return Shuf; 14095 14096 // Canonicalize insert_vector_elt dag nodes. 14097 // Example: 14098 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 14099 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 14100 // 14101 // Do this only if the child insert_vector node has one use; also 14102 // do this only if indices are both constants and Idx1 < Idx0. 14103 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 14104 && isa<ConstantSDNode>(InVec.getOperand(2))) { 14105 unsigned OtherElt = InVec.getConstantOperandVal(2); 14106 if (Elt < OtherElt) { 14107 // Swap nodes. 14108 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, 14109 InVec.getOperand(0), InVal, EltNo); 14110 AddToWorklist(NewOp.getNode()); 14111 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 14112 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 14113 } 14114 } 14115 14116 // If we can't generate a legal BUILD_VECTOR, exit 14117 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 14118 return SDValue(); 14119 14120 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 14121 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 14122 // vector elements. 14123 SmallVector<SDValue, 8> Ops; 14124 // Do not combine these two vectors if the output vector will not replace 14125 // the input vector. 14126 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 14127 Ops.append(InVec.getNode()->op_begin(), 14128 InVec.getNode()->op_end()); 14129 } else if (InVec.isUndef()) { 14130 unsigned NElts = VT.getVectorNumElements(); 14131 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 14132 } else { 14133 return SDValue(); 14134 } 14135 14136 // Insert the element 14137 if (Elt < Ops.size()) { 14138 // All the operands of BUILD_VECTOR must have the same type; 14139 // we enforce that here. 14140 EVT OpVT = Ops[0].getValueType(); 14141 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal; 14142 } 14143 14144 // Return the new vector 14145 return DAG.getBuildVector(VT, DL, Ops); 14146 } 14147 14148 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 14149 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 14150 assert(!OriginalLoad->isVolatile()); 14151 14152 EVT ResultVT = EVE->getValueType(0); 14153 EVT VecEltVT = InVecVT.getVectorElementType(); 14154 unsigned Align = OriginalLoad->getAlignment(); 14155 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 14156 VecEltVT.getTypeForEVT(*DAG.getContext())); 14157 14158 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 14159 return SDValue(); 14160 14161 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ? 14162 ISD::NON_EXTLOAD : ISD::EXTLOAD; 14163 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT)) 14164 return SDValue(); 14165 14166 Align = NewAlign; 14167 14168 SDValue NewPtr = OriginalLoad->getBasePtr(); 14169 SDValue Offset; 14170 EVT PtrType = NewPtr.getValueType(); 14171 MachinePointerInfo MPI; 14172 SDLoc DL(EVE); 14173 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 14174 int Elt = ConstEltNo->getZExtValue(); 14175 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 14176 Offset = DAG.getConstant(PtrOff, DL, PtrType); 14177 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 14178 } else { 14179 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 14180 Offset = DAG.getNode( 14181 ISD::MUL, DL, PtrType, Offset, 14182 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 14183 MPI = OriginalLoad->getPointerInfo(); 14184 } 14185 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 14186 14187 // The replacement we need to do here is a little tricky: we need to 14188 // replace an extractelement of a load with a load. 14189 // Use ReplaceAllUsesOfValuesWith to do the replacement. 14190 // Note that this replacement assumes that the extractvalue is the only 14191 // use of the load; that's okay because we don't want to perform this 14192 // transformation in other cases anyway. 14193 SDValue Load; 14194 SDValue Chain; 14195 if (ResultVT.bitsGT(VecEltVT)) { 14196 // If the result type of vextract is wider than the load, then issue an 14197 // extending load instead. 14198 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 14199 VecEltVT) 14200 ? ISD::ZEXTLOAD 14201 : ISD::EXTLOAD; 14202 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 14203 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 14204 Align, OriginalLoad->getMemOperand()->getFlags(), 14205 OriginalLoad->getAAInfo()); 14206 Chain = Load.getValue(1); 14207 } else { 14208 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, 14209 MPI, Align, OriginalLoad->getMemOperand()->getFlags(), 14210 OriginalLoad->getAAInfo()); 14211 Chain = Load.getValue(1); 14212 if (ResultVT.bitsLT(VecEltVT)) 14213 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 14214 else 14215 Load = DAG.getBitcast(ResultVT, Load); 14216 } 14217 WorklistRemover DeadNodes(*this); 14218 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 14219 SDValue To[] = { Load, Chain }; 14220 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 14221 // Since we're explicitly calling ReplaceAllUses, add the new node to the 14222 // worklist explicitly as well. 14223 AddToWorklist(Load.getNode()); 14224 AddUsersToWorklist(Load.getNode()); // Add users too 14225 // Make sure to revisit this node to clean it up; it will usually be dead. 14226 AddToWorklist(EVE); 14227 ++OpsNarrowed; 14228 return SDValue(EVE, 0); 14229 } 14230 14231 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 14232 // (vextract (scalar_to_vector val, 0) -> val 14233 SDValue InVec = N->getOperand(0); 14234 EVT VT = InVec.getValueType(); 14235 EVT NVT = N->getValueType(0); 14236 14237 if (InVec.isUndef()) 14238 return DAG.getUNDEF(NVT); 14239 14240 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 14241 // Check if the result type doesn't match the inserted element type. A 14242 // SCALAR_TO_VECTOR may truncate the inserted element and the 14243 // EXTRACT_VECTOR_ELT may widen the extracted vector. 14244 SDValue InOp = InVec.getOperand(0); 14245 if (InOp.getValueType() != NVT) { 14246 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 14247 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 14248 } 14249 return InOp; 14250 } 14251 14252 SDValue EltNo = N->getOperand(1); 14253 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 14254 14255 // extract_vector_elt of out-of-bounds element -> UNDEF 14256 if (ConstEltNo && ConstEltNo->getAPIntValue().uge(VT.getVectorNumElements())) 14257 return DAG.getUNDEF(NVT); 14258 14259 // extract_vector_elt (build_vector x, y), 1 -> y 14260 if (ConstEltNo && 14261 InVec.getOpcode() == ISD::BUILD_VECTOR && 14262 TLI.isTypeLegal(VT) && 14263 (InVec.hasOneUse() || 14264 TLI.aggressivelyPreferBuildVectorSources(VT))) { 14265 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 14266 EVT InEltVT = Elt.getValueType(); 14267 14268 // Sometimes build_vector's scalar input types do not match result type. 14269 if (NVT == InEltVT) 14270 return Elt; 14271 14272 // TODO: It may be useful to truncate if free if the build_vector implicitly 14273 // converts. 14274 } 14275 14276 // extract_vector_elt (v2i32 (bitcast i64:x)), EltTrunc -> i32 (trunc i64:x) 14277 bool isLE = DAG.getDataLayout().isLittleEndian(); 14278 unsigned EltTrunc = isLE ? 0 : VT.getVectorNumElements() - 1; 14279 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 14280 ConstEltNo->getZExtValue() == EltTrunc && VT.isInteger()) { 14281 SDValue BCSrc = InVec.getOperand(0); 14282 if (BCSrc.getValueType().isScalarInteger()) 14283 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 14284 } 14285 14286 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 14287 // 14288 // This only really matters if the index is non-constant since other combines 14289 // on the constant elements already work. 14290 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && 14291 EltNo == InVec.getOperand(2)) { 14292 SDValue Elt = InVec.getOperand(1); 14293 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt; 14294 } 14295 14296 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 14297 // We only perform this optimization before the op legalization phase because 14298 // we may introduce new vector instructions which are not backed by TD 14299 // patterns. For example on AVX, extracting elements from a wide vector 14300 // without using extract_subvector. However, if we can find an underlying 14301 // scalar value, then we can always use that. 14302 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 14303 int NumElem = VT.getVectorNumElements(); 14304 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 14305 // Find the new index to extract from. 14306 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 14307 14308 // Extracting an undef index is undef. 14309 if (OrigElt == -1) 14310 return DAG.getUNDEF(NVT); 14311 14312 // Select the right vector half to extract from. 14313 SDValue SVInVec; 14314 if (OrigElt < NumElem) { 14315 SVInVec = InVec->getOperand(0); 14316 } else { 14317 SVInVec = InVec->getOperand(1); 14318 OrigElt -= NumElem; 14319 } 14320 14321 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 14322 SDValue InOp = SVInVec.getOperand(OrigElt); 14323 if (InOp.getValueType() != NVT) { 14324 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 14325 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 14326 } 14327 14328 return InOp; 14329 } 14330 14331 // FIXME: We should handle recursing on other vector shuffles and 14332 // scalar_to_vector here as well. 14333 14334 if (!LegalOperations || 14335 // FIXME: Should really be just isOperationLegalOrCustom. 14336 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VT) || 14337 TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VT)) { 14338 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 14339 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 14340 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 14341 } 14342 } 14343 14344 bool BCNumEltsChanged = false; 14345 EVT ExtVT = VT.getVectorElementType(); 14346 EVT LVT = ExtVT; 14347 14348 // If the result of load has to be truncated, then it's not necessarily 14349 // profitable. 14350 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 14351 return SDValue(); 14352 14353 if (InVec.getOpcode() == ISD::BITCAST) { 14354 // Don't duplicate a load with other uses. 14355 if (!InVec.hasOneUse()) 14356 return SDValue(); 14357 14358 EVT BCVT = InVec.getOperand(0).getValueType(); 14359 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 14360 return SDValue(); 14361 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 14362 BCNumEltsChanged = true; 14363 InVec = InVec.getOperand(0); 14364 ExtVT = BCVT.getVectorElementType(); 14365 } 14366 14367 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 14368 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 14369 ISD::isNormalLoad(InVec.getNode()) && 14370 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 14371 SDValue Index = N->getOperand(1); 14372 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) { 14373 if (!OrigLoad->isVolatile()) { 14374 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 14375 OrigLoad); 14376 } 14377 } 14378 } 14379 14380 // Perform only after legalization to ensure build_vector / vector_shuffle 14381 // optimizations have already been done. 14382 if (!LegalOperations) return SDValue(); 14383 14384 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 14385 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 14386 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 14387 14388 if (ConstEltNo) { 14389 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 14390 14391 LoadSDNode *LN0 = nullptr; 14392 const ShuffleVectorSDNode *SVN = nullptr; 14393 if (ISD::isNormalLoad(InVec.getNode())) { 14394 LN0 = cast<LoadSDNode>(InVec); 14395 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 14396 InVec.getOperand(0).getValueType() == ExtVT && 14397 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 14398 // Don't duplicate a load with other uses. 14399 if (!InVec.hasOneUse()) 14400 return SDValue(); 14401 14402 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 14403 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 14404 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 14405 // => 14406 // (load $addr+1*size) 14407 14408 // Don't duplicate a load with other uses. 14409 if (!InVec.hasOneUse()) 14410 return SDValue(); 14411 14412 // If the bit convert changed the number of elements, it is unsafe 14413 // to examine the mask. 14414 if (BCNumEltsChanged) 14415 return SDValue(); 14416 14417 // Select the input vector, guarding against out of range extract vector. 14418 unsigned NumElems = VT.getVectorNumElements(); 14419 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 14420 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 14421 14422 if (InVec.getOpcode() == ISD::BITCAST) { 14423 // Don't duplicate a load with other uses. 14424 if (!InVec.hasOneUse()) 14425 return SDValue(); 14426 14427 InVec = InVec.getOperand(0); 14428 } 14429 if (ISD::isNormalLoad(InVec.getNode())) { 14430 LN0 = cast<LoadSDNode>(InVec); 14431 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 14432 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 14433 } 14434 } 14435 14436 // Make sure we found a non-volatile load and the extractelement is 14437 // the only use. 14438 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 14439 return SDValue(); 14440 14441 // If Idx was -1 above, Elt is going to be -1, so just return undef. 14442 if (Elt == -1) 14443 return DAG.getUNDEF(LVT); 14444 14445 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 14446 } 14447 14448 return SDValue(); 14449 } 14450 14451 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 14452 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 14453 // We perform this optimization post type-legalization because 14454 // the type-legalizer often scalarizes integer-promoted vectors. 14455 // Performing this optimization before may create bit-casts which 14456 // will be type-legalized to complex code sequences. 14457 // We perform this optimization only before the operation legalizer because we 14458 // may introduce illegal operations. 14459 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 14460 return SDValue(); 14461 14462 unsigned NumInScalars = N->getNumOperands(); 14463 SDLoc DL(N); 14464 EVT VT = N->getValueType(0); 14465 14466 // Check to see if this is a BUILD_VECTOR of a bunch of values 14467 // which come from any_extend or zero_extend nodes. If so, we can create 14468 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 14469 // optimizations. We do not handle sign-extend because we can't fill the sign 14470 // using shuffles. 14471 EVT SourceType = MVT::Other; 14472 bool AllAnyExt = true; 14473 14474 for (unsigned i = 0; i != NumInScalars; ++i) { 14475 SDValue In = N->getOperand(i); 14476 // Ignore undef inputs. 14477 if (In.isUndef()) continue; 14478 14479 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 14480 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 14481 14482 // Abort if the element is not an extension. 14483 if (!ZeroExt && !AnyExt) { 14484 SourceType = MVT::Other; 14485 break; 14486 } 14487 14488 // The input is a ZeroExt or AnyExt. Check the original type. 14489 EVT InTy = In.getOperand(0).getValueType(); 14490 14491 // Check that all of the widened source types are the same. 14492 if (SourceType == MVT::Other) 14493 // First time. 14494 SourceType = InTy; 14495 else if (InTy != SourceType) { 14496 // Multiple income types. Abort. 14497 SourceType = MVT::Other; 14498 break; 14499 } 14500 14501 // Check if all of the extends are ANY_EXTENDs. 14502 AllAnyExt &= AnyExt; 14503 } 14504 14505 // In order to have valid types, all of the inputs must be extended from the 14506 // same source type and all of the inputs must be any or zero extend. 14507 // Scalar sizes must be a power of two. 14508 EVT OutScalarTy = VT.getScalarType(); 14509 bool ValidTypes = SourceType != MVT::Other && 14510 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 14511 isPowerOf2_32(SourceType.getSizeInBits()); 14512 14513 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 14514 // turn into a single shuffle instruction. 14515 if (!ValidTypes) 14516 return SDValue(); 14517 14518 bool isLE = DAG.getDataLayout().isLittleEndian(); 14519 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 14520 assert(ElemRatio > 1 && "Invalid element size ratio"); 14521 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 14522 DAG.getConstant(0, DL, SourceType); 14523 14524 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 14525 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 14526 14527 // Populate the new build_vector 14528 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 14529 SDValue Cast = N->getOperand(i); 14530 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 14531 Cast.getOpcode() == ISD::ZERO_EXTEND || 14532 Cast.isUndef()) && "Invalid cast opcode"); 14533 SDValue In; 14534 if (Cast.isUndef()) 14535 In = DAG.getUNDEF(SourceType); 14536 else 14537 In = Cast->getOperand(0); 14538 unsigned Index = isLE ? (i * ElemRatio) : 14539 (i * ElemRatio + (ElemRatio - 1)); 14540 14541 assert(Index < Ops.size() && "Invalid index"); 14542 Ops[Index] = In; 14543 } 14544 14545 // The type of the new BUILD_VECTOR node. 14546 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 14547 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 14548 "Invalid vector size"); 14549 // Check if the new vector type is legal. 14550 if (!isTypeLegal(VecVT)) return SDValue(); 14551 14552 // Make the new BUILD_VECTOR. 14553 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops); 14554 14555 // The new BUILD_VECTOR node has the potential to be further optimized. 14556 AddToWorklist(BV.getNode()); 14557 // Bitcast to the desired type. 14558 return DAG.getBitcast(VT, BV); 14559 } 14560 14561 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 14562 EVT VT = N->getValueType(0); 14563 14564 unsigned NumInScalars = N->getNumOperands(); 14565 SDLoc DL(N); 14566 14567 EVT SrcVT = MVT::Other; 14568 unsigned Opcode = ISD::DELETED_NODE; 14569 unsigned NumDefs = 0; 14570 14571 for (unsigned i = 0; i != NumInScalars; ++i) { 14572 SDValue In = N->getOperand(i); 14573 unsigned Opc = In.getOpcode(); 14574 14575 if (Opc == ISD::UNDEF) 14576 continue; 14577 14578 // If all scalar values are floats and converted from integers. 14579 if (Opcode == ISD::DELETED_NODE && 14580 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 14581 Opcode = Opc; 14582 } 14583 14584 if (Opc != Opcode) 14585 return SDValue(); 14586 14587 EVT InVT = In.getOperand(0).getValueType(); 14588 14589 // If all scalar values are typed differently, bail out. It's chosen to 14590 // simplify BUILD_VECTOR of integer types. 14591 if (SrcVT == MVT::Other) 14592 SrcVT = InVT; 14593 if (SrcVT != InVT) 14594 return SDValue(); 14595 NumDefs++; 14596 } 14597 14598 // If the vector has just one element defined, it's not worth to fold it into 14599 // a vectorized one. 14600 if (NumDefs < 2) 14601 return SDValue(); 14602 14603 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 14604 && "Should only handle conversion from integer to float."); 14605 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 14606 14607 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 14608 14609 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 14610 return SDValue(); 14611 14612 // Just because the floating-point vector type is legal does not necessarily 14613 // mean that the corresponding integer vector type is. 14614 if (!isTypeLegal(NVT)) 14615 return SDValue(); 14616 14617 SmallVector<SDValue, 8> Opnds; 14618 for (unsigned i = 0; i != NumInScalars; ++i) { 14619 SDValue In = N->getOperand(i); 14620 14621 if (In.isUndef()) 14622 Opnds.push_back(DAG.getUNDEF(SrcVT)); 14623 else 14624 Opnds.push_back(In.getOperand(0)); 14625 } 14626 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds); 14627 AddToWorklist(BV.getNode()); 14628 14629 return DAG.getNode(Opcode, DL, VT, BV); 14630 } 14631 14632 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N, 14633 ArrayRef<int> VectorMask, 14634 SDValue VecIn1, SDValue VecIn2, 14635 unsigned LeftIdx) { 14636 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 14637 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy); 14638 14639 EVT VT = N->getValueType(0); 14640 EVT InVT1 = VecIn1.getValueType(); 14641 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1; 14642 14643 unsigned Vec2Offset = 0; 14644 unsigned NumElems = VT.getVectorNumElements(); 14645 unsigned ShuffleNumElems = NumElems; 14646 14647 // In case both the input vectors are extracted from same base 14648 // vector we do not need extra addend (Vec2Offset) while 14649 // computing shuffle mask. 14650 if (!VecIn2 || !(VecIn1.getOpcode() == ISD::EXTRACT_SUBVECTOR) || 14651 !(VecIn2.getOpcode() == ISD::EXTRACT_SUBVECTOR) || 14652 !(VecIn1.getOperand(0) == VecIn2.getOperand(0))) 14653 Vec2Offset = InVT1.getVectorNumElements(); 14654 14655 // We can't generate a shuffle node with mismatched input and output types. 14656 // Try to make the types match the type of the output. 14657 if (InVT1 != VT || InVT2 != VT) { 14658 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) { 14659 // If the output vector length is a multiple of both input lengths, 14660 // we can concatenate them and pad the rest with undefs. 14661 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits(); 14662 assert(NumConcats >= 2 && "Concat needs at least two inputs!"); 14663 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1)); 14664 ConcatOps[0] = VecIn1; 14665 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1); 14666 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 14667 VecIn2 = SDValue(); 14668 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) { 14669 if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems)) 14670 return SDValue(); 14671 14672 if (!VecIn2.getNode()) { 14673 // If we only have one input vector, and it's twice the size of the 14674 // output, split it in two. 14675 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, 14676 DAG.getConstant(NumElems, DL, IdxTy)); 14677 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx); 14678 // Since we now have shorter input vectors, adjust the offset of the 14679 // second vector's start. 14680 Vec2Offset = NumElems; 14681 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) { 14682 // VecIn1 is wider than the output, and we have another, possibly 14683 // smaller input. Pad the smaller input with undefs, shuffle at the 14684 // input vector width, and extract the output. 14685 // The shuffle type is different than VT, so check legality again. 14686 if (LegalOperations && 14687 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1)) 14688 return SDValue(); 14689 14690 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to 14691 // lower it back into a BUILD_VECTOR. So if the inserted type is 14692 // illegal, don't even try. 14693 if (InVT1 != InVT2) { 14694 if (!TLI.isTypeLegal(InVT2)) 14695 return SDValue(); 14696 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1, 14697 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx); 14698 } 14699 ShuffleNumElems = NumElems * 2; 14700 } else { 14701 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider 14702 // than VecIn1. We can't handle this for now - this case will disappear 14703 // when we start sorting the vectors by type. 14704 return SDValue(); 14705 } 14706 } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() && 14707 InVT1.getSizeInBits() == VT.getSizeInBits()) { 14708 SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2)); 14709 ConcatOps[0] = VecIn2; 14710 VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 14711 } else { 14712 // TODO: Support cases where the length mismatch isn't exactly by a 14713 // factor of 2. 14714 // TODO: Move this check upwards, so that if we have bad type 14715 // mismatches, we don't create any DAG nodes. 14716 return SDValue(); 14717 } 14718 } 14719 14720 // Initialize mask to undef. 14721 SmallVector<int, 8> Mask(ShuffleNumElems, -1); 14722 14723 // Only need to run up to the number of elements actually used, not the 14724 // total number of elements in the shuffle - if we are shuffling a wider 14725 // vector, the high lanes should be set to undef. 14726 for (unsigned i = 0; i != NumElems; ++i) { 14727 if (VectorMask[i] <= 0) 14728 continue; 14729 14730 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1); 14731 if (VectorMask[i] == (int)LeftIdx) { 14732 Mask[i] = ExtIndex; 14733 } else if (VectorMask[i] == (int)LeftIdx + 1) { 14734 Mask[i] = Vec2Offset + ExtIndex; 14735 } 14736 } 14737 14738 // The type the input vectors may have changed above. 14739 InVT1 = VecIn1.getValueType(); 14740 14741 // If we already have a VecIn2, it should have the same type as VecIn1. 14742 // If we don't, get an undef/zero vector of the appropriate type. 14743 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1); 14744 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type."); 14745 14746 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask); 14747 if (ShuffleNumElems > NumElems) 14748 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx); 14749 14750 return Shuffle; 14751 } 14752 14753 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 14754 // operations. If the types of the vectors we're extracting from allow it, 14755 // turn this into a vector_shuffle node. 14756 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) { 14757 SDLoc DL(N); 14758 EVT VT = N->getValueType(0); 14759 14760 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 14761 if (!isTypeLegal(VT)) 14762 return SDValue(); 14763 14764 // May only combine to shuffle after legalize if shuffle is legal. 14765 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 14766 return SDValue(); 14767 14768 bool UsesZeroVector = false; 14769 unsigned NumElems = N->getNumOperands(); 14770 14771 // Record, for each element of the newly built vector, which input vector 14772 // that element comes from. -1 stands for undef, 0 for the zero vector, 14773 // and positive values for the input vectors. 14774 // VectorMask maps each element to its vector number, and VecIn maps vector 14775 // numbers to their initial SDValues. 14776 14777 SmallVector<int, 8> VectorMask(NumElems, -1); 14778 SmallVector<SDValue, 8> VecIn; 14779 VecIn.push_back(SDValue()); 14780 14781 for (unsigned i = 0; i != NumElems; ++i) { 14782 SDValue Op = N->getOperand(i); 14783 14784 if (Op.isUndef()) 14785 continue; 14786 14787 // See if we can use a blend with a zero vector. 14788 // TODO: Should we generalize this to a blend with an arbitrary constant 14789 // vector? 14790 if (isNullConstant(Op) || isNullFPConstant(Op)) { 14791 UsesZeroVector = true; 14792 VectorMask[i] = 0; 14793 continue; 14794 } 14795 14796 // Not an undef or zero. If the input is something other than an 14797 // EXTRACT_VECTOR_ELT with an in-range constant index, bail out. 14798 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14799 !isa<ConstantSDNode>(Op.getOperand(1))) 14800 return SDValue(); 14801 SDValue ExtractedFromVec = Op.getOperand(0); 14802 14803 APInt ExtractIdx = cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue(); 14804 if (ExtractIdx.uge(ExtractedFromVec.getValueType().getVectorNumElements())) 14805 return SDValue(); 14806 14807 // All inputs must have the same element type as the output. 14808 if (VT.getVectorElementType() != 14809 ExtractedFromVec.getValueType().getVectorElementType()) 14810 return SDValue(); 14811 14812 // Have we seen this input vector before? 14813 // The vectors are expected to be tiny (usually 1 or 2 elements), so using 14814 // a map back from SDValues to numbers isn't worth it. 14815 unsigned Idx = std::distance( 14816 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec)); 14817 if (Idx == VecIn.size()) 14818 VecIn.push_back(ExtractedFromVec); 14819 14820 VectorMask[i] = Idx; 14821 } 14822 14823 // If we didn't find at least one input vector, bail out. 14824 if (VecIn.size() < 2) 14825 return SDValue(); 14826 14827 // If all the Operands of BUILD_VECTOR extract from same 14828 // vector, then split the vector efficiently based on the maximum 14829 // vector access index and adjust the VectorMask and 14830 // VecIn accordingly. 14831 if (VecIn.size() == 2) { 14832 unsigned MaxIndex = 0; 14833 unsigned NearestPow2 = 0; 14834 SDValue Vec = VecIn.back(); 14835 EVT InVT = Vec.getValueType(); 14836 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 14837 SmallVector<unsigned, 8> IndexVec(NumElems, 0); 14838 14839 for (unsigned i = 0; i < NumElems; i++) { 14840 if (VectorMask[i] <= 0) 14841 continue; 14842 unsigned Index = N->getOperand(i).getConstantOperandVal(1); 14843 IndexVec[i] = Index; 14844 MaxIndex = std::max(MaxIndex, Index); 14845 } 14846 14847 NearestPow2 = PowerOf2Ceil(MaxIndex); 14848 if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 && 14849 NumElems * 2 < NearestPow2) { 14850 unsigned SplitSize = NearestPow2 / 2; 14851 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), 14852 InVT.getVectorElementType(), SplitSize); 14853 if (TLI.isTypeLegal(SplitVT)) { 14854 SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, 14855 DAG.getConstant(SplitSize, DL, IdxTy)); 14856 SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, 14857 DAG.getConstant(0, DL, IdxTy)); 14858 VecIn.pop_back(); 14859 VecIn.push_back(VecIn1); 14860 VecIn.push_back(VecIn2); 14861 14862 for (unsigned i = 0; i < NumElems; i++) { 14863 if (VectorMask[i] <= 0) 14864 continue; 14865 VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2; 14866 } 14867 } 14868 } 14869 } 14870 14871 // TODO: We want to sort the vectors by descending length, so that adjacent 14872 // pairs have similar length, and the longer vector is always first in the 14873 // pair. 14874 14875 // TODO: Should this fire if some of the input vectors has illegal type (like 14876 // it does now), or should we let legalization run its course first? 14877 14878 // Shuffle phase: 14879 // Take pairs of vectors, and shuffle them so that the result has elements 14880 // from these vectors in the correct places. 14881 // For example, given: 14882 // t10: i32 = extract_vector_elt t1, Constant:i64<0> 14883 // t11: i32 = extract_vector_elt t2, Constant:i64<0> 14884 // t12: i32 = extract_vector_elt t3, Constant:i64<0> 14885 // t13: i32 = extract_vector_elt t1, Constant:i64<1> 14886 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13 14887 // We will generate: 14888 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2 14889 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef 14890 SmallVector<SDValue, 4> Shuffles; 14891 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) { 14892 unsigned LeftIdx = 2 * In + 1; 14893 SDValue VecLeft = VecIn[LeftIdx]; 14894 SDValue VecRight = 14895 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue(); 14896 14897 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft, 14898 VecRight, LeftIdx)) 14899 Shuffles.push_back(Shuffle); 14900 else 14901 return SDValue(); 14902 } 14903 14904 // If we need the zero vector as an "ingredient" in the blend tree, add it 14905 // to the list of shuffles. 14906 if (UsesZeroVector) 14907 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT) 14908 : DAG.getConstantFP(0.0, DL, VT)); 14909 14910 // If we only have one shuffle, we're done. 14911 if (Shuffles.size() == 1) 14912 return Shuffles[0]; 14913 14914 // Update the vector mask to point to the post-shuffle vectors. 14915 for (int &Vec : VectorMask) 14916 if (Vec == 0) 14917 Vec = Shuffles.size() - 1; 14918 else 14919 Vec = (Vec - 1) / 2; 14920 14921 // More than one shuffle. Generate a binary tree of blends, e.g. if from 14922 // the previous step we got the set of shuffles t10, t11, t12, t13, we will 14923 // generate: 14924 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2 14925 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4 14926 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6 14927 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8 14928 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11 14929 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13 14930 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21 14931 14932 // Make sure the initial size of the shuffle list is even. 14933 if (Shuffles.size() % 2) 14934 Shuffles.push_back(DAG.getUNDEF(VT)); 14935 14936 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) { 14937 if (CurSize % 2) { 14938 Shuffles[CurSize] = DAG.getUNDEF(VT); 14939 CurSize++; 14940 } 14941 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) { 14942 int Left = 2 * In; 14943 int Right = 2 * In + 1; 14944 SmallVector<int, 8> Mask(NumElems, -1); 14945 for (unsigned i = 0; i != NumElems; ++i) { 14946 if (VectorMask[i] == Left) { 14947 Mask[i] = i; 14948 VectorMask[i] = In; 14949 } else if (VectorMask[i] == Right) { 14950 Mask[i] = i + NumElems; 14951 VectorMask[i] = In; 14952 } 14953 } 14954 14955 Shuffles[In] = 14956 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask); 14957 } 14958 } 14959 return Shuffles[0]; 14960 } 14961 14962 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 14963 EVT VT = N->getValueType(0); 14964 14965 // A vector built entirely of undefs is undef. 14966 if (ISD::allOperandsUndef(N)) 14967 return DAG.getUNDEF(VT); 14968 14969 // If this is a splat of a bitcast from another vector, change to a 14970 // concat_vector. 14971 // For example: 14972 // (build_vector (i64 (bitcast (v2i32 X))), (i64 (bitcast (v2i32 X)))) -> 14973 // (v2i64 (bitcast (concat_vectors (v2i32 X), (v2i32 X)))) 14974 // 14975 // If X is a build_vector itself, the concat can become a larger build_vector. 14976 // TODO: Maybe this is useful for non-splat too? 14977 if (!LegalOperations) { 14978 if (SDValue Splat = cast<BuildVectorSDNode>(N)->getSplatValue()) { 14979 Splat = peekThroughBitcast(Splat); 14980 EVT SrcVT = Splat.getValueType(); 14981 if (SrcVT.isVector()) { 14982 unsigned NumElts = N->getNumOperands() * SrcVT.getVectorNumElements(); 14983 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), 14984 SrcVT.getVectorElementType(), NumElts); 14985 SmallVector<SDValue, 8> Ops(N->getNumOperands(), Splat); 14986 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), NewVT, Ops); 14987 return DAG.getBitcast(VT, Concat); 14988 } 14989 } 14990 } 14991 14992 // Check if we can express BUILD VECTOR via subvector extract. 14993 if (!LegalTypes && (N->getNumOperands() > 1)) { 14994 SDValue Op0 = N->getOperand(0); 14995 auto checkElem = [&](SDValue Op) -> uint64_t { 14996 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) && 14997 (Op0.getOperand(0) == Op.getOperand(0))) 14998 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 14999 return CNode->getZExtValue(); 15000 return -1; 15001 }; 15002 15003 int Offset = checkElem(Op0); 15004 for (unsigned i = 0; i < N->getNumOperands(); ++i) { 15005 if (Offset + i != checkElem(N->getOperand(i))) { 15006 Offset = -1; 15007 break; 15008 } 15009 } 15010 15011 if ((Offset == 0) && 15012 (Op0.getOperand(0).getValueType() == N->getValueType(0))) 15013 return Op0.getOperand(0); 15014 if ((Offset != -1) && 15015 ((Offset % N->getValueType(0).getVectorNumElements()) == 15016 0)) // IDX must be multiple of output size. 15017 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0), 15018 Op0.getOperand(0), Op0.getOperand(1)); 15019 } 15020 15021 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 15022 return V; 15023 15024 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 15025 return V; 15026 15027 if (SDValue V = reduceBuildVecToShuffle(N)) 15028 return V; 15029 15030 return SDValue(); 15031 } 15032 15033 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 15034 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15035 EVT OpVT = N->getOperand(0).getValueType(); 15036 15037 // If the operands are legal vectors, leave them alone. 15038 if (TLI.isTypeLegal(OpVT)) 15039 return SDValue(); 15040 15041 SDLoc DL(N); 15042 EVT VT = N->getValueType(0); 15043 SmallVector<SDValue, 8> Ops; 15044 15045 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 15046 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 15047 15048 // Keep track of what we encounter. 15049 bool AnyInteger = false; 15050 bool AnyFP = false; 15051 for (const SDValue &Op : N->ops()) { 15052 if (ISD::BITCAST == Op.getOpcode() && 15053 !Op.getOperand(0).getValueType().isVector()) 15054 Ops.push_back(Op.getOperand(0)); 15055 else if (ISD::UNDEF == Op.getOpcode()) 15056 Ops.push_back(ScalarUndef); 15057 else 15058 return SDValue(); 15059 15060 // Note whether we encounter an integer or floating point scalar. 15061 // If it's neither, bail out, it could be something weird like x86mmx. 15062 EVT LastOpVT = Ops.back().getValueType(); 15063 if (LastOpVT.isFloatingPoint()) 15064 AnyFP = true; 15065 else if (LastOpVT.isInteger()) 15066 AnyInteger = true; 15067 else 15068 return SDValue(); 15069 } 15070 15071 // If any of the operands is a floating point scalar bitcast to a vector, 15072 // use floating point types throughout, and bitcast everything. 15073 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 15074 if (AnyFP) { 15075 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 15076 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 15077 if (AnyInteger) { 15078 for (SDValue &Op : Ops) { 15079 if (Op.getValueType() == SVT) 15080 continue; 15081 if (Op.isUndef()) 15082 Op = ScalarUndef; 15083 else 15084 Op = DAG.getBitcast(SVT, Op); 15085 } 15086 } 15087 } 15088 15089 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 15090 VT.getSizeInBits() / SVT.getSizeInBits()); 15091 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 15092 } 15093 15094 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 15095 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 15096 // most two distinct vectors the same size as the result, attempt to turn this 15097 // into a legal shuffle. 15098 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 15099 EVT VT = N->getValueType(0); 15100 EVT OpVT = N->getOperand(0).getValueType(); 15101 int NumElts = VT.getVectorNumElements(); 15102 int NumOpElts = OpVT.getVectorNumElements(); 15103 15104 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 15105 SmallVector<int, 8> Mask; 15106 15107 for (SDValue Op : N->ops()) { 15108 // Peek through any bitcast. 15109 Op = peekThroughBitcast(Op); 15110 15111 // UNDEF nodes convert to UNDEF shuffle mask values. 15112 if (Op.isUndef()) { 15113 Mask.append((unsigned)NumOpElts, -1); 15114 continue; 15115 } 15116 15117 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 15118 return SDValue(); 15119 15120 // What vector are we extracting the subvector from and at what index? 15121 SDValue ExtVec = Op.getOperand(0); 15122 15123 // We want the EVT of the original extraction to correctly scale the 15124 // extraction index. 15125 EVT ExtVT = ExtVec.getValueType(); 15126 15127 // Peek through any bitcast. 15128 ExtVec = peekThroughBitcast(ExtVec); 15129 15130 // UNDEF nodes convert to UNDEF shuffle mask values. 15131 if (ExtVec.isUndef()) { 15132 Mask.append((unsigned)NumOpElts, -1); 15133 continue; 15134 } 15135 15136 if (!isa<ConstantSDNode>(Op.getOperand(1))) 15137 return SDValue(); 15138 int ExtIdx = Op.getConstantOperandVal(1); 15139 15140 // Ensure that we are extracting a subvector from a vector the same 15141 // size as the result. 15142 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 15143 return SDValue(); 15144 15145 // Scale the subvector index to account for any bitcast. 15146 int NumExtElts = ExtVT.getVectorNumElements(); 15147 if (0 == (NumExtElts % NumElts)) 15148 ExtIdx /= (NumExtElts / NumElts); 15149 else if (0 == (NumElts % NumExtElts)) 15150 ExtIdx *= (NumElts / NumExtElts); 15151 else 15152 return SDValue(); 15153 15154 // At most we can reference 2 inputs in the final shuffle. 15155 if (SV0.isUndef() || SV0 == ExtVec) { 15156 SV0 = ExtVec; 15157 for (int i = 0; i != NumOpElts; ++i) 15158 Mask.push_back(i + ExtIdx); 15159 } else if (SV1.isUndef() || SV1 == ExtVec) { 15160 SV1 = ExtVec; 15161 for (int i = 0; i != NumOpElts; ++i) 15162 Mask.push_back(i + ExtIdx + NumElts); 15163 } else { 15164 return SDValue(); 15165 } 15166 } 15167 15168 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 15169 return SDValue(); 15170 15171 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 15172 DAG.getBitcast(VT, SV1), Mask); 15173 } 15174 15175 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 15176 // If we only have one input vector, we don't need to do any concatenation. 15177 if (N->getNumOperands() == 1) 15178 return N->getOperand(0); 15179 15180 // Check if all of the operands are undefs. 15181 EVT VT = N->getValueType(0); 15182 if (ISD::allOperandsUndef(N)) 15183 return DAG.getUNDEF(VT); 15184 15185 // Optimize concat_vectors where all but the first of the vectors are undef. 15186 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 15187 return Op.isUndef(); 15188 })) { 15189 SDValue In = N->getOperand(0); 15190 assert(In.getValueType().isVector() && "Must concat vectors"); 15191 15192 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 15193 if (In->getOpcode() == ISD::BITCAST && 15194 !In->getOperand(0).getValueType().isVector()) { 15195 SDValue Scalar = In->getOperand(0); 15196 15197 // If the bitcast type isn't legal, it might be a trunc of a legal type; 15198 // look through the trunc so we can still do the transform: 15199 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 15200 if (Scalar->getOpcode() == ISD::TRUNCATE && 15201 !TLI.isTypeLegal(Scalar.getValueType()) && 15202 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 15203 Scalar = Scalar->getOperand(0); 15204 15205 EVT SclTy = Scalar->getValueType(0); 15206 15207 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 15208 return SDValue(); 15209 15210 // Bail out if the vector size is not a multiple of the scalar size. 15211 if (VT.getSizeInBits() % SclTy.getSizeInBits()) 15212 return SDValue(); 15213 15214 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits(); 15215 if (VNTNumElms < 2) 15216 return SDValue(); 15217 15218 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms); 15219 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 15220 return SDValue(); 15221 15222 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar); 15223 return DAG.getBitcast(VT, Res); 15224 } 15225 } 15226 15227 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 15228 // We have already tested above for an UNDEF only concatenation. 15229 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 15230 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 15231 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 15232 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 15233 }; 15234 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 15235 SmallVector<SDValue, 8> Opnds; 15236 EVT SVT = VT.getScalarType(); 15237 15238 EVT MinVT = SVT; 15239 if (!SVT.isFloatingPoint()) { 15240 // If BUILD_VECTOR are from built from integer, they may have different 15241 // operand types. Get the smallest type and truncate all operands to it. 15242 bool FoundMinVT = false; 15243 for (const SDValue &Op : N->ops()) 15244 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 15245 EVT OpSVT = Op.getOperand(0).getValueType(); 15246 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 15247 FoundMinVT = true; 15248 } 15249 assert(FoundMinVT && "Concat vector type mismatch"); 15250 } 15251 15252 for (const SDValue &Op : N->ops()) { 15253 EVT OpVT = Op.getValueType(); 15254 unsigned NumElts = OpVT.getVectorNumElements(); 15255 15256 if (ISD::UNDEF == Op.getOpcode()) 15257 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 15258 15259 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 15260 if (SVT.isFloatingPoint()) { 15261 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 15262 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 15263 } else { 15264 for (unsigned i = 0; i != NumElts; ++i) 15265 Opnds.push_back( 15266 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 15267 } 15268 } 15269 } 15270 15271 assert(VT.getVectorNumElements() == Opnds.size() && 15272 "Concat vector type mismatch"); 15273 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 15274 } 15275 15276 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 15277 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 15278 return V; 15279 15280 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 15281 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 15282 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 15283 return V; 15284 15285 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 15286 // nodes often generate nop CONCAT_VECTOR nodes. 15287 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 15288 // place the incoming vectors at the exact same location. 15289 SDValue SingleSource = SDValue(); 15290 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 15291 15292 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 15293 SDValue Op = N->getOperand(i); 15294 15295 if (Op.isUndef()) 15296 continue; 15297 15298 // Check if this is the identity extract: 15299 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 15300 return SDValue(); 15301 15302 // Find the single incoming vector for the extract_subvector. 15303 if (SingleSource.getNode()) { 15304 if (Op.getOperand(0) != SingleSource) 15305 return SDValue(); 15306 } else { 15307 SingleSource = Op.getOperand(0); 15308 15309 // Check the source type is the same as the type of the result. 15310 // If not, this concat may extend the vector, so we can not 15311 // optimize it away. 15312 if (SingleSource.getValueType() != N->getValueType(0)) 15313 return SDValue(); 15314 } 15315 15316 unsigned IdentityIndex = i * PartNumElem; 15317 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 15318 // The extract index must be constant. 15319 if (!CS) 15320 return SDValue(); 15321 15322 // Check that we are reading from the identity index. 15323 if (CS->getZExtValue() != IdentityIndex) 15324 return SDValue(); 15325 } 15326 15327 if (SingleSource.getNode()) 15328 return SingleSource; 15329 15330 return SDValue(); 15331 } 15332 15333 /// If we are extracting a subvector produced by a wide binary operator with at 15334 /// at least one operand that was the result of a vector concatenation, then try 15335 /// to use the narrow vector operands directly to avoid the concatenation and 15336 /// extraction. 15337 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) { 15338 // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share 15339 // some of these bailouts with other transforms. 15340 15341 // The extract index must be a constant, so we can map it to a concat operand. 15342 auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 15343 if (!ExtractIndex) 15344 return SDValue(); 15345 15346 // Only handle the case where we are doubling and then halving. A larger ratio 15347 // may require more than two narrow binops to replace the wide binop. 15348 EVT VT = Extract->getValueType(0); 15349 unsigned NumElems = VT.getVectorNumElements(); 15350 assert((ExtractIndex->getZExtValue() % NumElems) == 0 && 15351 "Extract index is not a multiple of the vector length."); 15352 if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2) 15353 return SDValue(); 15354 15355 // We are looking for an optionally bitcasted wide vector binary operator 15356 // feeding an extract subvector. 15357 SDValue BinOp = peekThroughBitcast(Extract->getOperand(0)); 15358 15359 // TODO: The motivating case for this transform is an x86 AVX1 target. That 15360 // target has temptingly almost legal versions of bitwise logic ops in 256-bit 15361 // flavors, but no other 256-bit integer support. This could be extended to 15362 // handle any binop, but that may require fixing/adding other folds to avoid 15363 // codegen regressions. 15364 unsigned BOpcode = BinOp.getOpcode(); 15365 if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR) 15366 return SDValue(); 15367 15368 // The binop must be a vector type, so we can chop it in half. 15369 EVT WideBVT = BinOp.getValueType(); 15370 if (!WideBVT.isVector()) 15371 return SDValue(); 15372 15373 // Bail out if the target does not support a narrower version of the binop. 15374 EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(), 15375 WideBVT.getVectorNumElements() / 2); 15376 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15377 if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT)) 15378 return SDValue(); 15379 15380 // Peek through bitcasts of the binary operator operands if needed. 15381 SDValue LHS = peekThroughBitcast(BinOp.getOperand(0)); 15382 SDValue RHS = peekThroughBitcast(BinOp.getOperand(1)); 15383 15384 // We need at least one concatenation operation of a binop operand to make 15385 // this transform worthwhile. The concat must double the input vector sizes. 15386 // TODO: Should we also handle INSERT_SUBVECTOR patterns? 15387 bool ConcatL = 15388 LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2; 15389 bool ConcatR = 15390 RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2; 15391 if (!ConcatL && !ConcatR) 15392 return SDValue(); 15393 15394 // If one of the binop operands was not the result of a concat, we must 15395 // extract a half-sized operand for our new narrow binop. We can't just reuse 15396 // the original extract index operand because we may have bitcasted. 15397 unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems; 15398 unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements(); 15399 EVT ExtBOIdxVT = Extract->getOperand(1).getValueType(); 15400 SDLoc DL(Extract); 15401 15402 // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN 15403 // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N) 15404 // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN 15405 SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum)) 15406 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 15407 BinOp.getOperand(0), 15408 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT)); 15409 15410 SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum)) 15411 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 15412 BinOp.getOperand(1), 15413 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT)); 15414 15415 SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y); 15416 return DAG.getBitcast(VT, NarrowBinOp); 15417 } 15418 15419 /// If we are extracting a subvector from a wide vector load, convert to a 15420 /// narrow load to eliminate the extraction: 15421 /// (extract_subvector (load wide vector)) --> (load narrow vector) 15422 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) { 15423 // TODO: Add support for big-endian. The offset calculation must be adjusted. 15424 if (DAG.getDataLayout().isBigEndian()) 15425 return SDValue(); 15426 15427 // TODO: The one-use check is overly conservative. Check the cost of the 15428 // extract instead or remove that condition entirely. 15429 auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0)); 15430 auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 15431 if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() || 15432 !ExtIdx) 15433 return SDValue(); 15434 15435 // The narrow load will be offset from the base address of the old load if 15436 // we are extracting from something besides index 0 (little-endian). 15437 EVT VT = Extract->getValueType(0); 15438 SDLoc DL(Extract); 15439 SDValue BaseAddr = Ld->getOperand(1); 15440 unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize(); 15441 15442 // TODO: Use "BaseIndexOffset" to make this more effective. 15443 SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL); 15444 MachineFunction &MF = DAG.getMachineFunction(); 15445 MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset, 15446 VT.getStoreSize()); 15447 SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO); 15448 DAG.makeEquivalentMemoryOrdering(Ld, NewLd); 15449 return NewLd; 15450 } 15451 15452 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 15453 EVT NVT = N->getValueType(0); 15454 SDValue V = N->getOperand(0); 15455 15456 // Extract from UNDEF is UNDEF. 15457 if (V.isUndef()) 15458 return DAG.getUNDEF(NVT); 15459 15460 if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT)) 15461 if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG)) 15462 return NarrowLoad; 15463 15464 // Combine: 15465 // (extract_subvec (concat V1, V2, ...), i) 15466 // Into: 15467 // Vi if possible 15468 // Only operand 0 is checked as 'concat' assumes all inputs of the same 15469 // type. 15470 if (V->getOpcode() == ISD::CONCAT_VECTORS && 15471 isa<ConstantSDNode>(N->getOperand(1)) && 15472 V->getOperand(0).getValueType() == NVT) { 15473 unsigned Idx = N->getConstantOperandVal(1); 15474 unsigned NumElems = NVT.getVectorNumElements(); 15475 assert((Idx % NumElems) == 0 && 15476 "IDX in concat is not a multiple of the result vector length."); 15477 return V->getOperand(Idx / NumElems); 15478 } 15479 15480 // Skip bitcasting 15481 V = peekThroughBitcast(V); 15482 15483 // If the input is a build vector. Try to make a smaller build vector. 15484 if (V->getOpcode() == ISD::BUILD_VECTOR) { 15485 if (auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))) { 15486 EVT InVT = V->getValueType(0); 15487 unsigned ExtractSize = NVT.getSizeInBits(); 15488 unsigned EltSize = InVT.getScalarSizeInBits(); 15489 // Only do this if we won't split any elements. 15490 if (ExtractSize % EltSize == 0) { 15491 unsigned NumElems = ExtractSize / EltSize; 15492 EVT ExtractVT = EVT::getVectorVT(*DAG.getContext(), 15493 InVT.getVectorElementType(), NumElems); 15494 if ((Level < AfterLegalizeDAG || 15495 TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT)) && 15496 (!LegalTypes || TLI.isTypeLegal(ExtractVT))) { 15497 unsigned IdxVal = (Idx->getZExtValue() * NVT.getScalarSizeInBits()) / 15498 EltSize; 15499 15500 // Extract the pieces from the original build_vector. 15501 SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N), 15502 makeArrayRef(V->op_begin() + IdxVal, 15503 NumElems)); 15504 return DAG.getBitcast(NVT, BuildVec); 15505 } 15506 } 15507 } 15508 } 15509 15510 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 15511 // Handle only simple case where vector being inserted and vector 15512 // being extracted are of same size. 15513 EVT SmallVT = V->getOperand(1).getValueType(); 15514 if (!NVT.bitsEq(SmallVT)) 15515 return SDValue(); 15516 15517 // Only handle cases where both indexes are constants. 15518 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15519 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 15520 15521 if (InsIdx && ExtIdx) { 15522 // Combine: 15523 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 15524 // Into: 15525 // indices are equal or bit offsets are equal => V1 15526 // otherwise => (extract_subvec V1, ExtIdx) 15527 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() == 15528 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits()) 15529 return DAG.getBitcast(NVT, V->getOperand(1)); 15530 return DAG.getNode( 15531 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, 15532 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)), 15533 N->getOperand(1)); 15534 } 15535 } 15536 15537 if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG)) 15538 return NarrowBOp; 15539 15540 return SDValue(); 15541 } 15542 15543 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 15544 // or turn a shuffle of a single concat into simpler shuffle then concat. 15545 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 15546 EVT VT = N->getValueType(0); 15547 unsigned NumElts = VT.getVectorNumElements(); 15548 15549 SDValue N0 = N->getOperand(0); 15550 SDValue N1 = N->getOperand(1); 15551 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 15552 15553 SmallVector<SDValue, 4> Ops; 15554 EVT ConcatVT = N0.getOperand(0).getValueType(); 15555 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 15556 unsigned NumConcats = NumElts / NumElemsPerConcat; 15557 15558 // Special case: shuffle(concat(A,B)) can be more efficiently represented 15559 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 15560 // half vector elements. 15561 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 15562 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 15563 SVN->getMask().end(), [](int i) { return i == -1; })) { 15564 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 15565 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 15566 N1 = DAG.getUNDEF(ConcatVT); 15567 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 15568 } 15569 15570 // Look at every vector that's inserted. We're looking for exact 15571 // subvector-sized copies from a concatenated vector 15572 for (unsigned I = 0; I != NumConcats; ++I) { 15573 // Make sure we're dealing with a copy. 15574 unsigned Begin = I * NumElemsPerConcat; 15575 bool AllUndef = true, NoUndef = true; 15576 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 15577 if (SVN->getMaskElt(J) >= 0) 15578 AllUndef = false; 15579 else 15580 NoUndef = false; 15581 } 15582 15583 if (NoUndef) { 15584 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 15585 return SDValue(); 15586 15587 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 15588 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 15589 return SDValue(); 15590 15591 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 15592 if (FirstElt < N0.getNumOperands()) 15593 Ops.push_back(N0.getOperand(FirstElt)); 15594 else 15595 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 15596 15597 } else if (AllUndef) { 15598 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 15599 } else { // Mixed with general masks and undefs, can't do optimization. 15600 return SDValue(); 15601 } 15602 } 15603 15604 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 15605 } 15606 15607 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 15608 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 15609 // 15610 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always 15611 // a simplification in some sense, but it isn't appropriate in general: some 15612 // BUILD_VECTORs are substantially cheaper than others. The general case 15613 // of a BUILD_VECTOR requires inserting each element individually (or 15614 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of 15615 // all constants is a single constant pool load. A BUILD_VECTOR where each 15616 // element is identical is a splat. A BUILD_VECTOR where most of the operands 15617 // are undef lowers to a small number of element insertions. 15618 // 15619 // To deal with this, we currently use a bunch of mostly arbitrary heuristics. 15620 // We don't fold shuffles where one side is a non-zero constant, and we don't 15621 // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate 15622 // non-constant operands. This seems to work out reasonably well in practice. 15623 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN, 15624 SelectionDAG &DAG, 15625 const TargetLowering &TLI) { 15626 EVT VT = SVN->getValueType(0); 15627 unsigned NumElts = VT.getVectorNumElements(); 15628 SDValue N0 = SVN->getOperand(0); 15629 SDValue N1 = SVN->getOperand(1); 15630 15631 if (!N0->hasOneUse() || !N1->hasOneUse()) 15632 return SDValue(); 15633 15634 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as 15635 // discussed above. 15636 if (!N1.isUndef()) { 15637 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode()); 15638 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode()); 15639 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode())) 15640 return SDValue(); 15641 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode())) 15642 return SDValue(); 15643 } 15644 15645 // If both inputs are splats of the same value then we can safely merge this 15646 // to a single BUILD_VECTOR with undef elements based on the shuffle mask. 15647 bool IsSplat = false; 15648 auto *BV0 = dyn_cast<BuildVectorSDNode>(N0); 15649 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 15650 if (BV0 && BV1) 15651 if (SDValue Splat0 = BV0->getSplatValue()) 15652 IsSplat = (Splat0 == BV1->getSplatValue()); 15653 15654 SmallVector<SDValue, 8> Ops; 15655 SmallSet<SDValue, 16> DuplicateOps; 15656 for (int M : SVN->getMask()) { 15657 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 15658 if (M >= 0) { 15659 int Idx = M < (int)NumElts ? M : M - NumElts; 15660 SDValue &S = (M < (int)NumElts ? N0 : N1); 15661 if (S.getOpcode() == ISD::BUILD_VECTOR) { 15662 Op = S.getOperand(Idx); 15663 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) { 15664 assert(Idx == 0 && "Unexpected SCALAR_TO_VECTOR operand index."); 15665 Op = S.getOperand(0); 15666 } else { 15667 // Operand can't be combined - bail out. 15668 return SDValue(); 15669 } 15670 } 15671 15672 // Don't duplicate a non-constant BUILD_VECTOR operand unless we're 15673 // generating a splat; semantically, this is fine, but it's likely to 15674 // generate low-quality code if the target can't reconstruct an appropriate 15675 // shuffle. 15676 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op)) 15677 if (!IsSplat && !DuplicateOps.insert(Op).second) 15678 return SDValue(); 15679 15680 Ops.push_back(Op); 15681 } 15682 15683 // BUILD_VECTOR requires all inputs to be of the same type, find the 15684 // maximum type and extend them all. 15685 EVT SVT = VT.getScalarType(); 15686 if (SVT.isInteger()) 15687 for (SDValue &Op : Ops) 15688 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 15689 if (SVT != VT.getScalarType()) 15690 for (SDValue &Op : Ops) 15691 Op = TLI.isZExtFree(Op.getValueType(), SVT) 15692 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT) 15693 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT); 15694 return DAG.getBuildVector(VT, SDLoc(SVN), Ops); 15695 } 15696 15697 // Match shuffles that can be converted to any_vector_extend_in_reg. 15698 // This is often generated during legalization. 15699 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src)) 15700 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case. 15701 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN, 15702 SelectionDAG &DAG, 15703 const TargetLowering &TLI, 15704 bool LegalOperations, 15705 bool LegalTypes) { 15706 EVT VT = SVN->getValueType(0); 15707 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 15708 15709 // TODO Add support for big-endian when we have a test case. 15710 if (!VT.isInteger() || IsBigEndian) 15711 return SDValue(); 15712 15713 unsigned NumElts = VT.getVectorNumElements(); 15714 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 15715 ArrayRef<int> Mask = SVN->getMask(); 15716 SDValue N0 = SVN->getOperand(0); 15717 15718 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32)) 15719 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) { 15720 for (unsigned i = 0; i != NumElts; ++i) { 15721 if (Mask[i] < 0) 15722 continue; 15723 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale)) 15724 continue; 15725 return false; 15726 } 15727 return true; 15728 }; 15729 15730 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for 15731 // power-of-2 extensions as they are the most likely. 15732 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) { 15733 // Check for non power of 2 vector sizes 15734 if (NumElts % Scale != 0) 15735 continue; 15736 if (!isAnyExtend(Scale)) 15737 continue; 15738 15739 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale); 15740 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale); 15741 if (!LegalTypes || TLI.isTypeLegal(OutVT)) 15742 if (!LegalOperations || 15743 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT)) 15744 return DAG.getBitcast(VT, 15745 DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT)); 15746 } 15747 15748 return SDValue(); 15749 } 15750 15751 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of 15752 // each source element of a large type into the lowest elements of a smaller 15753 // destination type. This is often generated during legalization. 15754 // If the source node itself was a '*_extend_vector_inreg' node then we should 15755 // then be able to remove it. 15756 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, 15757 SelectionDAG &DAG) { 15758 EVT VT = SVN->getValueType(0); 15759 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 15760 15761 // TODO Add support for big-endian when we have a test case. 15762 if (!VT.isInteger() || IsBigEndian) 15763 return SDValue(); 15764 15765 SDValue N0 = peekThroughBitcast(SVN->getOperand(0)); 15766 15767 unsigned Opcode = N0.getOpcode(); 15768 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG && 15769 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG && 15770 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG) 15771 return SDValue(); 15772 15773 SDValue N00 = N0.getOperand(0); 15774 ArrayRef<int> Mask = SVN->getMask(); 15775 unsigned NumElts = VT.getVectorNumElements(); 15776 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 15777 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits(); 15778 unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits(); 15779 15780 if (ExtDstSizeInBits % ExtSrcSizeInBits != 0) 15781 return SDValue(); 15782 unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits; 15783 15784 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1> 15785 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1> 15786 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1> 15787 auto isTruncate = [&Mask, &NumElts](unsigned Scale) { 15788 for (unsigned i = 0; i != NumElts; ++i) { 15789 if (Mask[i] < 0) 15790 continue; 15791 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale)) 15792 continue; 15793 return false; 15794 } 15795 return true; 15796 }; 15797 15798 // At the moment we just handle the case where we've truncated back to the 15799 // same size as before the extension. 15800 // TODO: handle more extension/truncation cases as cases arise. 15801 if (EltSizeInBits != ExtSrcSizeInBits) 15802 return SDValue(); 15803 15804 // We can remove *extend_vector_inreg only if the truncation happens at 15805 // the same scale as the extension. 15806 if (isTruncate(ExtScale)) 15807 return DAG.getBitcast(VT, N00); 15808 15809 return SDValue(); 15810 } 15811 15812 // Combine shuffles of splat-shuffles of the form: 15813 // shuffle (shuffle V, undef, splat-mask), undef, M 15814 // If splat-mask contains undef elements, we need to be careful about 15815 // introducing undef's in the folded mask which are not the result of composing 15816 // the masks of the shuffles. 15817 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask, 15818 ShuffleVectorSDNode *Splat, 15819 SelectionDAG &DAG) { 15820 ArrayRef<int> SplatMask = Splat->getMask(); 15821 assert(UserMask.size() == SplatMask.size() && "Mask length mismatch"); 15822 15823 // Prefer simplifying to the splat-shuffle, if possible. This is legal if 15824 // every undef mask element in the splat-shuffle has a corresponding undef 15825 // element in the user-shuffle's mask or if the composition of mask elements 15826 // would result in undef. 15827 // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask): 15828 // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u] 15829 // In this case it is not legal to simplify to the splat-shuffle because we 15830 // may be exposing the users of the shuffle an undef element at index 1 15831 // which was not there before the combine. 15832 // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u] 15833 // In this case the composition of masks yields SplatMask, so it's ok to 15834 // simplify to the splat-shuffle. 15835 // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u] 15836 // In this case the composed mask includes all undef elements of SplatMask 15837 // and in addition sets element zero to undef. It is safe to simplify to 15838 // the splat-shuffle. 15839 auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask, 15840 ArrayRef<int> SplatMask) { 15841 for (unsigned i = 0, e = UserMask.size(); i != e; ++i) 15842 if (UserMask[i] != -1 && SplatMask[i] == -1 && 15843 SplatMask[UserMask[i]] != -1) 15844 return false; 15845 return true; 15846 }; 15847 if (CanSimplifyToExistingSplat(UserMask, SplatMask)) 15848 return SDValue(Splat, 0); 15849 15850 // Create a new shuffle with a mask that is composed of the two shuffles' 15851 // masks. 15852 SmallVector<int, 32> NewMask; 15853 for (int Idx : UserMask) 15854 NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]); 15855 15856 return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat), 15857 Splat->getOperand(0), Splat->getOperand(1), 15858 NewMask); 15859 } 15860 15861 /// If the shuffle mask is taking exactly one element from the first vector 15862 /// operand and passing through all other elements from the second vector 15863 /// operand, return the index of the mask element that is choosing an element 15864 /// from the first operand. Otherwise, return -1. 15865 static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) { 15866 int MaskSize = Mask.size(); 15867 int EltFromOp0 = -1; 15868 // TODO: This does not match if there are undef elements in the shuffle mask. 15869 // Should we ignore undefs in the shuffle mask instead? The trade-off is 15870 // removing an instruction (a shuffle), but losing the knowledge that some 15871 // vector lanes are not needed. 15872 for (int i = 0; i != MaskSize; ++i) { 15873 if (Mask[i] >= 0 && Mask[i] < MaskSize) { 15874 // We're looking for a shuffle of exactly one element from operand 0. 15875 if (EltFromOp0 != -1) 15876 return -1; 15877 EltFromOp0 = i; 15878 } else if (Mask[i] != i + MaskSize) { 15879 // Nothing from operand 1 can change lanes. 15880 return -1; 15881 } 15882 } 15883 return EltFromOp0; 15884 } 15885 15886 /// If a shuffle inserts exactly one element from a source vector operand into 15887 /// another vector operand and we can access the specified element as a scalar, 15888 /// then we can eliminate the shuffle. 15889 static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf, 15890 SelectionDAG &DAG) { 15891 // First, check if we are taking one element of a vector and shuffling that 15892 // element into another vector. 15893 ArrayRef<int> Mask = Shuf->getMask(); 15894 SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end()); 15895 SDValue Op0 = Shuf->getOperand(0); 15896 SDValue Op1 = Shuf->getOperand(1); 15897 int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask); 15898 if (ShufOp0Index == -1) { 15899 // Commute mask and check again. 15900 ShuffleVectorSDNode::commuteMask(CommutedMask); 15901 ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask); 15902 if (ShufOp0Index == -1) 15903 return SDValue(); 15904 // Commute operands to match the commuted shuffle mask. 15905 std::swap(Op0, Op1); 15906 Mask = CommutedMask; 15907 } 15908 15909 // The shuffle inserts exactly one element from operand 0 into operand 1. 15910 // Now see if we can access that element as a scalar via a real insert element 15911 // instruction. 15912 // TODO: We can try harder to locate the element as a scalar. Examples: it 15913 // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant. 15914 assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() && 15915 "Shuffle mask value must be from operand 0"); 15916 if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT) 15917 return SDValue(); 15918 15919 auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2)); 15920 if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index]) 15921 return SDValue(); 15922 15923 // There's an existing insertelement with constant insertion index, so we 15924 // don't need to check the legality/profitability of a replacement operation 15925 // that differs at most in the constant value. The target should be able to 15926 // lower any of those in a similar way. If not, legalization will expand this 15927 // to a scalar-to-vector plus shuffle. 15928 // 15929 // Note that the shuffle may move the scalar from the position that the insert 15930 // element used. Therefore, our new insert element occurs at the shuffle's 15931 // mask index value, not the insert's index value. 15932 // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C' 15933 SDValue NewInsIndex = DAG.getConstant(ShufOp0Index, SDLoc(Shuf), 15934 Op0.getOperand(2).getValueType()); 15935 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(), 15936 Op1, Op0.getOperand(1), NewInsIndex); 15937 } 15938 15939 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 15940 EVT VT = N->getValueType(0); 15941 unsigned NumElts = VT.getVectorNumElements(); 15942 15943 SDValue N0 = N->getOperand(0); 15944 SDValue N1 = N->getOperand(1); 15945 15946 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 15947 15948 // Canonicalize shuffle undef, undef -> undef 15949 if (N0.isUndef() && N1.isUndef()) 15950 return DAG.getUNDEF(VT); 15951 15952 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 15953 15954 // Canonicalize shuffle v, v -> v, undef 15955 if (N0 == N1) { 15956 SmallVector<int, 8> NewMask; 15957 for (unsigned i = 0; i != NumElts; ++i) { 15958 int Idx = SVN->getMaskElt(i); 15959 if (Idx >= (int)NumElts) Idx -= NumElts; 15960 NewMask.push_back(Idx); 15961 } 15962 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 15963 } 15964 15965 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 15966 if (N0.isUndef()) 15967 return DAG.getCommutedVectorShuffle(*SVN); 15968 15969 // Remove references to rhs if it is undef 15970 if (N1.isUndef()) { 15971 bool Changed = false; 15972 SmallVector<int, 8> NewMask; 15973 for (unsigned i = 0; i != NumElts; ++i) { 15974 int Idx = SVN->getMaskElt(i); 15975 if (Idx >= (int)NumElts) { 15976 Idx = -1; 15977 Changed = true; 15978 } 15979 NewMask.push_back(Idx); 15980 } 15981 if (Changed) 15982 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 15983 } 15984 15985 if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG)) 15986 return InsElt; 15987 15988 // A shuffle of a single vector that is a splat can always be folded. 15989 if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0)) 15990 if (N1->isUndef() && N0Shuf->isSplat()) 15991 return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG); 15992 15993 // If it is a splat, check if the argument vector is another splat or a 15994 // build_vector. 15995 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 15996 SDNode *V = N0.getNode(); 15997 15998 // If this is a bit convert that changes the element type of the vector but 15999 // not the number of vector elements, look through it. Be careful not to 16000 // look though conversions that change things like v4f32 to v2f64. 16001 if (V->getOpcode() == ISD::BITCAST) { 16002 SDValue ConvInput = V->getOperand(0); 16003 if (ConvInput.getValueType().isVector() && 16004 ConvInput.getValueType().getVectorNumElements() == NumElts) 16005 V = ConvInput.getNode(); 16006 } 16007 16008 if (V->getOpcode() == ISD::BUILD_VECTOR) { 16009 assert(V->getNumOperands() == NumElts && 16010 "BUILD_VECTOR has wrong number of operands"); 16011 SDValue Base; 16012 bool AllSame = true; 16013 for (unsigned i = 0; i != NumElts; ++i) { 16014 if (!V->getOperand(i).isUndef()) { 16015 Base = V->getOperand(i); 16016 break; 16017 } 16018 } 16019 // Splat of <u, u, u, u>, return <u, u, u, u> 16020 if (!Base.getNode()) 16021 return N0; 16022 for (unsigned i = 0; i != NumElts; ++i) { 16023 if (V->getOperand(i) != Base) { 16024 AllSame = false; 16025 break; 16026 } 16027 } 16028 // Splat of <x, x, x, x>, return <x, x, x, x> 16029 if (AllSame) 16030 return N0; 16031 16032 // Canonicalize any other splat as a build_vector. 16033 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 16034 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 16035 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 16036 16037 // We may have jumped through bitcasts, so the type of the 16038 // BUILD_VECTOR may not match the type of the shuffle. 16039 if (V->getValueType(0) != VT) 16040 NewBV = DAG.getBitcast(VT, NewBV); 16041 return NewBV; 16042 } 16043 } 16044 16045 // Simplify source operands based on shuffle mask. 16046 if (SimplifyDemandedVectorElts(SDValue(N, 0))) 16047 return SDValue(N, 0); 16048 16049 // Match shuffles that can be converted to any_vector_extend_in_reg. 16050 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations, LegalTypes)) 16051 return V; 16052 16053 // Combine "truncate_vector_in_reg" style shuffles. 16054 if (SDValue V = combineTruncationShuffle(SVN, DAG)) 16055 return V; 16056 16057 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 16058 Level < AfterLegalizeVectorOps && 16059 (N1.isUndef() || 16060 (N1.getOpcode() == ISD::CONCAT_VECTORS && 16061 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 16062 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 16063 return V; 16064 } 16065 16066 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 16067 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 16068 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 16069 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI)) 16070 return Res; 16071 16072 // If this shuffle only has a single input that is a bitcasted shuffle, 16073 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 16074 // back to their original types. 16075 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 16076 N1.isUndef() && Level < AfterLegalizeVectorOps && 16077 TLI.isTypeLegal(VT)) { 16078 16079 // Peek through the bitcast only if there is one user. 16080 SDValue BC0 = N0; 16081 while (BC0.getOpcode() == ISD::BITCAST) { 16082 if (!BC0.hasOneUse()) 16083 break; 16084 BC0 = BC0.getOperand(0); 16085 } 16086 16087 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 16088 if (Scale == 1) 16089 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 16090 16091 SmallVector<int, 8> NewMask; 16092 for (int M : Mask) 16093 for (int s = 0; s != Scale; ++s) 16094 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 16095 return NewMask; 16096 }; 16097 16098 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 16099 EVT SVT = VT.getScalarType(); 16100 EVT InnerVT = BC0->getValueType(0); 16101 EVT InnerSVT = InnerVT.getScalarType(); 16102 16103 // Determine which shuffle works with the smaller scalar type. 16104 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 16105 EVT ScaleSVT = ScaleVT.getScalarType(); 16106 16107 if (TLI.isTypeLegal(ScaleVT) && 16108 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 16109 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 16110 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 16111 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 16112 16113 // Scale the shuffle masks to the smaller scalar type. 16114 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 16115 SmallVector<int, 8> InnerMask = 16116 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 16117 SmallVector<int, 8> OuterMask = 16118 ScaleShuffleMask(SVN->getMask(), OuterScale); 16119 16120 // Merge the shuffle masks. 16121 SmallVector<int, 8> NewMask; 16122 for (int M : OuterMask) 16123 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 16124 16125 // Test for shuffle mask legality over both commutations. 16126 SDValue SV0 = BC0->getOperand(0); 16127 SDValue SV1 = BC0->getOperand(1); 16128 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 16129 if (!LegalMask) { 16130 std::swap(SV0, SV1); 16131 ShuffleVectorSDNode::commuteMask(NewMask); 16132 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 16133 } 16134 16135 if (LegalMask) { 16136 SV0 = DAG.getBitcast(ScaleVT, SV0); 16137 SV1 = DAG.getBitcast(ScaleVT, SV1); 16138 return DAG.getBitcast( 16139 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 16140 } 16141 } 16142 } 16143 } 16144 16145 // Canonicalize shuffles according to rules: 16146 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 16147 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 16148 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 16149 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 16150 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 16151 TLI.isTypeLegal(VT)) { 16152 // The incoming shuffle must be of the same type as the result of the 16153 // current shuffle. 16154 assert(N1->getOperand(0).getValueType() == VT && 16155 "Shuffle types don't match"); 16156 16157 SDValue SV0 = N1->getOperand(0); 16158 SDValue SV1 = N1->getOperand(1); 16159 bool HasSameOp0 = N0 == SV0; 16160 bool IsSV1Undef = SV1.isUndef(); 16161 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 16162 // Commute the operands of this shuffle so that next rule 16163 // will trigger. 16164 return DAG.getCommutedVectorShuffle(*SVN); 16165 } 16166 16167 // Try to fold according to rules: 16168 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 16169 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 16170 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 16171 // Don't try to fold shuffles with illegal type. 16172 // Only fold if this shuffle is the only user of the other shuffle. 16173 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 16174 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 16175 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 16176 16177 // Don't try to fold splats; they're likely to simplify somehow, or they 16178 // might be free. 16179 if (OtherSV->isSplat()) 16180 return SDValue(); 16181 16182 // The incoming shuffle must be of the same type as the result of the 16183 // current shuffle. 16184 assert(OtherSV->getOperand(0).getValueType() == VT && 16185 "Shuffle types don't match"); 16186 16187 SDValue SV0, SV1; 16188 SmallVector<int, 4> Mask; 16189 // Compute the combined shuffle mask for a shuffle with SV0 as the first 16190 // operand, and SV1 as the second operand. 16191 for (unsigned i = 0; i != NumElts; ++i) { 16192 int Idx = SVN->getMaskElt(i); 16193 if (Idx < 0) { 16194 // Propagate Undef. 16195 Mask.push_back(Idx); 16196 continue; 16197 } 16198 16199 SDValue CurrentVec; 16200 if (Idx < (int)NumElts) { 16201 // This shuffle index refers to the inner shuffle N0. Lookup the inner 16202 // shuffle mask to identify which vector is actually referenced. 16203 Idx = OtherSV->getMaskElt(Idx); 16204 if (Idx < 0) { 16205 // Propagate Undef. 16206 Mask.push_back(Idx); 16207 continue; 16208 } 16209 16210 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 16211 : OtherSV->getOperand(1); 16212 } else { 16213 // This shuffle index references an element within N1. 16214 CurrentVec = N1; 16215 } 16216 16217 // Simple case where 'CurrentVec' is UNDEF. 16218 if (CurrentVec.isUndef()) { 16219 Mask.push_back(-1); 16220 continue; 16221 } 16222 16223 // Canonicalize the shuffle index. We don't know yet if CurrentVec 16224 // will be the first or second operand of the combined shuffle. 16225 Idx = Idx % NumElts; 16226 if (!SV0.getNode() || SV0 == CurrentVec) { 16227 // Ok. CurrentVec is the left hand side. 16228 // Update the mask accordingly. 16229 SV0 = CurrentVec; 16230 Mask.push_back(Idx); 16231 continue; 16232 } 16233 16234 // Bail out if we cannot convert the shuffle pair into a single shuffle. 16235 if (SV1.getNode() && SV1 != CurrentVec) 16236 return SDValue(); 16237 16238 // Ok. CurrentVec is the right hand side. 16239 // Update the mask accordingly. 16240 SV1 = CurrentVec; 16241 Mask.push_back(Idx + NumElts); 16242 } 16243 16244 // Check if all indices in Mask are Undef. In case, propagate Undef. 16245 bool isUndefMask = true; 16246 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 16247 isUndefMask &= Mask[i] < 0; 16248 16249 if (isUndefMask) 16250 return DAG.getUNDEF(VT); 16251 16252 if (!SV0.getNode()) 16253 SV0 = DAG.getUNDEF(VT); 16254 if (!SV1.getNode()) 16255 SV1 = DAG.getUNDEF(VT); 16256 16257 // Avoid introducing shuffles with illegal mask. 16258 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 16259 ShuffleVectorSDNode::commuteMask(Mask); 16260 16261 if (!TLI.isShuffleMaskLegal(Mask, VT)) 16262 return SDValue(); 16263 16264 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 16265 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 16266 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 16267 std::swap(SV0, SV1); 16268 } 16269 16270 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 16271 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 16272 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 16273 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask); 16274 } 16275 16276 return SDValue(); 16277 } 16278 16279 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 16280 SDValue InVal = N->getOperand(0); 16281 EVT VT = N->getValueType(0); 16282 16283 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 16284 // with a VECTOR_SHUFFLE and possible truncate. 16285 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 16286 SDValue InVec = InVal->getOperand(0); 16287 SDValue EltNo = InVal->getOperand(1); 16288 auto InVecT = InVec.getValueType(); 16289 if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) { 16290 SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1); 16291 int Elt = C0->getZExtValue(); 16292 NewMask[0] = Elt; 16293 SDValue Val; 16294 // If we have an implict truncate do truncate here as long as it's legal. 16295 // if it's not legal, this should 16296 if (VT.getScalarType() != InVal.getValueType() && 16297 InVal.getValueType().isScalarInteger() && 16298 isTypeLegal(VT.getScalarType())) { 16299 Val = 16300 DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal); 16301 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val); 16302 } 16303 if (VT.getScalarType() == InVecT.getScalarType() && 16304 VT.getVectorNumElements() <= InVecT.getVectorNumElements() && 16305 TLI.isShuffleMaskLegal(NewMask, VT)) { 16306 Val = DAG.getVectorShuffle(InVecT, SDLoc(N), InVec, 16307 DAG.getUNDEF(InVecT), NewMask); 16308 // If the initial vector is the correct size this shuffle is a 16309 // valid result. 16310 if (VT == InVecT) 16311 return Val; 16312 // If not we must truncate the vector. 16313 if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) { 16314 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 16315 SDValue ZeroIdx = DAG.getConstant(0, SDLoc(N), IdxTy); 16316 EVT SubVT = 16317 EVT::getVectorVT(*DAG.getContext(), InVecT.getVectorElementType(), 16318 VT.getVectorNumElements()); 16319 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, Val, 16320 ZeroIdx); 16321 return Val; 16322 } 16323 } 16324 } 16325 } 16326 16327 return SDValue(); 16328 } 16329 16330 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 16331 EVT VT = N->getValueType(0); 16332 SDValue N0 = N->getOperand(0); 16333 SDValue N1 = N->getOperand(1); 16334 SDValue N2 = N->getOperand(2); 16335 16336 // If inserting an UNDEF, just return the original vector. 16337 if (N1.isUndef()) 16338 return N0; 16339 16340 // For nested INSERT_SUBVECTORs, attempt to combine inner node first to allow 16341 // us to pull BITCASTs from input to output. 16342 if (N0.hasOneUse() && N0->getOpcode() == ISD::INSERT_SUBVECTOR) 16343 if (SDValue NN0 = visitINSERT_SUBVECTOR(N0.getNode())) 16344 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, NN0, N1, N2); 16345 16346 // If this is an insert of an extracted vector into an undef vector, we can 16347 // just use the input to the extract. 16348 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 16349 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT) 16350 return N1.getOperand(0); 16351 16352 // If we are inserting a bitcast value into an undef, with the same 16353 // number of elements, just use the bitcast input of the extract. 16354 // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 -> 16355 // BITCAST (INSERT_SUBVECTOR UNDEF N1 N2) 16356 if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST && 16357 N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR && 16358 N1.getOperand(0).getOperand(1) == N2 && 16359 N1.getOperand(0).getOperand(0).getValueType().getVectorNumElements() == 16360 VT.getVectorNumElements() && 16361 N1.getOperand(0).getOperand(0).getValueType().getSizeInBits() == 16362 VT.getSizeInBits()) { 16363 return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0)); 16364 } 16365 16366 // If both N1 and N2 are bitcast values on which insert_subvector 16367 // would makes sense, pull the bitcast through. 16368 // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 -> 16369 // BITCAST (INSERT_SUBVECTOR N0 N1 N2) 16370 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) { 16371 SDValue CN0 = N0.getOperand(0); 16372 SDValue CN1 = N1.getOperand(0); 16373 EVT CN0VT = CN0.getValueType(); 16374 EVT CN1VT = CN1.getValueType(); 16375 if (CN0VT.isVector() && CN1VT.isVector() && 16376 CN0VT.getVectorElementType() == CN1VT.getVectorElementType() && 16377 CN0VT.getVectorNumElements() == VT.getVectorNumElements()) { 16378 SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), 16379 CN0.getValueType(), CN0, CN1, N2); 16380 return DAG.getBitcast(VT, NewINSERT); 16381 } 16382 } 16383 16384 // Combine INSERT_SUBVECTORs where we are inserting to the same index. 16385 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) 16386 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) 16387 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && 16388 N0.getOperand(1).getValueType() == N1.getValueType() && 16389 N0.getOperand(2) == N2) 16390 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), 16391 N1, N2); 16392 16393 if (!isa<ConstantSDNode>(N2)) 16394 return SDValue(); 16395 16396 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue(); 16397 16398 // Canonicalize insert_subvector dag nodes. 16399 // Example: 16400 // (insert_subvector (insert_subvector A, Idx0), Idx1) 16401 // -> (insert_subvector (insert_subvector A, Idx1), Idx0) 16402 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() && 16403 N1.getValueType() == N0.getOperand(1).getValueType() && 16404 isa<ConstantSDNode>(N0.getOperand(2))) { 16405 unsigned OtherIdx = N0.getConstantOperandVal(2); 16406 if (InsIdx < OtherIdx) { 16407 // Swap nodes. 16408 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, 16409 N0.getOperand(0), N1, N2); 16410 AddToWorklist(NewOp.getNode()); 16411 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()), 16412 VT, NewOp, N0.getOperand(1), N0.getOperand(2)); 16413 } 16414 } 16415 16416 // If the input vector is a concatenation, and the insert replaces 16417 // one of the pieces, we can optimize into a single concat_vectors. 16418 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() && 16419 N0.getOperand(0).getValueType() == N1.getValueType()) { 16420 unsigned Factor = N1.getValueType().getVectorNumElements(); 16421 16422 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end()); 16423 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1; 16424 16425 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 16426 } 16427 16428 return SDValue(); 16429 } 16430 16431 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 16432 SDValue N0 = N->getOperand(0); 16433 16434 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 16435 if (N0->getOpcode() == ISD::FP16_TO_FP) 16436 return N0->getOperand(0); 16437 16438 return SDValue(); 16439 } 16440 16441 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 16442 SDValue N0 = N->getOperand(0); 16443 16444 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 16445 if (N0->getOpcode() == ISD::AND) { 16446 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 16447 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 16448 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 16449 N0.getOperand(0)); 16450 } 16451 } 16452 16453 return SDValue(); 16454 } 16455 16456 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 16457 /// with the destination vector and a zero vector. 16458 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 16459 /// vector_shuffle V, Zero, <0, 4, 2, 4> 16460 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 16461 assert(N->getOpcode() == ISD::AND && "Unexpected opcode!"); 16462 16463 EVT VT = N->getValueType(0); 16464 SDValue LHS = N->getOperand(0); 16465 SDValue RHS = peekThroughBitcast(N->getOperand(1)); 16466 SDLoc DL(N); 16467 16468 // Make sure we're not running after operation legalization where it 16469 // may have custom lowered the vector shuffles. 16470 if (LegalOperations) 16471 return SDValue(); 16472 16473 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 16474 return SDValue(); 16475 16476 EVT RVT = RHS.getValueType(); 16477 unsigned NumElts = RHS.getNumOperands(); 16478 16479 // Attempt to create a valid clear mask, splitting the mask into 16480 // sub elements and checking to see if each is 16481 // all zeros or all ones - suitable for shuffle masking. 16482 auto BuildClearMask = [&](int Split) { 16483 int NumSubElts = NumElts * Split; 16484 int NumSubBits = RVT.getScalarSizeInBits() / Split; 16485 16486 SmallVector<int, 8> Indices; 16487 for (int i = 0; i != NumSubElts; ++i) { 16488 int EltIdx = i / Split; 16489 int SubIdx = i % Split; 16490 SDValue Elt = RHS.getOperand(EltIdx); 16491 if (Elt.isUndef()) { 16492 Indices.push_back(-1); 16493 continue; 16494 } 16495 16496 APInt Bits; 16497 if (isa<ConstantSDNode>(Elt)) 16498 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 16499 else if (isa<ConstantFPSDNode>(Elt)) 16500 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 16501 else 16502 return SDValue(); 16503 16504 // Extract the sub element from the constant bit mask. 16505 if (DAG.getDataLayout().isBigEndian()) { 16506 Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits); 16507 } else { 16508 Bits.lshrInPlace(SubIdx * NumSubBits); 16509 } 16510 16511 if (Split > 1) 16512 Bits = Bits.trunc(NumSubBits); 16513 16514 if (Bits.isAllOnesValue()) 16515 Indices.push_back(i); 16516 else if (Bits == 0) 16517 Indices.push_back(i + NumSubElts); 16518 else 16519 return SDValue(); 16520 } 16521 16522 // Let's see if the target supports this vector_shuffle. 16523 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 16524 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 16525 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 16526 return SDValue(); 16527 16528 SDValue Zero = DAG.getConstant(0, DL, ClearVT); 16529 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL, 16530 DAG.getBitcast(ClearVT, LHS), 16531 Zero, Indices)); 16532 }; 16533 16534 // Determine maximum split level (byte level masking). 16535 int MaxSplit = 1; 16536 if (RVT.getScalarSizeInBits() % 8 == 0) 16537 MaxSplit = RVT.getScalarSizeInBits() / 8; 16538 16539 for (int Split = 1; Split <= MaxSplit; ++Split) 16540 if (RVT.getScalarSizeInBits() % Split == 0) 16541 if (SDValue S = BuildClearMask(Split)) 16542 return S; 16543 16544 return SDValue(); 16545 } 16546 16547 /// Visit a binary vector operation, like ADD. 16548 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 16549 assert(N->getValueType(0).isVector() && 16550 "SimplifyVBinOp only works on vectors!"); 16551 16552 SDValue LHS = N->getOperand(0); 16553 SDValue RHS = N->getOperand(1); 16554 SDValue Ops[] = {LHS, RHS}; 16555 16556 // See if we can constant fold the vector operation. 16557 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 16558 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 16559 return Fold; 16560 16561 // Type legalization might introduce new shuffles in the DAG. 16562 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 16563 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 16564 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 16565 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 16566 LHS.getOperand(1).isUndef() && 16567 RHS.getOperand(1).isUndef()) { 16568 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 16569 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 16570 16571 if (SVN0->getMask().equals(SVN1->getMask())) { 16572 EVT VT = N->getValueType(0); 16573 SDValue UndefVector = LHS.getOperand(1); 16574 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 16575 LHS.getOperand(0), RHS.getOperand(0), 16576 N->getFlags()); 16577 AddUsersToWorklist(N); 16578 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 16579 SVN0->getMask()); 16580 } 16581 } 16582 16583 return SDValue(); 16584 } 16585 16586 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 16587 SDValue N2) { 16588 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 16589 16590 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 16591 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 16592 16593 // If we got a simplified select_cc node back from SimplifySelectCC, then 16594 // break it down into a new SETCC node, and a new SELECT node, and then return 16595 // the SELECT node, since we were called with a SELECT node. 16596 if (SCC.getNode()) { 16597 // Check to see if we got a select_cc back (to turn into setcc/select). 16598 // Otherwise, just return whatever node we got back, like fabs. 16599 if (SCC.getOpcode() == ISD::SELECT_CC) { 16600 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 16601 N0.getValueType(), 16602 SCC.getOperand(0), SCC.getOperand(1), 16603 SCC.getOperand(4)); 16604 AddToWorklist(SETCC.getNode()); 16605 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 16606 SCC.getOperand(2), SCC.getOperand(3)); 16607 } 16608 16609 return SCC; 16610 } 16611 return SDValue(); 16612 } 16613 16614 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 16615 /// being selected between, see if we can simplify the select. Callers of this 16616 /// should assume that TheSelect is deleted if this returns true. As such, they 16617 /// should return the appropriate thing (e.g. the node) back to the top-level of 16618 /// the DAG combiner loop to avoid it being looked at. 16619 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 16620 SDValue RHS) { 16621 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 16622 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 16623 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 16624 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 16625 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 16626 SDValue Sqrt = RHS; 16627 ISD::CondCode CC; 16628 SDValue CmpLHS; 16629 const ConstantFPSDNode *Zero = nullptr; 16630 16631 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 16632 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 16633 CmpLHS = TheSelect->getOperand(0); 16634 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 16635 } else { 16636 // SELECT or VSELECT 16637 SDValue Cmp = TheSelect->getOperand(0); 16638 if (Cmp.getOpcode() == ISD::SETCC) { 16639 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 16640 CmpLHS = Cmp.getOperand(0); 16641 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 16642 } 16643 } 16644 if (Zero && Zero->isZero() && 16645 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 16646 CC == ISD::SETULT || CC == ISD::SETLT)) { 16647 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 16648 CombineTo(TheSelect, Sqrt); 16649 return true; 16650 } 16651 } 16652 } 16653 // Cannot simplify select with vector condition 16654 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 16655 16656 // If this is a select from two identical things, try to pull the operation 16657 // through the select. 16658 if (LHS.getOpcode() != RHS.getOpcode() || 16659 !LHS.hasOneUse() || !RHS.hasOneUse()) 16660 return false; 16661 16662 // If this is a load and the token chain is identical, replace the select 16663 // of two loads with a load through a select of the address to load from. 16664 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 16665 // constants have been dropped into the constant pool. 16666 if (LHS.getOpcode() == ISD::LOAD) { 16667 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 16668 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 16669 16670 // Token chains must be identical. 16671 if (LHS.getOperand(0) != RHS.getOperand(0) || 16672 // Do not let this transformation reduce the number of volatile loads. 16673 LLD->isVolatile() || RLD->isVolatile() || 16674 // FIXME: If either is a pre/post inc/dec load, 16675 // we'd need to split out the address adjustment. 16676 LLD->isIndexed() || RLD->isIndexed() || 16677 // If this is an EXTLOAD, the VT's must match. 16678 LLD->getMemoryVT() != RLD->getMemoryVT() || 16679 // If this is an EXTLOAD, the kind of extension must match. 16680 (LLD->getExtensionType() != RLD->getExtensionType() && 16681 // The only exception is if one of the extensions is anyext. 16682 LLD->getExtensionType() != ISD::EXTLOAD && 16683 RLD->getExtensionType() != ISD::EXTLOAD) || 16684 // FIXME: this discards src value information. This is 16685 // over-conservative. It would be beneficial to be able to remember 16686 // both potential memory locations. Since we are discarding 16687 // src value info, don't do the transformation if the memory 16688 // locations are not in the default address space. 16689 LLD->getPointerInfo().getAddrSpace() != 0 || 16690 RLD->getPointerInfo().getAddrSpace() != 0 || 16691 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 16692 LLD->getBasePtr().getValueType())) 16693 return false; 16694 16695 // Check that the select condition doesn't reach either load. If so, 16696 // folding this will induce a cycle into the DAG. If not, this is safe to 16697 // xform, so create a select of the addresses. 16698 SDValue Addr; 16699 if (TheSelect->getOpcode() == ISD::SELECT) { 16700 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 16701 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 16702 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 16703 return false; 16704 // The loads must not depend on one another. 16705 if (LLD->isPredecessorOf(RLD) || 16706 RLD->isPredecessorOf(LLD)) 16707 return false; 16708 Addr = DAG.getSelect(SDLoc(TheSelect), 16709 LLD->getBasePtr().getValueType(), 16710 TheSelect->getOperand(0), LLD->getBasePtr(), 16711 RLD->getBasePtr()); 16712 } else { // Otherwise SELECT_CC 16713 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 16714 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 16715 16716 if ((LLD->hasAnyUseOfValue(1) && 16717 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 16718 (RLD->hasAnyUseOfValue(1) && 16719 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 16720 return false; 16721 16722 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 16723 LLD->getBasePtr().getValueType(), 16724 TheSelect->getOperand(0), 16725 TheSelect->getOperand(1), 16726 LLD->getBasePtr(), RLD->getBasePtr(), 16727 TheSelect->getOperand(4)); 16728 } 16729 16730 SDValue Load; 16731 // It is safe to replace the two loads if they have different alignments, 16732 // but the new load must be the minimum (most restrictive) alignment of the 16733 // inputs. 16734 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 16735 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 16736 if (!RLD->isInvariant()) 16737 MMOFlags &= ~MachineMemOperand::MOInvariant; 16738 if (!RLD->isDereferenceable()) 16739 MMOFlags &= ~MachineMemOperand::MODereferenceable; 16740 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 16741 // FIXME: Discards pointer and AA info. 16742 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 16743 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 16744 MMOFlags); 16745 } else { 16746 // FIXME: Discards pointer and AA info. 16747 Load = DAG.getExtLoad( 16748 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 16749 : LLD->getExtensionType(), 16750 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 16751 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 16752 } 16753 16754 // Users of the select now use the result of the load. 16755 CombineTo(TheSelect, Load); 16756 16757 // Users of the old loads now use the new load's chain. We know the 16758 // old-load value is dead now. 16759 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 16760 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 16761 return true; 16762 } 16763 16764 return false; 16765 } 16766 16767 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and 16768 /// bitwise 'and'. 16769 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, 16770 SDValue N1, SDValue N2, SDValue N3, 16771 ISD::CondCode CC) { 16772 // If this is a select where the false operand is zero and the compare is a 16773 // check of the sign bit, see if we can perform the "gzip trick": 16774 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A 16775 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A 16776 EVT XType = N0.getValueType(); 16777 EVT AType = N2.getValueType(); 16778 if (!isNullConstant(N3) || !XType.bitsGE(AType)) 16779 return SDValue(); 16780 16781 // If the comparison is testing for a positive value, we have to invert 16782 // the sign bit mask, so only do that transform if the target has a bitwise 16783 // 'and not' instruction (the invert is free). 16784 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) { 16785 // (X > -1) ? A : 0 16786 // (X > 0) ? X : 0 <-- This is canonical signed max. 16787 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2))) 16788 return SDValue(); 16789 } else if (CC == ISD::SETLT) { 16790 // (X < 0) ? A : 0 16791 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min. 16792 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2))) 16793 return SDValue(); 16794 } else { 16795 return SDValue(); 16796 } 16797 16798 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit 16799 // constant. 16800 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 16801 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 16802 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 16803 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1; 16804 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); 16805 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt); 16806 AddToWorklist(Shift.getNode()); 16807 16808 if (XType.bitsGT(AType)) { 16809 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 16810 AddToWorklist(Shift.getNode()); 16811 } 16812 16813 if (CC == ISD::SETGT) 16814 Shift = DAG.getNOT(DL, Shift, AType); 16815 16816 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 16817 } 16818 16819 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy); 16820 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt); 16821 AddToWorklist(Shift.getNode()); 16822 16823 if (XType.bitsGT(AType)) { 16824 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 16825 AddToWorklist(Shift.getNode()); 16826 } 16827 16828 if (CC == ISD::SETGT) 16829 Shift = DAG.getNOT(DL, Shift, AType); 16830 16831 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 16832 } 16833 16834 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 16835 /// where 'cond' is the comparison specified by CC. 16836 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 16837 SDValue N2, SDValue N3, ISD::CondCode CC, 16838 bool NotExtCompare) { 16839 // (x ? y : y) -> y. 16840 if (N2 == N3) return N2; 16841 16842 EVT VT = N2.getValueType(); 16843 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 16844 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 16845 16846 // Determine if the condition we're dealing with is constant 16847 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 16848 N0, N1, CC, DL, false); 16849 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 16850 16851 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 16852 // fold select_cc true, x, y -> x 16853 // fold select_cc false, x, y -> y 16854 return !SCCC->isNullValue() ? N2 : N3; 16855 } 16856 16857 // Check to see if we can simplify the select into an fabs node 16858 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 16859 // Allow either -0.0 or 0.0 16860 if (CFP->isZero()) { 16861 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 16862 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 16863 N0 == N2 && N3.getOpcode() == ISD::FNEG && 16864 N2 == N3.getOperand(0)) 16865 return DAG.getNode(ISD::FABS, DL, VT, N0); 16866 16867 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 16868 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 16869 N0 == N3 && N2.getOpcode() == ISD::FNEG && 16870 N2.getOperand(0) == N3) 16871 return DAG.getNode(ISD::FABS, DL, VT, N3); 16872 } 16873 } 16874 16875 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 16876 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 16877 // in it. This is a win when the constant is not otherwise available because 16878 // it replaces two constant pool loads with one. We only do this if the FP 16879 // type is known to be legal, because if it isn't, then we are before legalize 16880 // types an we want the other legalization to happen first (e.g. to avoid 16881 // messing with soft float) and if the ConstantFP is not legal, because if 16882 // it is legal, we may not need to store the FP constant in a constant pool. 16883 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 16884 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 16885 if (TLI.isTypeLegal(N2.getValueType()) && 16886 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 16887 TargetLowering::Legal && 16888 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 16889 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 16890 // If both constants have multiple uses, then we won't need to do an 16891 // extra load, they are likely around in registers for other users. 16892 (TV->hasOneUse() || FV->hasOneUse())) { 16893 Constant *Elts[] = { 16894 const_cast<ConstantFP*>(FV->getConstantFPValue()), 16895 const_cast<ConstantFP*>(TV->getConstantFPValue()) 16896 }; 16897 Type *FPTy = Elts[0]->getType(); 16898 const DataLayout &TD = DAG.getDataLayout(); 16899 16900 // Create a ConstantArray of the two constants. 16901 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 16902 SDValue CPIdx = 16903 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 16904 TD.getPrefTypeAlignment(FPTy)); 16905 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 16906 16907 // Get the offsets to the 0 and 1 element of the array so that we can 16908 // select between them. 16909 SDValue Zero = DAG.getIntPtrConstant(0, DL); 16910 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 16911 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 16912 16913 SDValue Cond = DAG.getSetCC(DL, 16914 getSetCCResultType(N0.getValueType()), 16915 N0, N1, CC); 16916 AddToWorklist(Cond.getNode()); 16917 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 16918 Cond, One, Zero); 16919 AddToWorklist(CstOffset.getNode()); 16920 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 16921 CstOffset); 16922 AddToWorklist(CPIdx.getNode()); 16923 return DAG.getLoad( 16924 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 16925 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 16926 Alignment); 16927 } 16928 } 16929 16930 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC)) 16931 return V; 16932 16933 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 16934 // where y is has a single bit set. 16935 // A plaintext description would be, we can turn the SELECT_CC into an AND 16936 // when the condition can be materialized as an all-ones register. Any 16937 // single bit-test can be materialized as an all-ones register with 16938 // shift-left and shift-right-arith. 16939 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 16940 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 16941 SDValue AndLHS = N0->getOperand(0); 16942 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 16943 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 16944 // Shift the tested bit over the sign bit. 16945 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 16946 SDValue ShlAmt = 16947 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 16948 getShiftAmountTy(AndLHS.getValueType())); 16949 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 16950 16951 // Now arithmetic right shift it all the way over, so the result is either 16952 // all-ones, or zero. 16953 SDValue ShrAmt = 16954 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 16955 getShiftAmountTy(Shl.getValueType())); 16956 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 16957 16958 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 16959 } 16960 } 16961 16962 // fold select C, 16, 0 -> shl C, 4 16963 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 16964 TLI.getBooleanContents(N0.getValueType()) == 16965 TargetLowering::ZeroOrOneBooleanContent) { 16966 16967 // If the caller doesn't want us to simplify this into a zext of a compare, 16968 // don't do it. 16969 if (NotExtCompare && N2C->isOne()) 16970 return SDValue(); 16971 16972 // Get a SetCC of the condition 16973 // NOTE: Don't create a SETCC if it's not legal on this target. 16974 if (!LegalOperations || 16975 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 16976 SDValue Temp, SCC; 16977 // cast from setcc result type to select result type 16978 if (LegalTypes) { 16979 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 16980 N0, N1, CC); 16981 if (N2.getValueType().bitsLT(SCC.getValueType())) 16982 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 16983 N2.getValueType()); 16984 else 16985 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 16986 N2.getValueType(), SCC); 16987 } else { 16988 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 16989 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 16990 N2.getValueType(), SCC); 16991 } 16992 16993 AddToWorklist(SCC.getNode()); 16994 AddToWorklist(Temp.getNode()); 16995 16996 if (N2C->isOne()) 16997 return Temp; 16998 16999 // shl setcc result by log2 n2c 17000 return DAG.getNode( 17001 ISD::SHL, DL, N2.getValueType(), Temp, 17002 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 17003 getShiftAmountTy(Temp.getValueType()))); 17004 } 17005 } 17006 17007 // Check to see if this is an integer abs. 17008 // select_cc setg[te] X, 0, X, -X -> 17009 // select_cc setgt X, -1, X, -X -> 17010 // select_cc setl[te] X, 0, -X, X -> 17011 // select_cc setlt X, 1, -X, X -> 17012 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 17013 if (N1C) { 17014 ConstantSDNode *SubC = nullptr; 17015 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 17016 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 17017 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 17018 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 17019 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 17020 (N1C->isOne() && CC == ISD::SETLT)) && 17021 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 17022 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 17023 17024 EVT XType = N0.getValueType(); 17025 if (SubC && SubC->isNullValue() && XType.isInteger()) { 17026 SDLoc DL(N0); 17027 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 17028 N0, 17029 DAG.getConstant(XType.getSizeInBits() - 1, DL, 17030 getShiftAmountTy(N0.getValueType()))); 17031 SDValue Add = DAG.getNode(ISD::ADD, DL, 17032 XType, N0, Shift); 17033 AddToWorklist(Shift.getNode()); 17034 AddToWorklist(Add.getNode()); 17035 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 17036 } 17037 } 17038 17039 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 17040 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 17041 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 17042 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 17043 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 17044 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 17045 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 17046 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 17047 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 17048 SDValue ValueOnZero = N2; 17049 SDValue Count = N3; 17050 // If the condition is NE instead of E, swap the operands. 17051 if (CC == ISD::SETNE) 17052 std::swap(ValueOnZero, Count); 17053 // Check if the value on zero is a constant equal to the bits in the type. 17054 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 17055 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 17056 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 17057 // legal, combine to just cttz. 17058 if ((Count.getOpcode() == ISD::CTTZ || 17059 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 17060 N0 == Count.getOperand(0) && 17061 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 17062 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 17063 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 17064 // legal, combine to just ctlz. 17065 if ((Count.getOpcode() == ISD::CTLZ || 17066 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 17067 N0 == Count.getOperand(0) && 17068 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 17069 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 17070 } 17071 } 17072 } 17073 17074 return SDValue(); 17075 } 17076 17077 /// This is a stub for TargetLowering::SimplifySetCC. 17078 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 17079 ISD::CondCode Cond, const SDLoc &DL, 17080 bool foldBooleans) { 17081 TargetLowering::DAGCombinerInfo 17082 DagCombineInfo(DAG, Level, false, this); 17083 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 17084 } 17085 17086 /// Given an ISD::SDIV node expressing a divide by constant, return 17087 /// a DAG expression to select that will generate the same value by multiplying 17088 /// by a magic number. 17089 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 17090 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 17091 // when optimising for minimum size, we don't want to expand a div to a mul 17092 // and a shift. 17093 if (DAG.getMachineFunction().getFunction().optForMinSize()) 17094 return SDValue(); 17095 17096 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 17097 if (!C) 17098 return SDValue(); 17099 17100 // Avoid division by zero. 17101 if (C->isNullValue()) 17102 return SDValue(); 17103 17104 std::vector<SDNode *> Built; 17105 SDValue S = 17106 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 17107 17108 for (SDNode *N : Built) 17109 AddToWorklist(N); 17110 return S; 17111 } 17112 17113 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 17114 /// DAG expression that will generate the same value by right shifting. 17115 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 17116 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 17117 if (!C) 17118 return SDValue(); 17119 17120 // Avoid division by zero. 17121 if (C->isNullValue()) 17122 return SDValue(); 17123 17124 std::vector<SDNode *> Built; 17125 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 17126 17127 for (SDNode *N : Built) 17128 AddToWorklist(N); 17129 return S; 17130 } 17131 17132 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 17133 /// expression that will generate the same value by multiplying by a magic 17134 /// number. 17135 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 17136 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 17137 // when optimising for minimum size, we don't want to expand a div to a mul 17138 // and a shift. 17139 if (DAG.getMachineFunction().getFunction().optForMinSize()) 17140 return SDValue(); 17141 17142 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 17143 if (!C) 17144 return SDValue(); 17145 17146 // Avoid division by zero. 17147 if (C->isNullValue()) 17148 return SDValue(); 17149 17150 std::vector<SDNode *> Built; 17151 SDValue S = 17152 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 17153 17154 for (SDNode *N : Built) 17155 AddToWorklist(N); 17156 return S; 17157 } 17158 17159 /// Determines the LogBase2 value for a non-null input value using the 17160 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V). 17161 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) { 17162 EVT VT = V.getValueType(); 17163 unsigned EltBits = VT.getScalarSizeInBits(); 17164 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V); 17165 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT); 17166 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz); 17167 return LogBase2; 17168 } 17169 17170 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 17171 /// For the reciprocal, we need to find the zero of the function: 17172 /// F(X) = A X - 1 [which has a zero at X = 1/A] 17173 /// => 17174 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 17175 /// does not require additional intermediate precision] 17176 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) { 17177 if (Level >= AfterLegalizeDAG) 17178 return SDValue(); 17179 17180 // TODO: Handle half and/or extended types? 17181 EVT VT = Op.getValueType(); 17182 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 17183 return SDValue(); 17184 17185 // If estimates are explicitly disabled for this function, we're done. 17186 MachineFunction &MF = DAG.getMachineFunction(); 17187 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF); 17188 if (Enabled == TLI.ReciprocalEstimate::Disabled) 17189 return SDValue(); 17190 17191 // Estimates may be explicitly enabled for this type with a custom number of 17192 // refinement steps. 17193 int Iterations = TLI.getDivRefinementSteps(VT, MF); 17194 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) { 17195 AddToWorklist(Est.getNode()); 17196 17197 if (Iterations) { 17198 EVT VT = Op.getValueType(); 17199 SDLoc DL(Op); 17200 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 17201 17202 // Newton iterations: Est = Est + Est (1 - Arg * Est) 17203 for (int i = 0; i < Iterations; ++i) { 17204 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 17205 AddToWorklist(NewEst.getNode()); 17206 17207 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 17208 AddToWorklist(NewEst.getNode()); 17209 17210 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 17211 AddToWorklist(NewEst.getNode()); 17212 17213 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 17214 AddToWorklist(Est.getNode()); 17215 } 17216 } 17217 return Est; 17218 } 17219 17220 return SDValue(); 17221 } 17222 17223 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 17224 /// For the reciprocal sqrt, we need to find the zero of the function: 17225 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 17226 /// => 17227 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 17228 /// As a result, we precompute A/2 prior to the iteration loop. 17229 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 17230 unsigned Iterations, 17231 SDNodeFlags Flags, bool Reciprocal) { 17232 EVT VT = Arg.getValueType(); 17233 SDLoc DL(Arg); 17234 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 17235 17236 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 17237 // this entire sequence requires only one FP constant. 17238 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 17239 AddToWorklist(HalfArg.getNode()); 17240 17241 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 17242 AddToWorklist(HalfArg.getNode()); 17243 17244 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 17245 for (unsigned i = 0; i < Iterations; ++i) { 17246 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 17247 AddToWorklist(NewEst.getNode()); 17248 17249 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 17250 AddToWorklist(NewEst.getNode()); 17251 17252 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 17253 AddToWorklist(NewEst.getNode()); 17254 17255 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 17256 AddToWorklist(Est.getNode()); 17257 } 17258 17259 // If non-reciprocal square root is requested, multiply the result by Arg. 17260 if (!Reciprocal) { 17261 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 17262 AddToWorklist(Est.getNode()); 17263 } 17264 17265 return Est; 17266 } 17267 17268 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 17269 /// For the reciprocal sqrt, we need to find the zero of the function: 17270 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 17271 /// => 17272 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 17273 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 17274 unsigned Iterations, 17275 SDNodeFlags Flags, bool Reciprocal) { 17276 EVT VT = Arg.getValueType(); 17277 SDLoc DL(Arg); 17278 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 17279 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 17280 17281 // This routine must enter the loop below to work correctly 17282 // when (Reciprocal == false). 17283 assert(Iterations > 0); 17284 17285 // Newton iterations for reciprocal square root: 17286 // E = (E * -0.5) * ((A * E) * E + -3.0) 17287 for (unsigned i = 0; i < Iterations; ++i) { 17288 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 17289 AddToWorklist(AE.getNode()); 17290 17291 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 17292 AddToWorklist(AEE.getNode()); 17293 17294 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 17295 AddToWorklist(RHS.getNode()); 17296 17297 // When calculating a square root at the last iteration build: 17298 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 17299 // (notice a common subexpression) 17300 SDValue LHS; 17301 if (Reciprocal || (i + 1) < Iterations) { 17302 // RSQRT: LHS = (E * -0.5) 17303 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 17304 } else { 17305 // SQRT: LHS = (A * E) * -0.5 17306 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 17307 } 17308 AddToWorklist(LHS.getNode()); 17309 17310 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 17311 AddToWorklist(Est.getNode()); 17312 } 17313 17314 return Est; 17315 } 17316 17317 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 17318 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 17319 /// Op can be zero. 17320 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, 17321 bool Reciprocal) { 17322 if (Level >= AfterLegalizeDAG) 17323 return SDValue(); 17324 17325 // TODO: Handle half and/or extended types? 17326 EVT VT = Op.getValueType(); 17327 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 17328 return SDValue(); 17329 17330 // If estimates are explicitly disabled for this function, we're done. 17331 MachineFunction &MF = DAG.getMachineFunction(); 17332 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF); 17333 if (Enabled == TLI.ReciprocalEstimate::Disabled) 17334 return SDValue(); 17335 17336 // Estimates may be explicitly enabled for this type with a custom number of 17337 // refinement steps. 17338 int Iterations = TLI.getSqrtRefinementSteps(VT, MF); 17339 17340 bool UseOneConstNR = false; 17341 if (SDValue Est = 17342 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR, 17343 Reciprocal)) { 17344 AddToWorklist(Est.getNode()); 17345 17346 if (Iterations) { 17347 Est = UseOneConstNR 17348 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 17349 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 17350 17351 if (!Reciprocal) { 17352 // The estimate is now completely wrong if the input was exactly 0.0 or 17353 // possibly a denormal. Force the answer to 0.0 for those cases. 17354 EVT VT = Op.getValueType(); 17355 SDLoc DL(Op); 17356 EVT CCVT = getSetCCResultType(VT); 17357 ISD::NodeType SelOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT; 17358 const Function &F = DAG.getMachineFunction().getFunction(); 17359 Attribute Denorms = F.getFnAttribute("denormal-fp-math"); 17360 if (Denorms.getValueAsString().equals("ieee")) { 17361 // fabs(X) < SmallestNormal ? 0.0 : Est 17362 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 17363 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem); 17364 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT); 17365 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 17366 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op); 17367 SDValue IsDenorm = DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT); 17368 Est = DAG.getNode(SelOpcode, DL, VT, IsDenorm, FPZero, Est); 17369 AddToWorklist(Fabs.getNode()); 17370 AddToWorklist(IsDenorm.getNode()); 17371 AddToWorklist(Est.getNode()); 17372 } else { 17373 // X == 0.0 ? 0.0 : Est 17374 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 17375 SDValue IsZero = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 17376 Est = DAG.getNode(SelOpcode, DL, VT, IsZero, FPZero, Est); 17377 AddToWorklist(IsZero.getNode()); 17378 AddToWorklist(Est.getNode()); 17379 } 17380 } 17381 } 17382 return Est; 17383 } 17384 17385 return SDValue(); 17386 } 17387 17388 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) { 17389 return buildSqrtEstimateImpl(Op, Flags, true); 17390 } 17391 17392 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) { 17393 return buildSqrtEstimateImpl(Op, Flags, false); 17394 } 17395 17396 /// Return true if there is any possibility that the two addresses overlap. 17397 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 17398 // If they are the same then they must be aliases. 17399 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 17400 17401 // If they are both volatile then they cannot be reordered. 17402 if (Op0->isVolatile() && Op1->isVolatile()) return true; 17403 17404 // If one operation reads from invariant memory, and the other may store, they 17405 // cannot alias. These should really be checking the equivalent of mayWrite, 17406 // but it only matters for memory nodes other than load /store. 17407 if (Op0->isInvariant() && Op1->writeMem()) 17408 return false; 17409 17410 if (Op1->isInvariant() && Op0->writeMem()) 17411 return false; 17412 17413 unsigned NumBytes0 = Op0->getMemoryVT().getStoreSize(); 17414 unsigned NumBytes1 = Op1->getMemoryVT().getStoreSize(); 17415 17416 // Check for BaseIndexOffset matching. 17417 BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0, DAG); 17418 BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1, DAG); 17419 int64_t PtrDiff; 17420 if (BasePtr0.getBase().getNode() && BasePtr1.getBase().getNode()) { 17421 if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff)) 17422 return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0)); 17423 17424 // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be 17425 // able to calculate their relative offset if at least one arises 17426 // from an alloca. However, these allocas cannot overlap and we 17427 // can infer there is no alias. 17428 if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase())) 17429 if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) { 17430 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 17431 // If the base are the same frame index but the we couldn't find a 17432 // constant offset, (indices are different) be conservative. 17433 if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) || 17434 !MFI.isFixedObjectIndex(B->getIndex()))) 17435 return false; 17436 } 17437 17438 bool IsFI0 = isa<FrameIndexSDNode>(BasePtr0.getBase()); 17439 bool IsFI1 = isa<FrameIndexSDNode>(BasePtr1.getBase()); 17440 bool IsGV0 = isa<GlobalAddressSDNode>(BasePtr0.getBase()); 17441 bool IsGV1 = isa<GlobalAddressSDNode>(BasePtr1.getBase()); 17442 bool IsCV0 = isa<ConstantPoolSDNode>(BasePtr0.getBase()); 17443 bool IsCV1 = isa<ConstantPoolSDNode>(BasePtr1.getBase()); 17444 17445 // If of mismatched base types or checkable indices we can check 17446 // they do not alias. 17447 if ((BasePtr0.getIndex() == BasePtr1.getIndex() || (IsFI0 != IsFI1) || 17448 (IsGV0 != IsGV1) || (IsCV0 != IsCV1)) && 17449 (IsFI0 || IsGV0 || IsCV0) && (IsFI1 || IsGV1 || IsCV1)) 17450 return false; 17451 } 17452 17453 // If we know required SrcValue1 and SrcValue2 have relatively large 17454 // alignment compared to the size and offset of the access, we may be able 17455 // to prove they do not alias. This check is conservative for now to catch 17456 // cases created by splitting vector types. 17457 int64_t SrcValOffset0 = Op0->getSrcValueOffset(); 17458 int64_t SrcValOffset1 = Op1->getSrcValueOffset(); 17459 unsigned OrigAlignment0 = Op0->getOriginalAlignment(); 17460 unsigned OrigAlignment1 = Op1->getOriginalAlignment(); 17461 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 && 17462 NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) { 17463 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0; 17464 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1; 17465 17466 // There is no overlap between these relatively aligned accesses of 17467 // similar size. Return no alias. 17468 if ((OffAlign0 + NumBytes0) <= OffAlign1 || 17469 (OffAlign1 + NumBytes1) <= OffAlign0) 17470 return false; 17471 } 17472 17473 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 17474 ? CombinerGlobalAA 17475 : DAG.getSubtarget().useAA(); 17476 #ifndef NDEBUG 17477 if (CombinerAAOnlyFunc.getNumOccurrences() && 17478 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 17479 UseAA = false; 17480 #endif 17481 17482 if (UseAA && AA && 17483 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 17484 // Use alias analysis information. 17485 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1); 17486 int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset; 17487 int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset; 17488 AliasResult AAResult = 17489 AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0, 17490 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 17491 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1, 17492 UseTBAA ? Op1->getAAInfo() : AAMDNodes()) ); 17493 if (AAResult == NoAlias) 17494 return false; 17495 } 17496 17497 // Otherwise we have to assume they alias. 17498 return true; 17499 } 17500 17501 /// Walk up chain skipping non-aliasing memory nodes, 17502 /// looking for aliasing nodes and adding them to the Aliases vector. 17503 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 17504 SmallVectorImpl<SDValue> &Aliases) { 17505 SmallVector<SDValue, 8> Chains; // List of chains to visit. 17506 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 17507 17508 // Get alias information for node. 17509 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 17510 17511 // Starting off. 17512 Chains.push_back(OriginalChain); 17513 unsigned Depth = 0; 17514 17515 // Look at each chain and determine if it is an alias. If so, add it to the 17516 // aliases list. If not, then continue up the chain looking for the next 17517 // candidate. 17518 while (!Chains.empty()) { 17519 SDValue Chain = Chains.pop_back_val(); 17520 17521 // For TokenFactor nodes, look at each operand and only continue up the 17522 // chain until we reach the depth limit. 17523 // 17524 // FIXME: The depth check could be made to return the last non-aliasing 17525 // chain we found before we hit a tokenfactor rather than the original 17526 // chain. 17527 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 17528 Aliases.clear(); 17529 Aliases.push_back(OriginalChain); 17530 return; 17531 } 17532 17533 // Don't bother if we've been before. 17534 if (!Visited.insert(Chain.getNode()).second) 17535 continue; 17536 17537 switch (Chain.getOpcode()) { 17538 case ISD::EntryToken: 17539 // Entry token is ideal chain operand, but handled in FindBetterChain. 17540 break; 17541 17542 case ISD::LOAD: 17543 case ISD::STORE: { 17544 // Get alias information for Chain. 17545 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 17546 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 17547 17548 // If chain is alias then stop here. 17549 if (!(IsLoad && IsOpLoad) && 17550 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 17551 Aliases.push_back(Chain); 17552 } else { 17553 // Look further up the chain. 17554 Chains.push_back(Chain.getOperand(0)); 17555 ++Depth; 17556 } 17557 break; 17558 } 17559 17560 case ISD::TokenFactor: 17561 // We have to check each of the operands of the token factor for "small" 17562 // token factors, so we queue them up. Adding the operands to the queue 17563 // (stack) in reverse order maintains the original order and increases the 17564 // likelihood that getNode will find a matching token factor (CSE.) 17565 if (Chain.getNumOperands() > 16) { 17566 Aliases.push_back(Chain); 17567 break; 17568 } 17569 for (unsigned n = Chain.getNumOperands(); n;) 17570 Chains.push_back(Chain.getOperand(--n)); 17571 ++Depth; 17572 break; 17573 17574 case ISD::CopyFromReg: 17575 // Forward past CopyFromReg. 17576 Chains.push_back(Chain.getOperand(0)); 17577 ++Depth; 17578 break; 17579 17580 default: 17581 // For all other instructions we will just have to take what we can get. 17582 Aliases.push_back(Chain); 17583 break; 17584 } 17585 } 17586 } 17587 17588 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 17589 /// (aliasing node.) 17590 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 17591 if (OptLevel == CodeGenOpt::None) 17592 return OldChain; 17593 17594 // Ops for replacing token factor. 17595 SmallVector<SDValue, 8> Aliases; 17596 17597 // Accumulate all the aliases to this node. 17598 GatherAllAliases(N, OldChain, Aliases); 17599 17600 // If no operands then chain to entry token. 17601 if (Aliases.size() == 0) 17602 return DAG.getEntryNode(); 17603 17604 // If a single operand then chain to it. We don't need to revisit it. 17605 if (Aliases.size() == 1) 17606 return Aliases[0]; 17607 17608 // Construct a custom tailored token factor. 17609 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 17610 } 17611 17612 // This function tries to collect a bunch of potentially interesting 17613 // nodes to improve the chains of, all at once. This might seem 17614 // redundant, as this function gets called when visiting every store 17615 // node, so why not let the work be done on each store as it's visited? 17616 // 17617 // I believe this is mainly important because MergeConsecutiveStores 17618 // is unable to deal with merging stores of different sizes, so unless 17619 // we improve the chains of all the potential candidates up-front 17620 // before running MergeConsecutiveStores, it might only see some of 17621 // the nodes that will eventually be candidates, and then not be able 17622 // to go from a partially-merged state to the desired final 17623 // fully-merged state. 17624 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 17625 if (OptLevel == CodeGenOpt::None) 17626 return false; 17627 17628 // This holds the base pointer, index, and the offset in bytes from the base 17629 // pointer. 17630 BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); 17631 17632 // We must have a base and an offset. 17633 if (!BasePtr.getBase().getNode()) 17634 return false; 17635 17636 // Do not handle stores to undef base pointers. 17637 if (BasePtr.getBase().isUndef()) 17638 return false; 17639 17640 SmallVector<StoreSDNode *, 8> ChainedStores; 17641 ChainedStores.push_back(St); 17642 17643 // Walk up the chain and look for nodes with offsets from the same 17644 // base pointer. Stop when reaching an instruction with a different kind 17645 // or instruction which has a different base pointer. 17646 StoreSDNode *Index = St; 17647 while (Index) { 17648 // If the chain has more than one use, then we can't reorder the mem ops. 17649 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 17650 break; 17651 17652 if (Index->isVolatile() || Index->isIndexed()) 17653 break; 17654 17655 // Find the base pointer and offset for this memory node. 17656 BaseIndexOffset Ptr = BaseIndexOffset::match(Index, DAG); 17657 17658 // Check that the base pointer is the same as the original one. 17659 if (!BasePtr.equalBaseIndex(Ptr, DAG)) 17660 break; 17661 17662 // Walk up the chain to find the next store node, ignoring any 17663 // intermediate loads. Any other kind of node will halt the loop. 17664 SDNode *NextInChain = Index->getChain().getNode(); 17665 while (true) { 17666 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 17667 // We found a store node. Use it for the next iteration. 17668 if (STn->isVolatile() || STn->isIndexed()) { 17669 Index = nullptr; 17670 break; 17671 } 17672 ChainedStores.push_back(STn); 17673 Index = STn; 17674 break; 17675 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 17676 NextInChain = Ldn->getChain().getNode(); 17677 continue; 17678 } else { 17679 Index = nullptr; 17680 break; 17681 } 17682 } // end while 17683 } 17684 17685 // At this point, ChainedStores lists all of the Store nodes 17686 // reachable by iterating up through chain nodes matching the above 17687 // conditions. For each such store identified, try to find an 17688 // earlier chain to attach the store to which won't violate the 17689 // required ordering. 17690 bool MadeChangeToSt = false; 17691 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 17692 17693 for (StoreSDNode *ChainedStore : ChainedStores) { 17694 SDValue Chain = ChainedStore->getChain(); 17695 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 17696 17697 if (Chain != BetterChain) { 17698 if (ChainedStore == St) 17699 MadeChangeToSt = true; 17700 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 17701 } 17702 } 17703 17704 // Do all replacements after finding the replacements to make to avoid making 17705 // the chains more complicated by introducing new TokenFactors. 17706 for (auto Replacement : BetterChains) 17707 replaceStoreChain(Replacement.first, Replacement.second); 17708 17709 return MadeChangeToSt; 17710 } 17711 17712 /// This is the entry point for the file. 17713 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA, 17714 CodeGenOpt::Level OptLevel) { 17715 /// This is the main entry point to this class. 17716 DAGCombiner(*this, AA, OptLevel).Run(Level); 17717 } 17718