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 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 236 237 bool CombineToPreIndexedLoadStore(SDNode *N); 238 bool CombineToPostIndexedLoadStore(SDNode *N); 239 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 240 bool SliceUpLoad(SDNode *N); 241 242 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 243 /// load. 244 /// 245 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 246 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 247 /// \param EltNo index of the vector element to load. 248 /// \param OriginalLoad load that EVE came from to be replaced. 249 /// \returns EVE on success SDValue() on failure. 250 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 251 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 252 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 253 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 254 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 255 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 256 SDValue PromoteIntBinOp(SDValue Op); 257 SDValue PromoteIntShiftOp(SDValue Op); 258 SDValue PromoteExtend(SDValue Op); 259 bool PromoteLoad(SDValue Op); 260 261 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc, 262 SDValue ExtLoad, const SDLoc &DL, 263 ISD::NodeType ExtType); 264 265 /// Call the node-specific routine that knows how to fold each 266 /// particular type of node. If that doesn't do anything, try the 267 /// target-specific DAG combines. 268 SDValue combine(SDNode *N); 269 270 // Visitation implementation - Implement dag node combining for different 271 // node types. The semantics are as follows: 272 // Return Value: 273 // SDValue.getNode() == 0 - No change was made 274 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 275 // otherwise - N should be replaced by the returned Operand. 276 // 277 SDValue visitTokenFactor(SDNode *N); 278 SDValue visitMERGE_VALUES(SDNode *N); 279 SDValue visitADD(SDNode *N); 280 SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference); 281 SDValue visitSUB(SDNode *N); 282 SDValue visitADDC(SDNode *N); 283 SDValue visitUADDO(SDNode *N); 284 SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N); 285 SDValue visitSUBC(SDNode *N); 286 SDValue visitUSUBO(SDNode *N); 287 SDValue visitADDE(SDNode *N); 288 SDValue visitADDCARRY(SDNode *N); 289 SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N); 290 SDValue visitSUBE(SDNode *N); 291 SDValue visitSUBCARRY(SDNode *N); 292 SDValue visitMUL(SDNode *N); 293 SDValue useDivRem(SDNode *N); 294 SDValue visitSDIV(SDNode *N); 295 SDValue visitUDIV(SDNode *N); 296 SDValue visitREM(SDNode *N); 297 SDValue visitMULHU(SDNode *N); 298 SDValue visitMULHS(SDNode *N); 299 SDValue visitSMUL_LOHI(SDNode *N); 300 SDValue visitUMUL_LOHI(SDNode *N); 301 SDValue visitSMULO(SDNode *N); 302 SDValue visitUMULO(SDNode *N); 303 SDValue visitIMINMAX(SDNode *N); 304 SDValue visitAND(SDNode *N); 305 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference); 306 SDValue visitOR(SDNode *N); 307 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference); 308 SDValue visitXOR(SDNode *N); 309 SDValue SimplifyVBinOp(SDNode *N); 310 SDValue visitSHL(SDNode *N); 311 SDValue visitSRA(SDNode *N); 312 SDValue visitSRL(SDNode *N); 313 SDValue visitRotate(SDNode *N); 314 SDValue visitABS(SDNode *N); 315 SDValue visitBSWAP(SDNode *N); 316 SDValue visitBITREVERSE(SDNode *N); 317 SDValue visitCTLZ(SDNode *N); 318 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 319 SDValue visitCTTZ(SDNode *N); 320 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 321 SDValue visitCTPOP(SDNode *N); 322 SDValue visitSELECT(SDNode *N); 323 SDValue visitVSELECT(SDNode *N); 324 SDValue visitSELECT_CC(SDNode *N); 325 SDValue visitSETCC(SDNode *N); 326 SDValue visitSETCCE(SDNode *N); 327 SDValue visitSETCCCARRY(SDNode *N); 328 SDValue visitSIGN_EXTEND(SDNode *N); 329 SDValue visitZERO_EXTEND(SDNode *N); 330 SDValue visitANY_EXTEND(SDNode *N); 331 SDValue visitAssertExt(SDNode *N); 332 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 333 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 334 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N); 335 SDValue visitTRUNCATE(SDNode *N); 336 SDValue visitBITCAST(SDNode *N); 337 SDValue visitBUILD_PAIR(SDNode *N); 338 SDValue visitFADD(SDNode *N); 339 SDValue visitFSUB(SDNode *N); 340 SDValue visitFMUL(SDNode *N); 341 SDValue visitFMA(SDNode *N); 342 SDValue visitFDIV(SDNode *N); 343 SDValue visitFREM(SDNode *N); 344 SDValue visitFSQRT(SDNode *N); 345 SDValue visitFCOPYSIGN(SDNode *N); 346 SDValue visitSINT_TO_FP(SDNode *N); 347 SDValue visitUINT_TO_FP(SDNode *N); 348 SDValue visitFP_TO_SINT(SDNode *N); 349 SDValue visitFP_TO_UINT(SDNode *N); 350 SDValue visitFP_ROUND(SDNode *N); 351 SDValue visitFP_ROUND_INREG(SDNode *N); 352 SDValue visitFP_EXTEND(SDNode *N); 353 SDValue visitFNEG(SDNode *N); 354 SDValue visitFABS(SDNode *N); 355 SDValue visitFCEIL(SDNode *N); 356 SDValue visitFTRUNC(SDNode *N); 357 SDValue visitFFLOOR(SDNode *N); 358 SDValue visitFMINNUM(SDNode *N); 359 SDValue visitFMAXNUM(SDNode *N); 360 SDValue visitBRCOND(SDNode *N); 361 SDValue visitBR_CC(SDNode *N); 362 SDValue visitLOAD(SDNode *N); 363 364 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 365 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 366 367 SDValue visitSTORE(SDNode *N); 368 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 369 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 370 SDValue visitBUILD_VECTOR(SDNode *N); 371 SDValue visitCONCAT_VECTORS(SDNode *N); 372 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 373 SDValue visitVECTOR_SHUFFLE(SDNode *N); 374 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 375 SDValue visitINSERT_SUBVECTOR(SDNode *N); 376 SDValue visitMLOAD(SDNode *N); 377 SDValue visitMSTORE(SDNode *N); 378 SDValue visitMGATHER(SDNode *N); 379 SDValue visitMSCATTER(SDNode *N); 380 SDValue visitFP_TO_FP16(SDNode *N); 381 SDValue visitFP16_TO_FP(SDNode *N); 382 383 SDValue visitFADDForFMACombine(SDNode *N); 384 SDValue visitFSUBForFMACombine(SDNode *N); 385 SDValue visitFMULForFMADistributiveCombine(SDNode *N); 386 387 SDValue XformToShuffleWithZero(SDNode *N); 388 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS, 389 SDValue RHS); 390 391 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 392 393 SDValue foldSelectOfConstants(SDNode *N); 394 SDValue foldVSelectOfConstants(SDNode *N); 395 SDValue foldBinOpIntoSelect(SDNode *BO); 396 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 397 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 398 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2); 399 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 400 SDValue N2, SDValue N3, ISD::CondCode CC, 401 bool NotExtCompare = false); 402 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1, 403 SDValue N2, SDValue N3, ISD::CondCode CC); 404 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 405 const SDLoc &DL); 406 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 407 const SDLoc &DL, bool foldBooleans = true); 408 409 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 410 SDValue &CC) const; 411 bool isOneUseSetCC(SDValue N) const; 412 413 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 414 unsigned HiOp); 415 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 416 SDValue CombineExtLoad(SDNode *N); 417 SDValue combineRepeatedFPDivisors(SDNode *N); 418 SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex); 419 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 420 SDValue BuildSDIV(SDNode *N); 421 SDValue BuildSDIVPow2(SDNode *N); 422 SDValue BuildUDIV(SDNode *N); 423 SDValue BuildLogBase2(SDValue Op, const SDLoc &DL); 424 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags); 425 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags); 426 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags); 427 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip); 428 SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations, 429 SDNodeFlags Flags, bool Reciprocal); 430 SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations, 431 SDNodeFlags Flags, bool Reciprocal); 432 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 433 bool DemandHighBits = true); 434 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 435 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 436 SDValue InnerPos, SDValue InnerNeg, 437 unsigned PosOpcode, unsigned NegOpcode, 438 const SDLoc &DL); 439 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL); 440 SDValue MatchLoadCombine(SDNode *N); 441 SDValue ReduceLoadWidth(SDNode *N); 442 SDValue ReduceLoadOpStoreWidth(SDNode *N); 443 SDValue splitMergedValStore(StoreSDNode *ST); 444 SDValue TransformFPLoadStorePair(SDNode *N); 445 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 446 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 447 SDValue reduceBuildVecToShuffle(SDNode *N); 448 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N, 449 ArrayRef<int> VectorMask, SDValue VecIn1, 450 SDValue VecIn2, unsigned LeftIdx); 451 SDValue matchVSelectOpSizesWithSetCC(SDNode *N); 452 453 /// Walk up chain skipping non-aliasing memory nodes, 454 /// looking for aliasing nodes and adding them to the Aliases vector. 455 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 456 SmallVectorImpl<SDValue> &Aliases); 457 458 /// Return true if there is any possibility that the two addresses overlap. 459 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 460 461 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 462 /// chain (aliasing node.) 463 SDValue FindBetterChain(SDNode *N, SDValue Chain); 464 465 /// Try to replace a store and any possibly adjacent stores on 466 /// consecutive chains with better chains. Return true only if St is 467 /// replaced. 468 /// 469 /// Notice that other chains may still be replaced even if the function 470 /// returns false. 471 bool findBetterNeighborChains(StoreSDNode *St); 472 473 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 474 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask); 475 476 /// Holds a pointer to an LSBaseSDNode as well as information on where it 477 /// is located in a sequence of memory operations connected by a chain. 478 struct MemOpLink { 479 // Ptr to the mem node. 480 LSBaseSDNode *MemNode; 481 482 // Offset from the base ptr. 483 int64_t OffsetFromBase; 484 485 MemOpLink(LSBaseSDNode *N, int64_t Offset) 486 : MemNode(N), OffsetFromBase(Offset) {} 487 }; 488 489 /// This is a helper function for visitMUL to check the profitability 490 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 491 /// MulNode is the original multiply, AddNode is (add x, c1), 492 /// and ConstNode is c2. 493 bool isMulAddWithConstProfitable(SDNode *MulNode, 494 SDValue &AddNode, 495 SDValue &ConstNode); 496 497 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 498 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 499 /// the type of the loaded value to be extended. 500 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 501 EVT LoadResultTy, EVT &ExtVT); 502 503 /// Helper function to calculate whether the given Load can have its 504 /// width reduced to ExtVT. 505 bool isLegalNarrowLoad(LoadSDNode *LoadN, ISD::LoadExtType ExtType, 506 EVT &ExtVT, unsigned ShAmt = 0); 507 508 /// Used by BackwardsPropagateMask to find suitable loads. 509 bool SearchForAndLoads(SDNode *N, SmallPtrSetImpl<LoadSDNode*> &Loads, 510 SmallPtrSetImpl<SDNode*> &NodeWithConsts, 511 ConstantSDNode *Mask, SDNode *&UncombinedNode); 512 /// Attempt to propagate a given AND node back to load leaves so that they 513 /// can be combined into narrow loads. 514 bool BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG); 515 516 /// Helper function for MergeConsecutiveStores which merges the 517 /// component store chains. 518 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 519 unsigned NumStores); 520 521 /// This is a helper function for MergeConsecutiveStores. When the 522 /// source elements of the consecutive stores are all constants or 523 /// all extracted vector elements, try to merge them into one 524 /// larger store introducing bitcasts if necessary. \return True 525 /// if a merged store was created. 526 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 527 EVT MemVT, unsigned NumStores, 528 bool IsConstantSrc, bool UseVector, 529 bool UseTrunc); 530 531 /// This is a helper function for MergeConsecutiveStores. Stores 532 /// that potentially may be merged with St are placed in 533 /// StoreNodes. 534 void getStoreMergeCandidates(StoreSDNode *St, 535 SmallVectorImpl<MemOpLink> &StoreNodes); 536 537 /// Helper function for MergeConsecutiveStores. Checks if 538 /// candidate stores have indirect dependency through their 539 /// operands. \return True if safe to merge. 540 bool checkMergeStoreCandidatesForDependencies( 541 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores); 542 543 /// Merge consecutive store operations into a wide store. 544 /// This optimization uses wide integers or vectors when possible. 545 /// \return number of stores that were merged into a merged store (the 546 /// affected nodes are stored as a prefix in \p StoreNodes). 547 bool MergeConsecutiveStores(StoreSDNode *N); 548 549 /// \brief Try to transform a truncation where C is a constant: 550 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 551 /// 552 /// \p N needs to be a truncation and its first operand an AND. Other 553 /// requirements are checked by the function (e.g. that trunc is 554 /// single-use) and if missed an empty SDValue is returned. 555 SDValue distributeTruncateThroughAnd(SDNode *N); 556 557 public: 558 /// Runs the dag combiner on all nodes in the work list 559 void Run(CombineLevel AtLevel); 560 561 SelectionDAG &getDAG() const { return DAG; } 562 563 /// Returns a type large enough to hold any valid shift amount - before type 564 /// legalization these can be huge. 565 EVT getShiftAmountTy(EVT LHSTy) { 566 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 567 if (LHSTy.isVector()) 568 return LHSTy; 569 auto &DL = DAG.getDataLayout(); 570 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 571 : TLI.getPointerTy(DL); 572 } 573 574 /// This method returns true if we are running before type legalization or 575 /// if the specified VT is legal. 576 bool isTypeLegal(const EVT &VT) { 577 if (!LegalTypes) return true; 578 return TLI.isTypeLegal(VT); 579 } 580 581 /// Convenience wrapper around TargetLowering::getSetCCResultType 582 EVT getSetCCResultType(EVT VT) const { 583 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 584 } 585 }; 586 587 /// This class is a DAGUpdateListener that removes any deleted 588 /// nodes from the worklist. 589 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 590 DAGCombiner &DC; 591 592 public: 593 explicit WorklistRemover(DAGCombiner &dc) 594 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 595 596 void NodeDeleted(SDNode *N, SDNode *E) override { 597 DC.removeFromWorklist(N); 598 } 599 }; 600 601 } // end anonymous namespace 602 603 //===----------------------------------------------------------------------===// 604 // TargetLowering::DAGCombinerInfo implementation 605 //===----------------------------------------------------------------------===// 606 607 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 608 ((DAGCombiner*)DC)->AddToWorklist(N); 609 } 610 611 SDValue TargetLowering::DAGCombinerInfo:: 612 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 613 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 614 } 615 616 SDValue TargetLowering::DAGCombinerInfo:: 617 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 618 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 619 } 620 621 SDValue TargetLowering::DAGCombinerInfo:: 622 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 623 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 624 } 625 626 void TargetLowering::DAGCombinerInfo:: 627 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 628 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 629 } 630 631 //===----------------------------------------------------------------------===// 632 // Helper Functions 633 //===----------------------------------------------------------------------===// 634 635 void DAGCombiner::deleteAndRecombine(SDNode *N) { 636 removeFromWorklist(N); 637 638 // If the operands of this node are only used by the node, they will now be 639 // dead. Make sure to re-visit them and recursively delete dead nodes. 640 for (const SDValue &Op : N->ops()) 641 // For an operand generating multiple values, one of the values may 642 // become dead allowing further simplification (e.g. split index 643 // arithmetic from an indexed load). 644 if (Op->hasOneUse() || Op->getNumValues() > 1) 645 AddToWorklist(Op.getNode()); 646 647 DAG.DeleteNode(N); 648 } 649 650 /// Return 1 if we can compute the negated form of the specified expression for 651 /// the same cost as the expression itself, or 2 if we can compute the negated 652 /// form more cheaply than the expression itself. 653 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 654 const TargetLowering &TLI, 655 const TargetOptions *Options, 656 unsigned Depth = 0) { 657 // fneg is removable even if it has multiple uses. 658 if (Op.getOpcode() == ISD::FNEG) return 2; 659 660 // Don't allow anything with multiple uses. 661 if (!Op.hasOneUse()) return 0; 662 663 // Don't recurse exponentially. 664 if (Depth > 6) return 0; 665 666 switch (Op.getOpcode()) { 667 default: return false; 668 case ISD::ConstantFP: { 669 if (!LegalOperations) 670 return 1; 671 672 // Don't invert constant FP values after legalization unless the target says 673 // the negated constant is legal. 674 EVT VT = Op.getValueType(); 675 return TLI.isOperationLegal(ISD::ConstantFP, VT) || 676 TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT); 677 } 678 case ISD::FADD: 679 // FIXME: determine better conditions for this xform. 680 if (!Options->UnsafeFPMath) return 0; 681 682 // After operation legalization, it might not be legal to create new FSUBs. 683 if (LegalOperations && 684 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 685 return 0; 686 687 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 688 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 689 Options, Depth + 1)) 690 return V; 691 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 692 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 693 Depth + 1); 694 case ISD::FSUB: 695 // We can't turn -(A-B) into B-A when we honor signed zeros. 696 if (!Options->NoSignedZerosFPMath && 697 !Op.getNode()->getFlags().hasNoSignedZeros()) 698 return 0; 699 700 // fold (fneg (fsub A, B)) -> (fsub B, A) 701 return 1; 702 703 case ISD::FMUL: 704 case ISD::FDIV: 705 if (Options->HonorSignDependentRoundingFPMath()) return 0; 706 707 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 708 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 709 Options, Depth + 1)) 710 return V; 711 712 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 713 Depth + 1); 714 715 case ISD::FP_EXTEND: 716 case ISD::FP_ROUND: 717 case ISD::FSIN: 718 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 719 Depth + 1); 720 } 721 } 722 723 /// If isNegatibleForFree returns true, return the newly negated expression. 724 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 725 bool LegalOperations, unsigned Depth = 0) { 726 const TargetOptions &Options = DAG.getTarget().Options; 727 // fneg is removable even if it has multiple uses. 728 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 729 730 // Don't allow anything with multiple uses. 731 assert(Op.hasOneUse() && "Unknown reuse!"); 732 733 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 734 735 const SDNodeFlags Flags = Op.getNode()->getFlags(); 736 737 switch (Op.getOpcode()) { 738 default: llvm_unreachable("Unknown code"); 739 case ISD::ConstantFP: { 740 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 741 V.changeSign(); 742 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 743 } 744 case ISD::FADD: 745 // FIXME: determine better conditions for this xform. 746 assert(Options.UnsafeFPMath); 747 748 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 749 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 750 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 751 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 752 GetNegatedExpression(Op.getOperand(0), DAG, 753 LegalOperations, Depth+1), 754 Op.getOperand(1), Flags); 755 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 756 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 757 GetNegatedExpression(Op.getOperand(1), DAG, 758 LegalOperations, Depth+1), 759 Op.getOperand(0), Flags); 760 case ISD::FSUB: 761 // fold (fneg (fsub 0, B)) -> B 762 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 763 if (N0CFP->isZero()) 764 return Op.getOperand(1); 765 766 // fold (fneg (fsub A, B)) -> (fsub B, A) 767 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 768 Op.getOperand(1), Op.getOperand(0), Flags); 769 770 case ISD::FMUL: 771 case ISD::FDIV: 772 assert(!Options.HonorSignDependentRoundingFPMath()); 773 774 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 775 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 776 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 777 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 778 GetNegatedExpression(Op.getOperand(0), DAG, 779 LegalOperations, Depth+1), 780 Op.getOperand(1), Flags); 781 782 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 783 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 784 Op.getOperand(0), 785 GetNegatedExpression(Op.getOperand(1), DAG, 786 LegalOperations, Depth+1), Flags); 787 788 case ISD::FP_EXTEND: 789 case ISD::FSIN: 790 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 791 GetNegatedExpression(Op.getOperand(0), DAG, 792 LegalOperations, Depth+1)); 793 case ISD::FP_ROUND: 794 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 795 GetNegatedExpression(Op.getOperand(0), DAG, 796 LegalOperations, Depth+1), 797 Op.getOperand(1)); 798 } 799 } 800 801 // APInts must be the same size for most operations, this helper 802 // function zero extends the shorter of the pair so that they match. 803 // We provide an Offset so that we can create bitwidths that won't overflow. 804 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) { 805 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth()); 806 LHS = LHS.zextOrSelf(Bits); 807 RHS = RHS.zextOrSelf(Bits); 808 } 809 810 // Return true if this node is a setcc, or is a select_cc 811 // that selects between the target values used for true and false, making it 812 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 813 // the appropriate nodes based on the type of node we are checking. This 814 // simplifies life a bit for the callers. 815 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 816 SDValue &CC) const { 817 if (N.getOpcode() == ISD::SETCC) { 818 LHS = N.getOperand(0); 819 RHS = N.getOperand(1); 820 CC = N.getOperand(2); 821 return true; 822 } 823 824 if (N.getOpcode() != ISD::SELECT_CC || 825 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 826 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 827 return false; 828 829 if (TLI.getBooleanContents(N.getValueType()) == 830 TargetLowering::UndefinedBooleanContent) 831 return false; 832 833 LHS = N.getOperand(0); 834 RHS = N.getOperand(1); 835 CC = N.getOperand(4); 836 return true; 837 } 838 839 /// Return true if this is a SetCC-equivalent operation with only one use. 840 /// If this is true, it allows the users to invert the operation for free when 841 /// it is profitable to do so. 842 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 843 SDValue N0, N1, N2; 844 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 845 return true; 846 return false; 847 } 848 849 // \brief Returns the SDNode if it is a constant float BuildVector 850 // or constant float. 851 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 852 if (isa<ConstantFPSDNode>(N)) 853 return N.getNode(); 854 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 855 return N.getNode(); 856 return nullptr; 857 } 858 859 // Determines if it is a constant integer or a build vector of constant 860 // integers (and undefs). 861 // Do not permit build vector implicit truncation. 862 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) { 863 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N)) 864 return !(Const->isOpaque() && NoOpaques); 865 if (N.getOpcode() != ISD::BUILD_VECTOR) 866 return false; 867 unsigned BitWidth = N.getScalarValueSizeInBits(); 868 for (const SDValue &Op : N->op_values()) { 869 if (Op.isUndef()) 870 continue; 871 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op); 872 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth || 873 (Const->isOpaque() && NoOpaques)) 874 return false; 875 } 876 return true; 877 } 878 879 // Determines if it is a constant null integer or a splatted vector of a 880 // constant null integer (with no undefs). 881 // Build vector implicit truncation is not an issue for null values. 882 static bool isNullConstantOrNullSplatConstant(SDValue N) { 883 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 884 return Splat->isNullValue(); 885 return false; 886 } 887 888 // Determines if it is a constant integer of one or a splatted vector of a 889 // constant integer of one (with no undefs). 890 // Do not permit build vector implicit truncation. 891 static bool isOneConstantOrOneSplatConstant(SDValue N) { 892 unsigned BitWidth = N.getScalarValueSizeInBits(); 893 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 894 return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth; 895 return false; 896 } 897 898 // Determines if it is a constant integer of all ones or a splatted vector of a 899 // constant integer of all ones (with no undefs). 900 // Do not permit build vector implicit truncation. 901 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) { 902 unsigned BitWidth = N.getScalarValueSizeInBits(); 903 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 904 return Splat->isAllOnesValue() && 905 Splat->getAPIntValue().getBitWidth() == BitWidth; 906 return false; 907 } 908 909 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with 910 // undef's. 911 static bool isAnyConstantBuildVector(const SDNode *N) { 912 return ISD::isBuildVectorOfConstantSDNodes(N) || 913 ISD::isBuildVectorOfConstantFPSDNodes(N); 914 } 915 916 // Attempt to match a unary predicate against a scalar/splat constant or 917 // every element of a constant BUILD_VECTOR. 918 static bool matchUnaryPredicate(SDValue Op, 919 std::function<bool(ConstantSDNode *)> Match) { 920 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) 921 return Match(Cst); 922 923 if (ISD::BUILD_VECTOR != Op.getOpcode()) 924 return false; 925 926 EVT SVT = Op.getValueType().getScalarType(); 927 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 928 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i)); 929 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 930 return false; 931 } 932 return true; 933 } 934 935 // Attempt to match a binary predicate against a pair of scalar/splat constants 936 // or every element of a pair of constant BUILD_VECTORs. 937 static bool matchBinaryPredicate( 938 SDValue LHS, SDValue RHS, 939 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match) { 940 if (LHS.getValueType() != RHS.getValueType()) 941 return false; 942 943 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 944 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 945 return Match(LHSCst, RHSCst); 946 947 if (ISD::BUILD_VECTOR != LHS.getOpcode() || 948 ISD::BUILD_VECTOR != RHS.getOpcode()) 949 return false; 950 951 EVT SVT = LHS.getValueType().getScalarType(); 952 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 953 auto *LHSCst = dyn_cast<ConstantSDNode>(LHS.getOperand(i)); 954 auto *RHSCst = dyn_cast<ConstantSDNode>(RHS.getOperand(i)); 955 if (!LHSCst || !RHSCst) 956 return false; 957 if (LHSCst->getValueType(0) != SVT || 958 LHSCst->getValueType(0) != RHSCst->getValueType(0)) 959 return false; 960 if (!Match(LHSCst, RHSCst)) 961 return false; 962 } 963 return true; 964 } 965 966 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 967 SDValue N1) { 968 EVT VT = N0.getValueType(); 969 if (N0.getOpcode() == Opc) { 970 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 971 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 972 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 973 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 974 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 975 return SDValue(); 976 } 977 if (N0.hasOneUse()) { 978 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 979 // use 980 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 981 if (!OpNode.getNode()) 982 return SDValue(); 983 AddToWorklist(OpNode.getNode()); 984 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 985 } 986 } 987 } 988 989 if (N1.getOpcode() == Opc) { 990 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 991 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 992 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 993 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 994 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 995 return SDValue(); 996 } 997 if (N1.hasOneUse()) { 998 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 999 // use 1000 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 1001 if (!OpNode.getNode()) 1002 return SDValue(); 1003 AddToWorklist(OpNode.getNode()); 1004 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 1005 } 1006 } 1007 } 1008 1009 return SDValue(); 1010 } 1011 1012 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 1013 bool AddTo) { 1014 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 1015 ++NodesCombined; 1016 DEBUG(dbgs() << "\nReplacing.1 "; 1017 N->dump(&DAG); 1018 dbgs() << "\nWith: "; 1019 To[0].getNode()->dump(&DAG); 1020 dbgs() << " and " << NumTo-1 << " other values\n"); 1021 for (unsigned i = 0, e = NumTo; i != e; ++i) 1022 assert((!To[i].getNode() || 1023 N->getValueType(i) == To[i].getValueType()) && 1024 "Cannot combine value to value of different type!"); 1025 1026 WorklistRemover DeadNodes(*this); 1027 DAG.ReplaceAllUsesWith(N, To); 1028 if (AddTo) { 1029 // Push the new nodes and any users onto the worklist 1030 for (unsigned i = 0, e = NumTo; i != e; ++i) { 1031 if (To[i].getNode()) { 1032 AddToWorklist(To[i].getNode()); 1033 AddUsersToWorklist(To[i].getNode()); 1034 } 1035 } 1036 } 1037 1038 // Finally, if the node is now dead, remove it from the graph. The node 1039 // may not be dead if the replacement process recursively simplified to 1040 // something else needing this node. 1041 if (N->use_empty()) 1042 deleteAndRecombine(N); 1043 return SDValue(N, 0); 1044 } 1045 1046 void DAGCombiner:: 1047 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 1048 // Replace all uses. If any nodes become isomorphic to other nodes and 1049 // are deleted, make sure to remove them from our worklist. 1050 WorklistRemover DeadNodes(*this); 1051 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 1052 1053 // Push the new node and any (possibly new) users onto the worklist. 1054 AddToWorklist(TLO.New.getNode()); 1055 AddUsersToWorklist(TLO.New.getNode()); 1056 1057 // Finally, if the node is now dead, remove it from the graph. The node 1058 // may not be dead if the replacement process recursively simplified to 1059 // something else needing this node. 1060 if (TLO.Old.getNode()->use_empty()) 1061 deleteAndRecombine(TLO.Old.getNode()); 1062 } 1063 1064 /// Check the specified integer node value to see if it can be simplified or if 1065 /// things it uses can be simplified by bit propagation. If so, return true. 1066 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 1067 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 1068 KnownBits Known; 1069 if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO)) 1070 return false; 1071 1072 // Revisit the node. 1073 AddToWorklist(Op.getNode()); 1074 1075 // Replace the old value with the new one. 1076 ++NodesCombined; 1077 DEBUG(dbgs() << "\nReplacing.2 "; 1078 TLO.Old.getNode()->dump(&DAG); 1079 dbgs() << "\nWith: "; 1080 TLO.New.getNode()->dump(&DAG); 1081 dbgs() << '\n'); 1082 1083 CommitTargetLoweringOpt(TLO); 1084 return true; 1085 } 1086 1087 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 1088 SDLoc DL(Load); 1089 EVT VT = Load->getValueType(0); 1090 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0)); 1091 1092 DEBUG(dbgs() << "\nReplacing.9 "; 1093 Load->dump(&DAG); 1094 dbgs() << "\nWith: "; 1095 Trunc.getNode()->dump(&DAG); 1096 dbgs() << '\n'); 1097 WorklistRemover DeadNodes(*this); 1098 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 1099 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 1100 deleteAndRecombine(Load); 1101 AddToWorklist(Trunc.getNode()); 1102 } 1103 1104 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 1105 Replace = false; 1106 SDLoc DL(Op); 1107 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 1108 LoadSDNode *LD = cast<LoadSDNode>(Op); 1109 EVT MemVT = LD->getMemoryVT(); 1110 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1111 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1112 : ISD::EXTLOAD) 1113 : LD->getExtensionType(); 1114 Replace = true; 1115 return DAG.getExtLoad(ExtType, DL, PVT, 1116 LD->getChain(), LD->getBasePtr(), 1117 MemVT, LD->getMemOperand()); 1118 } 1119 1120 unsigned Opc = Op.getOpcode(); 1121 switch (Opc) { 1122 default: break; 1123 case ISD::AssertSext: 1124 if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT)) 1125 return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1)); 1126 break; 1127 case ISD::AssertZext: 1128 if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT)) 1129 return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1)); 1130 break; 1131 case ISD::Constant: { 1132 unsigned ExtOpc = 1133 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1134 return DAG.getNode(ExtOpc, DL, PVT, Op); 1135 } 1136 } 1137 1138 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 1139 return SDValue(); 1140 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op); 1141 } 1142 1143 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1144 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1145 return SDValue(); 1146 EVT OldVT = Op.getValueType(); 1147 SDLoc DL(Op); 1148 bool Replace = false; 1149 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1150 if (!NewOp.getNode()) 1151 return SDValue(); 1152 AddToWorklist(NewOp.getNode()); 1153 1154 if (Replace) 1155 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1156 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp, 1157 DAG.getValueType(OldVT)); 1158 } 1159 1160 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1161 EVT OldVT = Op.getValueType(); 1162 SDLoc DL(Op); 1163 bool Replace = false; 1164 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1165 if (!NewOp.getNode()) 1166 return SDValue(); 1167 AddToWorklist(NewOp.getNode()); 1168 1169 if (Replace) 1170 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1171 return DAG.getZeroExtendInReg(NewOp, DL, OldVT); 1172 } 1173 1174 /// Promote the specified integer binary operation if the target indicates it is 1175 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1176 /// i32 since i16 instructions are longer. 1177 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1178 if (!LegalOperations) 1179 return SDValue(); 1180 1181 EVT VT = Op.getValueType(); 1182 if (VT.isVector() || !VT.isInteger()) 1183 return SDValue(); 1184 1185 // If operation type is 'undesirable', e.g. i16 on x86, consider 1186 // promoting it. 1187 unsigned Opc = Op.getOpcode(); 1188 if (TLI.isTypeDesirableForOp(Opc, VT)) 1189 return SDValue(); 1190 1191 EVT PVT = VT; 1192 // Consult target whether it is a good idea to promote this operation and 1193 // what's the right type to promote it to. 1194 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1195 assert(PVT != VT && "Don't know what type to promote to!"); 1196 1197 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1198 1199 bool Replace0 = false; 1200 SDValue N0 = Op.getOperand(0); 1201 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1202 1203 bool Replace1 = false; 1204 SDValue N1 = Op.getOperand(1); 1205 SDValue NN1 = PromoteOperand(N1, PVT, Replace1); 1206 SDLoc DL(Op); 1207 1208 SDValue RV = 1209 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1)); 1210 1211 // We are always replacing N0/N1's use in N and only need 1212 // additional replacements if there are additional uses. 1213 Replace0 &= !N0->hasOneUse(); 1214 Replace1 &= (N0 != N1) && !N1->hasOneUse(); 1215 1216 // Combine Op here so it is preserved past replacements. 1217 CombineTo(Op.getNode(), RV); 1218 1219 // If operands have a use ordering, make sure we deal with 1220 // predecessor first. 1221 if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) { 1222 std::swap(N0, N1); 1223 std::swap(NN0, NN1); 1224 } 1225 1226 if (Replace0) { 1227 AddToWorklist(NN0.getNode()); 1228 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1229 } 1230 if (Replace1) { 1231 AddToWorklist(NN1.getNode()); 1232 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1233 } 1234 return Op; 1235 } 1236 return SDValue(); 1237 } 1238 1239 /// Promote the specified integer shift operation if the target indicates it is 1240 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1241 /// i32 since i16 instructions are longer. 1242 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1243 if (!LegalOperations) 1244 return SDValue(); 1245 1246 EVT VT = Op.getValueType(); 1247 if (VT.isVector() || !VT.isInteger()) 1248 return SDValue(); 1249 1250 // If operation type is 'undesirable', e.g. i16 on x86, consider 1251 // promoting it. 1252 unsigned Opc = Op.getOpcode(); 1253 if (TLI.isTypeDesirableForOp(Opc, VT)) 1254 return SDValue(); 1255 1256 EVT PVT = VT; 1257 // Consult target whether it is a good idea to promote this operation and 1258 // what's the right type to promote it to. 1259 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1260 assert(PVT != VT && "Don't know what type to promote to!"); 1261 1262 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1263 1264 bool Replace = false; 1265 SDValue N0 = Op.getOperand(0); 1266 SDValue N1 = Op.getOperand(1); 1267 if (Opc == ISD::SRA) 1268 N0 = SExtPromoteOperand(N0, PVT); 1269 else if (Opc == ISD::SRL) 1270 N0 = ZExtPromoteOperand(N0, PVT); 1271 else 1272 N0 = PromoteOperand(N0, PVT, Replace); 1273 1274 if (!N0.getNode()) 1275 return SDValue(); 1276 1277 SDLoc DL(Op); 1278 SDValue RV = 1279 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1)); 1280 1281 AddToWorklist(N0.getNode()); 1282 if (Replace) 1283 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1284 1285 // Deal with Op being deleted. 1286 if (Op && Op.getOpcode() != ISD::DELETED_NODE) 1287 return RV; 1288 } 1289 return SDValue(); 1290 } 1291 1292 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1293 if (!LegalOperations) 1294 return SDValue(); 1295 1296 EVT VT = Op.getValueType(); 1297 if (VT.isVector() || !VT.isInteger()) 1298 return SDValue(); 1299 1300 // If operation type is 'undesirable', e.g. i16 on x86, consider 1301 // promoting it. 1302 unsigned Opc = Op.getOpcode(); 1303 if (TLI.isTypeDesirableForOp(Opc, VT)) 1304 return SDValue(); 1305 1306 EVT PVT = VT; 1307 // Consult target whether it is a good idea to promote this operation and 1308 // what's the right type to promote it to. 1309 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1310 assert(PVT != VT && "Don't know what type to promote to!"); 1311 // fold (aext (aext x)) -> (aext x) 1312 // fold (aext (zext x)) -> (zext x) 1313 // fold (aext (sext x)) -> (sext x) 1314 DEBUG(dbgs() << "\nPromoting "; 1315 Op.getNode()->dump(&DAG)); 1316 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1317 } 1318 return SDValue(); 1319 } 1320 1321 bool DAGCombiner::PromoteLoad(SDValue Op) { 1322 if (!LegalOperations) 1323 return false; 1324 1325 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1326 return false; 1327 1328 EVT VT = Op.getValueType(); 1329 if (VT.isVector() || !VT.isInteger()) 1330 return false; 1331 1332 // If operation type is 'undesirable', e.g. i16 on x86, consider 1333 // promoting it. 1334 unsigned Opc = Op.getOpcode(); 1335 if (TLI.isTypeDesirableForOp(Opc, VT)) 1336 return false; 1337 1338 EVT PVT = VT; 1339 // Consult target whether it is a good idea to promote this operation and 1340 // what's the right type to promote it to. 1341 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1342 assert(PVT != VT && "Don't know what type to promote to!"); 1343 1344 SDLoc DL(Op); 1345 SDNode *N = Op.getNode(); 1346 LoadSDNode *LD = cast<LoadSDNode>(N); 1347 EVT MemVT = LD->getMemoryVT(); 1348 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1349 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1350 : ISD::EXTLOAD) 1351 : LD->getExtensionType(); 1352 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT, 1353 LD->getChain(), LD->getBasePtr(), 1354 MemVT, LD->getMemOperand()); 1355 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD); 1356 1357 DEBUG(dbgs() << "\nPromoting "; 1358 N->dump(&DAG); 1359 dbgs() << "\nTo: "; 1360 Result.getNode()->dump(&DAG); 1361 dbgs() << '\n'); 1362 WorklistRemover DeadNodes(*this); 1363 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1364 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1365 deleteAndRecombine(N); 1366 AddToWorklist(Result.getNode()); 1367 return true; 1368 } 1369 return false; 1370 } 1371 1372 /// \brief Recursively delete a node which has no uses and any operands for 1373 /// which it is the only use. 1374 /// 1375 /// Note that this both deletes the nodes and removes them from the worklist. 1376 /// It also adds any nodes who have had a user deleted to the worklist as they 1377 /// may now have only one use and subject to other combines. 1378 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1379 if (!N->use_empty()) 1380 return false; 1381 1382 SmallSetVector<SDNode *, 16> Nodes; 1383 Nodes.insert(N); 1384 do { 1385 N = Nodes.pop_back_val(); 1386 if (!N) 1387 continue; 1388 1389 if (N->use_empty()) { 1390 for (const SDValue &ChildN : N->op_values()) 1391 Nodes.insert(ChildN.getNode()); 1392 1393 removeFromWorklist(N); 1394 DAG.DeleteNode(N); 1395 } else { 1396 AddToWorklist(N); 1397 } 1398 } while (!Nodes.empty()); 1399 return true; 1400 } 1401 1402 //===----------------------------------------------------------------------===// 1403 // Main DAG Combiner implementation 1404 //===----------------------------------------------------------------------===// 1405 1406 void DAGCombiner::Run(CombineLevel AtLevel) { 1407 // set the instance variables, so that the various visit routines may use it. 1408 Level = AtLevel; 1409 LegalOperations = Level >= AfterLegalizeVectorOps; 1410 LegalTypes = Level >= AfterLegalizeTypes; 1411 1412 // Add all the dag nodes to the worklist. 1413 for (SDNode &Node : DAG.allnodes()) 1414 AddToWorklist(&Node); 1415 1416 // Create a dummy node (which is not added to allnodes), that adds a reference 1417 // to the root node, preventing it from being deleted, and tracking any 1418 // changes of the root. 1419 HandleSDNode Dummy(DAG.getRoot()); 1420 1421 // While the worklist isn't empty, find a node and try to combine it. 1422 while (!WorklistMap.empty()) { 1423 SDNode *N; 1424 // The Worklist holds the SDNodes in order, but it may contain null entries. 1425 do { 1426 N = Worklist.pop_back_val(); 1427 } while (!N); 1428 1429 bool GoodWorklistEntry = WorklistMap.erase(N); 1430 (void)GoodWorklistEntry; 1431 assert(GoodWorklistEntry && 1432 "Found a worklist entry without a corresponding map entry!"); 1433 1434 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1435 // N is deleted from the DAG, since they too may now be dead or may have a 1436 // reduced number of uses, allowing other xforms. 1437 if (recursivelyDeleteUnusedNodes(N)) 1438 continue; 1439 1440 WorklistRemover DeadNodes(*this); 1441 1442 // If this combine is running after legalizing the DAG, re-legalize any 1443 // nodes pulled off the worklist. 1444 if (Level == AfterLegalizeDAG) { 1445 SmallSetVector<SDNode *, 16> UpdatedNodes; 1446 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1447 1448 for (SDNode *LN : UpdatedNodes) { 1449 AddToWorklist(LN); 1450 AddUsersToWorklist(LN); 1451 } 1452 if (!NIsValid) 1453 continue; 1454 } 1455 1456 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1457 1458 // Add any operands of the new node which have not yet been combined to the 1459 // worklist as well. Because the worklist uniques things already, this 1460 // won't repeatedly process the same operand. 1461 CombinedNodes.insert(N); 1462 for (const SDValue &ChildN : N->op_values()) 1463 if (!CombinedNodes.count(ChildN.getNode())) 1464 AddToWorklist(ChildN.getNode()); 1465 1466 SDValue RV = combine(N); 1467 1468 if (!RV.getNode()) 1469 continue; 1470 1471 ++NodesCombined; 1472 1473 // If we get back the same node we passed in, rather than a new node or 1474 // zero, we know that the node must have defined multiple values and 1475 // CombineTo was used. Since CombineTo takes care of the worklist 1476 // mechanics for us, we have no work to do in this case. 1477 if (RV.getNode() == N) 1478 continue; 1479 1480 assert(N->getOpcode() != ISD::DELETED_NODE && 1481 RV.getOpcode() != ISD::DELETED_NODE && 1482 "Node was deleted but visit returned new node!"); 1483 1484 DEBUG(dbgs() << " ... into: "; 1485 RV.getNode()->dump(&DAG)); 1486 1487 if (N->getNumValues() == RV.getNode()->getNumValues()) 1488 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1489 else { 1490 assert(N->getValueType(0) == RV.getValueType() && 1491 N->getNumValues() == 1 && "Type mismatch"); 1492 DAG.ReplaceAllUsesWith(N, &RV); 1493 } 1494 1495 // Push the new node and any users onto the worklist 1496 AddToWorklist(RV.getNode()); 1497 AddUsersToWorklist(RV.getNode()); 1498 1499 // Finally, if the node is now dead, remove it from the graph. The node 1500 // may not be dead if the replacement process recursively simplified to 1501 // something else needing this node. This will also take care of adding any 1502 // operands which have lost a user to the worklist. 1503 recursivelyDeleteUnusedNodes(N); 1504 } 1505 1506 // If the root changed (e.g. it was a dead load, update the root). 1507 DAG.setRoot(Dummy.getValue()); 1508 DAG.RemoveDeadNodes(); 1509 } 1510 1511 SDValue DAGCombiner::visit(SDNode *N) { 1512 switch (N->getOpcode()) { 1513 default: break; 1514 case ISD::TokenFactor: return visitTokenFactor(N); 1515 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1516 case ISD::ADD: return visitADD(N); 1517 case ISD::SUB: return visitSUB(N); 1518 case ISD::ADDC: return visitADDC(N); 1519 case ISD::UADDO: return visitUADDO(N); 1520 case ISD::SUBC: return visitSUBC(N); 1521 case ISD::USUBO: return visitUSUBO(N); 1522 case ISD::ADDE: return visitADDE(N); 1523 case ISD::ADDCARRY: return visitADDCARRY(N); 1524 case ISD::SUBE: return visitSUBE(N); 1525 case ISD::SUBCARRY: return visitSUBCARRY(N); 1526 case ISD::MUL: return visitMUL(N); 1527 case ISD::SDIV: return visitSDIV(N); 1528 case ISD::UDIV: return visitUDIV(N); 1529 case ISD::SREM: 1530 case ISD::UREM: return visitREM(N); 1531 case ISD::MULHU: return visitMULHU(N); 1532 case ISD::MULHS: return visitMULHS(N); 1533 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1534 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1535 case ISD::SMULO: return visitSMULO(N); 1536 case ISD::UMULO: return visitUMULO(N); 1537 case ISD::SMIN: 1538 case ISD::SMAX: 1539 case ISD::UMIN: 1540 case ISD::UMAX: return visitIMINMAX(N); 1541 case ISD::AND: return visitAND(N); 1542 case ISD::OR: return visitOR(N); 1543 case ISD::XOR: return visitXOR(N); 1544 case ISD::SHL: return visitSHL(N); 1545 case ISD::SRA: return visitSRA(N); 1546 case ISD::SRL: return visitSRL(N); 1547 case ISD::ROTR: 1548 case ISD::ROTL: return visitRotate(N); 1549 case ISD::ABS: return visitABS(N); 1550 case ISD::BSWAP: return visitBSWAP(N); 1551 case ISD::BITREVERSE: return visitBITREVERSE(N); 1552 case ISD::CTLZ: return visitCTLZ(N); 1553 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1554 case ISD::CTTZ: return visitCTTZ(N); 1555 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1556 case ISD::CTPOP: return visitCTPOP(N); 1557 case ISD::SELECT: return visitSELECT(N); 1558 case ISD::VSELECT: return visitVSELECT(N); 1559 case ISD::SELECT_CC: return visitSELECT_CC(N); 1560 case ISD::SETCC: return visitSETCC(N); 1561 case ISD::SETCCE: return visitSETCCE(N); 1562 case ISD::SETCCCARRY: return visitSETCCCARRY(N); 1563 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1564 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1565 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1566 case ISD::AssertSext: 1567 case ISD::AssertZext: return visitAssertExt(N); 1568 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1569 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1570 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1571 case ISD::TRUNCATE: return visitTRUNCATE(N); 1572 case ISD::BITCAST: return visitBITCAST(N); 1573 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1574 case ISD::FADD: return visitFADD(N); 1575 case ISD::FSUB: return visitFSUB(N); 1576 case ISD::FMUL: return visitFMUL(N); 1577 case ISD::FMA: return visitFMA(N); 1578 case ISD::FDIV: return visitFDIV(N); 1579 case ISD::FREM: return visitFREM(N); 1580 case ISD::FSQRT: return visitFSQRT(N); 1581 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1582 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1583 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1584 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1585 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1586 case ISD::FP_ROUND: return visitFP_ROUND(N); 1587 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1588 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1589 case ISD::FNEG: return visitFNEG(N); 1590 case ISD::FABS: return visitFABS(N); 1591 case ISD::FFLOOR: return visitFFLOOR(N); 1592 case ISD::FMINNUM: return visitFMINNUM(N); 1593 case ISD::FMAXNUM: return visitFMAXNUM(N); 1594 case ISD::FCEIL: return visitFCEIL(N); 1595 case ISD::FTRUNC: return visitFTRUNC(N); 1596 case ISD::BRCOND: return visitBRCOND(N); 1597 case ISD::BR_CC: return visitBR_CC(N); 1598 case ISD::LOAD: return visitLOAD(N); 1599 case ISD::STORE: return visitSTORE(N); 1600 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1601 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1602 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1603 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1604 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1605 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1606 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1607 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1608 case ISD::MGATHER: return visitMGATHER(N); 1609 case ISD::MLOAD: return visitMLOAD(N); 1610 case ISD::MSCATTER: return visitMSCATTER(N); 1611 case ISD::MSTORE: return visitMSTORE(N); 1612 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1613 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1614 } 1615 return SDValue(); 1616 } 1617 1618 SDValue DAGCombiner::combine(SDNode *N) { 1619 SDValue RV = visit(N); 1620 1621 // If nothing happened, try a target-specific DAG combine. 1622 if (!RV.getNode()) { 1623 assert(N->getOpcode() != ISD::DELETED_NODE && 1624 "Node was deleted but visit returned NULL!"); 1625 1626 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1627 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1628 1629 // Expose the DAG combiner to the target combiner impls. 1630 TargetLowering::DAGCombinerInfo 1631 DagCombineInfo(DAG, Level, false, this); 1632 1633 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1634 } 1635 } 1636 1637 // If nothing happened still, try promoting the operation. 1638 if (!RV.getNode()) { 1639 switch (N->getOpcode()) { 1640 default: break; 1641 case ISD::ADD: 1642 case ISD::SUB: 1643 case ISD::MUL: 1644 case ISD::AND: 1645 case ISD::OR: 1646 case ISD::XOR: 1647 RV = PromoteIntBinOp(SDValue(N, 0)); 1648 break; 1649 case ISD::SHL: 1650 case ISD::SRA: 1651 case ISD::SRL: 1652 RV = PromoteIntShiftOp(SDValue(N, 0)); 1653 break; 1654 case ISD::SIGN_EXTEND: 1655 case ISD::ZERO_EXTEND: 1656 case ISD::ANY_EXTEND: 1657 RV = PromoteExtend(SDValue(N, 0)); 1658 break; 1659 case ISD::LOAD: 1660 if (PromoteLoad(SDValue(N, 0))) 1661 RV = SDValue(N, 0); 1662 break; 1663 } 1664 } 1665 1666 // If N is a commutative binary node, try eliminate it if the commuted 1667 // version is already present in the DAG. 1668 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) && 1669 N->getNumValues() == 1) { 1670 SDValue N0 = N->getOperand(0); 1671 SDValue N1 = N->getOperand(1); 1672 1673 // Constant operands are canonicalized to RHS. 1674 if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) { 1675 SDValue Ops[] = {N1, N0}; 1676 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1677 N->getFlags()); 1678 if (CSENode) 1679 return SDValue(CSENode, 0); 1680 } 1681 } 1682 1683 return RV; 1684 } 1685 1686 /// Given a node, return its input chain if it has one, otherwise return a null 1687 /// sd operand. 1688 static SDValue getInputChainForNode(SDNode *N) { 1689 if (unsigned NumOps = N->getNumOperands()) { 1690 if (N->getOperand(0).getValueType() == MVT::Other) 1691 return N->getOperand(0); 1692 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1693 return N->getOperand(NumOps-1); 1694 for (unsigned i = 1; i < NumOps-1; ++i) 1695 if (N->getOperand(i).getValueType() == MVT::Other) 1696 return N->getOperand(i); 1697 } 1698 return SDValue(); 1699 } 1700 1701 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1702 // If N has two operands, where one has an input chain equal to the other, 1703 // the 'other' chain is redundant. 1704 if (N->getNumOperands() == 2) { 1705 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1706 return N->getOperand(0); 1707 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1708 return N->getOperand(1); 1709 } 1710 1711 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1712 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1713 SmallPtrSet<SDNode*, 16> SeenOps; 1714 bool Changed = false; // If we should replace this token factor. 1715 1716 // Start out with this token factor. 1717 TFs.push_back(N); 1718 1719 // Iterate through token factors. The TFs grows when new token factors are 1720 // encountered. 1721 for (unsigned i = 0; i < TFs.size(); ++i) { 1722 SDNode *TF = TFs[i]; 1723 1724 // Check each of the operands. 1725 for (const SDValue &Op : TF->op_values()) { 1726 switch (Op.getOpcode()) { 1727 case ISD::EntryToken: 1728 // Entry tokens don't need to be added to the list. They are 1729 // redundant. 1730 Changed = true; 1731 break; 1732 1733 case ISD::TokenFactor: 1734 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) { 1735 // Queue up for processing. 1736 TFs.push_back(Op.getNode()); 1737 // Clean up in case the token factor is removed. 1738 AddToWorklist(Op.getNode()); 1739 Changed = true; 1740 break; 1741 } 1742 LLVM_FALLTHROUGH; 1743 1744 default: 1745 // Only add if it isn't already in the list. 1746 if (SeenOps.insert(Op.getNode()).second) 1747 Ops.push_back(Op); 1748 else 1749 Changed = true; 1750 break; 1751 } 1752 } 1753 } 1754 1755 // Remove Nodes that are chained to another node in the list. Do so 1756 // by walking up chains breath-first stopping when we've seen 1757 // another operand. In general we must climb to the EntryNode, but we can exit 1758 // early if we find all remaining work is associated with just one operand as 1759 // no further pruning is possible. 1760 1761 // List of nodes to search through and original Ops from which they originate. 1762 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist; 1763 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op. 1764 SmallPtrSet<SDNode *, 16> SeenChains; 1765 bool DidPruneOps = false; 1766 1767 unsigned NumLeftToConsider = 0; 1768 for (const SDValue &Op : Ops) { 1769 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++)); 1770 OpWorkCount.push_back(1); 1771 } 1772 1773 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) { 1774 // If this is an Op, we can remove the op from the list. Remark any 1775 // search associated with it as from the current OpNumber. 1776 if (SeenOps.count(Op) != 0) { 1777 Changed = true; 1778 DidPruneOps = true; 1779 unsigned OrigOpNumber = 0; 1780 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op) 1781 OrigOpNumber++; 1782 assert((OrigOpNumber != Ops.size()) && 1783 "expected to find TokenFactor Operand"); 1784 // Re-mark worklist from OrigOpNumber to OpNumber 1785 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) { 1786 if (Worklist[i].second == OrigOpNumber) { 1787 Worklist[i].second = OpNumber; 1788 } 1789 } 1790 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber]; 1791 OpWorkCount[OrigOpNumber] = 0; 1792 NumLeftToConsider--; 1793 } 1794 // Add if it's a new chain 1795 if (SeenChains.insert(Op).second) { 1796 OpWorkCount[OpNumber]++; 1797 Worklist.push_back(std::make_pair(Op, OpNumber)); 1798 } 1799 }; 1800 1801 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) { 1802 // We need at least be consider at least 2 Ops to prune. 1803 if (NumLeftToConsider <= 1) 1804 break; 1805 auto CurNode = Worklist[i].first; 1806 auto CurOpNumber = Worklist[i].second; 1807 assert((OpWorkCount[CurOpNumber] > 0) && 1808 "Node should not appear in worklist"); 1809 switch (CurNode->getOpcode()) { 1810 case ISD::EntryToken: 1811 // Hitting EntryToken is the only way for the search to terminate without 1812 // hitting 1813 // another operand's search. Prevent us from marking this operand 1814 // considered. 1815 NumLeftToConsider++; 1816 break; 1817 case ISD::TokenFactor: 1818 for (const SDValue &Op : CurNode->op_values()) 1819 AddToWorklist(i, Op.getNode(), CurOpNumber); 1820 break; 1821 case ISD::CopyFromReg: 1822 case ISD::CopyToReg: 1823 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber); 1824 break; 1825 default: 1826 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode)) 1827 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber); 1828 break; 1829 } 1830 OpWorkCount[CurOpNumber]--; 1831 if (OpWorkCount[CurOpNumber] == 0) 1832 NumLeftToConsider--; 1833 } 1834 1835 // If we've changed things around then replace token factor. 1836 if (Changed) { 1837 SDValue Result; 1838 if (Ops.empty()) { 1839 // The entry token is the only possible outcome. 1840 Result = DAG.getEntryNode(); 1841 } else { 1842 if (DidPruneOps) { 1843 SmallVector<SDValue, 8> PrunedOps; 1844 // 1845 for (const SDValue &Op : Ops) { 1846 if (SeenChains.count(Op.getNode()) == 0) 1847 PrunedOps.push_back(Op); 1848 } 1849 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps); 1850 } else { 1851 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1852 } 1853 } 1854 return Result; 1855 } 1856 return SDValue(); 1857 } 1858 1859 /// MERGE_VALUES can always be eliminated. 1860 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1861 WorklistRemover DeadNodes(*this); 1862 // Replacing results may cause a different MERGE_VALUES to suddenly 1863 // be CSE'd with N, and carry its uses with it. Iterate until no 1864 // uses remain, to ensure that the node can be safely deleted. 1865 // First add the users of this node to the work list so that they 1866 // can be tried again once they have new operands. 1867 AddUsersToWorklist(N); 1868 do { 1869 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1870 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1871 } while (!N->use_empty()); 1872 deleteAndRecombine(N); 1873 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1874 } 1875 1876 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1877 /// ConstantSDNode pointer else nullptr. 1878 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1879 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1880 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1881 } 1882 1883 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) { 1884 auto BinOpcode = BO->getOpcode(); 1885 assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB || 1886 BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV || 1887 BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || 1888 BinOpcode == ISD::UREM || BinOpcode == ISD::AND || 1889 BinOpcode == ISD::OR || BinOpcode == ISD::XOR || 1890 BinOpcode == ISD::SHL || BinOpcode == ISD::SRL || 1891 BinOpcode == ISD::SRA || BinOpcode == ISD::FADD || 1892 BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || 1893 BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) && 1894 "Unexpected binary operator"); 1895 1896 // Bail out if any constants are opaque because we can't constant fold those. 1897 SDValue C1 = BO->getOperand(1); 1898 if (!isConstantOrConstantVector(C1, true) && 1899 !isConstantFPBuildVectorOrConstantFP(C1)) 1900 return SDValue(); 1901 1902 // Don't do this unless the old select is going away. We want to eliminate the 1903 // binary operator, not replace a binop with a select. 1904 // TODO: Handle ISD::SELECT_CC. 1905 SDValue Sel = BO->getOperand(0); 1906 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) 1907 return SDValue(); 1908 1909 SDValue CT = Sel.getOperand(1); 1910 if (!isConstantOrConstantVector(CT, true) && 1911 !isConstantFPBuildVectorOrConstantFP(CT)) 1912 return SDValue(); 1913 1914 SDValue CF = Sel.getOperand(2); 1915 if (!isConstantOrConstantVector(CF, true) && 1916 !isConstantFPBuildVectorOrConstantFP(CF)) 1917 return SDValue(); 1918 1919 // We have a select-of-constants followed by a binary operator with a 1920 // constant. Eliminate the binop by pulling the constant math into the select. 1921 // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1 1922 EVT VT = Sel.getValueType(); 1923 SDLoc DL(Sel); 1924 SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1); 1925 if (!NewCT.isUndef() && 1926 !isConstantOrConstantVector(NewCT, true) && 1927 !isConstantFPBuildVectorOrConstantFP(NewCT)) 1928 return SDValue(); 1929 1930 SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1); 1931 if (!NewCF.isUndef() && 1932 !isConstantOrConstantVector(NewCF, true) && 1933 !isConstantFPBuildVectorOrConstantFP(NewCF)) 1934 return SDValue(); 1935 1936 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF); 1937 } 1938 1939 SDValue DAGCombiner::visitADD(SDNode *N) { 1940 SDValue N0 = N->getOperand(0); 1941 SDValue N1 = N->getOperand(1); 1942 EVT VT = N0.getValueType(); 1943 SDLoc DL(N); 1944 1945 // fold vector ops 1946 if (VT.isVector()) { 1947 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1948 return FoldedVOp; 1949 1950 // fold (add x, 0) -> x, vector edition 1951 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1952 return N0; 1953 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1954 return N1; 1955 } 1956 1957 // fold (add x, undef) -> undef 1958 if (N0.isUndef()) 1959 return N0; 1960 1961 if (N1.isUndef()) 1962 return N1; 1963 1964 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 1965 // canonicalize constant to RHS 1966 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 1967 return DAG.getNode(ISD::ADD, DL, VT, N1, N0); 1968 // fold (add c1, c2) -> c1+c2 1969 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(), 1970 N1.getNode()); 1971 } 1972 1973 // fold (add x, 0) -> x 1974 if (isNullConstant(N1)) 1975 return N0; 1976 1977 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) { 1978 // fold ((c1-A)+c2) -> (c1+c2)-A 1979 if (N0.getOpcode() == ISD::SUB && 1980 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) { 1981 // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic. 1982 return DAG.getNode(ISD::SUB, DL, VT, 1983 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)), 1984 N0.getOperand(1)); 1985 } 1986 1987 // add (sext i1 X), 1 -> zext (not i1 X) 1988 // We don't transform this pattern: 1989 // add (zext i1 X), -1 -> sext (not i1 X) 1990 // because most (?) targets generate better code for the zext form. 1991 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() && 1992 isOneConstantOrOneSplatConstant(N1)) { 1993 SDValue X = N0.getOperand(0); 1994 if ((!LegalOperations || 1995 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) && 1996 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) && 1997 X.getScalarValueSizeInBits() == 1) { 1998 SDValue Not = DAG.getNOT(DL, X, X.getValueType()); 1999 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not); 2000 } 2001 } 2002 2003 // Undo the add -> or combine to merge constant offsets from a frame index. 2004 if (N0.getOpcode() == ISD::OR && 2005 isa<FrameIndexSDNode>(N0.getOperand(0)) && 2006 isa<ConstantSDNode>(N0.getOperand(1)) && 2007 DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) { 2008 SDValue Add0 = DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(1)); 2009 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0); 2010 } 2011 } 2012 2013 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2014 return NewSel; 2015 2016 // reassociate add 2017 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1)) 2018 return RADD; 2019 2020 // fold ((0-A) + B) -> B-A 2021 if (N0.getOpcode() == ISD::SUB && 2022 isNullConstantOrNullSplatConstant(N0.getOperand(0))) 2023 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); 2024 2025 // fold (A + (0-B)) -> A-B 2026 if (N1.getOpcode() == ISD::SUB && 2027 isNullConstantOrNullSplatConstant(N1.getOperand(0))) 2028 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1)); 2029 2030 // fold (A+(B-A)) -> B 2031 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 2032 return N1.getOperand(0); 2033 2034 // fold ((B-A)+A) -> B 2035 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 2036 return N0.getOperand(0); 2037 2038 // fold (A+(B-(A+C))) to (B-C) 2039 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 2040 N0 == N1.getOperand(1).getOperand(0)) 2041 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2042 N1.getOperand(1).getOperand(1)); 2043 2044 // fold (A+(B-(C+A))) to (B-C) 2045 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 2046 N0 == N1.getOperand(1).getOperand(1)) 2047 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2048 N1.getOperand(1).getOperand(0)); 2049 2050 // fold (A+((B-A)+or-C)) to (B+or-C) 2051 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 2052 N1.getOperand(0).getOpcode() == ISD::SUB && 2053 N0 == N1.getOperand(0).getOperand(1)) 2054 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0), 2055 N1.getOperand(1)); 2056 2057 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 2058 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 2059 SDValue N00 = N0.getOperand(0); 2060 SDValue N01 = N0.getOperand(1); 2061 SDValue N10 = N1.getOperand(0); 2062 SDValue N11 = N1.getOperand(1); 2063 2064 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10)) 2065 return DAG.getNode(ISD::SUB, DL, VT, 2066 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 2067 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 2068 } 2069 2070 if (SimplifyDemandedBits(SDValue(N, 0))) 2071 return SDValue(N, 0); 2072 2073 // fold (a+b) -> (a|b) iff a and b share no bits. 2074 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 2075 DAG.haveNoCommonBitsSet(N0, N1)) 2076 return DAG.getNode(ISD::OR, DL, VT, N0, N1); 2077 2078 if (SDValue Combined = visitADDLike(N0, N1, N)) 2079 return Combined; 2080 2081 if (SDValue Combined = visitADDLike(N1, N0, N)) 2082 return Combined; 2083 2084 return SDValue(); 2085 } 2086 2087 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) { 2088 bool Masked = false; 2089 2090 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization. 2091 while (true) { 2092 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) { 2093 V = V.getOperand(0); 2094 continue; 2095 } 2096 2097 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) { 2098 Masked = true; 2099 V = V.getOperand(0); 2100 continue; 2101 } 2102 2103 break; 2104 } 2105 2106 // If this is not a carry, return. 2107 if (V.getResNo() != 1) 2108 return SDValue(); 2109 2110 if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY && 2111 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO) 2112 return SDValue(); 2113 2114 // If the result is masked, then no matter what kind of bool it is we can 2115 // return. If it isn't, then we need to make sure the bool type is either 0 or 2116 // 1 and not other values. 2117 if (Masked || 2118 TLI.getBooleanContents(V.getValueType()) == 2119 TargetLoweringBase::ZeroOrOneBooleanContent) 2120 return V; 2121 2122 return SDValue(); 2123 } 2124 2125 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) { 2126 EVT VT = N0.getValueType(); 2127 SDLoc DL(LocReference); 2128 2129 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 2130 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 2131 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0))) 2132 return DAG.getNode(ISD::SUB, DL, VT, N0, 2133 DAG.getNode(ISD::SHL, DL, VT, 2134 N1.getOperand(0).getOperand(1), 2135 N1.getOperand(1))); 2136 2137 if (N1.getOpcode() == ISD::AND) { 2138 SDValue AndOp0 = N1.getOperand(0); 2139 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 2140 unsigned DestBits = VT.getScalarSizeInBits(); 2141 2142 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 2143 // and similar xforms where the inner op is either ~0 or 0. 2144 if (NumSignBits == DestBits && 2145 isOneConstantOrOneSplatConstant(N1->getOperand(1))) 2146 return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0); 2147 } 2148 2149 // add (sext i1), X -> sub X, (zext i1) 2150 if (N0.getOpcode() == ISD::SIGN_EXTEND && 2151 N0.getOperand(0).getValueType() == MVT::i1 && 2152 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 2153 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 2154 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 2155 } 2156 2157 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 2158 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2159 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2160 if (TN->getVT() == MVT::i1) { 2161 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2162 DAG.getConstant(1, DL, VT)); 2163 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 2164 } 2165 } 2166 2167 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2168 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) && 2169 N1.getResNo() == 0) 2170 return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(), 2171 N0, N1.getOperand(0), N1.getOperand(2)); 2172 2173 // (add X, Carry) -> (addcarry X, 0, Carry) 2174 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2175 if (SDValue Carry = getAsCarry(TLI, N1)) 2176 return DAG.getNode(ISD::ADDCARRY, DL, 2177 DAG.getVTList(VT, Carry.getValueType()), N0, 2178 DAG.getConstant(0, DL, VT), Carry); 2179 2180 return SDValue(); 2181 } 2182 2183 SDValue DAGCombiner::visitADDC(SDNode *N) { 2184 SDValue N0 = N->getOperand(0); 2185 SDValue N1 = N->getOperand(1); 2186 EVT VT = N0.getValueType(); 2187 SDLoc DL(N); 2188 2189 // If the flag result is dead, turn this into an ADD. 2190 if (!N->hasAnyUseOfValue(1)) 2191 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2192 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2193 2194 // canonicalize constant to RHS. 2195 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2196 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2197 if (N0C && !N1C) 2198 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0); 2199 2200 // fold (addc x, 0) -> x + no carry out 2201 if (isNullConstant(N1)) 2202 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 2203 DL, MVT::Glue)); 2204 2205 // If it cannot overflow, transform into an add. 2206 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2207 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2208 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2209 2210 return SDValue(); 2211 } 2212 2213 SDValue DAGCombiner::visitUADDO(SDNode *N) { 2214 SDValue N0 = N->getOperand(0); 2215 SDValue N1 = N->getOperand(1); 2216 EVT VT = N0.getValueType(); 2217 if (VT.isVector()) 2218 return SDValue(); 2219 2220 EVT CarryVT = N->getValueType(1); 2221 SDLoc DL(N); 2222 2223 // If the flag result is dead, turn this into an ADD. 2224 if (!N->hasAnyUseOfValue(1)) 2225 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2226 DAG.getUNDEF(CarryVT)); 2227 2228 // canonicalize constant to RHS. 2229 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2230 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2231 if (N0C && !N1C) 2232 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0); 2233 2234 // fold (uaddo x, 0) -> x + no carry out 2235 if (isNullConstant(N1)) 2236 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2237 2238 // If it cannot overflow, transform into an add. 2239 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2240 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2241 DAG.getConstant(0, DL, CarryVT)); 2242 2243 if (SDValue Combined = visitUADDOLike(N0, N1, N)) 2244 return Combined; 2245 2246 if (SDValue Combined = visitUADDOLike(N1, N0, N)) 2247 return Combined; 2248 2249 return SDValue(); 2250 } 2251 2252 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) { 2253 auto VT = N0.getValueType(); 2254 2255 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2256 // If Y + 1 cannot overflow. 2257 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) { 2258 SDValue Y = N1.getOperand(0); 2259 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType()); 2260 if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never) 2261 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y, 2262 N1.getOperand(2)); 2263 } 2264 2265 // (uaddo X, Carry) -> (addcarry X, 0, Carry) 2266 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2267 if (SDValue Carry = getAsCarry(TLI, N1)) 2268 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, 2269 DAG.getConstant(0, SDLoc(N), VT), Carry); 2270 2271 return SDValue(); 2272 } 2273 2274 SDValue DAGCombiner::visitADDE(SDNode *N) { 2275 SDValue N0 = N->getOperand(0); 2276 SDValue N1 = N->getOperand(1); 2277 SDValue CarryIn = N->getOperand(2); 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::ADDE, SDLoc(N), N->getVTList(), 2284 N1, N0, CarryIn); 2285 2286 // fold (adde x, y, false) -> (addc x, y) 2287 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2288 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 2289 2290 return SDValue(); 2291 } 2292 2293 SDValue DAGCombiner::visitADDCARRY(SDNode *N) { 2294 SDValue N0 = N->getOperand(0); 2295 SDValue N1 = N->getOperand(1); 2296 SDValue CarryIn = N->getOperand(2); 2297 SDLoc DL(N); 2298 2299 // canonicalize constant to RHS 2300 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2301 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2302 if (N0C && !N1C) 2303 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn); 2304 2305 // fold (addcarry x, y, false) -> (uaddo x, y) 2306 if (isNullConstant(CarryIn)) 2307 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1); 2308 2309 // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry. 2310 if (isNullConstant(N0) && isNullConstant(N1)) { 2311 EVT VT = N0.getValueType(); 2312 EVT CarryVT = CarryIn.getValueType(); 2313 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT); 2314 AddToWorklist(CarryExt.getNode()); 2315 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt, 2316 DAG.getConstant(1, DL, VT)), 2317 DAG.getConstant(0, DL, CarryVT)); 2318 } 2319 2320 if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N)) 2321 return Combined; 2322 2323 if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N)) 2324 return Combined; 2325 2326 return SDValue(); 2327 } 2328 2329 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, 2330 SDNode *N) { 2331 // Iff the flag result is dead: 2332 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry) 2333 if ((N0.getOpcode() == ISD::ADD || 2334 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) && 2335 isNullConstant(N1) && !N->hasAnyUseOfValue(1)) 2336 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), 2337 N0.getOperand(0), N0.getOperand(1), CarryIn); 2338 2339 /** 2340 * When one of the addcarry argument is itself a carry, we may be facing 2341 * a diamond carry propagation. In which case we try to transform the DAG 2342 * to ensure linear carry propagation if that is possible. 2343 * 2344 * We are trying to get: 2345 * (addcarry X, 0, (addcarry A, B, Z):Carry) 2346 */ 2347 if (auto Y = getAsCarry(TLI, N1)) { 2348 /** 2349 * (uaddo A, B) 2350 * / \ 2351 * Carry Sum 2352 * | \ 2353 * | (addcarry *, 0, Z) 2354 * | / 2355 * \ Carry 2356 * | / 2357 * (addcarry X, *, *) 2358 */ 2359 if (Y.getOpcode() == ISD::UADDO && 2360 CarryIn.getResNo() == 1 && 2361 CarryIn.getOpcode() == ISD::ADDCARRY && 2362 isNullConstant(CarryIn.getOperand(1)) && 2363 CarryIn.getOperand(0) == Y.getValue(0)) { 2364 auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(), 2365 Y.getOperand(0), Y.getOperand(1), 2366 CarryIn.getOperand(2)); 2367 AddToWorklist(NewY.getNode()); 2368 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, 2369 DAG.getConstant(0, SDLoc(N), N0.getValueType()), 2370 NewY.getValue(1)); 2371 } 2372 } 2373 2374 return SDValue(); 2375 } 2376 2377 // Since it may not be valid to emit a fold to zero for vector initializers 2378 // check if we can before folding. 2379 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 2380 SelectionDAG &DAG, bool LegalOperations, 2381 bool LegalTypes) { 2382 if (!VT.isVector()) 2383 return DAG.getConstant(0, DL, VT); 2384 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 2385 return DAG.getConstant(0, DL, VT); 2386 return SDValue(); 2387 } 2388 2389 SDValue DAGCombiner::visitSUB(SDNode *N) { 2390 SDValue N0 = N->getOperand(0); 2391 SDValue N1 = N->getOperand(1); 2392 EVT VT = N0.getValueType(); 2393 SDLoc DL(N); 2394 2395 // fold vector ops 2396 if (VT.isVector()) { 2397 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2398 return FoldedVOp; 2399 2400 // fold (sub x, 0) -> x, vector edition 2401 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2402 return N0; 2403 } 2404 2405 // fold (sub x, x) -> 0 2406 // FIXME: Refactor this and xor and other similar operations together. 2407 if (N0 == N1) 2408 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes); 2409 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2410 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 2411 // fold (sub c1, c2) -> c1-c2 2412 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(), 2413 N1.getNode()); 2414 } 2415 2416 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2417 return NewSel; 2418 2419 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2420 2421 // fold (sub x, c) -> (add x, -c) 2422 if (N1C) { 2423 return DAG.getNode(ISD::ADD, DL, VT, N0, 2424 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 2425 } 2426 2427 if (isNullConstantOrNullSplatConstant(N0)) { 2428 unsigned BitWidth = VT.getScalarSizeInBits(); 2429 // Right-shifting everything out but the sign bit followed by negation is 2430 // the same as flipping arithmetic/logical shift type without the negation: 2431 // -(X >>u 31) -> (X >>s 31) 2432 // -(X >>s 31) -> (X >>u 31) 2433 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) { 2434 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1)); 2435 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) { 2436 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA; 2437 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT)) 2438 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1)); 2439 } 2440 } 2441 2442 // 0 - X --> 0 if the sub is NUW. 2443 if (N->getFlags().hasNoUnsignedWrap()) 2444 return N0; 2445 2446 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) { 2447 // N1 is either 0 or the minimum signed value. If the sub is NSW, then 2448 // N1 must be 0 because negating the minimum signed value is undefined. 2449 if (N->getFlags().hasNoSignedWrap()) 2450 return N0; 2451 2452 // 0 - X --> X if X is 0 or the minimum signed value. 2453 return N1; 2454 } 2455 } 2456 2457 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 2458 if (isAllOnesConstantOrAllOnesSplatConstant(N0)) 2459 return DAG.getNode(ISD::XOR, DL, VT, N1, N0); 2460 2461 // fold A-(A-B) -> B 2462 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 2463 return N1.getOperand(1); 2464 2465 // fold (A+B)-A -> B 2466 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 2467 return N0.getOperand(1); 2468 2469 // fold (A+B)-B -> A 2470 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 2471 return N0.getOperand(0); 2472 2473 // fold C2-(A+C1) -> (C2-C1)-A 2474 if (N1.getOpcode() == ISD::ADD) { 2475 SDValue N11 = N1.getOperand(1); 2476 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) && 2477 isConstantOrConstantVector(N11, /* NoOpaques */ true)) { 2478 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11); 2479 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0)); 2480 } 2481 } 2482 2483 // fold ((A+(B+or-C))-B) -> A+or-C 2484 if (N0.getOpcode() == ISD::ADD && 2485 (N0.getOperand(1).getOpcode() == ISD::SUB || 2486 N0.getOperand(1).getOpcode() == ISD::ADD) && 2487 N0.getOperand(1).getOperand(0) == N1) 2488 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0), 2489 N0.getOperand(1).getOperand(1)); 2490 2491 // fold ((A+(C+B))-B) -> A+C 2492 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD && 2493 N0.getOperand(1).getOperand(1) == N1) 2494 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), 2495 N0.getOperand(1).getOperand(0)); 2496 2497 // fold ((A-(B-C))-C) -> A-B 2498 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB && 2499 N0.getOperand(1).getOperand(1) == N1) 2500 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), 2501 N0.getOperand(1).getOperand(0)); 2502 2503 // If either operand of a sub is undef, the result is undef 2504 if (N0.isUndef()) 2505 return N0; 2506 if (N1.isUndef()) 2507 return N1; 2508 2509 // If the relocation model supports it, consider symbol offsets. 2510 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 2511 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 2512 // fold (sub Sym, c) -> Sym-c 2513 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 2514 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 2515 GA->getOffset() - 2516 (uint64_t)N1C->getSExtValue()); 2517 // fold (sub Sym+c1, Sym+c2) -> c1-c2 2518 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 2519 if (GA->getGlobal() == GB->getGlobal()) 2520 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 2521 DL, VT); 2522 } 2523 2524 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 2525 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2526 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2527 if (TN->getVT() == MVT::i1) { 2528 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2529 DAG.getConstant(1, DL, VT)); 2530 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 2531 } 2532 } 2533 2534 return SDValue(); 2535 } 2536 2537 SDValue DAGCombiner::visitSUBC(SDNode *N) { 2538 SDValue N0 = N->getOperand(0); 2539 SDValue N1 = N->getOperand(1); 2540 EVT VT = N0.getValueType(); 2541 SDLoc DL(N); 2542 2543 // If the flag result is dead, turn this into an SUB. 2544 if (!N->hasAnyUseOfValue(1)) 2545 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2546 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2547 2548 // fold (subc x, x) -> 0 + no borrow 2549 if (N0 == N1) 2550 return CombineTo(N, DAG.getConstant(0, DL, VT), 2551 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2552 2553 // fold (subc x, 0) -> x + no borrow 2554 if (isNullConstant(N1)) 2555 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2556 2557 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2558 if (isAllOnesConstant(N0)) 2559 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2560 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2561 2562 return SDValue(); 2563 } 2564 2565 SDValue DAGCombiner::visitUSUBO(SDNode *N) { 2566 SDValue N0 = N->getOperand(0); 2567 SDValue N1 = N->getOperand(1); 2568 EVT VT = N0.getValueType(); 2569 if (VT.isVector()) 2570 return SDValue(); 2571 2572 EVT CarryVT = N->getValueType(1); 2573 SDLoc DL(N); 2574 2575 // If the flag result is dead, turn this into an SUB. 2576 if (!N->hasAnyUseOfValue(1)) 2577 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2578 DAG.getUNDEF(CarryVT)); 2579 2580 // fold (usubo x, x) -> 0 + no borrow 2581 if (N0 == N1) 2582 return CombineTo(N, DAG.getConstant(0, DL, VT), 2583 DAG.getConstant(0, DL, CarryVT)); 2584 2585 // fold (usubo x, 0) -> x + no borrow 2586 if (isNullConstant(N1)) 2587 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2588 2589 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2590 if (isAllOnesConstant(N0)) 2591 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2592 DAG.getConstant(0, DL, CarryVT)); 2593 2594 return SDValue(); 2595 } 2596 2597 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2598 SDValue N0 = N->getOperand(0); 2599 SDValue N1 = N->getOperand(1); 2600 SDValue CarryIn = N->getOperand(2); 2601 2602 // fold (sube x, y, false) -> (subc x, y) 2603 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2604 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2605 2606 return SDValue(); 2607 } 2608 2609 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) { 2610 SDValue N0 = N->getOperand(0); 2611 SDValue N1 = N->getOperand(1); 2612 SDValue CarryIn = N->getOperand(2); 2613 2614 // fold (subcarry x, y, false) -> (usubo x, y) 2615 if (isNullConstant(CarryIn)) 2616 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1); 2617 2618 return SDValue(); 2619 } 2620 2621 SDValue DAGCombiner::visitMUL(SDNode *N) { 2622 SDValue N0 = N->getOperand(0); 2623 SDValue N1 = N->getOperand(1); 2624 EVT VT = N0.getValueType(); 2625 2626 // fold (mul x, undef) -> 0 2627 if (N0.isUndef() || N1.isUndef()) 2628 return DAG.getConstant(0, SDLoc(N), VT); 2629 2630 bool N0IsConst = false; 2631 bool N1IsConst = false; 2632 bool N1IsOpaqueConst = false; 2633 bool N0IsOpaqueConst = false; 2634 APInt ConstValue0, ConstValue1; 2635 // fold vector ops 2636 if (VT.isVector()) { 2637 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2638 return FoldedVOp; 2639 2640 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0); 2641 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 2642 assert((!N0IsConst || 2643 ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) && 2644 "Splat APInt should be element width"); 2645 assert((!N1IsConst || 2646 ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) && 2647 "Splat APInt should be element width"); 2648 } else { 2649 N0IsConst = isa<ConstantSDNode>(N0); 2650 if (N0IsConst) { 2651 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2652 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2653 } 2654 N1IsConst = isa<ConstantSDNode>(N1); 2655 if (N1IsConst) { 2656 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2657 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2658 } 2659 } 2660 2661 // fold (mul c1, c2) -> c1*c2 2662 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2663 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2664 N0.getNode(), N1.getNode()); 2665 2666 // canonicalize constant to RHS (vector doesn't have to splat) 2667 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2668 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2669 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2670 // fold (mul x, 0) -> 0 2671 if (N1IsConst && ConstValue1.isNullValue()) 2672 return N1; 2673 // fold (mul x, 1) -> x 2674 if (N1IsConst && ConstValue1.isOneValue()) 2675 return N0; 2676 2677 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2678 return NewSel; 2679 2680 // fold (mul x, -1) -> 0-x 2681 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2682 SDLoc DL(N); 2683 return DAG.getNode(ISD::SUB, DL, VT, 2684 DAG.getConstant(0, DL, VT), N0); 2685 } 2686 // fold (mul x, (1 << c)) -> x << c 2687 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 2688 DAG.isKnownToBeAPowerOfTwo(N1) && 2689 (!VT.isVector() || Level <= AfterLegalizeVectorOps)) { 2690 SDLoc DL(N); 2691 SDValue LogBase2 = BuildLogBase2(N1, DL); 2692 AddToWorklist(LogBase2.getNode()); 2693 2694 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 2695 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 2696 AddToWorklist(Trunc.getNode()); 2697 return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc); 2698 } 2699 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2700 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) { 2701 unsigned Log2Val = (-ConstValue1).logBase2(); 2702 SDLoc DL(N); 2703 // FIXME: If the input is something that is easily negated (e.g. a 2704 // single-use add), we should put the negate there. 2705 return DAG.getNode(ISD::SUB, DL, VT, 2706 DAG.getConstant(0, DL, VT), 2707 DAG.getNode(ISD::SHL, DL, VT, N0, 2708 DAG.getConstant(Log2Val, DL, 2709 getShiftAmountTy(N0.getValueType())))); 2710 } 2711 2712 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2713 if (N0.getOpcode() == ISD::SHL && 2714 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 2715 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 2716 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 2717 if (isConstantOrConstantVector(C3)) 2718 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 2719 } 2720 2721 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2722 // use. 2723 { 2724 SDValue Sh(nullptr, 0), Y(nullptr, 0); 2725 2726 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2727 if (N0.getOpcode() == ISD::SHL && 2728 isConstantOrConstantVector(N0.getOperand(1)) && 2729 N0.getNode()->hasOneUse()) { 2730 Sh = N0; Y = N1; 2731 } else if (N1.getOpcode() == ISD::SHL && 2732 isConstantOrConstantVector(N1.getOperand(1)) && 2733 N1.getNode()->hasOneUse()) { 2734 Sh = N1; Y = N0; 2735 } 2736 2737 if (Sh.getNode()) { 2738 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 2739 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 2740 } 2741 } 2742 2743 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2744 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2745 N0.getOpcode() == ISD::ADD && 2746 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2747 isMulAddWithConstProfitable(N, N0, N1)) 2748 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2749 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2750 N0.getOperand(0), N1), 2751 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2752 N0.getOperand(1), N1)); 2753 2754 // reassociate mul 2755 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2756 return RMUL; 2757 2758 return SDValue(); 2759 } 2760 2761 /// Return true if divmod libcall is available. 2762 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2763 const TargetLowering &TLI) { 2764 RTLIB::Libcall LC; 2765 EVT NodeType = Node->getValueType(0); 2766 if (!NodeType.isSimple()) 2767 return false; 2768 switch (NodeType.getSimpleVT().SimpleTy) { 2769 default: return false; // No libcall for vector types. 2770 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2771 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2772 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2773 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2774 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2775 } 2776 2777 return TLI.getLibcallName(LC) != nullptr; 2778 } 2779 2780 /// Issue divrem if both quotient and remainder are needed. 2781 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2782 if (Node->use_empty()) 2783 return SDValue(); // This is a dead node, leave it alone. 2784 2785 unsigned Opcode = Node->getOpcode(); 2786 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2787 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2788 2789 // DivMod lib calls can still work on non-legal types if using lib-calls. 2790 EVT VT = Node->getValueType(0); 2791 if (VT.isVector() || !VT.isInteger()) 2792 return SDValue(); 2793 2794 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 2795 return SDValue(); 2796 2797 // If DIVREM is going to get expanded into a libcall, 2798 // but there is no libcall available, then don't combine. 2799 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2800 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2801 return SDValue(); 2802 2803 // If div is legal, it's better to do the normal expansion 2804 unsigned OtherOpcode = 0; 2805 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2806 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2807 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2808 return SDValue(); 2809 } else { 2810 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2811 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2812 return SDValue(); 2813 } 2814 2815 SDValue Op0 = Node->getOperand(0); 2816 SDValue Op1 = Node->getOperand(1); 2817 SDValue combined; 2818 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2819 UE = Op0.getNode()->use_end(); UI != UE;) { 2820 SDNode *User = *UI++; 2821 if (User == Node || User->use_empty()) 2822 continue; 2823 // Convert the other matching node(s), too; 2824 // otherwise, the DIVREM may get target-legalized into something 2825 // target-specific that we won't be able to recognize. 2826 unsigned UserOpc = User->getOpcode(); 2827 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2828 User->getOperand(0) == Op0 && 2829 User->getOperand(1) == Op1) { 2830 if (!combined) { 2831 if (UserOpc == OtherOpcode) { 2832 SDVTList VTs = DAG.getVTList(VT, VT); 2833 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2834 } else if (UserOpc == DivRemOpc) { 2835 combined = SDValue(User, 0); 2836 } else { 2837 assert(UserOpc == Opcode); 2838 continue; 2839 } 2840 } 2841 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2842 CombineTo(User, combined); 2843 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2844 CombineTo(User, combined.getValue(1)); 2845 } 2846 } 2847 return combined; 2848 } 2849 2850 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) { 2851 SDValue N0 = N->getOperand(0); 2852 SDValue N1 = N->getOperand(1); 2853 EVT VT = N->getValueType(0); 2854 SDLoc DL(N); 2855 2856 if (DAG.isUndef(N->getOpcode(), {N0, N1})) 2857 return DAG.getUNDEF(VT); 2858 2859 // undef / X -> 0 2860 // undef % X -> 0 2861 if (N0.isUndef()) 2862 return DAG.getConstant(0, DL, VT); 2863 2864 return SDValue(); 2865 } 2866 2867 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2868 SDValue N0 = N->getOperand(0); 2869 SDValue N1 = N->getOperand(1); 2870 EVT VT = N->getValueType(0); 2871 2872 // fold vector ops 2873 if (VT.isVector()) 2874 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2875 return FoldedVOp; 2876 2877 SDLoc DL(N); 2878 2879 // fold (sdiv c1, c2) -> c1/c2 2880 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2881 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2882 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2883 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2884 // fold (sdiv X, 1) -> X 2885 if (N1C && N1C->isOne()) 2886 return N0; 2887 // fold (sdiv X, -1) -> 0-X 2888 if (N1C && N1C->isAllOnesValue()) 2889 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0); 2890 2891 if (SDValue V = simplifyDivRem(N, DAG)) 2892 return V; 2893 2894 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2895 return NewSel; 2896 2897 // If we know the sign bits of both operands are zero, strength reduce to a 2898 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2899 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2900 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2901 2902 // fold (sdiv X, pow2) -> simple ops after legalize 2903 // FIXME: We check for the exact bit here because the generic lowering gives 2904 // better results in that case. The target-specific lowering should learn how 2905 // to handle exact sdivs efficiently. 2906 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2907 !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() || 2908 (-N1C->getAPIntValue()).isPowerOf2())) { 2909 // Target-specific implementation of sdiv x, pow2. 2910 if (SDValue Res = BuildSDIVPow2(N)) 2911 return Res; 2912 2913 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2914 2915 // Splat the sign bit into the register 2916 SDValue SGN = 2917 DAG.getNode(ISD::SRA, DL, VT, N0, 2918 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2919 getShiftAmountTy(N0.getValueType()))); 2920 AddToWorklist(SGN.getNode()); 2921 2922 // Add (N0 < 0) ? abs2 - 1 : 0; 2923 SDValue SRL = 2924 DAG.getNode(ISD::SRL, DL, VT, SGN, 2925 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2926 getShiftAmountTy(SGN.getValueType()))); 2927 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2928 AddToWorklist(SRL.getNode()); 2929 AddToWorklist(ADD.getNode()); // Divide by pow2 2930 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2931 DAG.getConstant(lg2, DL, 2932 getShiftAmountTy(ADD.getValueType()))); 2933 2934 // If we're dividing by a positive value, we're done. Otherwise, we must 2935 // negate the result. 2936 if (N1C->getAPIntValue().isNonNegative()) 2937 return SRA; 2938 2939 AddToWorklist(SRA.getNode()); 2940 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2941 } 2942 2943 // If integer divide is expensive and we satisfy the requirements, emit an 2944 // alternate sequence. Targets may check function attributes for size/speed 2945 // trade-offs. 2946 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 2947 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2948 if (SDValue Op = BuildSDIV(N)) 2949 return Op; 2950 2951 // sdiv, srem -> sdivrem 2952 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 2953 // true. Otherwise, we break the simplification logic in visitREM(). 2954 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2955 if (SDValue DivRem = useDivRem(N)) 2956 return DivRem; 2957 2958 return SDValue(); 2959 } 2960 2961 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2962 SDValue N0 = N->getOperand(0); 2963 SDValue N1 = N->getOperand(1); 2964 EVT VT = N->getValueType(0); 2965 2966 // fold vector ops 2967 if (VT.isVector()) 2968 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2969 return FoldedVOp; 2970 2971 SDLoc DL(N); 2972 2973 // fold (udiv c1, c2) -> c1/c2 2974 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2975 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2976 if (N0C && N1C) 2977 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2978 N0C, N1C)) 2979 return Folded; 2980 2981 if (SDValue V = simplifyDivRem(N, DAG)) 2982 return V; 2983 2984 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2985 return NewSel; 2986 2987 // fold (udiv x, (1 << c)) -> x >>u c 2988 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 2989 DAG.isKnownToBeAPowerOfTwo(N1)) { 2990 SDValue LogBase2 = BuildLogBase2(N1, DL); 2991 AddToWorklist(LogBase2.getNode()); 2992 2993 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 2994 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 2995 AddToWorklist(Trunc.getNode()); 2996 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 2997 } 2998 2999 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 3000 if (N1.getOpcode() == ISD::SHL) { 3001 SDValue N10 = N1.getOperand(0); 3002 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) && 3003 DAG.isKnownToBeAPowerOfTwo(N10)) { 3004 SDValue LogBase2 = BuildLogBase2(N10, DL); 3005 AddToWorklist(LogBase2.getNode()); 3006 3007 EVT ADDVT = N1.getOperand(1).getValueType(); 3008 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT); 3009 AddToWorklist(Trunc.getNode()); 3010 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc); 3011 AddToWorklist(Add.getNode()); 3012 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 3013 } 3014 } 3015 3016 // fold (udiv x, c) -> alternate 3017 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3018 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 3019 if (SDValue Op = BuildUDIV(N)) 3020 return Op; 3021 3022 // sdiv, srem -> sdivrem 3023 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 3024 // true. Otherwise, we break the simplification logic in visitREM(). 3025 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 3026 if (SDValue DivRem = useDivRem(N)) 3027 return DivRem; 3028 3029 return SDValue(); 3030 } 3031 3032 // handles ISD::SREM and ISD::UREM 3033 SDValue DAGCombiner::visitREM(SDNode *N) { 3034 unsigned Opcode = N->getOpcode(); 3035 SDValue N0 = N->getOperand(0); 3036 SDValue N1 = N->getOperand(1); 3037 EVT VT = N->getValueType(0); 3038 bool isSigned = (Opcode == ISD::SREM); 3039 SDLoc DL(N); 3040 3041 // fold (rem c1, c2) -> c1%c2 3042 ConstantSDNode *N0C = isConstOrConstSplat(N0); 3043 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3044 if (N0C && N1C) 3045 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 3046 return Folded; 3047 3048 if (SDValue V = simplifyDivRem(N, DAG)) 3049 return V; 3050 3051 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3052 return NewSel; 3053 3054 if (isSigned) { 3055 // If we know the sign bits of both operands are zero, strength reduce to a 3056 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 3057 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 3058 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 3059 } else { 3060 SDValue NegOne = DAG.getAllOnesConstant(DL, VT); 3061 if (DAG.isKnownToBeAPowerOfTwo(N1)) { 3062 // fold (urem x, pow2) -> (and x, pow2-1) 3063 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 3064 AddToWorklist(Add.getNode()); 3065 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 3066 } 3067 if (N1.getOpcode() == ISD::SHL && 3068 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) { 3069 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 3070 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 3071 AddToWorklist(Add.getNode()); 3072 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 3073 } 3074 } 3075 3076 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3077 3078 // If X/C can be simplified by the division-by-constant logic, lower 3079 // X%C to the equivalent of X-X/C*C. 3080 // To avoid mangling nodes, this simplification requires that the combine() 3081 // call for the speculative DIV must not cause a DIVREM conversion. We guard 3082 // against this by skipping the simplification if isIntDivCheap(). When 3083 // div is not cheap, combine will not return a DIVREM. Regardless, 3084 // checking cheapness here makes sense since the simplification results in 3085 // fatter code. 3086 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 3087 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 3088 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 3089 AddToWorklist(Div.getNode()); 3090 SDValue OptimizedDiv = combine(Div.getNode()); 3091 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 3092 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 3093 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 3094 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 3095 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 3096 AddToWorklist(Mul.getNode()); 3097 return Sub; 3098 } 3099 } 3100 3101 // sdiv, srem -> sdivrem 3102 if (SDValue DivRem = useDivRem(N)) 3103 return DivRem.getValue(1); 3104 3105 return SDValue(); 3106 } 3107 3108 SDValue DAGCombiner::visitMULHS(SDNode *N) { 3109 SDValue N0 = N->getOperand(0); 3110 SDValue N1 = N->getOperand(1); 3111 EVT VT = N->getValueType(0); 3112 SDLoc DL(N); 3113 3114 if (VT.isVector()) { 3115 // fold (mulhs x, 0) -> 0 3116 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3117 return N1; 3118 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3119 return N0; 3120 } 3121 3122 // fold (mulhs x, 0) -> 0 3123 if (isNullConstant(N1)) 3124 return N1; 3125 // fold (mulhs x, 1) -> (sra x, size(x)-1) 3126 if (isOneConstant(N1)) 3127 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 3128 DAG.getConstant(N0.getValueSizeInBits() - 1, DL, 3129 getShiftAmountTy(N0.getValueType()))); 3130 3131 // fold (mulhs x, undef) -> 0 3132 if (N0.isUndef() || N1.isUndef()) 3133 return DAG.getConstant(0, DL, VT); 3134 3135 // If the type twice as wide is legal, transform the mulhs to a wider multiply 3136 // plus a shift. 3137 if (VT.isSimple() && !VT.isVector()) { 3138 MVT Simple = VT.getSimpleVT(); 3139 unsigned SimpleSize = Simple.getSizeInBits(); 3140 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3141 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3142 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 3143 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 3144 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 3145 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 3146 DAG.getConstant(SimpleSize, DL, 3147 getShiftAmountTy(N1.getValueType()))); 3148 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 3149 } 3150 } 3151 3152 return SDValue(); 3153 } 3154 3155 SDValue DAGCombiner::visitMULHU(SDNode *N) { 3156 SDValue N0 = N->getOperand(0); 3157 SDValue N1 = N->getOperand(1); 3158 EVT VT = N->getValueType(0); 3159 SDLoc DL(N); 3160 3161 if (VT.isVector()) { 3162 // fold (mulhu x, 0) -> 0 3163 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3164 return N1; 3165 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3166 return N0; 3167 } 3168 3169 // fold (mulhu x, 0) -> 0 3170 if (isNullConstant(N1)) 3171 return N1; 3172 // fold (mulhu x, 1) -> 0 3173 if (isOneConstant(N1)) 3174 return DAG.getConstant(0, DL, N0.getValueType()); 3175 // fold (mulhu x, undef) -> 0 3176 if (N0.isUndef() || N1.isUndef()) 3177 return DAG.getConstant(0, DL, VT); 3178 3179 // If the type twice as wide is legal, transform the mulhu to a wider multiply 3180 // plus a shift. 3181 if (VT.isSimple() && !VT.isVector()) { 3182 MVT Simple = VT.getSimpleVT(); 3183 unsigned SimpleSize = Simple.getSizeInBits(); 3184 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3185 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3186 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 3187 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 3188 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 3189 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 3190 DAG.getConstant(SimpleSize, DL, 3191 getShiftAmountTy(N1.getValueType()))); 3192 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 3193 } 3194 } 3195 3196 return SDValue(); 3197 } 3198 3199 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 3200 /// give the opcodes for the two computations that are being performed. Return 3201 /// true if a simplification was made. 3202 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 3203 unsigned HiOp) { 3204 // If the high half is not needed, just compute the low half. 3205 bool HiExists = N->hasAnyUseOfValue(1); 3206 if (!HiExists && 3207 (!LegalOperations || 3208 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 3209 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 3210 return CombineTo(N, Res, Res); 3211 } 3212 3213 // If the low half is not needed, just compute the high half. 3214 bool LoExists = N->hasAnyUseOfValue(0); 3215 if (!LoExists && 3216 (!LegalOperations || 3217 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 3218 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 3219 return CombineTo(N, Res, Res); 3220 } 3221 3222 // If both halves are used, return as it is. 3223 if (LoExists && HiExists) 3224 return SDValue(); 3225 3226 // If the two computed results can be simplified separately, separate them. 3227 if (LoExists) { 3228 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 3229 AddToWorklist(Lo.getNode()); 3230 SDValue LoOpt = combine(Lo.getNode()); 3231 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 3232 (!LegalOperations || 3233 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 3234 return CombineTo(N, LoOpt, LoOpt); 3235 } 3236 3237 if (HiExists) { 3238 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 3239 AddToWorklist(Hi.getNode()); 3240 SDValue HiOpt = combine(Hi.getNode()); 3241 if (HiOpt.getNode() && HiOpt != Hi && 3242 (!LegalOperations || 3243 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 3244 return CombineTo(N, HiOpt, HiOpt); 3245 } 3246 3247 return SDValue(); 3248 } 3249 3250 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 3251 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 3252 return Res; 3253 3254 EVT VT = N->getValueType(0); 3255 SDLoc DL(N); 3256 3257 // If the type is twice as wide is legal, transform the mulhu to a wider 3258 // multiply plus a shift. 3259 if (VT.isSimple() && !VT.isVector()) { 3260 MVT Simple = VT.getSimpleVT(); 3261 unsigned SimpleSize = Simple.getSizeInBits(); 3262 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3263 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3264 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 3265 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 3266 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3267 // Compute the high part as N1. 3268 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3269 DAG.getConstant(SimpleSize, DL, 3270 getShiftAmountTy(Lo.getValueType()))); 3271 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3272 // Compute the low part as N0. 3273 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3274 return CombineTo(N, Lo, Hi); 3275 } 3276 } 3277 3278 return SDValue(); 3279 } 3280 3281 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 3282 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 3283 return Res; 3284 3285 EVT VT = N->getValueType(0); 3286 SDLoc DL(N); 3287 3288 // If the type is twice as wide is legal, transform the mulhu to a wider 3289 // multiply plus a shift. 3290 if (VT.isSimple() && !VT.isVector()) { 3291 MVT Simple = VT.getSimpleVT(); 3292 unsigned SimpleSize = Simple.getSizeInBits(); 3293 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3294 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3295 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 3296 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 3297 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3298 // Compute the high part as N1. 3299 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3300 DAG.getConstant(SimpleSize, DL, 3301 getShiftAmountTy(Lo.getValueType()))); 3302 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3303 // Compute the low part as N0. 3304 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3305 return CombineTo(N, Lo, Hi); 3306 } 3307 } 3308 3309 return SDValue(); 3310 } 3311 3312 SDValue DAGCombiner::visitSMULO(SDNode *N) { 3313 // (smulo x, 2) -> (saddo x, x) 3314 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 3315 if (C2->getAPIntValue() == 2) 3316 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 3317 N->getOperand(0), N->getOperand(0)); 3318 3319 return SDValue(); 3320 } 3321 3322 SDValue DAGCombiner::visitUMULO(SDNode *N) { 3323 // (umulo x, 2) -> (uaddo x, x) 3324 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 3325 if (C2->getAPIntValue() == 2) 3326 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 3327 N->getOperand(0), N->getOperand(0)); 3328 3329 return SDValue(); 3330 } 3331 3332 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 3333 SDValue N0 = N->getOperand(0); 3334 SDValue N1 = N->getOperand(1); 3335 EVT VT = N0.getValueType(); 3336 3337 // fold vector ops 3338 if (VT.isVector()) 3339 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3340 return FoldedVOp; 3341 3342 // fold operation with constant operands. 3343 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3344 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 3345 if (N0C && N1C) 3346 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 3347 3348 // canonicalize constant to RHS 3349 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3350 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3351 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 3352 3353 return SDValue(); 3354 } 3355 3356 /// If this is a binary operator with two operands of the same opcode, try to 3357 /// simplify it. 3358 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 3359 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 3360 EVT VT = N0.getValueType(); 3361 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 3362 3363 // Bail early if none of these transforms apply. 3364 if (N0.getNumOperands() == 0) return SDValue(); 3365 3366 // For each of OP in AND/OR/XOR: 3367 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 3368 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 3369 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 3370 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 3371 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 3372 // 3373 // do not sink logical op inside of a vector extend, since it may combine 3374 // into a vsetcc. 3375 EVT Op0VT = N0.getOperand(0).getValueType(); 3376 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 3377 N0.getOpcode() == ISD::SIGN_EXTEND || 3378 N0.getOpcode() == ISD::BSWAP || 3379 // Avoid infinite looping with PromoteIntBinOp. 3380 (N0.getOpcode() == ISD::ANY_EXTEND && 3381 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 3382 (N0.getOpcode() == ISD::TRUNCATE && 3383 (!TLI.isZExtFree(VT, Op0VT) || 3384 !TLI.isTruncateFree(Op0VT, VT)) && 3385 TLI.isTypeLegal(Op0VT))) && 3386 !VT.isVector() && 3387 Op0VT == N1.getOperand(0).getValueType() && 3388 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 3389 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 3390 N0.getOperand(0).getValueType(), 3391 N0.getOperand(0), N1.getOperand(0)); 3392 AddToWorklist(ORNode.getNode()); 3393 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 3394 } 3395 3396 // For each of OP in SHL/SRL/SRA/AND... 3397 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 3398 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 3399 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 3400 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 3401 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 3402 N0.getOperand(1) == N1.getOperand(1)) { 3403 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 3404 N0.getOperand(0).getValueType(), 3405 N0.getOperand(0), N1.getOperand(0)); 3406 AddToWorklist(ORNode.getNode()); 3407 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 3408 ORNode, N0.getOperand(1)); 3409 } 3410 3411 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 3412 // Only perform this optimization up until type legalization, before 3413 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 3414 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 3415 // we don't want to undo this promotion. 3416 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 3417 // on scalars. 3418 if ((N0.getOpcode() == ISD::BITCAST || 3419 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 3420 Level <= AfterLegalizeTypes) { 3421 SDValue In0 = N0.getOperand(0); 3422 SDValue In1 = N1.getOperand(0); 3423 EVT In0Ty = In0.getValueType(); 3424 EVT In1Ty = In1.getValueType(); 3425 SDLoc DL(N); 3426 // If both incoming values are integers, and the original types are the 3427 // same. 3428 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 3429 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 3430 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 3431 AddToWorklist(Op.getNode()); 3432 return BC; 3433 } 3434 } 3435 3436 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 3437 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 3438 // If both shuffles use the same mask, and both shuffle within a single 3439 // vector, then it is worthwhile to move the swizzle after the operation. 3440 // The type-legalizer generates this pattern when loading illegal 3441 // vector types from memory. In many cases this allows additional shuffle 3442 // optimizations. 3443 // There are other cases where moving the shuffle after the xor/and/or 3444 // is profitable even if shuffles don't perform a swizzle. 3445 // If both shuffles use the same mask, and both shuffles have the same first 3446 // or second operand, then it might still be profitable to move the shuffle 3447 // after the xor/and/or operation. 3448 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 3449 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 3450 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 3451 3452 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 3453 "Inputs to shuffles are not the same type"); 3454 3455 // Check that both shuffles use the same mask. The masks are known to be of 3456 // the same length because the result vector type is the same. 3457 // Check also that shuffles have only one use to avoid introducing extra 3458 // instructions. 3459 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 3460 SVN0->getMask().equals(SVN1->getMask())) { 3461 SDValue ShOp = N0->getOperand(1); 3462 3463 // Don't try to fold this node if it requires introducing a 3464 // build vector of all zeros that might be illegal at this stage. 3465 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3466 if (!LegalTypes) 3467 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3468 else 3469 ShOp = SDValue(); 3470 } 3471 3472 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 3473 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 3474 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 3475 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 3476 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3477 N0->getOperand(0), N1->getOperand(0)); 3478 AddToWorklist(NewNode.getNode()); 3479 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 3480 SVN0->getMask()); 3481 } 3482 3483 // Don't try to fold this node if it requires introducing a 3484 // build vector of all zeros that might be illegal at this stage. 3485 ShOp = N0->getOperand(0); 3486 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3487 if (!LegalTypes) 3488 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3489 else 3490 ShOp = SDValue(); 3491 } 3492 3493 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 3494 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 3495 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 3496 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 3497 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3498 N0->getOperand(1), N1->getOperand(1)); 3499 AddToWorklist(NewNode.getNode()); 3500 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 3501 SVN0->getMask()); 3502 } 3503 } 3504 } 3505 3506 return SDValue(); 3507 } 3508 3509 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient. 3510 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 3511 const SDLoc &DL) { 3512 SDValue LL, LR, RL, RR, N0CC, N1CC; 3513 if (!isSetCCEquivalent(N0, LL, LR, N0CC) || 3514 !isSetCCEquivalent(N1, RL, RR, N1CC)) 3515 return SDValue(); 3516 3517 assert(N0.getValueType() == N1.getValueType() && 3518 "Unexpected operand types for bitwise logic op"); 3519 assert(LL.getValueType() == LR.getValueType() && 3520 RL.getValueType() == RR.getValueType() && 3521 "Unexpected operand types for setcc"); 3522 3523 // If we're here post-legalization or the logic op type is not i1, the logic 3524 // op type must match a setcc result type. Also, all folds require new 3525 // operations on the left and right operands, so those types must match. 3526 EVT VT = N0.getValueType(); 3527 EVT OpVT = LL.getValueType(); 3528 if (LegalOperations || VT != MVT::i1) 3529 if (VT != getSetCCResultType(OpVT)) 3530 return SDValue(); 3531 if (OpVT != RL.getValueType()) 3532 return SDValue(); 3533 3534 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get(); 3535 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get(); 3536 bool IsInteger = OpVT.isInteger(); 3537 if (LR == RR && CC0 == CC1 && IsInteger) { 3538 bool IsZero = isNullConstantOrNullSplatConstant(LR); 3539 bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR); 3540 3541 // All bits clear? 3542 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero; 3543 // All sign bits clear? 3544 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1; 3545 // Any bits set? 3546 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero; 3547 // Any sign bits set? 3548 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero; 3549 3550 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0) 3551 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1) 3552 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0) 3553 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0) 3554 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) { 3555 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL); 3556 AddToWorklist(Or.getNode()); 3557 return DAG.getSetCC(DL, VT, Or, LR, CC1); 3558 } 3559 3560 // All bits set? 3561 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1; 3562 // All sign bits set? 3563 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero; 3564 // Any bits clear? 3565 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1; 3566 // Any sign bits clear? 3567 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1; 3568 3569 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1) 3570 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0) 3571 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1) 3572 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1) 3573 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) { 3574 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL); 3575 AddToWorklist(And.getNode()); 3576 return DAG.getSetCC(DL, VT, And, LR, CC1); 3577 } 3578 } 3579 3580 // TODO: What is the 'or' equivalent of this fold? 3581 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2) 3582 if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 && 3583 IsInteger && CC0 == ISD::SETNE && 3584 ((isNullConstant(LR) && isAllOnesConstant(RR)) || 3585 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 3586 SDValue One = DAG.getConstant(1, DL, OpVT); 3587 SDValue Two = DAG.getConstant(2, DL, OpVT); 3588 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One); 3589 AddToWorklist(Add.getNode()); 3590 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE); 3591 } 3592 3593 // Try more general transforms if the predicates match and the only user of 3594 // the compares is the 'and' or 'or'. 3595 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 && 3596 N0.hasOneUse() && N1.hasOneUse()) { 3597 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0 3598 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0 3599 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) { 3600 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR); 3601 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR); 3602 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR); 3603 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3604 return DAG.getSetCC(DL, VT, Or, Zero, CC1); 3605 } 3606 } 3607 3608 // Canonicalize equivalent operands to LL == RL. 3609 if (LL == RR && LR == RL) { 3610 CC1 = ISD::getSetCCSwappedOperands(CC1); 3611 std::swap(RL, RR); 3612 } 3613 3614 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 3615 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 3616 if (LL == RL && LR == RR) { 3617 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger) 3618 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger); 3619 if (NewCC != ISD::SETCC_INVALID && 3620 (!LegalOperations || 3621 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) && 3622 TLI.isOperationLegal(ISD::SETCC, OpVT)))) 3623 return DAG.getSetCC(DL, VT, LL, LR, NewCC); 3624 } 3625 3626 return SDValue(); 3627 } 3628 3629 /// This contains all DAGCombine rules which reduce two values combined by 3630 /// an And operation to a single value. This makes them reusable in the context 3631 /// of visitSELECT(). Rules involving constants are not included as 3632 /// visitSELECT() already handles those cases. 3633 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) { 3634 EVT VT = N1.getValueType(); 3635 SDLoc DL(N); 3636 3637 // fold (and x, undef) -> 0 3638 if (N0.isUndef() || N1.isUndef()) 3639 return DAG.getConstant(0, DL, VT); 3640 3641 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL)) 3642 return V; 3643 3644 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 3645 VT.getSizeInBits() <= 64) { 3646 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3647 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 3648 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 3649 // immediate for an add, but it is legal if its top c2 bits are set, 3650 // transform the ADD so the immediate doesn't need to be materialized 3651 // in a register. 3652 APInt ADDC = ADDI->getAPIntValue(); 3653 APInt SRLC = SRLI->getAPIntValue(); 3654 if (ADDC.getMinSignedBits() <= 64 && 3655 SRLC.ult(VT.getSizeInBits()) && 3656 !TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3657 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3658 SRLC.getZExtValue()); 3659 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 3660 ADDC |= Mask; 3661 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3662 SDLoc DL0(N0); 3663 SDValue NewAdd = 3664 DAG.getNode(ISD::ADD, DL0, VT, 3665 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 3666 CombineTo(N0.getNode(), NewAdd); 3667 // Return N so it doesn't get rechecked! 3668 return SDValue(N, 0); 3669 } 3670 } 3671 } 3672 } 3673 } 3674 } 3675 3676 // Reduce bit extract of low half of an integer to the narrower type. 3677 // (and (srl i64:x, K), KMask) -> 3678 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 3679 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 3680 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 3681 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3682 unsigned Size = VT.getSizeInBits(); 3683 const APInt &AndMask = CAnd->getAPIntValue(); 3684 unsigned ShiftBits = CShift->getZExtValue(); 3685 3686 // Bail out, this node will probably disappear anyway. 3687 if (ShiftBits == 0) 3688 return SDValue(); 3689 3690 unsigned MaskBits = AndMask.countTrailingOnes(); 3691 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 3692 3693 if (AndMask.isMask() && 3694 // Required bits must not span the two halves of the integer and 3695 // must fit in the half size type. 3696 (ShiftBits + MaskBits <= Size / 2) && 3697 TLI.isNarrowingProfitable(VT, HalfVT) && 3698 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 3699 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 3700 TLI.isTruncateFree(VT, HalfVT) && 3701 TLI.isZExtFree(HalfVT, VT)) { 3702 // The isNarrowingProfitable is to avoid regressions on PPC and 3703 // AArch64 which match a few 64-bit bit insert / bit extract patterns 3704 // on downstream users of this. Those patterns could probably be 3705 // extended to handle extensions mixed in. 3706 3707 SDValue SL(N0); 3708 assert(MaskBits <= Size); 3709 3710 // Extracting the highest bit of the low half. 3711 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 3712 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 3713 N0.getOperand(0)); 3714 3715 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 3716 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 3717 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 3718 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 3719 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 3720 } 3721 } 3722 } 3723 } 3724 3725 return SDValue(); 3726 } 3727 3728 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 3729 EVT LoadResultTy, EVT &ExtVT) { 3730 if (!AndC->getAPIntValue().isMask()) 3731 return false; 3732 3733 unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes(); 3734 3735 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3736 EVT LoadedVT = LoadN->getMemoryVT(); 3737 3738 if (ExtVT == LoadedVT && 3739 (!LegalOperations || 3740 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 3741 // ZEXTLOAD will match without needing to change the size of the value being 3742 // loaded. 3743 return true; 3744 } 3745 3746 // Do not change the width of a volatile load. 3747 if (LoadN->isVolatile()) 3748 return false; 3749 3750 // Do not generate loads of non-round integer types since these can 3751 // be expensive (and would be wrong if the type is not byte sized). 3752 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 3753 return false; 3754 3755 if (LegalOperations && 3756 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 3757 return false; 3758 3759 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 3760 return false; 3761 3762 return true; 3763 } 3764 3765 bool DAGCombiner::isLegalNarrowLoad(LoadSDNode *LoadN, ISD::LoadExtType ExtType, 3766 EVT &ExtVT, unsigned ShAmt) { 3767 // Don't transform one with multiple uses, this would require adding a new 3768 // load. 3769 if (!SDValue(LoadN, 0).hasOneUse()) 3770 return false; 3771 3772 if (LegalOperations && 3773 !TLI.isLoadExtLegal(ExtType, LoadN->getValueType(0), ExtVT)) 3774 return false; 3775 3776 // Do not generate loads of non-round integer types since these can 3777 // be expensive (and would be wrong if the type is not byte sized). 3778 if (!ExtVT.isRound()) 3779 return false; 3780 3781 // Don't change the width of a volatile load. 3782 if (LoadN->isVolatile()) 3783 return false; 3784 3785 // Verify that we are actually reducing a load width here. 3786 if (LoadN->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits()) 3787 return false; 3788 3789 // For the transform to be legal, the load must produce only two values 3790 // (the value loaded and the chain). Don't transform a pre-increment 3791 // load, for example, which produces an extra value. Otherwise the 3792 // transformation is not equivalent, and the downstream logic to replace 3793 // uses gets things wrong. 3794 if (LoadN->getNumValues() > 2) 3795 return false; 3796 3797 // If the load that we're shrinking is an extload and we're not just 3798 // discarding the extension we can't simply shrink the load. Bail. 3799 // TODO: It would be possible to merge the extensions in some cases. 3800 if (LoadN->getExtensionType() != ISD::NON_EXTLOAD && 3801 LoadN->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 3802 return false; 3803 3804 if (!TLI.shouldReduceLoadWidth(LoadN, ExtType, ExtVT)) 3805 return false; 3806 3807 // It's not possible to generate a constant of extended or untyped type. 3808 EVT PtrType = LoadN->getOperand(1).getValueType(); 3809 if (PtrType == MVT::Untyped || PtrType.isExtended()) 3810 return false; 3811 3812 return true; 3813 } 3814 3815 bool DAGCombiner::SearchForAndLoads(SDNode *N, 3816 SmallPtrSetImpl<LoadSDNode*> &Loads, 3817 SmallPtrSetImpl<SDNode*> &NodesWithConsts, 3818 ConstantSDNode *Mask, 3819 SDNode *&NodeToMask) { 3820 // Recursively search for the operands, looking for loads which can be 3821 // narrowed. 3822 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i) { 3823 SDValue Op = N->getOperand(i); 3824 3825 if (Op.getValueType().isVector()) 3826 return false; 3827 3828 // Some constants may need fixing up later if they are too large. 3829 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3830 if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) && 3831 (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue()) 3832 NodesWithConsts.insert(N); 3833 continue; 3834 } 3835 3836 if (!Op.hasOneUse()) 3837 return false; 3838 3839 switch(Op.getOpcode()) { 3840 case ISD::LOAD: { 3841 auto *Load = cast<LoadSDNode>(Op); 3842 EVT ExtVT; 3843 if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) && 3844 isLegalNarrowLoad(Load, ISD::ZEXTLOAD, ExtVT)) { 3845 // Only add this load if we can make it more narrow. 3846 if (ExtVT.bitsLT(Load->getMemoryVT())) 3847 Loads.insert(Load); 3848 continue; 3849 } 3850 return false; 3851 } 3852 case ISD::ZERO_EXTEND: 3853 case ISD::AssertZext: { 3854 unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes(); 3855 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3856 EVT VT = Op.getOpcode() == ISD::AssertZext ? 3857 cast<VTSDNode>(Op.getOperand(1))->getVT() : 3858 Op.getOperand(0).getValueType(); 3859 3860 // We can accept extending nodes if the mask is wider or an equal 3861 // width to the original type. 3862 if (ExtVT.bitsGE(VT)) 3863 continue; 3864 break; 3865 } 3866 case ISD::OR: 3867 case ISD::XOR: 3868 case ISD::AND: 3869 if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask, 3870 NodeToMask)) 3871 return false; 3872 continue; 3873 } 3874 3875 // Allow one node which will masked along with any loads found. 3876 if (NodeToMask) 3877 return false; 3878 NodeToMask = Op.getNode(); 3879 } 3880 return true; 3881 } 3882 3883 bool DAGCombiner::BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG) { 3884 auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1)); 3885 if (!Mask) 3886 return false; 3887 3888 if (!Mask->getAPIntValue().isMask()) 3889 return false; 3890 3891 // No need to do anything if the and directly uses a load. 3892 if (isa<LoadSDNode>(N->getOperand(0))) 3893 return false; 3894 3895 SmallPtrSet<LoadSDNode*, 8> Loads; 3896 SmallPtrSet<SDNode*, 2> NodesWithConsts; 3897 SDNode *FixupNode = nullptr; 3898 if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) { 3899 if (Loads.size() == 0) 3900 return false; 3901 3902 SDValue MaskOp = N->getOperand(1); 3903 3904 // If it exists, fixup the single node we allow in the tree that needs 3905 // masking. 3906 if (FixupNode) { 3907 SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode), 3908 FixupNode->getValueType(0), 3909 SDValue(FixupNode, 0), MaskOp); 3910 DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And); 3911 DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), 3912 MaskOp); 3913 } 3914 3915 // Narrow any constants that need it. 3916 for (auto *LogicN : NodesWithConsts) { 3917 auto *C = cast<ConstantSDNode>(LogicN->getOperand(1)); 3918 SDValue And = DAG.getNode(ISD::AND, SDLoc(C), C->getValueType(0), 3919 SDValue(C, 0), MaskOp); 3920 DAG.UpdateNodeOperands(LogicN, LogicN->getOperand(0), And); 3921 } 3922 3923 // Create narrow loads. 3924 for (auto *Load : Loads) { 3925 SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0), 3926 SDValue(Load, 0), MaskOp); 3927 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And); 3928 DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp); 3929 SDValue NewLoad = ReduceLoadWidth(And.getNode()); 3930 assert(NewLoad && 3931 "Shouldn't be masking the load if it can't be narrowed"); 3932 CombineTo(Load, NewLoad, NewLoad.getValue(1)); 3933 } 3934 DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode()); 3935 return true; 3936 } 3937 return false; 3938 } 3939 3940 SDValue DAGCombiner::visitAND(SDNode *N) { 3941 SDValue N0 = N->getOperand(0); 3942 SDValue N1 = N->getOperand(1); 3943 EVT VT = N1.getValueType(); 3944 3945 // x & x --> x 3946 if (N0 == N1) 3947 return N0; 3948 3949 // fold vector ops 3950 if (VT.isVector()) { 3951 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3952 return FoldedVOp; 3953 3954 // fold (and x, 0) -> 0, vector edition 3955 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3956 // do not return N0, because undef node may exist in N0 3957 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()), 3958 SDLoc(N), N0.getValueType()); 3959 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3960 // do not return N1, because undef node may exist in N1 3961 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()), 3962 SDLoc(N), N1.getValueType()); 3963 3964 // fold (and x, -1) -> x, vector edition 3965 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3966 return N1; 3967 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3968 return N0; 3969 } 3970 3971 // fold (and c1, c2) -> c1&c2 3972 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3973 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3974 if (N0C && N1C && !N1C->isOpaque()) 3975 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3976 // canonicalize constant to RHS 3977 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3978 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3979 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3980 // fold (and x, -1) -> x 3981 if (isAllOnesConstant(N1)) 3982 return N0; 3983 // if (and x, c) is known to be zero, return 0 3984 unsigned BitWidth = VT.getScalarSizeInBits(); 3985 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3986 APInt::getAllOnesValue(BitWidth))) 3987 return DAG.getConstant(0, SDLoc(N), VT); 3988 3989 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3990 return NewSel; 3991 3992 // reassociate and 3993 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3994 return RAND; 3995 3996 // Try to convert a constant mask AND into a shuffle clear mask. 3997 if (VT.isVector()) 3998 if (SDValue Shuffle = XformToShuffleWithZero(N)) 3999 return Shuffle; 4000 4001 // fold (and (or x, C), D) -> D if (C & D) == D 4002 auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) { 4003 return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue()); 4004 }; 4005 if (N0.getOpcode() == ISD::OR && 4006 matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset)) 4007 return N1; 4008 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 4009 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4010 SDValue N0Op0 = N0.getOperand(0); 4011 APInt Mask = ~N1C->getAPIntValue(); 4012 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits()); 4013 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 4014 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 4015 N0.getValueType(), N0Op0); 4016 4017 // Replace uses of the AND with uses of the Zero extend node. 4018 CombineTo(N, Zext); 4019 4020 // We actually want to replace all uses of the any_extend with the 4021 // zero_extend, to avoid duplicating things. This will later cause this 4022 // AND to be folded. 4023 CombineTo(N0.getNode(), Zext); 4024 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4025 } 4026 } 4027 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 4028 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 4029 // already be zero by virtue of the width of the base type of the load. 4030 // 4031 // the 'X' node here can either be nothing or an extract_vector_elt to catch 4032 // more cases. 4033 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 4034 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 4035 N0.getOperand(0).getOpcode() == ISD::LOAD && 4036 N0.getOperand(0).getResNo() == 0) || 4037 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 4038 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 4039 N0 : N0.getOperand(0) ); 4040 4041 // Get the constant (if applicable) the zero'th operand is being ANDed with. 4042 // This can be a pure constant or a vector splat, in which case we treat the 4043 // vector as a scalar and use the splat value. 4044 APInt Constant = APInt::getNullValue(1); 4045 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 4046 Constant = C->getAPIntValue(); 4047 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 4048 APInt SplatValue, SplatUndef; 4049 unsigned SplatBitSize; 4050 bool HasAnyUndefs; 4051 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 4052 SplatBitSize, HasAnyUndefs); 4053 if (IsSplat) { 4054 // Undef bits can contribute to a possible optimisation if set, so 4055 // set them. 4056 SplatValue |= SplatUndef; 4057 4058 // The splat value may be something like "0x00FFFFFF", which means 0 for 4059 // the first vector value and FF for the rest, repeating. We need a mask 4060 // that will apply equally to all members of the vector, so AND all the 4061 // lanes of the constant together. 4062 EVT VT = Vector->getValueType(0); 4063 unsigned BitWidth = VT.getScalarSizeInBits(); 4064 4065 // If the splat value has been compressed to a bitlength lower 4066 // than the size of the vector lane, we need to re-expand it to 4067 // the lane size. 4068 if (BitWidth > SplatBitSize) 4069 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 4070 SplatBitSize < BitWidth; 4071 SplatBitSize = SplatBitSize * 2) 4072 SplatValue |= SplatValue.shl(SplatBitSize); 4073 4074 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 4075 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 4076 if (SplatBitSize % BitWidth == 0) { 4077 Constant = APInt::getAllOnesValue(BitWidth); 4078 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 4079 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 4080 } 4081 } 4082 } 4083 4084 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 4085 // actually legal and isn't going to get expanded, else this is a false 4086 // optimisation. 4087 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 4088 Load->getValueType(0), 4089 Load->getMemoryVT()); 4090 4091 // Resize the constant to the same size as the original memory access before 4092 // extension. If it is still the AllOnesValue then this AND is completely 4093 // unneeded. 4094 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits()); 4095 4096 bool B; 4097 switch (Load->getExtensionType()) { 4098 default: B = false; break; 4099 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 4100 case ISD::ZEXTLOAD: 4101 case ISD::NON_EXTLOAD: B = true; break; 4102 } 4103 4104 if (B && Constant.isAllOnesValue()) { 4105 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 4106 // preserve semantics once we get rid of the AND. 4107 SDValue NewLoad(Load, 0); 4108 4109 // Fold the AND away. NewLoad may get replaced immediately. 4110 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 4111 4112 if (Load->getExtensionType() == ISD::EXTLOAD) { 4113 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 4114 Load->getValueType(0), SDLoc(Load), 4115 Load->getChain(), Load->getBasePtr(), 4116 Load->getOffset(), Load->getMemoryVT(), 4117 Load->getMemOperand()); 4118 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 4119 if (Load->getNumValues() == 3) { 4120 // PRE/POST_INC loads have 3 values. 4121 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 4122 NewLoad.getValue(2) }; 4123 CombineTo(Load, To, 3, true); 4124 } else { 4125 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 4126 } 4127 } 4128 4129 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4130 } 4131 } 4132 4133 // fold (and (load x), 255) -> (zextload x, i8) 4134 // fold (and (extload x, i16), 255) -> (zextload x, i8) 4135 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 4136 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD || 4137 (N0.getOpcode() == ISD::ANY_EXTEND && 4138 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 4139 if (SDValue Res = ReduceLoadWidth(N)) { 4140 LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND 4141 ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0); 4142 4143 AddToWorklist(N); 4144 CombineTo(LN0, Res, Res.getValue(1)); 4145 return SDValue(N, 0); 4146 } 4147 } 4148 4149 if (Level >= AfterLegalizeTypes) { 4150 // Attempt to propagate the AND back up to the leaves which, if they're 4151 // loads, can be combined to narrow loads and the AND node can be removed. 4152 // Perform after legalization so that extend nodes will already be 4153 // combined into the loads. 4154 if (BackwardsPropagateMask(N, DAG)) { 4155 return SDValue(N, 0); 4156 } 4157 } 4158 4159 if (SDValue Combined = visitANDLike(N0, N1, N)) 4160 return Combined; 4161 4162 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 4163 if (N0.getOpcode() == N1.getOpcode()) 4164 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4165 return Tmp; 4166 4167 // Masking the negated extension of a boolean is just the zero-extended 4168 // boolean: 4169 // and (sub 0, zext(bool X)), 1 --> zext(bool X) 4170 // and (sub 0, sext(bool X)), 1 --> zext(bool X) 4171 // 4172 // Note: the SimplifyDemandedBits fold below can make an information-losing 4173 // transform, and then we have no way to find this better fold. 4174 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) { 4175 if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) { 4176 SDValue SubRHS = N0.getOperand(1); 4177 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND && 4178 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 4179 return SubRHS; 4180 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND && 4181 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 4182 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0)); 4183 } 4184 } 4185 4186 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 4187 // fold (and (sra)) -> (and (srl)) when possible. 4188 if (SimplifyDemandedBits(SDValue(N, 0))) 4189 return SDValue(N, 0); 4190 4191 // fold (zext_inreg (extload x)) -> (zextload x) 4192 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 4193 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4194 EVT MemVT = LN0->getMemoryVT(); 4195 // If we zero all the possible extended bits, then we can turn this into 4196 // a zextload if we are running before legalize or the operation is legal. 4197 unsigned BitWidth = N1.getScalarValueSizeInBits(); 4198 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 4199 BitWidth - MemVT.getScalarSizeInBits())) && 4200 ((!LegalOperations && !LN0->isVolatile()) || 4201 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 4202 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 4203 LN0->getChain(), LN0->getBasePtr(), 4204 MemVT, LN0->getMemOperand()); 4205 AddToWorklist(N); 4206 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 4207 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4208 } 4209 } 4210 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 4211 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 4212 N0.hasOneUse()) { 4213 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4214 EVT MemVT = LN0->getMemoryVT(); 4215 // If we zero all the possible extended bits, then we can turn this into 4216 // a zextload if we are running before legalize or the operation is legal. 4217 unsigned BitWidth = N1.getScalarValueSizeInBits(); 4218 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 4219 BitWidth - MemVT.getScalarSizeInBits())) && 4220 ((!LegalOperations && !LN0->isVolatile()) || 4221 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 4222 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 4223 LN0->getChain(), LN0->getBasePtr(), 4224 MemVT, LN0->getMemOperand()); 4225 AddToWorklist(N); 4226 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 4227 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4228 } 4229 } 4230 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 4231 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 4232 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 4233 N0.getOperand(1), false)) 4234 return BSwap; 4235 } 4236 4237 return SDValue(); 4238 } 4239 4240 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 4241 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 4242 bool DemandHighBits) { 4243 if (!LegalOperations) 4244 return SDValue(); 4245 4246 EVT VT = N->getValueType(0); 4247 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 4248 return SDValue(); 4249 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 4250 return SDValue(); 4251 4252 // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff) 4253 bool LookPassAnd0 = false; 4254 bool LookPassAnd1 = false; 4255 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 4256 std::swap(N0, N1); 4257 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 4258 std::swap(N0, N1); 4259 if (N0.getOpcode() == ISD::AND) { 4260 if (!N0.getNode()->hasOneUse()) 4261 return SDValue(); 4262 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4263 if (!N01C || N01C->getZExtValue() != 0xFF00) 4264 return SDValue(); 4265 N0 = N0.getOperand(0); 4266 LookPassAnd0 = true; 4267 } 4268 4269 if (N1.getOpcode() == ISD::AND) { 4270 if (!N1.getNode()->hasOneUse()) 4271 return SDValue(); 4272 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 4273 if (!N11C || N11C->getZExtValue() != 0xFF) 4274 return SDValue(); 4275 N1 = N1.getOperand(0); 4276 LookPassAnd1 = true; 4277 } 4278 4279 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 4280 std::swap(N0, N1); 4281 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 4282 return SDValue(); 4283 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse()) 4284 return SDValue(); 4285 4286 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4287 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 4288 if (!N01C || !N11C) 4289 return SDValue(); 4290 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 4291 return SDValue(); 4292 4293 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 4294 SDValue N00 = N0->getOperand(0); 4295 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 4296 if (!N00.getNode()->hasOneUse()) 4297 return SDValue(); 4298 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 4299 if (!N001C || N001C->getZExtValue() != 0xFF) 4300 return SDValue(); 4301 N00 = N00.getOperand(0); 4302 LookPassAnd0 = true; 4303 } 4304 4305 SDValue N10 = N1->getOperand(0); 4306 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 4307 if (!N10.getNode()->hasOneUse()) 4308 return SDValue(); 4309 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 4310 if (!N101C || N101C->getZExtValue() != 0xFF00) 4311 return SDValue(); 4312 N10 = N10.getOperand(0); 4313 LookPassAnd1 = true; 4314 } 4315 4316 if (N00 != N10) 4317 return SDValue(); 4318 4319 // Make sure everything beyond the low halfword gets set to zero since the SRL 4320 // 16 will clear the top bits. 4321 unsigned OpSizeInBits = VT.getSizeInBits(); 4322 if (DemandHighBits && OpSizeInBits > 16) { 4323 // If the left-shift isn't masked out then the only way this is a bswap is 4324 // if all bits beyond the low 8 are 0. In that case the entire pattern 4325 // reduces to a left shift anyway: leave it for other parts of the combiner. 4326 if (!LookPassAnd0) 4327 return SDValue(); 4328 4329 // However, if the right shift isn't masked out then it might be because 4330 // it's not needed. See if we can spot that too. 4331 if (!LookPassAnd1 && 4332 !DAG.MaskedValueIsZero( 4333 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 4334 return SDValue(); 4335 } 4336 4337 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 4338 if (OpSizeInBits > 16) { 4339 SDLoc DL(N); 4340 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 4341 DAG.getConstant(OpSizeInBits - 16, DL, 4342 getShiftAmountTy(VT))); 4343 } 4344 return Res; 4345 } 4346 4347 /// Return true if the specified node is an element that makes up a 32-bit 4348 /// packed halfword byteswap. 4349 /// ((x & 0x000000ff) << 8) | 4350 /// ((x & 0x0000ff00) >> 8) | 4351 /// ((x & 0x00ff0000) << 8) | 4352 /// ((x & 0xff000000) >> 8) 4353 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 4354 if (!N.getNode()->hasOneUse()) 4355 return false; 4356 4357 unsigned Opc = N.getOpcode(); 4358 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 4359 return false; 4360 4361 SDValue N0 = N.getOperand(0); 4362 unsigned Opc0 = N0.getOpcode(); 4363 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL) 4364 return false; 4365 4366 ConstantSDNode *N1C = nullptr; 4367 // SHL or SRL: look upstream for AND mask operand 4368 if (Opc == ISD::AND) 4369 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4370 else if (Opc0 == ISD::AND) 4371 N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4372 if (!N1C) 4373 return false; 4374 4375 unsigned MaskByteOffset; 4376 switch (N1C->getZExtValue()) { 4377 default: 4378 return false; 4379 case 0xFF: MaskByteOffset = 0; break; 4380 case 0xFF00: MaskByteOffset = 1; break; 4381 case 0xFF0000: MaskByteOffset = 2; break; 4382 case 0xFF000000: MaskByteOffset = 3; break; 4383 } 4384 4385 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 4386 if (Opc == ISD::AND) { 4387 if (MaskByteOffset == 0 || MaskByteOffset == 2) { 4388 // (x >> 8) & 0xff 4389 // (x >> 8) & 0xff0000 4390 if (Opc0 != ISD::SRL) 4391 return false; 4392 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4393 if (!C || C->getZExtValue() != 8) 4394 return false; 4395 } else { 4396 // (x << 8) & 0xff00 4397 // (x << 8) & 0xff000000 4398 if (Opc0 != ISD::SHL) 4399 return false; 4400 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4401 if (!C || C->getZExtValue() != 8) 4402 return false; 4403 } 4404 } else if (Opc == ISD::SHL) { 4405 // (x & 0xff) << 8 4406 // (x & 0xff0000) << 8 4407 if (MaskByteOffset != 0 && MaskByteOffset != 2) 4408 return false; 4409 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4410 if (!C || C->getZExtValue() != 8) 4411 return false; 4412 } else { // Opc == ISD::SRL 4413 // (x & 0xff00) >> 8 4414 // (x & 0xff000000) >> 8 4415 if (MaskByteOffset != 1 && MaskByteOffset != 3) 4416 return false; 4417 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4418 if (!C || C->getZExtValue() != 8) 4419 return false; 4420 } 4421 4422 if (Parts[MaskByteOffset]) 4423 return false; 4424 4425 Parts[MaskByteOffset] = N0.getOperand(0).getNode(); 4426 return true; 4427 } 4428 4429 /// Match a 32-bit packed halfword bswap. That is 4430 /// ((x & 0x000000ff) << 8) | 4431 /// ((x & 0x0000ff00) >> 8) | 4432 /// ((x & 0x00ff0000) << 8) | 4433 /// ((x & 0xff000000) >> 8) 4434 /// => (rotl (bswap x), 16) 4435 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 4436 if (!LegalOperations) 4437 return SDValue(); 4438 4439 EVT VT = N->getValueType(0); 4440 if (VT != MVT::i32) 4441 return SDValue(); 4442 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 4443 return SDValue(); 4444 4445 // Look for either 4446 // (or (or (and), (and)), (or (and), (and))) 4447 // (or (or (or (and), (and)), (and)), (and)) 4448 if (N0.getOpcode() != ISD::OR) 4449 return SDValue(); 4450 SDValue N00 = N0.getOperand(0); 4451 SDValue N01 = N0.getOperand(1); 4452 SDNode *Parts[4] = {}; 4453 4454 if (N1.getOpcode() == ISD::OR && 4455 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 4456 // (or (or (and), (and)), (or (and), (and))) 4457 if (!isBSwapHWordElement(N00, Parts)) 4458 return SDValue(); 4459 4460 if (!isBSwapHWordElement(N01, Parts)) 4461 return SDValue(); 4462 SDValue N10 = N1.getOperand(0); 4463 if (!isBSwapHWordElement(N10, Parts)) 4464 return SDValue(); 4465 SDValue N11 = N1.getOperand(1); 4466 if (!isBSwapHWordElement(N11, Parts)) 4467 return SDValue(); 4468 } else { 4469 // (or (or (or (and), (and)), (and)), (and)) 4470 if (!isBSwapHWordElement(N1, Parts)) 4471 return SDValue(); 4472 if (!isBSwapHWordElement(N01, Parts)) 4473 return SDValue(); 4474 if (N00.getOpcode() != ISD::OR) 4475 return SDValue(); 4476 SDValue N000 = N00.getOperand(0); 4477 if (!isBSwapHWordElement(N000, Parts)) 4478 return SDValue(); 4479 SDValue N001 = N00.getOperand(1); 4480 if (!isBSwapHWordElement(N001, Parts)) 4481 return SDValue(); 4482 } 4483 4484 // Make sure the parts are all coming from the same node. 4485 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 4486 return SDValue(); 4487 4488 SDLoc DL(N); 4489 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 4490 SDValue(Parts[0], 0)); 4491 4492 // Result of the bswap should be rotated by 16. If it's not legal, then 4493 // do (x << 16) | (x >> 16). 4494 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 4495 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 4496 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 4497 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 4498 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 4499 return DAG.getNode(ISD::OR, DL, VT, 4500 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 4501 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 4502 } 4503 4504 /// This contains all DAGCombine rules which reduce two values combined by 4505 /// an Or operation to a single value \see visitANDLike(). 4506 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) { 4507 EVT VT = N1.getValueType(); 4508 SDLoc DL(N); 4509 4510 // fold (or x, undef) -> -1 4511 if (!LegalOperations && (N0.isUndef() || N1.isUndef())) 4512 return DAG.getAllOnesConstant(DL, VT); 4513 4514 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL)) 4515 return V; 4516 4517 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 4518 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 4519 // Don't increase # computations. 4520 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 4521 // We can only do this xform if we know that bits from X that are set in C2 4522 // but not in C1 are already zero. Likewise for Y. 4523 if (const ConstantSDNode *N0O1C = 4524 getAsNonOpaqueConstant(N0.getOperand(1))) { 4525 if (const ConstantSDNode *N1O1C = 4526 getAsNonOpaqueConstant(N1.getOperand(1))) { 4527 // We can only do this xform if we know that bits from X that are set in 4528 // C2 but not in C1 are already zero. Likewise for Y. 4529 const APInt &LHSMask = N0O1C->getAPIntValue(); 4530 const APInt &RHSMask = N1O1C->getAPIntValue(); 4531 4532 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 4533 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 4534 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 4535 N0.getOperand(0), N1.getOperand(0)); 4536 return DAG.getNode(ISD::AND, DL, VT, X, 4537 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 4538 } 4539 } 4540 } 4541 } 4542 4543 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 4544 if (N0.getOpcode() == ISD::AND && 4545 N1.getOpcode() == ISD::AND && 4546 N0.getOperand(0) == N1.getOperand(0) && 4547 // Don't increase # computations. 4548 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 4549 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 4550 N0.getOperand(1), N1.getOperand(1)); 4551 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X); 4552 } 4553 4554 return SDValue(); 4555 } 4556 4557 SDValue DAGCombiner::visitOR(SDNode *N) { 4558 SDValue N0 = N->getOperand(0); 4559 SDValue N1 = N->getOperand(1); 4560 EVT VT = N1.getValueType(); 4561 4562 // x | x --> x 4563 if (N0 == N1) 4564 return N0; 4565 4566 // fold vector ops 4567 if (VT.isVector()) { 4568 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4569 return FoldedVOp; 4570 4571 // fold (or x, 0) -> x, vector edition 4572 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4573 return N1; 4574 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4575 return N0; 4576 4577 // fold (or x, -1) -> -1, vector edition 4578 if (ISD::isBuildVectorAllOnes(N0.getNode())) 4579 // do not return N0, because undef node may exist in N0 4580 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType()); 4581 if (ISD::isBuildVectorAllOnes(N1.getNode())) 4582 // do not return N1, because undef node may exist in N1 4583 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType()); 4584 4585 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 4586 // Do this only if the resulting shuffle is legal. 4587 if (isa<ShuffleVectorSDNode>(N0) && 4588 isa<ShuffleVectorSDNode>(N1) && 4589 // Avoid folding a node with illegal type. 4590 TLI.isTypeLegal(VT)) { 4591 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 4592 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 4593 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 4594 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 4595 // Ensure both shuffles have a zero input. 4596 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) { 4597 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 4598 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 4599 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 4600 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 4601 bool CanFold = true; 4602 int NumElts = VT.getVectorNumElements(); 4603 SmallVector<int, 4> Mask(NumElts); 4604 4605 for (int i = 0; i != NumElts; ++i) { 4606 int M0 = SV0->getMaskElt(i); 4607 int M1 = SV1->getMaskElt(i); 4608 4609 // Determine if either index is pointing to a zero vector. 4610 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 4611 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 4612 4613 // If one element is zero and the otherside is undef, keep undef. 4614 // This also handles the case that both are undef. 4615 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 4616 Mask[i] = -1; 4617 continue; 4618 } 4619 4620 // Make sure only one of the elements is zero. 4621 if (M0Zero == M1Zero) { 4622 CanFold = false; 4623 break; 4624 } 4625 4626 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 4627 4628 // We have a zero and non-zero element. If the non-zero came from 4629 // SV0 make the index a LHS index. If it came from SV1, make it 4630 // a RHS index. We need to mod by NumElts because we don't care 4631 // which operand it came from in the original shuffles. 4632 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 4633 } 4634 4635 if (CanFold) { 4636 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 4637 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 4638 4639 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 4640 if (!LegalMask) { 4641 std::swap(NewLHS, NewRHS); 4642 ShuffleVectorSDNode::commuteMask(Mask); 4643 LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 4644 } 4645 4646 if (LegalMask) 4647 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask); 4648 } 4649 } 4650 } 4651 } 4652 4653 // fold (or c1, c2) -> c1|c2 4654 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4655 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4656 if (N0C && N1C && !N1C->isOpaque()) 4657 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 4658 // canonicalize constant to RHS 4659 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4660 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4661 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 4662 // fold (or x, 0) -> x 4663 if (isNullConstant(N1)) 4664 return N0; 4665 // fold (or x, -1) -> -1 4666 if (isAllOnesConstant(N1)) 4667 return N1; 4668 4669 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4670 return NewSel; 4671 4672 // fold (or x, c) -> c iff (x & ~c) == 0 4673 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 4674 return N1; 4675 4676 if (SDValue Combined = visitORLike(N0, N1, N)) 4677 return Combined; 4678 4679 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 4680 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 4681 return BSwap; 4682 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 4683 return BSwap; 4684 4685 // reassociate or 4686 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 4687 return ROR; 4688 4689 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 4690 // iff (c1 & c2) != 0. 4691 auto MatchIntersect = [](ConstantSDNode *LHS, ConstantSDNode *RHS) { 4692 return LHS->getAPIntValue().intersects(RHS->getAPIntValue()); 4693 }; 4694 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4695 matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect)) { 4696 if (SDValue COR = DAG.FoldConstantArithmetic( 4697 ISD::OR, SDLoc(N1), VT, N1.getNode(), N0.getOperand(1).getNode())) { 4698 SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1); 4699 AddToWorklist(IOR.getNode()); 4700 return DAG.getNode(ISD::AND, SDLoc(N), VT, COR, IOR); 4701 } 4702 } 4703 4704 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 4705 if (N0.getOpcode() == N1.getOpcode()) 4706 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4707 return Tmp; 4708 4709 // See if this is some rotate idiom. 4710 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 4711 return SDValue(Rot, 0); 4712 4713 if (SDValue Load = MatchLoadCombine(N)) 4714 return Load; 4715 4716 // Simplify the operands using demanded-bits information. 4717 if (SimplifyDemandedBits(SDValue(N, 0))) 4718 return SDValue(N, 0); 4719 4720 return SDValue(); 4721 } 4722 4723 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 4724 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 4725 if (Op.getOpcode() == ISD::AND) { 4726 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 4727 Mask = Op.getOperand(1); 4728 Op = Op.getOperand(0); 4729 } else { 4730 return false; 4731 } 4732 } 4733 4734 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 4735 Shift = Op; 4736 return true; 4737 } 4738 4739 return false; 4740 } 4741 4742 // Return true if we can prove that, whenever Neg and Pos are both in the 4743 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 4744 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 4745 // 4746 // (or (shift1 X, Neg), (shift2 X, Pos)) 4747 // 4748 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 4749 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 4750 // to consider shift amounts with defined behavior. 4751 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 4752 // If EltSize is a power of 2 then: 4753 // 4754 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 4755 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 4756 // 4757 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 4758 // for the stronger condition: 4759 // 4760 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 4761 // 4762 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 4763 // we can just replace Neg with Neg' for the rest of the function. 4764 // 4765 // In other cases we check for the even stronger condition: 4766 // 4767 // Neg == EltSize - Pos [B] 4768 // 4769 // for all Neg and Pos. Note that the (or ...) then invokes undefined 4770 // behavior if Pos == 0 (and consequently Neg == EltSize). 4771 // 4772 // We could actually use [A] whenever EltSize is a power of 2, but the 4773 // only extra cases that it would match are those uninteresting ones 4774 // where Neg and Pos are never in range at the same time. E.g. for 4775 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 4776 // as well as (sub 32, Pos), but: 4777 // 4778 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 4779 // 4780 // always invokes undefined behavior for 32-bit X. 4781 // 4782 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 4783 unsigned MaskLoBits = 0; 4784 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 4785 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 4786 if (NegC->getAPIntValue() == EltSize - 1) { 4787 Neg = Neg.getOperand(0); 4788 MaskLoBits = Log2_64(EltSize); 4789 } 4790 } 4791 } 4792 4793 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 4794 if (Neg.getOpcode() != ISD::SUB) 4795 return false; 4796 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 4797 if (!NegC) 4798 return false; 4799 SDValue NegOp1 = Neg.getOperand(1); 4800 4801 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 4802 // Pos'. The truncation is redundant for the purpose of the equality. 4803 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 4804 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4805 if (PosC->getAPIntValue() == EltSize - 1) 4806 Pos = Pos.getOperand(0); 4807 4808 // The condition we need is now: 4809 // 4810 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 4811 // 4812 // If NegOp1 == Pos then we need: 4813 // 4814 // EltSize & Mask == NegC & Mask 4815 // 4816 // (because "x & Mask" is a truncation and distributes through subtraction). 4817 APInt Width; 4818 if (Pos == NegOp1) 4819 Width = NegC->getAPIntValue(); 4820 4821 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 4822 // Then the condition we want to prove becomes: 4823 // 4824 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 4825 // 4826 // which, again because "x & Mask" is a truncation, becomes: 4827 // 4828 // NegC & Mask == (EltSize - PosC) & Mask 4829 // EltSize & Mask == (NegC + PosC) & Mask 4830 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 4831 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4832 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 4833 else 4834 return false; 4835 } else 4836 return false; 4837 4838 // Now we just need to check that EltSize & Mask == Width & Mask. 4839 if (MaskLoBits) 4840 // EltSize & Mask is 0 since Mask is EltSize - 1. 4841 return Width.getLoBits(MaskLoBits) == 0; 4842 return Width == EltSize; 4843 } 4844 4845 // A subroutine of MatchRotate used once we have found an OR of two opposite 4846 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 4847 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 4848 // former being preferred if supported. InnerPos and InnerNeg are Pos and 4849 // Neg with outer conversions stripped away. 4850 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 4851 SDValue Neg, SDValue InnerPos, 4852 SDValue InnerNeg, unsigned PosOpcode, 4853 unsigned NegOpcode, const SDLoc &DL) { 4854 // fold (or (shl x, (*ext y)), 4855 // (srl x, (*ext (sub 32, y)))) -> 4856 // (rotl x, y) or (rotr x, (sub 32, y)) 4857 // 4858 // fold (or (shl x, (*ext (sub 32, y))), 4859 // (srl x, (*ext y))) -> 4860 // (rotr x, y) or (rotl x, (sub 32, y)) 4861 EVT VT = Shifted.getValueType(); 4862 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 4863 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 4864 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 4865 HasPos ? Pos : Neg).getNode(); 4866 } 4867 4868 return nullptr; 4869 } 4870 4871 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 4872 // idioms for rotate, and if the target supports rotation instructions, generate 4873 // a rot[lr]. 4874 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 4875 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 4876 EVT VT = LHS.getValueType(); 4877 if (!TLI.isTypeLegal(VT)) return nullptr; 4878 4879 // The target must have at least one rotate flavor. 4880 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 4881 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 4882 if (!HasROTL && !HasROTR) return nullptr; 4883 4884 // Check for truncated rotate. 4885 if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE && 4886 LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) { 4887 assert(LHS.getValueType() == RHS.getValueType()); 4888 if (SDNode *Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) { 4889 return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(), 4890 SDValue(Rot, 0)).getNode(); 4891 } 4892 } 4893 4894 // Match "(X shl/srl V1) & V2" where V2 may not be present. 4895 SDValue LHSShift; // The shift. 4896 SDValue LHSMask; // AND value if any. 4897 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 4898 return nullptr; // Not part of a rotate. 4899 4900 SDValue RHSShift; // The shift. 4901 SDValue RHSMask; // AND value if any. 4902 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 4903 return nullptr; // Not part of a rotate. 4904 4905 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 4906 return nullptr; // Not shifting the same value. 4907 4908 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 4909 return nullptr; // Shifts must disagree. 4910 4911 // Canonicalize shl to left side in a shl/srl pair. 4912 if (RHSShift.getOpcode() == ISD::SHL) { 4913 std::swap(LHS, RHS); 4914 std::swap(LHSShift, RHSShift); 4915 std::swap(LHSMask, RHSMask); 4916 } 4917 4918 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4919 SDValue LHSShiftArg = LHSShift.getOperand(0); 4920 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4921 SDValue RHSShiftArg = RHSShift.getOperand(0); 4922 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4923 4924 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4925 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4926 auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS, 4927 ConstantSDNode *RHS) { 4928 return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits; 4929 }; 4930 if (matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) { 4931 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4932 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4933 4934 // If there is an AND of either shifted operand, apply it to the result. 4935 if (LHSMask.getNode() || RHSMask.getNode()) { 4936 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT); 4937 SDValue Mask = AllOnes; 4938 4939 if (LHSMask.getNode()) { 4940 SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt); 4941 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4942 DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits)); 4943 } 4944 if (RHSMask.getNode()) { 4945 SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt); 4946 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4947 DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits)); 4948 } 4949 4950 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4951 } 4952 4953 return Rot.getNode(); 4954 } 4955 4956 // If there is a mask here, and we have a variable shift, we can't be sure 4957 // that we're masking out the right stuff. 4958 if (LHSMask.getNode() || RHSMask.getNode()) 4959 return nullptr; 4960 4961 // If the shift amount is sign/zext/any-extended just peel it off. 4962 SDValue LExtOp0 = LHSShiftAmt; 4963 SDValue RExtOp0 = RHSShiftAmt; 4964 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4965 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4966 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4967 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4968 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4969 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4970 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4971 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4972 LExtOp0 = LHSShiftAmt.getOperand(0); 4973 RExtOp0 = RHSShiftAmt.getOperand(0); 4974 } 4975 4976 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4977 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4978 if (TryL) 4979 return TryL; 4980 4981 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4982 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4983 if (TryR) 4984 return TryR; 4985 4986 return nullptr; 4987 } 4988 4989 namespace { 4990 4991 /// Represents known origin of an individual byte in load combine pattern. The 4992 /// value of the byte is either constant zero or comes from memory. 4993 struct ByteProvider { 4994 // For constant zero providers Load is set to nullptr. For memory providers 4995 // Load represents the node which loads the byte from memory. 4996 // ByteOffset is the offset of the byte in the value produced by the load. 4997 LoadSDNode *Load = nullptr; 4998 unsigned ByteOffset = 0; 4999 5000 ByteProvider() = default; 5001 5002 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) { 5003 return ByteProvider(Load, ByteOffset); 5004 } 5005 5006 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); } 5007 5008 bool isConstantZero() const { return !Load; } 5009 bool isMemory() const { return Load; } 5010 5011 bool operator==(const ByteProvider &Other) const { 5012 return Other.Load == Load && Other.ByteOffset == ByteOffset; 5013 } 5014 5015 private: 5016 ByteProvider(LoadSDNode *Load, unsigned ByteOffset) 5017 : Load(Load), ByteOffset(ByteOffset) {} 5018 }; 5019 5020 } // end anonymous namespace 5021 5022 /// Recursively traverses the expression calculating the origin of the requested 5023 /// byte of the given value. Returns None if the provider can't be calculated. 5024 /// 5025 /// For all the values except the root of the expression verifies that the value 5026 /// has exactly one use and if it's not true return None. This way if the origin 5027 /// of the byte is returned it's guaranteed that the values which contribute to 5028 /// the byte are not used outside of this expression. 5029 /// 5030 /// Because the parts of the expression are not allowed to have more than one 5031 /// use this function iterates over trees, not DAGs. So it never visits the same 5032 /// node more than once. 5033 static const Optional<ByteProvider> 5034 calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth, 5035 bool Root = false) { 5036 // Typical i64 by i8 pattern requires recursion up to 8 calls depth 5037 if (Depth == 10) 5038 return None; 5039 5040 if (!Root && !Op.hasOneUse()) 5041 return None; 5042 5043 assert(Op.getValueType().isScalarInteger() && "can't handle other types"); 5044 unsigned BitWidth = Op.getValueSizeInBits(); 5045 if (BitWidth % 8 != 0) 5046 return None; 5047 unsigned ByteWidth = BitWidth / 8; 5048 assert(Index < ByteWidth && "invalid index requested"); 5049 (void) ByteWidth; 5050 5051 switch (Op.getOpcode()) { 5052 case ISD::OR: { 5053 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1); 5054 if (!LHS) 5055 return None; 5056 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1); 5057 if (!RHS) 5058 return None; 5059 5060 if (LHS->isConstantZero()) 5061 return RHS; 5062 if (RHS->isConstantZero()) 5063 return LHS; 5064 return None; 5065 } 5066 case ISD::SHL: { 5067 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 5068 if (!ShiftOp) 5069 return None; 5070 5071 uint64_t BitShift = ShiftOp->getZExtValue(); 5072 if (BitShift % 8 != 0) 5073 return None; 5074 uint64_t ByteShift = BitShift / 8; 5075 5076 return Index < ByteShift 5077 ? ByteProvider::getConstantZero() 5078 : calculateByteProvider(Op->getOperand(0), Index - ByteShift, 5079 Depth + 1); 5080 } 5081 case ISD::ANY_EXTEND: 5082 case ISD::SIGN_EXTEND: 5083 case ISD::ZERO_EXTEND: { 5084 SDValue NarrowOp = Op->getOperand(0); 5085 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits(); 5086 if (NarrowBitWidth % 8 != 0) 5087 return None; 5088 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 5089 5090 if (Index >= NarrowByteWidth) 5091 return Op.getOpcode() == ISD::ZERO_EXTEND 5092 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 5093 : None; 5094 return calculateByteProvider(NarrowOp, Index, Depth + 1); 5095 } 5096 case ISD::BSWAP: 5097 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1, 5098 Depth + 1); 5099 case ISD::LOAD: { 5100 auto L = cast<LoadSDNode>(Op.getNode()); 5101 if (L->isVolatile() || L->isIndexed()) 5102 return None; 5103 5104 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits(); 5105 if (NarrowBitWidth % 8 != 0) 5106 return None; 5107 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 5108 5109 if (Index >= NarrowByteWidth) 5110 return L->getExtensionType() == ISD::ZEXTLOAD 5111 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 5112 : None; 5113 return ByteProvider::getMemory(L, Index); 5114 } 5115 } 5116 5117 return None; 5118 } 5119 5120 /// Match a pattern where a wide type scalar value is loaded by several narrow 5121 /// loads and combined by shifts and ors. Fold it into a single load or a load 5122 /// and a BSWAP if the targets supports it. 5123 /// 5124 /// Assuming little endian target: 5125 /// i8 *a = ... 5126 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24) 5127 /// => 5128 /// i32 val = *((i32)a) 5129 /// 5130 /// i8 *a = ... 5131 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3] 5132 /// => 5133 /// i32 val = BSWAP(*((i32)a)) 5134 /// 5135 /// TODO: This rule matches complex patterns with OR node roots and doesn't 5136 /// interact well with the worklist mechanism. When a part of the pattern is 5137 /// updated (e.g. one of the loads) its direct users are put into the worklist, 5138 /// but the root node of the pattern which triggers the load combine is not 5139 /// necessarily a direct user of the changed node. For example, once the address 5140 /// of t28 load is reassociated load combine won't be triggered: 5141 /// t25: i32 = add t4, Constant:i32<2> 5142 /// t26: i64 = sign_extend t25 5143 /// t27: i64 = add t2, t26 5144 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64 5145 /// t29: i32 = zero_extend t28 5146 /// t32: i32 = shl t29, Constant:i8<8> 5147 /// t33: i32 = or t23, t32 5148 /// As a possible fix visitLoad can check if the load can be a part of a load 5149 /// combine pattern and add corresponding OR roots to the worklist. 5150 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) { 5151 assert(N->getOpcode() == ISD::OR && 5152 "Can only match load combining against OR nodes"); 5153 5154 // Handles simple types only 5155 EVT VT = N->getValueType(0); 5156 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 5157 return SDValue(); 5158 unsigned ByteWidth = VT.getSizeInBits() / 8; 5159 5160 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5161 // Before legalize we can introduce too wide illegal loads which will be later 5162 // split into legal sized loads. This enables us to combine i64 load by i8 5163 // patterns to a couple of i32 loads on 32 bit targets. 5164 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT)) 5165 return SDValue(); 5166 5167 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = []( 5168 unsigned BW, unsigned i) { return i; }; 5169 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = []( 5170 unsigned BW, unsigned i) { return BW - i - 1; }; 5171 5172 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian(); 5173 auto MemoryByteOffset = [&] (ByteProvider P) { 5174 assert(P.isMemory() && "Must be a memory byte provider"); 5175 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits(); 5176 assert(LoadBitWidth % 8 == 0 && 5177 "can only analyze providers for individual bytes not bit"); 5178 unsigned LoadByteWidth = LoadBitWidth / 8; 5179 return IsBigEndianTarget 5180 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset) 5181 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset); 5182 }; 5183 5184 Optional<BaseIndexOffset> Base; 5185 SDValue Chain; 5186 5187 SmallSet<LoadSDNode *, 8> Loads; 5188 Optional<ByteProvider> FirstByteProvider; 5189 int64_t FirstOffset = INT64_MAX; 5190 5191 // Check if all the bytes of the OR we are looking at are loaded from the same 5192 // base address. Collect bytes offsets from Base address in ByteOffsets. 5193 SmallVector<int64_t, 4> ByteOffsets(ByteWidth); 5194 for (unsigned i = 0; i < ByteWidth; i++) { 5195 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true); 5196 if (!P || !P->isMemory()) // All the bytes must be loaded from memory 5197 return SDValue(); 5198 5199 LoadSDNode *L = P->Load; 5200 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() && 5201 "Must be enforced by calculateByteProvider"); 5202 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset"); 5203 5204 // All loads must share the same chain 5205 SDValue LChain = L->getChain(); 5206 if (!Chain) 5207 Chain = LChain; 5208 else if (Chain != LChain) 5209 return SDValue(); 5210 5211 // Loads must share the same base address 5212 BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG); 5213 int64_t ByteOffsetFromBase = 0; 5214 if (!Base) 5215 Base = Ptr; 5216 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase)) 5217 return SDValue(); 5218 5219 // Calculate the offset of the current byte from the base address 5220 ByteOffsetFromBase += MemoryByteOffset(*P); 5221 ByteOffsets[i] = ByteOffsetFromBase; 5222 5223 // Remember the first byte load 5224 if (ByteOffsetFromBase < FirstOffset) { 5225 FirstByteProvider = P; 5226 FirstOffset = ByteOffsetFromBase; 5227 } 5228 5229 Loads.insert(L); 5230 } 5231 assert(!Loads.empty() && "All the bytes of the value must be loaded from " 5232 "memory, so there must be at least one load which produces the value"); 5233 assert(Base && "Base address of the accessed memory location must be set"); 5234 assert(FirstOffset != INT64_MAX && "First byte offset must be set"); 5235 5236 // Check if the bytes of the OR we are looking at match with either big or 5237 // little endian value load 5238 bool BigEndian = true, LittleEndian = true; 5239 for (unsigned i = 0; i < ByteWidth; i++) { 5240 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset; 5241 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i); 5242 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i); 5243 if (!BigEndian && !LittleEndian) 5244 return SDValue(); 5245 } 5246 assert((BigEndian != LittleEndian) && "should be either or"); 5247 assert(FirstByteProvider && "must be set"); 5248 5249 // Ensure that the first byte is loaded from zero offset of the first load. 5250 // So the combined value can be loaded from the first load address. 5251 if (MemoryByteOffset(*FirstByteProvider) != 0) 5252 return SDValue(); 5253 LoadSDNode *FirstLoad = FirstByteProvider->Load; 5254 5255 // The node we are looking at matches with the pattern, check if we can 5256 // replace it with a single load and bswap if needed. 5257 5258 // If the load needs byte swap check if the target supports it 5259 bool NeedsBswap = IsBigEndianTarget != BigEndian; 5260 5261 // Before legalize we can introduce illegal bswaps which will be later 5262 // converted to an explicit bswap sequence. This way we end up with a single 5263 // load and byte shuffling instead of several loads and byte shuffling. 5264 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT)) 5265 return SDValue(); 5266 5267 // Check that a load of the wide type is both allowed and fast on the target 5268 bool Fast = false; 5269 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), 5270 VT, FirstLoad->getAddressSpace(), 5271 FirstLoad->getAlignment(), &Fast); 5272 if (!Allowed || !Fast) 5273 return SDValue(); 5274 5275 SDValue NewLoad = 5276 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(), 5277 FirstLoad->getPointerInfo(), FirstLoad->getAlignment()); 5278 5279 // Transfer chain users from old loads to the new load. 5280 for (LoadSDNode *L : Loads) 5281 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1)); 5282 5283 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad; 5284 } 5285 5286 SDValue DAGCombiner::visitXOR(SDNode *N) { 5287 SDValue N0 = N->getOperand(0); 5288 SDValue N1 = N->getOperand(1); 5289 EVT VT = N0.getValueType(); 5290 5291 // fold vector ops 5292 if (VT.isVector()) { 5293 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5294 return FoldedVOp; 5295 5296 // fold (xor x, 0) -> x, vector edition 5297 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5298 return N1; 5299 if (ISD::isBuildVectorAllZeros(N1.getNode())) 5300 return N0; 5301 } 5302 5303 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 5304 if (N0.isUndef() && N1.isUndef()) 5305 return DAG.getConstant(0, SDLoc(N), VT); 5306 // fold (xor x, undef) -> undef 5307 if (N0.isUndef()) 5308 return N0; 5309 if (N1.isUndef()) 5310 return N1; 5311 // fold (xor c1, c2) -> c1^c2 5312 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5313 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 5314 if (N0C && N1C) 5315 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 5316 // canonicalize constant to RHS 5317 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 5318 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 5319 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 5320 // fold (xor x, 0) -> x 5321 if (isNullConstant(N1)) 5322 return N0; 5323 5324 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5325 return NewSel; 5326 5327 // reassociate xor 5328 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 5329 return RXOR; 5330 5331 // fold !(x cc y) -> (x !cc y) 5332 SDValue LHS, RHS, CC; 5333 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 5334 bool isInt = LHS.getValueType().isInteger(); 5335 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 5336 isInt); 5337 5338 if (!LegalOperations || 5339 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 5340 switch (N0.getOpcode()) { 5341 default: 5342 llvm_unreachable("Unhandled SetCC Equivalent!"); 5343 case ISD::SETCC: 5344 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC); 5345 case ISD::SELECT_CC: 5346 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2), 5347 N0.getOperand(3), NotCC); 5348 } 5349 } 5350 } 5351 5352 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 5353 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 5354 N0.getNode()->hasOneUse() && 5355 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 5356 SDValue V = N0.getOperand(0); 5357 SDLoc DL(N0); 5358 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 5359 DAG.getConstant(1, DL, V.getValueType())); 5360 AddToWorklist(V.getNode()); 5361 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 5362 } 5363 5364 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 5365 if (isOneConstant(N1) && VT == MVT::i1 && 5366 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 5367 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5368 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 5369 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 5370 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 5371 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 5372 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 5373 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 5374 } 5375 } 5376 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 5377 if (isAllOnesConstant(N1) && 5378 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 5379 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5380 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 5381 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 5382 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 5383 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 5384 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 5385 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 5386 } 5387 } 5388 // fold (xor (and x, y), y) -> (and (not x), y) 5389 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 5390 N0->getOperand(1) == N1) { 5391 SDValue X = N0->getOperand(0); 5392 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 5393 AddToWorklist(NotX.getNode()); 5394 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 5395 } 5396 5397 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X) 5398 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5399 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && 5400 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) && 5401 TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { 5402 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1))) 5403 if (C->getAPIntValue() == (OpSizeInBits - 1)) 5404 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0)); 5405 } 5406 5407 // fold (xor x, x) -> 0 5408 if (N0 == N1) 5409 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 5410 5411 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 5412 // Here is a concrete example of this equivalence: 5413 // i16 x == 14 5414 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 5415 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 5416 // 5417 // => 5418 // 5419 // i16 ~1 == 0b1111111111111110 5420 // i16 rol(~1, 14) == 0b1011111111111111 5421 // 5422 // Some additional tips to help conceptualize this transform: 5423 // - Try to see the operation as placing a single zero in a value of all ones. 5424 // - There exists no value for x which would allow the result to contain zero. 5425 // - Values of x larger than the bitwidth are undefined and do not require a 5426 // consistent result. 5427 // - Pushing the zero left requires shifting one bits in from the right. 5428 // A rotate left of ~1 is a nice way of achieving the desired result. 5429 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 5430 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 5431 SDLoc DL(N); 5432 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 5433 N0.getOperand(1)); 5434 } 5435 5436 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 5437 if (N0.getOpcode() == N1.getOpcode()) 5438 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 5439 return Tmp; 5440 5441 // Simplify the expression using non-local knowledge. 5442 if (SimplifyDemandedBits(SDValue(N, 0))) 5443 return SDValue(N, 0); 5444 5445 return SDValue(); 5446 } 5447 5448 /// Handle transforms common to the three shifts, when the shift amount is a 5449 /// constant. 5450 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 5451 SDNode *LHS = N->getOperand(0).getNode(); 5452 if (!LHS->hasOneUse()) return SDValue(); 5453 5454 // We want to pull some binops through shifts, so that we have (and (shift)) 5455 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 5456 // thing happens with address calculations, so it's important to canonicalize 5457 // it. 5458 bool HighBitSet = false; // Can we transform this if the high bit is set? 5459 5460 switch (LHS->getOpcode()) { 5461 default: return SDValue(); 5462 case ISD::OR: 5463 case ISD::XOR: 5464 HighBitSet = false; // We can only transform sra if the high bit is clear. 5465 break; 5466 case ISD::AND: 5467 HighBitSet = true; // We can only transform sra if the high bit is set. 5468 break; 5469 case ISD::ADD: 5470 if (N->getOpcode() != ISD::SHL) 5471 return SDValue(); // only shl(add) not sr[al](add). 5472 HighBitSet = false; // We can only transform sra if the high bit is clear. 5473 break; 5474 } 5475 5476 // We require the RHS of the binop to be a constant and not opaque as well. 5477 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 5478 if (!BinOpCst) return SDValue(); 5479 5480 // FIXME: disable this unless the input to the binop is a shift by a constant 5481 // or is copy/select.Enable this in other cases when figure out it's exactly profitable. 5482 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 5483 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL || 5484 BinOpLHSVal->getOpcode() == ISD::SRA || 5485 BinOpLHSVal->getOpcode() == ISD::SRL; 5486 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg || 5487 BinOpLHSVal->getOpcode() == ISD::SELECT; 5488 5489 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) && 5490 !isCopyOrSelect) 5491 return SDValue(); 5492 5493 if (isCopyOrSelect && N->hasOneUse()) 5494 return SDValue(); 5495 5496 EVT VT = N->getValueType(0); 5497 5498 // If this is a signed shift right, and the high bit is modified by the 5499 // logical operation, do not perform the transformation. The highBitSet 5500 // boolean indicates the value of the high bit of the constant which would 5501 // cause it to be modified for this operation. 5502 if (N->getOpcode() == ISD::SRA) { 5503 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 5504 if (BinOpRHSSignSet != HighBitSet) 5505 return SDValue(); 5506 } 5507 5508 if (!TLI.isDesirableToCommuteWithShift(LHS)) 5509 return SDValue(); 5510 5511 // Fold the constants, shifting the binop RHS by the shift amount. 5512 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 5513 N->getValueType(0), 5514 LHS->getOperand(1), N->getOperand(1)); 5515 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 5516 5517 // Create the new shift. 5518 SDValue NewShift = DAG.getNode(N->getOpcode(), 5519 SDLoc(LHS->getOperand(0)), 5520 VT, LHS->getOperand(0), N->getOperand(1)); 5521 5522 // Create the new binop. 5523 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 5524 } 5525 5526 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 5527 assert(N->getOpcode() == ISD::TRUNCATE); 5528 assert(N->getOperand(0).getOpcode() == ISD::AND); 5529 5530 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 5531 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 5532 SDValue N01 = N->getOperand(0).getOperand(1); 5533 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) { 5534 SDLoc DL(N); 5535 EVT TruncVT = N->getValueType(0); 5536 SDValue N00 = N->getOperand(0).getOperand(0); 5537 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00); 5538 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01); 5539 AddToWorklist(Trunc00.getNode()); 5540 AddToWorklist(Trunc01.getNode()); 5541 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01); 5542 } 5543 } 5544 5545 return SDValue(); 5546 } 5547 5548 SDValue DAGCombiner::visitRotate(SDNode *N) { 5549 SDLoc dl(N); 5550 SDValue N0 = N->getOperand(0); 5551 SDValue N1 = N->getOperand(1); 5552 EVT VT = N->getValueType(0); 5553 unsigned Bitsize = VT.getScalarSizeInBits(); 5554 5555 // fold (rot x, 0) -> x 5556 if (isNullConstantOrNullSplatConstant(N1)) 5557 return N0; 5558 5559 // fold (rot x, c) -> (rot x, c % BitSize) 5560 if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) { 5561 if (Cst->getAPIntValue().uge(Bitsize)) { 5562 uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize); 5563 return DAG.getNode(N->getOpcode(), dl, VT, N0, 5564 DAG.getConstant(RotAmt, dl, N1.getValueType())); 5565 } 5566 } 5567 5568 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 5569 if (N1.getOpcode() == ISD::TRUNCATE && 5570 N1.getOperand(0).getOpcode() == ISD::AND) { 5571 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5572 return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1); 5573 } 5574 5575 unsigned NextOp = N0.getOpcode(); 5576 // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize) 5577 if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) { 5578 SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1); 5579 SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)); 5580 if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) { 5581 EVT ShiftVT = C1->getValueType(0); 5582 bool SameSide = (N->getOpcode() == NextOp); 5583 unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB; 5584 if (SDValue CombinedShift = 5585 DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) { 5586 SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT); 5587 SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic( 5588 ISD::SREM, dl, ShiftVT, CombinedShift.getNode(), 5589 BitsizeC.getNode()); 5590 return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0), 5591 CombinedShiftNorm); 5592 } 5593 } 5594 } 5595 return SDValue(); 5596 } 5597 5598 SDValue DAGCombiner::visitSHL(SDNode *N) { 5599 SDValue N0 = N->getOperand(0); 5600 SDValue N1 = N->getOperand(1); 5601 EVT VT = N0.getValueType(); 5602 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5603 5604 // fold vector ops 5605 if (VT.isVector()) { 5606 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5607 return FoldedVOp; 5608 5609 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 5610 // If setcc produces all-one true value then: 5611 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 5612 if (N1CV && N1CV->isConstant()) { 5613 if (N0.getOpcode() == ISD::AND) { 5614 SDValue N00 = N0->getOperand(0); 5615 SDValue N01 = N0->getOperand(1); 5616 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 5617 5618 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 5619 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 5620 TargetLowering::ZeroOrNegativeOneBooleanContent) { 5621 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 5622 N01CV, N1CV)) 5623 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 5624 } 5625 } 5626 } 5627 } 5628 5629 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5630 5631 // fold (shl c1, c2) -> c1<<c2 5632 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5633 if (N0C && N1C && !N1C->isOpaque()) 5634 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 5635 // fold (shl 0, x) -> 0 5636 if (isNullConstantOrNullSplatConstant(N0)) 5637 return N0; 5638 // fold (shl x, c >= size(x)) -> undef 5639 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 5640 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 5641 return Val->getAPIntValue().uge(OpSizeInBits); 5642 }; 5643 if (matchUnaryPredicate(N1, MatchShiftTooBig)) 5644 return DAG.getUNDEF(VT); 5645 // fold (shl x, 0) -> x 5646 if (N1C && N1C->isNullValue()) 5647 return N0; 5648 // fold (shl undef, x) -> 0 5649 if (N0.isUndef()) 5650 return DAG.getConstant(0, SDLoc(N), VT); 5651 5652 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5653 return NewSel; 5654 5655 // if (shl x, c) is known to be zero, return 0 5656 if (DAG.MaskedValueIsZero(SDValue(N, 0), 5657 APInt::getAllOnesValue(OpSizeInBits))) 5658 return DAG.getConstant(0, SDLoc(N), VT); 5659 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 5660 if (N1.getOpcode() == ISD::TRUNCATE && 5661 N1.getOperand(0).getOpcode() == ISD::AND) { 5662 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5663 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 5664 } 5665 5666 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5667 return SDValue(N, 0); 5668 5669 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 5670 if (N0.getOpcode() == ISD::SHL) { 5671 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 5672 ConstantSDNode *RHS) { 5673 APInt c1 = LHS->getAPIntValue(); 5674 APInt c2 = RHS->getAPIntValue(); 5675 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5676 return (c1 + c2).uge(OpSizeInBits); 5677 }; 5678 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 5679 return DAG.getConstant(0, SDLoc(N), VT); 5680 5681 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 5682 ConstantSDNode *RHS) { 5683 APInt c1 = LHS->getAPIntValue(); 5684 APInt c2 = RHS->getAPIntValue(); 5685 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5686 return (c1 + c2).ult(OpSizeInBits); 5687 }; 5688 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 5689 SDLoc DL(N); 5690 EVT ShiftVT = N1.getValueType(); 5691 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 5692 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum); 5693 } 5694 } 5695 5696 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 5697 // For this to be valid, the second form must not preserve any of the bits 5698 // that are shifted out by the inner shift in the first form. This means 5699 // the outer shift size must be >= the number of bits added by the ext. 5700 // As a corollary, we don't care what kind of ext it is. 5701 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 5702 N0.getOpcode() == ISD::ANY_EXTEND || 5703 N0.getOpcode() == ISD::SIGN_EXTEND) && 5704 N0.getOperand(0).getOpcode() == ISD::SHL) { 5705 SDValue N0Op0 = N0.getOperand(0); 5706 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5707 APInt c1 = N0Op0C1->getAPIntValue(); 5708 APInt c2 = N1C->getAPIntValue(); 5709 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5710 5711 EVT InnerShiftVT = N0Op0.getValueType(); 5712 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 5713 if (c2.uge(OpSizeInBits - InnerShiftSize)) { 5714 SDLoc DL(N0); 5715 APInt Sum = c1 + c2; 5716 if (Sum.uge(OpSizeInBits)) 5717 return DAG.getConstant(0, DL, VT); 5718 5719 return DAG.getNode( 5720 ISD::SHL, DL, VT, 5721 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)), 5722 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5723 } 5724 } 5725 } 5726 5727 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 5728 // Only fold this if the inner zext has no other uses to avoid increasing 5729 // the total number of instructions. 5730 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 5731 N0.getOperand(0).getOpcode() == ISD::SRL) { 5732 SDValue N0Op0 = N0.getOperand(0); 5733 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5734 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) { 5735 uint64_t c1 = N0Op0C1->getZExtValue(); 5736 uint64_t c2 = N1C->getZExtValue(); 5737 if (c1 == c2) { 5738 SDValue NewOp0 = N0.getOperand(0); 5739 EVT CountVT = NewOp0.getOperand(1).getValueType(); 5740 SDLoc DL(N); 5741 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 5742 NewOp0, 5743 DAG.getConstant(c2, DL, CountVT)); 5744 AddToWorklist(NewSHL.getNode()); 5745 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 5746 } 5747 } 5748 } 5749 } 5750 5751 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 5752 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 5753 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 5754 N0->getFlags().hasExact()) { 5755 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5756 uint64_t C1 = N0C1->getZExtValue(); 5757 uint64_t C2 = N1C->getZExtValue(); 5758 SDLoc DL(N); 5759 if (C1 <= C2) 5760 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5761 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 5762 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 5763 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 5764 } 5765 } 5766 5767 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 5768 // (and (srl x, (sub c1, c2), MASK) 5769 // Only fold this if the inner shift has no other uses -- if it does, folding 5770 // this will increase the total number of instructions. 5771 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5772 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5773 uint64_t c1 = N0C1->getZExtValue(); 5774 if (c1 < OpSizeInBits) { 5775 uint64_t c2 = N1C->getZExtValue(); 5776 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 5777 SDValue Shift; 5778 if (c2 > c1) { 5779 Mask <<= c2 - c1; 5780 SDLoc DL(N); 5781 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5782 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 5783 } else { 5784 Mask.lshrInPlace(c1 - c2); 5785 SDLoc DL(N); 5786 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 5787 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 5788 } 5789 SDLoc DL(N0); 5790 return DAG.getNode(ISD::AND, DL, VT, Shift, 5791 DAG.getConstant(Mask, DL, VT)); 5792 } 5793 } 5794 } 5795 5796 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 5797 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) && 5798 isConstantOrConstantVector(N1, /* No Opaques */ true)) { 5799 SDLoc DL(N); 5800 SDValue AllBits = DAG.getAllOnesConstant(DL, VT); 5801 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1); 5802 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask); 5803 } 5804 5805 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 5806 // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 5807 // Variant of version done on multiply, except mul by a power of 2 is turned 5808 // into a shift. 5809 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) && 5810 N0.getNode()->hasOneUse() && 5811 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5812 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5813 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 5814 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5815 AddToWorklist(Shl0.getNode()); 5816 AddToWorklist(Shl1.getNode()); 5817 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1); 5818 } 5819 5820 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 5821 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() && 5822 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5823 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5824 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5825 if (isConstantOrConstantVector(Shl)) 5826 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl); 5827 } 5828 5829 if (N1C && !N1C->isOpaque()) 5830 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 5831 return NewSHL; 5832 5833 return SDValue(); 5834 } 5835 5836 SDValue DAGCombiner::visitSRA(SDNode *N) { 5837 SDValue N0 = N->getOperand(0); 5838 SDValue N1 = N->getOperand(1); 5839 EVT VT = N0.getValueType(); 5840 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5841 5842 // Arithmetic shifting an all-sign-bit value is a no-op. 5843 // fold (sra 0, x) -> 0 5844 // fold (sra -1, x) -> -1 5845 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits) 5846 return N0; 5847 5848 // fold vector ops 5849 if (VT.isVector()) 5850 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5851 return FoldedVOp; 5852 5853 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5854 5855 // fold (sra c1, c2) -> (sra c1, c2) 5856 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5857 if (N0C && N1C && !N1C->isOpaque()) 5858 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 5859 // fold (sra x, c >= size(x)) -> undef 5860 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 5861 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 5862 return Val->getAPIntValue().uge(OpSizeInBits); 5863 }; 5864 if (matchUnaryPredicate(N1, MatchShiftTooBig)) 5865 return DAG.getUNDEF(VT); 5866 // fold (sra x, 0) -> x 5867 if (N1C && N1C->isNullValue()) 5868 return N0; 5869 5870 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5871 return NewSel; 5872 5873 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 5874 // sext_inreg. 5875 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 5876 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 5877 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 5878 if (VT.isVector()) 5879 ExtVT = EVT::getVectorVT(*DAG.getContext(), 5880 ExtVT, VT.getVectorNumElements()); 5881 if ((!LegalOperations || 5882 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 5883 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5884 N0.getOperand(0), DAG.getValueType(ExtVT)); 5885 } 5886 5887 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 5888 if (N0.getOpcode() == ISD::SRA) { 5889 SDLoc DL(N); 5890 EVT ShiftVT = N1.getValueType(); 5891 5892 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 5893 ConstantSDNode *RHS) { 5894 APInt c1 = LHS->getAPIntValue(); 5895 APInt c2 = RHS->getAPIntValue(); 5896 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5897 return (c1 + c2).uge(OpSizeInBits); 5898 }; 5899 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 5900 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), 5901 DAG.getConstant(OpSizeInBits - 1, DL, ShiftVT)); 5902 5903 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 5904 ConstantSDNode *RHS) { 5905 APInt c1 = LHS->getAPIntValue(); 5906 APInt c2 = RHS->getAPIntValue(); 5907 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5908 return (c1 + c2).ult(OpSizeInBits); 5909 }; 5910 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 5911 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 5912 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), Sum); 5913 } 5914 } 5915 5916 // fold (sra (shl X, m), (sub result_size, n)) 5917 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 5918 // result_size - n != m. 5919 // If truncate is free for the target sext(shl) is likely to result in better 5920 // code. 5921 if (N0.getOpcode() == ISD::SHL && N1C) { 5922 // Get the two constanst of the shifts, CN0 = m, CN = n. 5923 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 5924 if (N01C) { 5925 LLVMContext &Ctx = *DAG.getContext(); 5926 // Determine what the truncate's result bitsize and type would be. 5927 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 5928 5929 if (VT.isVector()) 5930 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 5931 5932 // Determine the residual right-shift amount. 5933 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 5934 5935 // If the shift is not a no-op (in which case this should be just a sign 5936 // extend already), the truncated to type is legal, sign_extend is legal 5937 // on that type, and the truncate to that type is both legal and free, 5938 // perform the transform. 5939 if ((ShiftAmt > 0) && 5940 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 5941 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 5942 TLI.isTruncateFree(VT, TruncVT)) { 5943 SDLoc DL(N); 5944 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 5945 getShiftAmountTy(N0.getOperand(0).getValueType())); 5946 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 5947 N0.getOperand(0), Amt); 5948 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 5949 Shift); 5950 return DAG.getNode(ISD::SIGN_EXTEND, DL, 5951 N->getValueType(0), Trunc); 5952 } 5953 } 5954 } 5955 5956 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 5957 if (N1.getOpcode() == ISD::TRUNCATE && 5958 N1.getOperand(0).getOpcode() == ISD::AND) { 5959 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5960 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 5961 } 5962 5963 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 5964 // if c1 is equal to the number of bits the trunc removes 5965 if (N0.getOpcode() == ISD::TRUNCATE && 5966 (N0.getOperand(0).getOpcode() == ISD::SRL || 5967 N0.getOperand(0).getOpcode() == ISD::SRA) && 5968 N0.getOperand(0).hasOneUse() && 5969 N0.getOperand(0).getOperand(1).hasOneUse() && 5970 N1C) { 5971 SDValue N0Op0 = N0.getOperand(0); 5972 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 5973 unsigned LargeShiftVal = LargeShift->getZExtValue(); 5974 EVT LargeVT = N0Op0.getValueType(); 5975 5976 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 5977 SDLoc DL(N); 5978 SDValue Amt = 5979 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 5980 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 5981 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 5982 N0Op0.getOperand(0), Amt); 5983 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 5984 } 5985 } 5986 } 5987 5988 // Simplify, based on bits shifted out of the LHS. 5989 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5990 return SDValue(N, 0); 5991 5992 // If the sign bit is known to be zero, switch this to a SRL. 5993 if (DAG.SignBitIsZero(N0)) 5994 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 5995 5996 if (N1C && !N1C->isOpaque()) 5997 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 5998 return NewSRA; 5999 6000 return SDValue(); 6001 } 6002 6003 SDValue DAGCombiner::visitSRL(SDNode *N) { 6004 SDValue N0 = N->getOperand(0); 6005 SDValue N1 = N->getOperand(1); 6006 EVT VT = N0.getValueType(); 6007 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 6008 6009 // fold vector ops 6010 if (VT.isVector()) 6011 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 6012 return FoldedVOp; 6013 6014 ConstantSDNode *N1C = isConstOrConstSplat(N1); 6015 6016 // fold (srl c1, c2) -> c1 >>u c2 6017 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 6018 if (N0C && N1C && !N1C->isOpaque()) 6019 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 6020 // fold (srl 0, x) -> 0 6021 if (isNullConstantOrNullSplatConstant(N0)) 6022 return N0; 6023 // fold (srl x, c >= size(x)) -> undef 6024 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 6025 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 6026 return Val->getAPIntValue().uge(OpSizeInBits); 6027 }; 6028 if (matchUnaryPredicate(N1, MatchShiftTooBig)) 6029 return DAG.getUNDEF(VT); 6030 // fold (srl x, 0) -> x 6031 if (N1C && N1C->isNullValue()) 6032 return N0; 6033 6034 if (SDValue NewSel = foldBinOpIntoSelect(N)) 6035 return NewSel; 6036 6037 // if (srl x, c) is known to be zero, return 0 6038 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 6039 APInt::getAllOnesValue(OpSizeInBits))) 6040 return DAG.getConstant(0, SDLoc(N), VT); 6041 6042 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 6043 if (N0.getOpcode() == ISD::SRL) { 6044 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 6045 ConstantSDNode *RHS) { 6046 APInt c1 = LHS->getAPIntValue(); 6047 APInt c2 = RHS->getAPIntValue(); 6048 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6049 return (c1 + c2).uge(OpSizeInBits); 6050 }; 6051 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 6052 return DAG.getConstant(0, SDLoc(N), VT); 6053 6054 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 6055 ConstantSDNode *RHS) { 6056 APInt c1 = LHS->getAPIntValue(); 6057 APInt c2 = RHS->getAPIntValue(); 6058 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6059 return (c1 + c2).ult(OpSizeInBits); 6060 }; 6061 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 6062 SDLoc DL(N); 6063 EVT ShiftVT = N1.getValueType(); 6064 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 6065 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum); 6066 } 6067 } 6068 6069 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 6070 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 6071 N0.getOperand(0).getOpcode() == ISD::SRL) { 6072 if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) { 6073 uint64_t c1 = N001C->getZExtValue(); 6074 uint64_t c2 = N1C->getZExtValue(); 6075 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 6076 EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType(); 6077 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 6078 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 6079 if (c1 + OpSizeInBits == InnerShiftSize) { 6080 SDLoc DL(N0); 6081 if (c1 + c2 >= InnerShiftSize) 6082 return DAG.getConstant(0, DL, VT); 6083 return DAG.getNode(ISD::TRUNCATE, DL, VT, 6084 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 6085 N0.getOperand(0).getOperand(0), 6086 DAG.getConstant(c1 + c2, DL, 6087 ShiftCountVT))); 6088 } 6089 } 6090 } 6091 6092 // fold (srl (shl x, c), c) -> (and x, cst2) 6093 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 6094 isConstantOrConstantVector(N1, /* NoOpaques */ true)) { 6095 SDLoc DL(N); 6096 SDValue Mask = 6097 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1); 6098 AddToWorklist(Mask.getNode()); 6099 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask); 6100 } 6101 6102 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 6103 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 6104 // Shifting in all undef bits? 6105 EVT SmallVT = N0.getOperand(0).getValueType(); 6106 unsigned BitSize = SmallVT.getScalarSizeInBits(); 6107 if (N1C->getZExtValue() >= BitSize) 6108 return DAG.getUNDEF(VT); 6109 6110 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 6111 uint64_t ShiftAmt = N1C->getZExtValue(); 6112 SDLoc DL0(N0); 6113 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 6114 N0.getOperand(0), 6115 DAG.getConstant(ShiftAmt, DL0, 6116 getShiftAmountTy(SmallVT))); 6117 AddToWorklist(SmallShift.getNode()); 6118 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt); 6119 SDLoc DL(N); 6120 return DAG.getNode(ISD::AND, DL, VT, 6121 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 6122 DAG.getConstant(Mask, DL, VT)); 6123 } 6124 } 6125 6126 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 6127 // bit, which is unmodified by sra. 6128 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 6129 if (N0.getOpcode() == ISD::SRA) 6130 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 6131 } 6132 6133 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 6134 if (N1C && N0.getOpcode() == ISD::CTLZ && 6135 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 6136 KnownBits Known; 6137 DAG.computeKnownBits(N0.getOperand(0), Known); 6138 6139 // If any of the input bits are KnownOne, then the input couldn't be all 6140 // zeros, thus the result of the srl will always be zero. 6141 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 6142 6143 // If all of the bits input the to ctlz node are known to be zero, then 6144 // the result of the ctlz is "32" and the result of the shift is one. 6145 APInt UnknownBits = ~Known.Zero; 6146 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 6147 6148 // Otherwise, check to see if there is exactly one bit input to the ctlz. 6149 if (UnknownBits.isPowerOf2()) { 6150 // Okay, we know that only that the single bit specified by UnknownBits 6151 // could be set on input to the CTLZ node. If this bit is set, the SRL 6152 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 6153 // to an SRL/XOR pair, which is likely to simplify more. 6154 unsigned ShAmt = UnknownBits.countTrailingZeros(); 6155 SDValue Op = N0.getOperand(0); 6156 6157 if (ShAmt) { 6158 SDLoc DL(N0); 6159 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 6160 DAG.getConstant(ShAmt, DL, 6161 getShiftAmountTy(Op.getValueType()))); 6162 AddToWorklist(Op.getNode()); 6163 } 6164 6165 SDLoc DL(N); 6166 return DAG.getNode(ISD::XOR, DL, VT, 6167 Op, DAG.getConstant(1, DL, VT)); 6168 } 6169 } 6170 6171 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 6172 if (N1.getOpcode() == ISD::TRUNCATE && 6173 N1.getOperand(0).getOpcode() == ISD::AND) { 6174 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 6175 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 6176 } 6177 6178 // fold operands of srl based on knowledge that the low bits are not 6179 // demanded. 6180 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 6181 return SDValue(N, 0); 6182 6183 if (N1C && !N1C->isOpaque()) 6184 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 6185 return NewSRL; 6186 6187 // Attempt to convert a srl of a load into a narrower zero-extending load. 6188 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 6189 return NarrowLoad; 6190 6191 // Here is a common situation. We want to optimize: 6192 // 6193 // %a = ... 6194 // %b = and i32 %a, 2 6195 // %c = srl i32 %b, 1 6196 // brcond i32 %c ... 6197 // 6198 // into 6199 // 6200 // %a = ... 6201 // %b = and %a, 2 6202 // %c = setcc eq %b, 0 6203 // brcond %c ... 6204 // 6205 // However when after the source operand of SRL is optimized into AND, the SRL 6206 // itself may not be optimized further. Look for it and add the BRCOND into 6207 // the worklist. 6208 if (N->hasOneUse()) { 6209 SDNode *Use = *N->use_begin(); 6210 if (Use->getOpcode() == ISD::BRCOND) 6211 AddToWorklist(Use); 6212 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 6213 // Also look pass the truncate. 6214 Use = *Use->use_begin(); 6215 if (Use->getOpcode() == ISD::BRCOND) 6216 AddToWorklist(Use); 6217 } 6218 } 6219 6220 return SDValue(); 6221 } 6222 6223 SDValue DAGCombiner::visitABS(SDNode *N) { 6224 SDValue N0 = N->getOperand(0); 6225 EVT VT = N->getValueType(0); 6226 6227 // fold (abs c1) -> c2 6228 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6229 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0); 6230 // fold (abs (abs x)) -> (abs x) 6231 if (N0.getOpcode() == ISD::ABS) 6232 return N0; 6233 // fold (abs x) -> x iff not-negative 6234 if (DAG.SignBitIsZero(N0)) 6235 return N0; 6236 return SDValue(); 6237 } 6238 6239 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 6240 SDValue N0 = N->getOperand(0); 6241 EVT VT = N->getValueType(0); 6242 6243 // fold (bswap c1) -> c2 6244 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6245 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 6246 // fold (bswap (bswap x)) -> x 6247 if (N0.getOpcode() == ISD::BSWAP) 6248 return N0->getOperand(0); 6249 return SDValue(); 6250 } 6251 6252 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 6253 SDValue N0 = N->getOperand(0); 6254 EVT VT = N->getValueType(0); 6255 6256 // fold (bitreverse c1) -> c2 6257 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6258 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0); 6259 // fold (bitreverse (bitreverse x)) -> x 6260 if (N0.getOpcode() == ISD::BITREVERSE) 6261 return N0.getOperand(0); 6262 return SDValue(); 6263 } 6264 6265 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 6266 SDValue N0 = N->getOperand(0); 6267 EVT VT = N->getValueType(0); 6268 6269 // fold (ctlz c1) -> c2 6270 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6271 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 6272 return SDValue(); 6273 } 6274 6275 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 6276 SDValue N0 = N->getOperand(0); 6277 EVT VT = N->getValueType(0); 6278 6279 // fold (ctlz_zero_undef c1) -> c2 6280 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6281 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 6282 return SDValue(); 6283 } 6284 6285 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 6286 SDValue N0 = N->getOperand(0); 6287 EVT VT = N->getValueType(0); 6288 6289 // fold (cttz c1) -> c2 6290 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6291 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 6292 return SDValue(); 6293 } 6294 6295 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 6296 SDValue N0 = N->getOperand(0); 6297 EVT VT = N->getValueType(0); 6298 6299 // fold (cttz_zero_undef c1) -> c2 6300 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6301 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 6302 return SDValue(); 6303 } 6304 6305 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 6306 SDValue N0 = N->getOperand(0); 6307 EVT VT = N->getValueType(0); 6308 6309 // fold (ctpop c1) -> c2 6310 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6311 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 6312 return SDValue(); 6313 } 6314 6315 /// \brief Generate Min/Max node 6316 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 6317 SDValue RHS, SDValue True, SDValue False, 6318 ISD::CondCode CC, const TargetLowering &TLI, 6319 SelectionDAG &DAG) { 6320 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 6321 return SDValue(); 6322 6323 switch (CC) { 6324 case ISD::SETOLT: 6325 case ISD::SETOLE: 6326 case ISD::SETLT: 6327 case ISD::SETLE: 6328 case ISD::SETULT: 6329 case ISD::SETULE: { 6330 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 6331 if (TLI.isOperationLegal(Opcode, VT)) 6332 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 6333 return SDValue(); 6334 } 6335 case ISD::SETOGT: 6336 case ISD::SETOGE: 6337 case ISD::SETGT: 6338 case ISD::SETGE: 6339 case ISD::SETUGT: 6340 case ISD::SETUGE: { 6341 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 6342 if (TLI.isOperationLegal(Opcode, VT)) 6343 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 6344 return SDValue(); 6345 } 6346 default: 6347 return SDValue(); 6348 } 6349 } 6350 6351 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) { 6352 SDValue Cond = N->getOperand(0); 6353 SDValue N1 = N->getOperand(1); 6354 SDValue N2 = N->getOperand(2); 6355 EVT VT = N->getValueType(0); 6356 EVT CondVT = Cond.getValueType(); 6357 SDLoc DL(N); 6358 6359 if (!VT.isInteger()) 6360 return SDValue(); 6361 6362 auto *C1 = dyn_cast<ConstantSDNode>(N1); 6363 auto *C2 = dyn_cast<ConstantSDNode>(N2); 6364 if (!C1 || !C2) 6365 return SDValue(); 6366 6367 // Only do this before legalization to avoid conflicting with target-specific 6368 // transforms in the other direction (create a select from a zext/sext). There 6369 // is also a target-independent combine here in DAGCombiner in the other 6370 // direction for (select Cond, -1, 0) when the condition is not i1. 6371 if (CondVT == MVT::i1 && !LegalOperations) { 6372 if (C1->isNullValue() && C2->isOne()) { 6373 // select Cond, 0, 1 --> zext (!Cond) 6374 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 6375 if (VT != MVT::i1) 6376 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond); 6377 return NotCond; 6378 } 6379 if (C1->isNullValue() && C2->isAllOnesValue()) { 6380 // select Cond, 0, -1 --> sext (!Cond) 6381 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 6382 if (VT != MVT::i1) 6383 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond); 6384 return NotCond; 6385 } 6386 if (C1->isOne() && C2->isNullValue()) { 6387 // select Cond, 1, 0 --> zext (Cond) 6388 if (VT != MVT::i1) 6389 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 6390 return Cond; 6391 } 6392 if (C1->isAllOnesValue() && C2->isNullValue()) { 6393 // select Cond, -1, 0 --> sext (Cond) 6394 if (VT != MVT::i1) 6395 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 6396 return Cond; 6397 } 6398 6399 // For any constants that differ by 1, we can transform the select into an 6400 // extend and add. Use a target hook because some targets may prefer to 6401 // transform in the other direction. 6402 if (TLI.convertSelectOfConstantsToMath(VT)) { 6403 if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) { 6404 // select Cond, C1, C1-1 --> add (zext Cond), C1-1 6405 if (VT != MVT::i1) 6406 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 6407 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 6408 } 6409 if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) { 6410 // select Cond, C1, C1+1 --> add (sext Cond), C1+1 6411 if (VT != MVT::i1) 6412 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 6413 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 6414 } 6415 } 6416 6417 return SDValue(); 6418 } 6419 6420 // fold (select Cond, 0, 1) -> (xor Cond, 1) 6421 // We can't do this reliably if integer based booleans have different contents 6422 // to floating point based booleans. This is because we can't tell whether we 6423 // have an integer-based boolean or a floating-point-based boolean unless we 6424 // can find the SETCC that produced it and inspect its operands. This is 6425 // fairly easy if C is the SETCC node, but it can potentially be 6426 // undiscoverable (or not reasonably discoverable). For example, it could be 6427 // in another basic block or it could require searching a complicated 6428 // expression. 6429 if (CondVT.isInteger() && 6430 TLI.getBooleanContents(false, true) == 6431 TargetLowering::ZeroOrOneBooleanContent && 6432 TLI.getBooleanContents(false, false) == 6433 TargetLowering::ZeroOrOneBooleanContent && 6434 C1->isNullValue() && C2->isOne()) { 6435 SDValue NotCond = 6436 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT)); 6437 if (VT.bitsEq(CondVT)) 6438 return NotCond; 6439 return DAG.getZExtOrTrunc(NotCond, DL, VT); 6440 } 6441 6442 return SDValue(); 6443 } 6444 6445 SDValue DAGCombiner::visitSELECT(SDNode *N) { 6446 SDValue N0 = N->getOperand(0); 6447 SDValue N1 = N->getOperand(1); 6448 SDValue N2 = N->getOperand(2); 6449 EVT VT = N->getValueType(0); 6450 EVT VT0 = N0.getValueType(); 6451 SDLoc DL(N); 6452 6453 // fold (select C, X, X) -> X 6454 if (N1 == N2) 6455 return N1; 6456 6457 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 6458 // fold (select true, X, Y) -> X 6459 // fold (select false, X, Y) -> Y 6460 return !N0C->isNullValue() ? N1 : N2; 6461 } 6462 6463 // fold (select X, X, Y) -> (or X, Y) 6464 // fold (select X, 1, Y) -> (or C, Y) 6465 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 6466 return DAG.getNode(ISD::OR, DL, VT, N0, N2); 6467 6468 if (SDValue V = foldSelectOfConstants(N)) 6469 return V; 6470 6471 // fold (select C, 0, X) -> (and (not C), X) 6472 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 6473 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 6474 AddToWorklist(NOTNode.getNode()); 6475 return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2); 6476 } 6477 // fold (select C, X, 1) -> (or (not C), X) 6478 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 6479 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 6480 AddToWorklist(NOTNode.getNode()); 6481 return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1); 6482 } 6483 // fold (select X, Y, X) -> (and X, Y) 6484 // fold (select X, Y, 0) -> (and X, Y) 6485 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 6486 return DAG.getNode(ISD::AND, DL, VT, N0, N1); 6487 6488 // If we can fold this based on the true/false value, do so. 6489 if (SimplifySelectOps(N, N1, N2)) 6490 return SDValue(N, 0); // Don't revisit N. 6491 6492 if (VT0 == MVT::i1) { 6493 // The code in this block deals with the following 2 equivalences: 6494 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 6495 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 6496 // The target can specify its preferred form with the 6497 // shouldNormalizeToSelectSequence() callback. However we always transform 6498 // to the right anyway if we find the inner select exists in the DAG anyway 6499 // and we always transform to the left side if we know that we can further 6500 // optimize the combination of the conditions. 6501 bool normalizeToSequence = 6502 TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 6503 // select (and Cond0, Cond1), X, Y 6504 // -> select Cond0, (select Cond1, X, Y), Y 6505 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 6506 SDValue Cond0 = N0->getOperand(0); 6507 SDValue Cond1 = N0->getOperand(1); 6508 SDValue InnerSelect = 6509 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2); 6510 if (normalizeToSequence || !InnerSelect.use_empty()) 6511 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, 6512 InnerSelect, N2); 6513 } 6514 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 6515 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 6516 SDValue Cond0 = N0->getOperand(0); 6517 SDValue Cond1 = N0->getOperand(1); 6518 SDValue InnerSelect = 6519 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2); 6520 if (normalizeToSequence || !InnerSelect.use_empty()) 6521 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1, 6522 InnerSelect); 6523 } 6524 6525 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 6526 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 6527 SDValue N1_0 = N1->getOperand(0); 6528 SDValue N1_1 = N1->getOperand(1); 6529 SDValue N1_2 = N1->getOperand(2); 6530 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 6531 // Create the actual and node if we can generate good code for it. 6532 if (!normalizeToSequence) { 6533 SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0); 6534 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2); 6535 } 6536 // Otherwise see if we can optimize the "and" to a better pattern. 6537 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 6538 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1, 6539 N2); 6540 } 6541 } 6542 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 6543 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 6544 SDValue N2_0 = N2->getOperand(0); 6545 SDValue N2_1 = N2->getOperand(1); 6546 SDValue N2_2 = N2->getOperand(2); 6547 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 6548 // Create the actual or node if we can generate good code for it. 6549 if (!normalizeToSequence) { 6550 SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0); 6551 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2); 6552 } 6553 // Otherwise see if we can optimize to a better pattern. 6554 if (SDValue Combined = visitORLike(N0, N2_0, N)) 6555 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1, 6556 N2_2); 6557 } 6558 } 6559 } 6560 6561 // select (xor Cond, 1), X, Y -> select Cond, Y, X 6562 if (VT0 == MVT::i1) { 6563 if (N0->getOpcode() == ISD::XOR) { 6564 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) { 6565 SDValue Cond0 = N0->getOperand(0); 6566 if (C->isOne()) 6567 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N2, N1); 6568 } 6569 } 6570 } 6571 6572 // fold selects based on a setcc into other things, such as min/max/abs 6573 if (N0.getOpcode() == ISD::SETCC) { 6574 // select x, y (fcmp lt x, y) -> fminnum x, y 6575 // select x, y (fcmp gt x, y) -> fmaxnum x, y 6576 // 6577 // This is OK if we don't care about what happens if either operand is a 6578 // NaN. 6579 // 6580 6581 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 6582 // no signed zeros as well as no nans. 6583 const TargetOptions &Options = DAG.getTarget().Options; 6584 if (Options.UnsafeFPMath && VT.isFloatingPoint() && N0.hasOneUse() && 6585 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 6586 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6587 6588 if (SDValue FMinMax = combineMinNumMaxNum( 6589 DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG)) 6590 return FMinMax; 6591 } 6592 6593 if ((!LegalOperations && 6594 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 6595 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 6596 return DAG.getNode(ISD::SELECT_CC, DL, VT, N0.getOperand(0), 6597 N0.getOperand(1), N1, N2, N0.getOperand(2)); 6598 return SimplifySelect(DL, N0, N1, N2); 6599 } 6600 6601 return SDValue(); 6602 } 6603 6604 static 6605 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 6606 SDLoc DL(N); 6607 EVT LoVT, HiVT; 6608 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 6609 6610 // Split the inputs. 6611 SDValue Lo, Hi, LL, LH, RL, RH; 6612 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 6613 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 6614 6615 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 6616 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 6617 6618 return std::make_pair(Lo, Hi); 6619 } 6620 6621 // This function assumes all the vselect's arguments are CONCAT_VECTOR 6622 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 6623 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 6624 SDLoc DL(N); 6625 SDValue Cond = N->getOperand(0); 6626 SDValue LHS = N->getOperand(1); 6627 SDValue RHS = N->getOperand(2); 6628 EVT VT = N->getValueType(0); 6629 int NumElems = VT.getVectorNumElements(); 6630 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 6631 RHS.getOpcode() == ISD::CONCAT_VECTORS && 6632 Cond.getOpcode() == ISD::BUILD_VECTOR); 6633 6634 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 6635 // binary ones here. 6636 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 6637 return SDValue(); 6638 6639 // We're sure we have an even number of elements due to the 6640 // concat_vectors we have as arguments to vselect. 6641 // Skip BV elements until we find one that's not an UNDEF 6642 // After we find an UNDEF element, keep looping until we get to half the 6643 // length of the BV and see if all the non-undef nodes are the same. 6644 ConstantSDNode *BottomHalf = nullptr; 6645 for (int i = 0; i < NumElems / 2; ++i) { 6646 if (Cond->getOperand(i)->isUndef()) 6647 continue; 6648 6649 if (BottomHalf == nullptr) 6650 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 6651 else if (Cond->getOperand(i).getNode() != BottomHalf) 6652 return SDValue(); 6653 } 6654 6655 // Do the same for the second half of the BuildVector 6656 ConstantSDNode *TopHalf = nullptr; 6657 for (int i = NumElems / 2; i < NumElems; ++i) { 6658 if (Cond->getOperand(i)->isUndef()) 6659 continue; 6660 6661 if (TopHalf == nullptr) 6662 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 6663 else if (Cond->getOperand(i).getNode() != TopHalf) 6664 return SDValue(); 6665 } 6666 6667 assert(TopHalf && BottomHalf && 6668 "One half of the selector was all UNDEFs and the other was all the " 6669 "same value. This should have been addressed before this function."); 6670 return DAG.getNode( 6671 ISD::CONCAT_VECTORS, DL, VT, 6672 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 6673 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 6674 } 6675 6676 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 6677 if (Level >= AfterLegalizeTypes) 6678 return SDValue(); 6679 6680 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 6681 SDValue Mask = MSC->getMask(); 6682 SDValue Data = MSC->getValue(); 6683 SDLoc DL(N); 6684 6685 // If the MSCATTER data type requires splitting and the mask is provided by a 6686 // SETCC, then split both nodes and its operands before legalization. This 6687 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6688 // and enables future optimizations (e.g. min/max pattern matching on X86). 6689 if (Mask.getOpcode() != ISD::SETCC) 6690 return SDValue(); 6691 6692 // Check if any splitting is required. 6693 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 6694 TargetLowering::TypeSplitVector) 6695 return SDValue(); 6696 SDValue MaskLo, MaskHi, Lo, Hi; 6697 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6698 6699 EVT LoVT, HiVT; 6700 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 6701 6702 SDValue Chain = MSC->getChain(); 6703 6704 EVT MemoryVT = MSC->getMemoryVT(); 6705 unsigned Alignment = MSC->getOriginalAlignment(); 6706 6707 EVT LoMemVT, HiMemVT; 6708 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6709 6710 SDValue DataLo, DataHi; 6711 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6712 6713 SDValue BasePtr = MSC->getBasePtr(); 6714 SDValue IndexLo, IndexHi; 6715 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 6716 6717 MachineMemOperand *MMO = DAG.getMachineFunction(). 6718 getMachineMemOperand(MSC->getPointerInfo(), 6719 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6720 Alignment, MSC->getAAInfo(), MSC->getRanges()); 6721 6722 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 6723 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 6724 DL, OpsLo, MMO); 6725 6726 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 6727 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 6728 DL, OpsHi, MMO); 6729 6730 AddToWorklist(Lo.getNode()); 6731 AddToWorklist(Hi.getNode()); 6732 6733 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6734 } 6735 6736 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 6737 if (Level >= AfterLegalizeTypes) 6738 return SDValue(); 6739 6740 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 6741 SDValue Mask = MST->getMask(); 6742 SDValue Data = MST->getValue(); 6743 EVT VT = Data.getValueType(); 6744 SDLoc DL(N); 6745 6746 // If the MSTORE data type requires splitting and the mask is provided by a 6747 // SETCC, then split both nodes and its operands before legalization. This 6748 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6749 // and enables future optimizations (e.g. min/max pattern matching on X86). 6750 if (Mask.getOpcode() == ISD::SETCC) { 6751 // Check if any splitting is required. 6752 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6753 TargetLowering::TypeSplitVector) 6754 return SDValue(); 6755 6756 SDValue MaskLo, MaskHi, Lo, Hi; 6757 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6758 6759 SDValue Chain = MST->getChain(); 6760 SDValue Ptr = MST->getBasePtr(); 6761 6762 EVT MemoryVT = MST->getMemoryVT(); 6763 unsigned Alignment = MST->getOriginalAlignment(); 6764 6765 // if Alignment is equal to the vector size, 6766 // take the half of it for the second part 6767 unsigned SecondHalfAlignment = 6768 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment; 6769 6770 EVT LoMemVT, HiMemVT; 6771 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6772 6773 SDValue DataLo, DataHi; 6774 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6775 6776 MachineMemOperand *MMO = DAG.getMachineFunction(). 6777 getMachineMemOperand(MST->getPointerInfo(), 6778 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6779 Alignment, MST->getAAInfo(), MST->getRanges()); 6780 6781 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 6782 MST->isTruncatingStore(), 6783 MST->isCompressingStore()); 6784 6785 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6786 MST->isCompressingStore()); 6787 6788 MMO = DAG.getMachineFunction(). 6789 getMachineMemOperand(MST->getPointerInfo(), 6790 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 6791 SecondHalfAlignment, MST->getAAInfo(), 6792 MST->getRanges()); 6793 6794 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 6795 MST->isTruncatingStore(), 6796 MST->isCompressingStore()); 6797 6798 AddToWorklist(Lo.getNode()); 6799 AddToWorklist(Hi.getNode()); 6800 6801 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6802 } 6803 return SDValue(); 6804 } 6805 6806 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 6807 if (Level >= AfterLegalizeTypes) 6808 return SDValue(); 6809 6810 MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N); 6811 SDValue Mask = MGT->getMask(); 6812 SDLoc DL(N); 6813 6814 // If the MGATHER result requires splitting and the mask is provided by a 6815 // SETCC, then split both nodes and its operands before legalization. This 6816 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6817 // and enables future optimizations (e.g. min/max pattern matching on X86). 6818 6819 if (Mask.getOpcode() != ISD::SETCC) 6820 return SDValue(); 6821 6822 EVT VT = N->getValueType(0); 6823 6824 // Check if any splitting is required. 6825 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6826 TargetLowering::TypeSplitVector) 6827 return SDValue(); 6828 6829 SDValue MaskLo, MaskHi, Lo, Hi; 6830 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6831 6832 SDValue Src0 = MGT->getValue(); 6833 SDValue Src0Lo, Src0Hi; 6834 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6835 6836 EVT LoVT, HiVT; 6837 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 6838 6839 SDValue Chain = MGT->getChain(); 6840 EVT MemoryVT = MGT->getMemoryVT(); 6841 unsigned Alignment = MGT->getOriginalAlignment(); 6842 6843 EVT LoMemVT, HiMemVT; 6844 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6845 6846 SDValue BasePtr = MGT->getBasePtr(); 6847 SDValue Index = MGT->getIndex(); 6848 SDValue IndexLo, IndexHi; 6849 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 6850 6851 MachineMemOperand *MMO = DAG.getMachineFunction(). 6852 getMachineMemOperand(MGT->getPointerInfo(), 6853 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6854 Alignment, MGT->getAAInfo(), MGT->getRanges()); 6855 6856 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 6857 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 6858 MMO); 6859 6860 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 6861 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 6862 MMO); 6863 6864 AddToWorklist(Lo.getNode()); 6865 AddToWorklist(Hi.getNode()); 6866 6867 // Build a factor node to remember that this load is independent of the 6868 // other one. 6869 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6870 Hi.getValue(1)); 6871 6872 // Legalized the chain result - switch anything that used the old chain to 6873 // use the new one. 6874 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 6875 6876 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6877 6878 SDValue RetOps[] = { GatherRes, Chain }; 6879 return DAG.getMergeValues(RetOps, DL); 6880 } 6881 6882 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 6883 if (Level >= AfterLegalizeTypes) 6884 return SDValue(); 6885 6886 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 6887 SDValue Mask = MLD->getMask(); 6888 SDLoc DL(N); 6889 6890 // If the MLOAD result requires splitting and the mask is provided by a 6891 // SETCC, then split both nodes and its operands before legalization. This 6892 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6893 // and enables future optimizations (e.g. min/max pattern matching on X86). 6894 if (Mask.getOpcode() == ISD::SETCC) { 6895 EVT VT = N->getValueType(0); 6896 6897 // Check if any splitting is required. 6898 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6899 TargetLowering::TypeSplitVector) 6900 return SDValue(); 6901 6902 SDValue MaskLo, MaskHi, Lo, Hi; 6903 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6904 6905 SDValue Src0 = MLD->getSrc0(); 6906 SDValue Src0Lo, Src0Hi; 6907 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6908 6909 EVT LoVT, HiVT; 6910 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 6911 6912 SDValue Chain = MLD->getChain(); 6913 SDValue Ptr = MLD->getBasePtr(); 6914 EVT MemoryVT = MLD->getMemoryVT(); 6915 unsigned Alignment = MLD->getOriginalAlignment(); 6916 6917 // if Alignment is equal to the vector size, 6918 // take the half of it for the second part 6919 unsigned SecondHalfAlignment = 6920 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 6921 Alignment/2 : Alignment; 6922 6923 EVT LoMemVT, HiMemVT; 6924 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6925 6926 MachineMemOperand *MMO = DAG.getMachineFunction(). 6927 getMachineMemOperand(MLD->getPointerInfo(), 6928 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6929 Alignment, MLD->getAAInfo(), MLD->getRanges()); 6930 6931 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 6932 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6933 6934 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6935 MLD->isExpandingLoad()); 6936 6937 MMO = DAG.getMachineFunction(). 6938 getMachineMemOperand(MLD->getPointerInfo(), 6939 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 6940 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 6941 6942 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 6943 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6944 6945 AddToWorklist(Lo.getNode()); 6946 AddToWorklist(Hi.getNode()); 6947 6948 // Build a factor node to remember that this load is independent of the 6949 // other one. 6950 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6951 Hi.getValue(1)); 6952 6953 // Legalized the chain result - switch anything that used the old chain to 6954 // use the new one. 6955 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 6956 6957 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6958 6959 SDValue RetOps[] = { LoadRes, Chain }; 6960 return DAG.getMergeValues(RetOps, DL); 6961 } 6962 return SDValue(); 6963 } 6964 6965 /// A vector select of 2 constant vectors can be simplified to math/logic to 6966 /// avoid a variable select instruction and possibly avoid constant loads. 6967 SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) { 6968 SDValue Cond = N->getOperand(0); 6969 SDValue N1 = N->getOperand(1); 6970 SDValue N2 = N->getOperand(2); 6971 EVT VT = N->getValueType(0); 6972 if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 || 6973 !TLI.convertSelectOfConstantsToMath(VT) || 6974 !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) || 6975 !ISD::isBuildVectorOfConstantSDNodes(N2.getNode())) 6976 return SDValue(); 6977 6978 // Check if we can use the condition value to increment/decrement a single 6979 // constant value. This simplifies a select to an add and removes a constant 6980 // load/materialization from the general case. 6981 bool AllAddOne = true; 6982 bool AllSubOne = true; 6983 unsigned Elts = VT.getVectorNumElements(); 6984 for (unsigned i = 0; i != Elts; ++i) { 6985 SDValue N1Elt = N1.getOperand(i); 6986 SDValue N2Elt = N2.getOperand(i); 6987 if (N1Elt.isUndef() || N2Elt.isUndef()) 6988 continue; 6989 6990 const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue(); 6991 const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue(); 6992 if (C1 != C2 + 1) 6993 AllAddOne = false; 6994 if (C1 != C2 - 1) 6995 AllSubOne = false; 6996 } 6997 6998 // Further simplifications for the extra-special cases where the constants are 6999 // all 0 or all -1 should be implemented as folds of these patterns. 7000 SDLoc DL(N); 7001 if (AllAddOne || AllSubOne) { 7002 // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C 7003 // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C 7004 auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND; 7005 SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond); 7006 return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2); 7007 } 7008 7009 // The general case for select-of-constants: 7010 // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2 7011 // ...but that only makes sense if a vselect is slower than 2 logic ops, so 7012 // leave that to a machine-specific pass. 7013 return SDValue(); 7014 } 7015 7016 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 7017 SDValue N0 = N->getOperand(0); 7018 SDValue N1 = N->getOperand(1); 7019 SDValue N2 = N->getOperand(2); 7020 SDLoc DL(N); 7021 7022 // fold (vselect C, X, X) -> X 7023 if (N1 == N2) 7024 return N1; 7025 7026 // Canonicalize integer abs. 7027 // vselect (setg[te] X, 0), X, -X -> 7028 // vselect (setgt X, -1), X, -X -> 7029 // vselect (setl[te] X, 0), -X, X -> 7030 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 7031 if (N0.getOpcode() == ISD::SETCC) { 7032 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 7033 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 7034 bool isAbs = false; 7035 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 7036 7037 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 7038 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 7039 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 7040 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 7041 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 7042 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 7043 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 7044 7045 if (isAbs) { 7046 EVT VT = LHS.getValueType(); 7047 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) 7048 return DAG.getNode(ISD::ABS, DL, VT, LHS); 7049 7050 SDValue Shift = DAG.getNode( 7051 ISD::SRA, DL, VT, LHS, 7052 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT)); 7053 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 7054 AddToWorklist(Shift.getNode()); 7055 AddToWorklist(Add.getNode()); 7056 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 7057 } 7058 } 7059 7060 if (SimplifySelectOps(N, N1, N2)) 7061 return SDValue(N, 0); // Don't revisit N. 7062 7063 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 7064 if (ISD::isBuildVectorAllOnes(N0.getNode())) 7065 return N1; 7066 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 7067 if (ISD::isBuildVectorAllZeros(N0.getNode())) 7068 return N2; 7069 7070 // The ConvertSelectToConcatVector function is assuming both the above 7071 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 7072 // and addressed. 7073 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 7074 N2.getOpcode() == ISD::CONCAT_VECTORS && 7075 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 7076 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 7077 return CV; 7078 } 7079 7080 if (SDValue V = foldVSelectOfConstants(N)) 7081 return V; 7082 7083 return SDValue(); 7084 } 7085 7086 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 7087 SDValue N0 = N->getOperand(0); 7088 SDValue N1 = N->getOperand(1); 7089 SDValue N2 = N->getOperand(2); 7090 SDValue N3 = N->getOperand(3); 7091 SDValue N4 = N->getOperand(4); 7092 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 7093 7094 // fold select_cc lhs, rhs, x, x, cc -> x 7095 if (N2 == N3) 7096 return N2; 7097 7098 // Determine if the condition we're dealing with is constant 7099 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 7100 CC, SDLoc(N), false)) { 7101 AddToWorklist(SCC.getNode()); 7102 7103 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 7104 if (!SCCC->isNullValue()) 7105 return N2; // cond always true -> true val 7106 else 7107 return N3; // cond always false -> false val 7108 } else if (SCC->isUndef()) { 7109 // When the condition is UNDEF, just return the first operand. This is 7110 // coherent the DAG creation, no setcc node is created in this case 7111 return N2; 7112 } else if (SCC.getOpcode() == ISD::SETCC) { 7113 // Fold to a simpler select_cc 7114 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 7115 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 7116 SCC.getOperand(2)); 7117 } 7118 } 7119 7120 // If we can fold this based on the true/false value, do so. 7121 if (SimplifySelectOps(N, N2, N3)) 7122 return SDValue(N, 0); // Don't revisit N. 7123 7124 // fold select_cc into other things, such as min/max/abs 7125 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 7126 } 7127 7128 SDValue DAGCombiner::visitSETCC(SDNode *N) { 7129 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 7130 cast<CondCodeSDNode>(N->getOperand(2))->get(), 7131 SDLoc(N)); 7132 } 7133 7134 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 7135 SDValue LHS = N->getOperand(0); 7136 SDValue RHS = N->getOperand(1); 7137 SDValue Carry = N->getOperand(2); 7138 SDValue Cond = N->getOperand(3); 7139 7140 // If Carry is false, fold to a regular SETCC. 7141 if (Carry.getOpcode() == ISD::CARRY_FALSE) 7142 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 7143 7144 return SDValue(); 7145 } 7146 7147 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) { 7148 SDValue LHS = N->getOperand(0); 7149 SDValue RHS = N->getOperand(1); 7150 SDValue Carry = N->getOperand(2); 7151 SDValue Cond = N->getOperand(3); 7152 7153 // If Carry is false, fold to a regular SETCC. 7154 if (isNullConstant(Carry)) 7155 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 7156 7157 return SDValue(); 7158 } 7159 7160 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 7161 /// a build_vector of constants. 7162 /// This function is called by the DAGCombiner when visiting sext/zext/aext 7163 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 7164 /// Vector extends are not folded if operations are legal; this is to 7165 /// avoid introducing illegal build_vector dag nodes. 7166 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 7167 SelectionDAG &DAG, bool LegalTypes, 7168 bool LegalOperations) { 7169 unsigned Opcode = N->getOpcode(); 7170 SDValue N0 = N->getOperand(0); 7171 EVT VT = N->getValueType(0); 7172 7173 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 7174 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 7175 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 7176 && "Expected EXTEND dag node in input!"); 7177 7178 // fold (sext c1) -> c1 7179 // fold (zext c1) -> c1 7180 // fold (aext c1) -> c1 7181 if (isa<ConstantSDNode>(N0)) 7182 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 7183 7184 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 7185 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 7186 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 7187 EVT SVT = VT.getScalarType(); 7188 if (!(VT.isVector() && 7189 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 7190 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 7191 return nullptr; 7192 7193 // We can fold this node into a build_vector. 7194 unsigned VTBits = SVT.getSizeInBits(); 7195 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits(); 7196 SmallVector<SDValue, 8> Elts; 7197 unsigned NumElts = VT.getVectorNumElements(); 7198 SDLoc DL(N); 7199 7200 for (unsigned i=0; i != NumElts; ++i) { 7201 SDValue Op = N0->getOperand(i); 7202 if (Op->isUndef()) { 7203 Elts.push_back(DAG.getUNDEF(SVT)); 7204 continue; 7205 } 7206 7207 SDLoc DL(Op); 7208 // Get the constant value and if needed trunc it to the size of the type. 7209 // Nodes like build_vector might have constants wider than the scalar type. 7210 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 7211 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 7212 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 7213 else 7214 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 7215 } 7216 7217 return DAG.getBuildVector(VT, DL, Elts).getNode(); 7218 } 7219 7220 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 7221 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 7222 // transformation. Returns true if extension are possible and the above 7223 // mentioned transformation is profitable. 7224 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 7225 unsigned ExtOpc, 7226 SmallVectorImpl<SDNode *> &ExtendNodes, 7227 const TargetLowering &TLI) { 7228 bool HasCopyToRegUses = false; 7229 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 7230 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 7231 UE = N0.getNode()->use_end(); 7232 UI != UE; ++UI) { 7233 SDNode *User = *UI; 7234 if (User == N) 7235 continue; 7236 if (UI.getUse().getResNo() != N0.getResNo()) 7237 continue; 7238 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 7239 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 7240 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 7241 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 7242 // Sign bits will be lost after a zext. 7243 return false; 7244 bool Add = false; 7245 for (unsigned i = 0; i != 2; ++i) { 7246 SDValue UseOp = User->getOperand(i); 7247 if (UseOp == N0) 7248 continue; 7249 if (!isa<ConstantSDNode>(UseOp)) 7250 return false; 7251 Add = true; 7252 } 7253 if (Add) 7254 ExtendNodes.push_back(User); 7255 continue; 7256 } 7257 // If truncates aren't free and there are users we can't 7258 // extend, it isn't worthwhile. 7259 if (!isTruncFree) 7260 return false; 7261 // Remember if this value is live-out. 7262 if (User->getOpcode() == ISD::CopyToReg) 7263 HasCopyToRegUses = true; 7264 } 7265 7266 if (HasCopyToRegUses) { 7267 bool BothLiveOut = false; 7268 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 7269 UI != UE; ++UI) { 7270 SDUse &Use = UI.getUse(); 7271 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 7272 BothLiveOut = true; 7273 break; 7274 } 7275 } 7276 if (BothLiveOut) 7277 // Both unextended and extended values are live out. There had better be 7278 // a good reason for the transformation. 7279 return ExtendNodes.size(); 7280 } 7281 return true; 7282 } 7283 7284 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 7285 SDValue Trunc, SDValue ExtLoad, 7286 const SDLoc &DL, ISD::NodeType ExtType) { 7287 // Extend SetCC uses if necessary. 7288 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 7289 SDNode *SetCC = SetCCs[i]; 7290 SmallVector<SDValue, 4> Ops; 7291 7292 for (unsigned j = 0; j != 2; ++j) { 7293 SDValue SOp = SetCC->getOperand(j); 7294 if (SOp == Trunc) 7295 Ops.push_back(ExtLoad); 7296 else 7297 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 7298 } 7299 7300 Ops.push_back(SetCC->getOperand(2)); 7301 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 7302 } 7303 } 7304 7305 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 7306 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 7307 SDValue N0 = N->getOperand(0); 7308 EVT DstVT = N->getValueType(0); 7309 EVT SrcVT = N0.getValueType(); 7310 7311 assert((N->getOpcode() == ISD::SIGN_EXTEND || 7312 N->getOpcode() == ISD::ZERO_EXTEND) && 7313 "Unexpected node type (not an extend)!"); 7314 7315 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 7316 // For example, on a target with legal v4i32, but illegal v8i32, turn: 7317 // (v8i32 (sext (v8i16 (load x)))) 7318 // into: 7319 // (v8i32 (concat_vectors (v4i32 (sextload x)), 7320 // (v4i32 (sextload (x + 16))))) 7321 // Where uses of the original load, i.e.: 7322 // (v8i16 (load x)) 7323 // are replaced with: 7324 // (v8i16 (truncate 7325 // (v8i32 (concat_vectors (v4i32 (sextload x)), 7326 // (v4i32 (sextload (x + 16))))))) 7327 // 7328 // This combine is only applicable to illegal, but splittable, vectors. 7329 // All legal types, and illegal non-vector types, are handled elsewhere. 7330 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 7331 // 7332 if (N0->getOpcode() != ISD::LOAD) 7333 return SDValue(); 7334 7335 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7336 7337 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 7338 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 7339 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 7340 return SDValue(); 7341 7342 SmallVector<SDNode *, 4> SetCCs; 7343 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 7344 return SDValue(); 7345 7346 ISD::LoadExtType ExtType = 7347 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 7348 7349 // Try to split the vector types to get down to legal types. 7350 EVT SplitSrcVT = SrcVT; 7351 EVT SplitDstVT = DstVT; 7352 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 7353 SplitSrcVT.getVectorNumElements() > 1) { 7354 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 7355 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 7356 } 7357 7358 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 7359 return SDValue(); 7360 7361 SDLoc DL(N); 7362 const unsigned NumSplits = 7363 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 7364 const unsigned Stride = SplitSrcVT.getStoreSize(); 7365 SmallVector<SDValue, 4> Loads; 7366 SmallVector<SDValue, 4> Chains; 7367 7368 SDValue BasePtr = LN0->getBasePtr(); 7369 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 7370 const unsigned Offset = Idx * Stride; 7371 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 7372 7373 SDValue SplitLoad = DAG.getExtLoad( 7374 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 7375 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 7376 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 7377 7378 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 7379 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 7380 7381 Loads.push_back(SplitLoad.getValue(0)); 7382 Chains.push_back(SplitLoad.getValue(1)); 7383 } 7384 7385 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 7386 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 7387 7388 // Simplify TF. 7389 AddToWorklist(NewChain.getNode()); 7390 7391 CombineTo(N, NewValue); 7392 7393 // Replace uses of the original load (before extension) 7394 // with a truncate of the concatenated sextloaded vectors. 7395 SDValue Trunc = 7396 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 7397 CombineTo(N0.getNode(), Trunc, NewChain); 7398 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 7399 (ISD::NodeType)N->getOpcode()); 7400 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7401 } 7402 7403 /// If we're narrowing or widening the result of a vector select and the final 7404 /// size is the same size as a setcc (compare) feeding the select, then try to 7405 /// apply the cast operation to the select's operands because matching vector 7406 /// sizes for a select condition and other operands should be more efficient. 7407 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) { 7408 unsigned CastOpcode = Cast->getOpcode(); 7409 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || 7410 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || 7411 CastOpcode == ISD::FP_ROUND) && 7412 "Unexpected opcode for vector select narrowing/widening"); 7413 7414 // We only do this transform before legal ops because the pattern may be 7415 // obfuscated by target-specific operations after legalization. Do not create 7416 // an illegal select op, however, because that may be difficult to lower. 7417 EVT VT = Cast->getValueType(0); 7418 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT)) 7419 return SDValue(); 7420 7421 SDValue VSel = Cast->getOperand(0); 7422 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() || 7423 VSel.getOperand(0).getOpcode() != ISD::SETCC) 7424 return SDValue(); 7425 7426 // Does the setcc have the same vector size as the casted select? 7427 SDValue SetCC = VSel.getOperand(0); 7428 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType()); 7429 if (SetCCVT.getSizeInBits() != VT.getSizeInBits()) 7430 return SDValue(); 7431 7432 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B) 7433 SDValue A = VSel.getOperand(1); 7434 SDValue B = VSel.getOperand(2); 7435 SDValue CastA, CastB; 7436 SDLoc DL(Cast); 7437 if (CastOpcode == ISD::FP_ROUND) { 7438 // FP_ROUND (fptrunc) has an extra flag operand to pass along. 7439 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1)); 7440 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1)); 7441 } else { 7442 CastA = DAG.getNode(CastOpcode, DL, VT, A); 7443 CastB = DAG.getNode(CastOpcode, DL, VT, B); 7444 } 7445 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB); 7446 } 7447 7448 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 7449 SDValue N0 = N->getOperand(0); 7450 EVT VT = N->getValueType(0); 7451 SDLoc DL(N); 7452 7453 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7454 LegalOperations)) 7455 return SDValue(Res, 0); 7456 7457 // fold (sext (sext x)) -> (sext x) 7458 // fold (sext (aext x)) -> (sext x) 7459 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 7460 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0)); 7461 7462 if (N0.getOpcode() == ISD::TRUNCATE) { 7463 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 7464 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 7465 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7466 SDNode *oye = N0.getOperand(0).getNode(); 7467 if (NarrowLoad.getNode() != N0.getNode()) { 7468 CombineTo(N0.getNode(), NarrowLoad); 7469 // CombineTo deleted the truncate, if needed, but not what's under it. 7470 AddToWorklist(oye); 7471 } 7472 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7473 } 7474 7475 // See if the value being truncated is already sign extended. If so, just 7476 // eliminate the trunc/sext pair. 7477 SDValue Op = N0.getOperand(0); 7478 unsigned OpBits = Op.getScalarValueSizeInBits(); 7479 unsigned MidBits = N0.getScalarValueSizeInBits(); 7480 unsigned DestBits = VT.getScalarSizeInBits(); 7481 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 7482 7483 if (OpBits == DestBits) { 7484 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 7485 // bits, it is already ready. 7486 if (NumSignBits > DestBits-MidBits) 7487 return Op; 7488 } else if (OpBits < DestBits) { 7489 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 7490 // bits, just sext from i32. 7491 if (NumSignBits > OpBits-MidBits) 7492 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op); 7493 } else { 7494 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 7495 // bits, just truncate to i32. 7496 if (NumSignBits > OpBits-MidBits) 7497 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 7498 } 7499 7500 // fold (sext (truncate x)) -> (sextinreg x). 7501 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 7502 N0.getValueType())) { 7503 if (OpBits < DestBits) 7504 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 7505 else if (OpBits > DestBits) 7506 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 7507 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op, 7508 DAG.getValueType(N0.getValueType())); 7509 } 7510 } 7511 7512 // fold (sext (load x)) -> (sext (truncate (sextload x))) 7513 // Only generate vector extloads when 1) they're legal, and 2) they are 7514 // deemed desirable by the target. 7515 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7516 ((!LegalOperations && !VT.isVector() && 7517 !cast<LoadSDNode>(N0)->isVolatile()) || 7518 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 7519 bool DoXform = true; 7520 SmallVector<SDNode*, 4> SetCCs; 7521 if (!N0.hasOneUse()) 7522 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 7523 if (VT.isVector()) 7524 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 7525 if (DoXform) { 7526 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7527 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 7528 LN0->getBasePtr(), N0.getValueType(), 7529 LN0->getMemOperand()); 7530 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7531 N0.getValueType(), ExtLoad); 7532 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND); 7533 // If the load value is used only by N, replace it via CombineTo N. 7534 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 7535 CombineTo(N, ExtLoad); 7536 if (NoReplaceTrunc) 7537 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7538 else 7539 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 7540 return SDValue(N, 0); 7541 } 7542 } 7543 7544 // fold (sext (load x)) to multiple smaller sextloads. 7545 // Only on illegal but splittable vectors. 7546 if (SDValue ExtLoad = CombineExtLoad(N)) 7547 return ExtLoad; 7548 7549 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 7550 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 7551 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 7552 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 7553 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7554 EVT MemVT = LN0->getMemoryVT(); 7555 if ((!LegalOperations && !LN0->isVolatile()) || 7556 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 7557 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 7558 LN0->getBasePtr(), MemVT, 7559 LN0->getMemOperand()); 7560 CombineTo(N, ExtLoad); 7561 CombineTo(N0.getNode(), 7562 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7563 N0.getValueType(), ExtLoad), 7564 ExtLoad.getValue(1)); 7565 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7566 } 7567 } 7568 7569 // fold (sext (and/or/xor (load x), cst)) -> 7570 // (and/or/xor (sextload x), (sext cst)) 7571 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 7572 N0.getOpcode() == ISD::XOR) && 7573 isa<LoadSDNode>(N0.getOperand(0)) && 7574 N0.getOperand(1).getOpcode() == ISD::Constant && 7575 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 7576 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 7577 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 7578 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 7579 bool DoXform = true; 7580 SmallVector<SDNode*, 4> SetCCs; 7581 if (!N0.hasOneUse()) 7582 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 7583 SetCCs, TLI); 7584 if (DoXform) { 7585 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 7586 LN0->getChain(), LN0->getBasePtr(), 7587 LN0->getMemoryVT(), 7588 LN0->getMemOperand()); 7589 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7590 Mask = Mask.sext(VT.getSizeInBits()); 7591 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 7592 ExtLoad, DAG.getConstant(Mask, DL, VT)); 7593 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 7594 SDLoc(N0.getOperand(0)), 7595 N0.getOperand(0).getValueType(), ExtLoad); 7596 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND); 7597 bool NoReplaceTruncAnd = !N0.hasOneUse(); 7598 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 7599 CombineTo(N, And); 7600 // If N0 has multiple uses, change other uses as well. 7601 if (NoReplaceTruncAnd) { 7602 SDValue TruncAnd = 7603 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 7604 CombineTo(N0.getNode(), TruncAnd); 7605 } 7606 if (NoReplaceTrunc) 7607 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7608 else 7609 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 7610 return SDValue(N,0); // Return N so it doesn't get rechecked! 7611 } 7612 } 7613 } 7614 7615 if (N0.getOpcode() == ISD::SETCC) { 7616 SDValue N00 = N0.getOperand(0); 7617 SDValue N01 = N0.getOperand(1); 7618 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 7619 EVT N00VT = N0.getOperand(0).getValueType(); 7620 7621 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 7622 // Only do this before legalize for now. 7623 if (VT.isVector() && !LegalOperations && 7624 TLI.getBooleanContents(N00VT) == 7625 TargetLowering::ZeroOrNegativeOneBooleanContent) { 7626 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 7627 // of the same size as the compared operands. Only optimize sext(setcc()) 7628 // if this is the case. 7629 EVT SVT = getSetCCResultType(N00VT); 7630 7631 // We know that the # elements of the results is the same as the 7632 // # elements of the compare (and the # elements of the compare result 7633 // for that matter). Check to see that they are the same size. If so, 7634 // we know that the element size of the sext'd result matches the 7635 // element size of the compare operands. 7636 if (VT.getSizeInBits() == SVT.getSizeInBits()) 7637 return DAG.getSetCC(DL, VT, N00, N01, CC); 7638 7639 // If the desired elements are smaller or larger than the source 7640 // elements, we can use a matching integer vector type and then 7641 // truncate/sign extend. 7642 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger(); 7643 if (SVT == MatchingVecType) { 7644 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC); 7645 return DAG.getSExtOrTrunc(VsetCC, DL, VT); 7646 } 7647 } 7648 7649 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 7650 // Here, T can be 1 or -1, depending on the type of the setcc and 7651 // getBooleanContents(). 7652 unsigned SetCCWidth = N0.getScalarValueSizeInBits(); 7653 7654 // To determine the "true" side of the select, we need to know the high bit 7655 // of the value returned by the setcc if it evaluates to true. 7656 // If the type of the setcc is i1, then the true case of the select is just 7657 // sext(i1 1), that is, -1. 7658 // If the type of the setcc is larger (say, i8) then the value of the high 7659 // bit depends on getBooleanContents(), so ask TLI for a real "true" value 7660 // of the appropriate width. 7661 SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT) 7662 : TLI.getConstTrueVal(DAG, VT, DL); 7663 SDValue Zero = DAG.getConstant(0, DL, VT); 7664 if (SDValue SCC = 7665 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true)) 7666 return SCC; 7667 7668 if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) { 7669 EVT SetCCVT = getSetCCResultType(N00VT); 7670 // Don't do this transform for i1 because there's a select transform 7671 // that would reverse it. 7672 // TODO: We should not do this transform at all without a target hook 7673 // because a sext is likely cheaper than a select? 7674 if (SetCCVT.getScalarSizeInBits() != 1 && 7675 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) { 7676 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC); 7677 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero); 7678 } 7679 } 7680 } 7681 7682 // fold (sext x) -> (zext x) if the sign bit is known zero. 7683 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 7684 DAG.SignBitIsZero(N0)) 7685 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0); 7686 7687 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 7688 return NewVSel; 7689 7690 return SDValue(); 7691 } 7692 7693 // isTruncateOf - If N is a truncate of some other value, return true, record 7694 // the value being truncated in Op and which of Op's bits are zero/one in Known. 7695 // This function computes KnownBits to avoid a duplicated call to 7696 // computeKnownBits in the caller. 7697 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 7698 KnownBits &Known) { 7699 if (N->getOpcode() == ISD::TRUNCATE) { 7700 Op = N->getOperand(0); 7701 DAG.computeKnownBits(Op, Known); 7702 return true; 7703 } 7704 7705 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 7706 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 7707 return false; 7708 7709 SDValue Op0 = N->getOperand(0); 7710 SDValue Op1 = N->getOperand(1); 7711 assert(Op0.getValueType() == Op1.getValueType()); 7712 7713 if (isNullConstant(Op0)) 7714 Op = Op1; 7715 else if (isNullConstant(Op1)) 7716 Op = Op0; 7717 else 7718 return false; 7719 7720 DAG.computeKnownBits(Op, Known); 7721 7722 if (!(Known.Zero | 1).isAllOnesValue()) 7723 return false; 7724 7725 return true; 7726 } 7727 7728 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 7729 SDValue N0 = N->getOperand(0); 7730 EVT VT = N->getValueType(0); 7731 7732 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7733 LegalOperations)) 7734 return SDValue(Res, 0); 7735 7736 // fold (zext (zext x)) -> (zext x) 7737 // fold (zext (aext x)) -> (zext x) 7738 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 7739 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 7740 N0.getOperand(0)); 7741 7742 // fold (zext (truncate x)) -> (zext x) or 7743 // (zext (truncate x)) -> (truncate x) 7744 // This is valid when the truncated bits of x are already zero. 7745 // FIXME: We should extend this to work for vectors too. 7746 SDValue Op; 7747 KnownBits Known; 7748 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) { 7749 APInt TruncatedBits = 7750 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 7751 APInt(Op.getValueSizeInBits(), 0) : 7752 APInt::getBitsSet(Op.getValueSizeInBits(), 7753 N0.getValueSizeInBits(), 7754 std::min(Op.getValueSizeInBits(), 7755 VT.getSizeInBits())); 7756 if (TruncatedBits.isSubsetOf(Known.Zero)) 7757 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 7758 } 7759 7760 // fold (zext (truncate x)) -> (and x, mask) 7761 if (N0.getOpcode() == ISD::TRUNCATE) { 7762 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 7763 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 7764 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7765 SDNode *oye = N0.getOperand(0).getNode(); 7766 if (NarrowLoad.getNode() != N0.getNode()) { 7767 CombineTo(N0.getNode(), NarrowLoad); 7768 // CombineTo deleted the truncate, if needed, but not what's under it. 7769 AddToWorklist(oye); 7770 } 7771 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7772 } 7773 7774 EVT SrcVT = N0.getOperand(0).getValueType(); 7775 EVT MinVT = N0.getValueType(); 7776 7777 // Try to mask before the extension to avoid having to generate a larger mask, 7778 // possibly over several sub-vectors. 7779 if (SrcVT.bitsLT(VT)) { 7780 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 7781 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 7782 SDValue Op = N0.getOperand(0); 7783 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 7784 AddToWorklist(Op.getNode()); 7785 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 7786 } 7787 } 7788 7789 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 7790 SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 7791 AddToWorklist(Op.getNode()); 7792 SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 7793 // We may safely transfer the debug info describing the truncate node over 7794 // to the equivalent and operation. 7795 DAG.transferDbgValues(N0, And); 7796 return And; 7797 } 7798 } 7799 7800 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 7801 // if either of the casts is not free. 7802 if (N0.getOpcode() == ISD::AND && 7803 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 7804 N0.getOperand(1).getOpcode() == ISD::Constant && 7805 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 7806 N0.getValueType()) || 7807 !TLI.isZExtFree(N0.getValueType(), VT))) { 7808 SDValue X = N0.getOperand(0).getOperand(0); 7809 X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT); 7810 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7811 Mask = Mask.zext(VT.getSizeInBits()); 7812 SDLoc DL(N); 7813 return DAG.getNode(ISD::AND, DL, VT, 7814 X, DAG.getConstant(Mask, DL, VT)); 7815 } 7816 7817 // fold (zext (load x)) -> (zext (truncate (zextload x))) 7818 // Only generate vector extloads when 1) they're legal, and 2) they are 7819 // deemed desirable by the target. 7820 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7821 ((!LegalOperations && !VT.isVector() && 7822 !cast<LoadSDNode>(N0)->isVolatile()) || 7823 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 7824 bool DoXform = true; 7825 SmallVector<SDNode*, 4> SetCCs; 7826 if (!N0.hasOneUse()) 7827 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 7828 if (VT.isVector()) 7829 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 7830 if (DoXform) { 7831 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7832 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 7833 LN0->getChain(), 7834 LN0->getBasePtr(), N0.getValueType(), 7835 LN0->getMemOperand()); 7836 7837 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7838 N0.getValueType(), ExtLoad); 7839 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), ISD::ZERO_EXTEND); 7840 // If the load value is used only by N, replace it via CombineTo N. 7841 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 7842 CombineTo(N, ExtLoad); 7843 if (NoReplaceTrunc) 7844 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7845 else 7846 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 7847 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7848 } 7849 } 7850 7851 // fold (zext (load x)) to multiple smaller zextloads. 7852 // Only on illegal but splittable vectors. 7853 if (SDValue ExtLoad = CombineExtLoad(N)) 7854 return ExtLoad; 7855 7856 // fold (zext (and/or/xor (load x), cst)) -> 7857 // (and/or/xor (zextload x), (zext cst)) 7858 // Unless (and (load x) cst) will match as a zextload already and has 7859 // additional users. 7860 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 7861 N0.getOpcode() == ISD::XOR) && 7862 isa<LoadSDNode>(N0.getOperand(0)) && 7863 N0.getOperand(1).getOpcode() == ISD::Constant && 7864 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 7865 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 7866 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 7867 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 7868 bool DoXform = true; 7869 SmallVector<SDNode*, 4> SetCCs; 7870 if (!N0.hasOneUse()) { 7871 if (N0.getOpcode() == ISD::AND) { 7872 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 7873 EVT LoadResultTy = AndC->getValueType(0); 7874 EVT ExtVT; 7875 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT)) 7876 DoXform = false; 7877 } 7878 if (DoXform) 7879 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 7880 ISD::ZERO_EXTEND, SetCCs, TLI); 7881 } 7882 if (DoXform) { 7883 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 7884 LN0->getChain(), LN0->getBasePtr(), 7885 LN0->getMemoryVT(), 7886 LN0->getMemOperand()); 7887 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7888 Mask = Mask.zext(VT.getSizeInBits()); 7889 SDLoc DL(N); 7890 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 7891 ExtLoad, DAG.getConstant(Mask, DL, VT)); 7892 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 7893 SDLoc(N0.getOperand(0)), 7894 N0.getOperand(0).getValueType(), ExtLoad); 7895 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::ZERO_EXTEND); 7896 bool NoReplaceTruncAnd = !N0.hasOneUse(); 7897 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 7898 CombineTo(N, And); 7899 // If N0 has multiple uses, change other uses as well. 7900 if (NoReplaceTruncAnd) { 7901 SDValue TruncAnd = 7902 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 7903 CombineTo(N0.getNode(), TruncAnd); 7904 } 7905 if (NoReplaceTrunc) 7906 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7907 else 7908 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 7909 return SDValue(N,0); // Return N so it doesn't get rechecked! 7910 } 7911 } 7912 } 7913 7914 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 7915 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 7916 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 7917 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 7918 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7919 EVT MemVT = LN0->getMemoryVT(); 7920 if ((!LegalOperations && !LN0->isVolatile()) || 7921 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 7922 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 7923 LN0->getChain(), 7924 LN0->getBasePtr(), MemVT, 7925 LN0->getMemOperand()); 7926 CombineTo(N, ExtLoad); 7927 CombineTo(N0.getNode(), 7928 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 7929 ExtLoad), 7930 ExtLoad.getValue(1)); 7931 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7932 } 7933 } 7934 7935 if (N0.getOpcode() == ISD::SETCC) { 7936 // Only do this before legalize for now. 7937 if (!LegalOperations && VT.isVector() && 7938 N0.getValueType().getVectorElementType() == MVT::i1) { 7939 EVT N00VT = N0.getOperand(0).getValueType(); 7940 if (getSetCCResultType(N00VT) == N0.getValueType()) 7941 return SDValue(); 7942 7943 // We know that the # elements of the results is the same as the # 7944 // elements of the compare (and the # elements of the compare result for 7945 // that matter). Check to see that they are the same size. If so, we know 7946 // that the element size of the sext'd result matches the element size of 7947 // the compare operands. 7948 SDLoc DL(N); 7949 SDValue VecOnes = DAG.getConstant(1, DL, VT); 7950 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 7951 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 7952 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 7953 N0.getOperand(1), N0.getOperand(2)); 7954 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes); 7955 } 7956 7957 // If the desired elements are smaller or larger than the source 7958 // elements we can use a matching integer vector type and then 7959 // truncate/sign extend. 7960 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); 7961 SDValue VsetCC = 7962 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 7963 N0.getOperand(1), N0.getOperand(2)); 7964 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT), 7965 VecOnes); 7966 } 7967 7968 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 7969 SDLoc DL(N); 7970 if (SDValue SCC = SimplifySelectCC( 7971 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 7972 DAG.getConstant(0, DL, VT), 7973 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 7974 return SCC; 7975 } 7976 7977 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 7978 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 7979 isa<ConstantSDNode>(N0.getOperand(1)) && 7980 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 7981 N0.hasOneUse()) { 7982 SDValue ShAmt = N0.getOperand(1); 7983 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 7984 if (N0.getOpcode() == ISD::SHL) { 7985 SDValue InnerZExt = N0.getOperand(0); 7986 // If the original shl may be shifting out bits, do not perform this 7987 // transformation. 7988 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() - 7989 InnerZExt.getOperand(0).getValueSizeInBits(); 7990 if (ShAmtVal > KnownZeroBits) 7991 return SDValue(); 7992 } 7993 7994 SDLoc DL(N); 7995 7996 // Ensure that the shift amount is wide enough for the shifted value. 7997 if (VT.getSizeInBits() >= 256) 7998 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 7999 8000 return DAG.getNode(N0.getOpcode(), DL, VT, 8001 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 8002 ShAmt); 8003 } 8004 8005 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 8006 return NewVSel; 8007 8008 return SDValue(); 8009 } 8010 8011 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 8012 SDValue N0 = N->getOperand(0); 8013 EVT VT = N->getValueType(0); 8014 8015 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8016 LegalOperations)) 8017 return SDValue(Res, 0); 8018 8019 // fold (aext (aext x)) -> (aext x) 8020 // fold (aext (zext x)) -> (zext x) 8021 // fold (aext (sext x)) -> (sext x) 8022 if (N0.getOpcode() == ISD::ANY_EXTEND || 8023 N0.getOpcode() == ISD::ZERO_EXTEND || 8024 N0.getOpcode() == ISD::SIGN_EXTEND) 8025 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 8026 8027 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 8028 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 8029 if (N0.getOpcode() == ISD::TRUNCATE) { 8030 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 8031 SDNode *oye = N0.getOperand(0).getNode(); 8032 if (NarrowLoad.getNode() != N0.getNode()) { 8033 CombineTo(N0.getNode(), NarrowLoad); 8034 // CombineTo deleted the truncate, if needed, but not what's under it. 8035 AddToWorklist(oye); 8036 } 8037 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8038 } 8039 } 8040 8041 // fold (aext (truncate x)) 8042 if (N0.getOpcode() == ISD::TRUNCATE) 8043 return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 8044 8045 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 8046 // if the trunc is not free. 8047 if (N0.getOpcode() == ISD::AND && 8048 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 8049 N0.getOperand(1).getOpcode() == ISD::Constant && 8050 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 8051 N0.getValueType())) { 8052 SDLoc DL(N); 8053 SDValue X = N0.getOperand(0).getOperand(0); 8054 X = DAG.getAnyExtOrTrunc(X, DL, VT); 8055 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 8056 Mask = Mask.zext(VT.getSizeInBits()); 8057 return DAG.getNode(ISD::AND, DL, VT, 8058 X, DAG.getConstant(Mask, DL, VT)); 8059 } 8060 8061 // fold (aext (load x)) -> (aext (truncate (extload x))) 8062 // None of the supported targets knows how to perform load and any_ext 8063 // on vectors in one instruction. We only perform this transformation on 8064 // scalars. 8065 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 8066 ISD::isUNINDEXEDLoad(N0.getNode()) && 8067 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 8068 bool DoXform = true; 8069 SmallVector<SDNode*, 4> SetCCs; 8070 if (!N0.hasOneUse()) 8071 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 8072 if (DoXform) { 8073 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8074 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 8075 LN0->getChain(), 8076 LN0->getBasePtr(), N0.getValueType(), 8077 LN0->getMemOperand()); 8078 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 8079 N0.getValueType(), ExtLoad); 8080 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 8081 ISD::ANY_EXTEND); 8082 // If the load value is used only by N, replace it via CombineTo N. 8083 bool NoReplaceTrunc = N0.hasOneUse(); 8084 CombineTo(N, ExtLoad); 8085 if (NoReplaceTrunc) 8086 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 8087 else 8088 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 8089 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8090 } 8091 } 8092 8093 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 8094 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 8095 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 8096 if (N0.getOpcode() == ISD::LOAD && 8097 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 8098 N0.hasOneUse()) { 8099 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8100 ISD::LoadExtType ExtType = LN0->getExtensionType(); 8101 EVT MemVT = LN0->getMemoryVT(); 8102 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 8103 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 8104 VT, LN0->getChain(), LN0->getBasePtr(), 8105 MemVT, LN0->getMemOperand()); 8106 CombineTo(N, ExtLoad); 8107 CombineTo(N0.getNode(), 8108 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 8109 N0.getValueType(), ExtLoad), 8110 ExtLoad.getValue(1)); 8111 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8112 } 8113 } 8114 8115 if (N0.getOpcode() == ISD::SETCC) { 8116 // For vectors: 8117 // aext(setcc) -> vsetcc 8118 // aext(setcc) -> truncate(vsetcc) 8119 // aext(setcc) -> aext(vsetcc) 8120 // Only do this before legalize for now. 8121 if (VT.isVector() && !LegalOperations) { 8122 EVT N00VT = N0.getOperand(0).getValueType(); 8123 if (getSetCCResultType(N00VT) == N0.getValueType()) 8124 return SDValue(); 8125 8126 // We know that the # elements of the results is the same as the 8127 // # elements of the compare (and the # elements of the compare result 8128 // for that matter). Check to see that they are the same size. If so, 8129 // we know that the element size of the sext'd result matches the 8130 // element size of the compare operands. 8131 if (VT.getSizeInBits() == N00VT.getSizeInBits()) 8132 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 8133 N0.getOperand(1), 8134 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 8135 // If the desired elements are smaller or larger than the source 8136 // elements we can use a matching integer vector type and then 8137 // truncate/any extend 8138 else { 8139 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); 8140 SDValue VsetCC = 8141 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 8142 N0.getOperand(1), 8143 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 8144 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 8145 } 8146 } 8147 8148 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 8149 SDLoc DL(N); 8150 if (SDValue SCC = SimplifySelectCC( 8151 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 8152 DAG.getConstant(0, DL, VT), 8153 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 8154 return SCC; 8155 } 8156 8157 return SDValue(); 8158 } 8159 8160 SDValue DAGCombiner::visitAssertExt(SDNode *N) { 8161 unsigned Opcode = N->getOpcode(); 8162 SDValue N0 = N->getOperand(0); 8163 SDValue N1 = N->getOperand(1); 8164 EVT AssertVT = cast<VTSDNode>(N1)->getVT(); 8165 8166 // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt) 8167 if (N0.getOpcode() == Opcode && 8168 AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT()) 8169 return N0; 8170 8171 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && 8172 N0.getOperand(0).getOpcode() == Opcode) { 8173 // We have an assert, truncate, assert sandwich. Make one stronger assert 8174 // by asserting on the smallest asserted type to the larger source type. 8175 // This eliminates the later assert: 8176 // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN 8177 // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN 8178 SDValue BigA = N0.getOperand(0); 8179 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT(); 8180 assert(BigA_AssertVT.bitsLE(N0.getValueType()) && 8181 "Asserting zero/sign-extended bits to a type larger than the " 8182 "truncated destination does not provide information"); 8183 8184 SDLoc DL(N); 8185 EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT; 8186 SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT); 8187 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(), 8188 BigA.getOperand(0), MinAssertVTVal); 8189 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert); 8190 } 8191 8192 return SDValue(); 8193 } 8194 8195 /// If the result of a wider load is shifted to right of N bits and then 8196 /// truncated to a narrower type and where N is a multiple of number of bits of 8197 /// the narrower type, transform it to a narrower load from address + N / num of 8198 /// bits of new type. Also narrow the load if the result is masked with an AND 8199 /// to effectively produce a smaller type. If the result is to be extended, also 8200 /// fold the extension to form a extending load. 8201 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 8202 unsigned Opc = N->getOpcode(); 8203 8204 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 8205 SDValue N0 = N->getOperand(0); 8206 EVT VT = N->getValueType(0); 8207 EVT ExtVT = VT; 8208 8209 // This transformation isn't valid for vector loads. 8210 if (VT.isVector()) 8211 return SDValue(); 8212 8213 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 8214 // extended to VT. 8215 if (Opc == ISD::SIGN_EXTEND_INREG) { 8216 ExtType = ISD::SEXTLOAD; 8217 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8218 } else if (Opc == ISD::SRL) { 8219 // Another special-case: SRL is basically zero-extending a narrower value, 8220 // or it maybe shifting a higher subword, half or byte into the lowest 8221 // bits. 8222 ExtType = ISD::ZEXTLOAD; 8223 N0 = SDValue(N, 0); 8224 8225 auto *LN0 = dyn_cast<LoadSDNode>(N0.getOperand(0)); 8226 auto *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8227 if (!N01 || !LN0) 8228 return SDValue(); 8229 8230 uint64_t ShiftAmt = N01->getZExtValue(); 8231 uint64_t MemoryWidth = LN0->getMemoryVT().getSizeInBits(); 8232 if (LN0->getExtensionType() != ISD::SEXTLOAD && MemoryWidth > ShiftAmt) 8233 ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShiftAmt); 8234 else 8235 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 8236 VT.getSizeInBits() - ShiftAmt); 8237 } else if (Opc == ISD::AND) { 8238 // An AND with a constant mask is the same as a truncate + zero-extend. 8239 auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8240 if (!AndC || !AndC->getAPIntValue().isMask()) 8241 return SDValue(); 8242 8243 unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes(); 8244 ExtType = ISD::ZEXTLOAD; 8245 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 8246 } 8247 8248 unsigned ShAmt = 0; 8249 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 8250 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 8251 ShAmt = N01->getZExtValue(); 8252 unsigned EVTBits = ExtVT.getSizeInBits(); 8253 // Is the shift amount a multiple of size of VT? 8254 if ((ShAmt & (EVTBits-1)) == 0) { 8255 N0 = N0.getOperand(0); 8256 // Is the load width a multiple of size of VT? 8257 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0) 8258 return SDValue(); 8259 } 8260 8261 // At this point, we must have a load or else we can't do the transform. 8262 if (!isa<LoadSDNode>(N0)) return SDValue(); 8263 8264 // Because a SRL must be assumed to *need* to zero-extend the high bits 8265 // (as opposed to anyext the high bits), we can't combine the zextload 8266 // lowering of SRL and an sextload. 8267 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 8268 return SDValue(); 8269 8270 // If the shift amount is larger than the input type then we're not 8271 // accessing any of the loaded bytes. If the load was a zextload/extload 8272 // then the result of the shift+trunc is zero/undef (handled elsewhere). 8273 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 8274 return SDValue(); 8275 } 8276 } 8277 8278 // If the load is shifted left (and the result isn't shifted back right), 8279 // we can fold the truncate through the shift. 8280 unsigned ShLeftAmt = 0; 8281 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 8282 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 8283 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 8284 ShLeftAmt = N01->getZExtValue(); 8285 N0 = N0.getOperand(0); 8286 } 8287 } 8288 8289 // If we haven't found a load, we can't narrow it. 8290 if (!isa<LoadSDNode>(N0)) 8291 return SDValue(); 8292 8293 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8294 if (!isLegalNarrowLoad(LN0, ExtType, ExtVT, ShAmt)) 8295 return SDValue(); 8296 8297 // For big endian targets, we need to adjust the offset to the pointer to 8298 // load the correct bytes. 8299 if (DAG.getDataLayout().isBigEndian()) { 8300 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 8301 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 8302 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 8303 } 8304 8305 EVT PtrType = N0.getOperand(1).getValueType(); 8306 uint64_t PtrOff = ShAmt / 8; 8307 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 8308 SDLoc DL(LN0); 8309 // The original load itself didn't wrap, so an offset within it doesn't. 8310 SDNodeFlags Flags; 8311 Flags.setNoUnsignedWrap(true); 8312 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 8313 PtrType, LN0->getBasePtr(), 8314 DAG.getConstant(PtrOff, DL, PtrType), 8315 Flags); 8316 AddToWorklist(NewPtr.getNode()); 8317 8318 SDValue Load; 8319 if (ExtType == ISD::NON_EXTLOAD) 8320 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 8321 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 8322 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8323 else 8324 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr, 8325 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 8326 NewAlign, LN0->getMemOperand()->getFlags(), 8327 LN0->getAAInfo()); 8328 8329 // Replace the old load's chain with the new load's chain. 8330 WorklistRemover DeadNodes(*this); 8331 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 8332 8333 // Shift the result left, if we've swallowed a left shift. 8334 SDValue Result = Load; 8335 if (ShLeftAmt != 0) { 8336 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 8337 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 8338 ShImmTy = VT; 8339 // If the shift amount is as large as the result size (but, presumably, 8340 // no larger than the source) then the useful bits of the result are 8341 // zero; we can't simply return the shortened shift, because the result 8342 // of that operation is undefined. 8343 SDLoc DL(N0); 8344 if (ShLeftAmt >= VT.getSizeInBits()) 8345 Result = DAG.getConstant(0, DL, VT); 8346 else 8347 Result = DAG.getNode(ISD::SHL, DL, VT, 8348 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 8349 } 8350 8351 // Return the new loaded value. 8352 return Result; 8353 } 8354 8355 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 8356 SDValue N0 = N->getOperand(0); 8357 SDValue N1 = N->getOperand(1); 8358 EVT VT = N->getValueType(0); 8359 EVT EVT = cast<VTSDNode>(N1)->getVT(); 8360 unsigned VTBits = VT.getScalarSizeInBits(); 8361 unsigned EVTBits = EVT.getScalarSizeInBits(); 8362 8363 if (N0.isUndef()) 8364 return DAG.getUNDEF(VT); 8365 8366 // fold (sext_in_reg c1) -> c1 8367 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 8368 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 8369 8370 // If the input is already sign extended, just drop the extension. 8371 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 8372 return N0; 8373 8374 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 8375 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 8376 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 8377 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 8378 N0.getOperand(0), N1); 8379 8380 // fold (sext_in_reg (sext x)) -> (sext x) 8381 // fold (sext_in_reg (aext x)) -> (sext x) 8382 // if x is small enough. 8383 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 8384 SDValue N00 = N0.getOperand(0); 8385 if (N00.getScalarValueSizeInBits() <= EVTBits && 8386 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 8387 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 8388 } 8389 8390 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x) 8391 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG || 8392 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG || 8393 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) && 8394 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) { 8395 if (!LegalOperations || 8396 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT)) 8397 return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT); 8398 } 8399 8400 // fold (sext_in_reg (zext x)) -> (sext x) 8401 // iff we are extending the source sign bit. 8402 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 8403 SDValue N00 = N0.getOperand(0); 8404 if (N00.getScalarValueSizeInBits() == EVTBits && 8405 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 8406 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 8407 } 8408 8409 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 8410 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1))) 8411 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType()); 8412 8413 // fold operands of sext_in_reg based on knowledge that the top bits are not 8414 // demanded. 8415 if (SimplifyDemandedBits(SDValue(N, 0))) 8416 return SDValue(N, 0); 8417 8418 // fold (sext_in_reg (load x)) -> (smaller sextload x) 8419 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 8420 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 8421 return NarrowLoad; 8422 8423 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 8424 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 8425 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 8426 if (N0.getOpcode() == ISD::SRL) { 8427 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 8428 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 8429 // We can turn this into an SRA iff the input to the SRL is already sign 8430 // extended enough. 8431 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 8432 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 8433 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 8434 N0.getOperand(0), N0.getOperand(1)); 8435 } 8436 } 8437 8438 // fold (sext_inreg (extload x)) -> (sextload x) 8439 // If sextload is not supported by target, we can only do the combine when 8440 // load has one use. Doing otherwise can block folding the extload with other 8441 // extends that the target does support. 8442 if (ISD::isEXTLoad(N0.getNode()) && 8443 ISD::isUNINDEXEDLoad(N0.getNode()) && 8444 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 8445 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile() && 8446 N0.hasOneUse()) || 8447 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 8448 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8449 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 8450 LN0->getChain(), 8451 LN0->getBasePtr(), EVT, 8452 LN0->getMemOperand()); 8453 CombineTo(N, ExtLoad); 8454 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 8455 AddToWorklist(ExtLoad.getNode()); 8456 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8457 } 8458 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 8459 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 8460 N0.hasOneUse() && 8461 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 8462 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 8463 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 8464 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8465 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 8466 LN0->getChain(), 8467 LN0->getBasePtr(), EVT, 8468 LN0->getMemOperand()); 8469 CombineTo(N, ExtLoad); 8470 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 8471 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8472 } 8473 8474 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 8475 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 8476 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 8477 N0.getOperand(1), false)) 8478 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 8479 BSwap, N1); 8480 } 8481 8482 return SDValue(); 8483 } 8484 8485 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 8486 SDValue N0 = N->getOperand(0); 8487 EVT VT = N->getValueType(0); 8488 8489 if (N0.isUndef()) 8490 return DAG.getUNDEF(VT); 8491 8492 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8493 LegalOperations)) 8494 return SDValue(Res, 0); 8495 8496 return SDValue(); 8497 } 8498 8499 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 8500 SDValue N0 = N->getOperand(0); 8501 EVT VT = N->getValueType(0); 8502 8503 if (N0.isUndef()) 8504 return DAG.getUNDEF(VT); 8505 8506 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8507 LegalOperations)) 8508 return SDValue(Res, 0); 8509 8510 return SDValue(); 8511 } 8512 8513 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 8514 SDValue N0 = N->getOperand(0); 8515 EVT VT = N->getValueType(0); 8516 bool isLE = DAG.getDataLayout().isLittleEndian(); 8517 8518 // noop truncate 8519 if (N0.getValueType() == N->getValueType(0)) 8520 return N0; 8521 8522 // fold (truncate (truncate x)) -> (truncate x) 8523 if (N0.getOpcode() == ISD::TRUNCATE) 8524 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 8525 8526 // fold (truncate c1) -> c1 8527 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 8528 SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 8529 if (C.getNode() != N) 8530 return C; 8531 } 8532 8533 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 8534 if (N0.getOpcode() == ISD::ZERO_EXTEND || 8535 N0.getOpcode() == ISD::SIGN_EXTEND || 8536 N0.getOpcode() == ISD::ANY_EXTEND) { 8537 // if the source is smaller than the dest, we still need an extend. 8538 if (N0.getOperand(0).getValueType().bitsLT(VT)) 8539 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 8540 // if the source is larger than the dest, than we just need the truncate. 8541 if (N0.getOperand(0).getValueType().bitsGT(VT)) 8542 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 8543 // if the source and dest are the same type, we can drop both the extend 8544 // and the truncate. 8545 return N0.getOperand(0); 8546 } 8547 8548 // If this is anyext(trunc), don't fold it, allow ourselves to be folded. 8549 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND)) 8550 return SDValue(); 8551 8552 // Fold extract-and-trunc into a narrow extract. For example: 8553 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 8554 // i32 y = TRUNCATE(i64 x) 8555 // -- becomes -- 8556 // v16i8 b = BITCAST (v2i64 val) 8557 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 8558 // 8559 // Note: We only run this optimization after type legalization (which often 8560 // creates this pattern) and before operation legalization after which 8561 // we need to be more careful about the vector instructions that we generate. 8562 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 8563 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 8564 EVT VecTy = N0.getOperand(0).getValueType(); 8565 EVT ExTy = N0.getValueType(); 8566 EVT TrTy = N->getValueType(0); 8567 8568 unsigned NumElem = VecTy.getVectorNumElements(); 8569 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 8570 8571 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 8572 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 8573 8574 SDValue EltNo = N0->getOperand(1); 8575 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 8576 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 8577 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 8578 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 8579 8580 SDLoc DL(N); 8581 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 8582 DAG.getBitcast(NVT, N0.getOperand(0)), 8583 DAG.getConstant(Index, DL, IndexTy)); 8584 } 8585 } 8586 8587 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 8588 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) { 8589 EVT SrcVT = N0.getValueType(); 8590 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 8591 TLI.isTruncateFree(SrcVT, VT)) { 8592 SDLoc SL(N0); 8593 SDValue Cond = N0.getOperand(0); 8594 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 8595 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 8596 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 8597 } 8598 } 8599 8600 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits() 8601 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 8602 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 8603 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 8604 SDValue Amt = N0.getOperand(1); 8605 KnownBits Known; 8606 DAG.computeKnownBits(Amt, Known); 8607 unsigned Size = VT.getScalarSizeInBits(); 8608 if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) { 8609 SDLoc SL(N); 8610 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 8611 8612 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 8613 if (AmtVT != Amt.getValueType()) { 8614 Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT); 8615 AddToWorklist(Amt.getNode()); 8616 } 8617 return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt); 8618 } 8619 } 8620 8621 // Fold a series of buildvector, bitcast, and truncate if possible. 8622 // For example fold 8623 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 8624 // (2xi32 (buildvector x, y)). 8625 if (Level == AfterLegalizeVectorOps && VT.isVector() && 8626 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 8627 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 8628 N0.getOperand(0).hasOneUse()) { 8629 SDValue BuildVect = N0.getOperand(0); 8630 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 8631 EVT TruncVecEltTy = VT.getVectorElementType(); 8632 8633 // Check that the element types match. 8634 if (BuildVectEltTy == TruncVecEltTy) { 8635 // Now we only need to compute the offset of the truncated elements. 8636 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 8637 unsigned TruncVecNumElts = VT.getVectorNumElements(); 8638 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 8639 8640 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 8641 "Invalid number of elements"); 8642 8643 SmallVector<SDValue, 8> Opnds; 8644 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 8645 Opnds.push_back(BuildVect.getOperand(i)); 8646 8647 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 8648 } 8649 } 8650 8651 // See if we can simplify the input to this truncate through knowledge that 8652 // only the low bits are being used. 8653 // For example "trunc (or (shl x, 8), y)" // -> trunc y 8654 // Currently we only perform this optimization on scalars because vectors 8655 // may have different active low bits. 8656 if (!VT.isVector()) { 8657 APInt Mask = 8658 APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits()); 8659 if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask)) 8660 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 8661 } 8662 8663 // fold (truncate (load x)) -> (smaller load x) 8664 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 8665 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 8666 if (SDValue Reduced = ReduceLoadWidth(N)) 8667 return Reduced; 8668 8669 // Handle the case where the load remains an extending load even 8670 // after truncation. 8671 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 8672 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8673 if (!LN0->isVolatile() && 8674 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 8675 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 8676 VT, LN0->getChain(), LN0->getBasePtr(), 8677 LN0->getMemoryVT(), 8678 LN0->getMemOperand()); 8679 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 8680 return NewLoad; 8681 } 8682 } 8683 } 8684 8685 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 8686 // where ... are all 'undef'. 8687 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 8688 SmallVector<EVT, 8> VTs; 8689 SDValue V; 8690 unsigned Idx = 0; 8691 unsigned NumDefs = 0; 8692 8693 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 8694 SDValue X = N0.getOperand(i); 8695 if (!X.isUndef()) { 8696 V = X; 8697 Idx = i; 8698 NumDefs++; 8699 } 8700 // Stop if more than one members are non-undef. 8701 if (NumDefs > 1) 8702 break; 8703 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 8704 VT.getVectorElementType(), 8705 X.getValueType().getVectorNumElements())); 8706 } 8707 8708 if (NumDefs == 0) 8709 return DAG.getUNDEF(VT); 8710 8711 if (NumDefs == 1) { 8712 assert(V.getNode() && "The single defined operand is empty!"); 8713 SmallVector<SDValue, 8> Opnds; 8714 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 8715 if (i != Idx) { 8716 Opnds.push_back(DAG.getUNDEF(VTs[i])); 8717 continue; 8718 } 8719 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 8720 AddToWorklist(NV.getNode()); 8721 Opnds.push_back(NV); 8722 } 8723 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 8724 } 8725 } 8726 8727 // Fold truncate of a bitcast of a vector to an extract of the low vector 8728 // element. 8729 // 8730 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx 8731 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 8732 SDValue VecSrc = N0.getOperand(0); 8733 EVT SrcVT = VecSrc.getValueType(); 8734 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 8735 (!LegalOperations || 8736 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 8737 SDLoc SL(N); 8738 8739 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 8740 unsigned Idx = isLE ? 0 : SrcVT.getVectorNumElements() - 1; 8741 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 8742 VecSrc, DAG.getConstant(Idx, SL, IdxVT)); 8743 } 8744 } 8745 8746 // Simplify the operands using demanded-bits information. 8747 if (!VT.isVector() && 8748 SimplifyDemandedBits(SDValue(N, 0))) 8749 return SDValue(N, 0); 8750 8751 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry) 8752 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry) 8753 // When the adde's carry is not used. 8754 if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) && 8755 N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) && 8756 (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) { 8757 SDLoc SL(N); 8758 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 8759 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 8760 auto VTs = DAG.getVTList(VT, N0->getValueType(1)); 8761 return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2)); 8762 } 8763 8764 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 8765 return NewVSel; 8766 8767 return SDValue(); 8768 } 8769 8770 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 8771 SDValue Elt = N->getOperand(i); 8772 if (Elt.getOpcode() != ISD::MERGE_VALUES) 8773 return Elt.getNode(); 8774 return Elt.getOperand(Elt.getResNo()).getNode(); 8775 } 8776 8777 /// build_pair (load, load) -> load 8778 /// if load locations are consecutive. 8779 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 8780 assert(N->getOpcode() == ISD::BUILD_PAIR); 8781 8782 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 8783 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 8784 8785 // A BUILD_PAIR is always having the least significant part in elt 0 and the 8786 // most significant part in elt 1. So when combining into one large load, we 8787 // need to consider the endianness. 8788 if (DAG.getDataLayout().isBigEndian()) 8789 std::swap(LD1, LD2); 8790 8791 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 8792 LD1->getAddressSpace() != LD2->getAddressSpace()) 8793 return SDValue(); 8794 EVT LD1VT = LD1->getValueType(0); 8795 unsigned LD1Bytes = LD1VT.getStoreSize(); 8796 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 8797 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 8798 unsigned Align = LD1->getAlignment(); 8799 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 8800 VT.getTypeForEVT(*DAG.getContext())); 8801 8802 if (NewAlign <= Align && 8803 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 8804 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 8805 LD1->getPointerInfo(), Align); 8806 } 8807 8808 return SDValue(); 8809 } 8810 8811 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 8812 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 8813 // and Lo parts; on big-endian machines it doesn't. 8814 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 8815 } 8816 8817 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 8818 const TargetLowering &TLI) { 8819 // If this is not a bitcast to an FP type or if the target doesn't have 8820 // IEEE754-compliant FP logic, we're done. 8821 EVT VT = N->getValueType(0); 8822 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 8823 return SDValue(); 8824 8825 // TODO: Use splat values for the constant-checking below and remove this 8826 // restriction. 8827 SDValue N0 = N->getOperand(0); 8828 EVT SourceVT = N0.getValueType(); 8829 if (SourceVT.isVector()) 8830 return SDValue(); 8831 8832 unsigned FPOpcode; 8833 APInt SignMask; 8834 switch (N0.getOpcode()) { 8835 case ISD::AND: 8836 FPOpcode = ISD::FABS; 8837 SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits()); 8838 break; 8839 case ISD::XOR: 8840 FPOpcode = ISD::FNEG; 8841 SignMask = APInt::getSignMask(SourceVT.getSizeInBits()); 8842 break; 8843 // TODO: ISD::OR --> ISD::FNABS? 8844 default: 8845 return SDValue(); 8846 } 8847 8848 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 8849 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 8850 SDValue LogicOp0 = N0.getOperand(0); 8851 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8852 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 8853 LogicOp0.getOpcode() == ISD::BITCAST && 8854 LogicOp0->getOperand(0).getValueType() == VT) 8855 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0)); 8856 8857 return SDValue(); 8858 } 8859 8860 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 8861 SDValue N0 = N->getOperand(0); 8862 EVT VT = N->getValueType(0); 8863 8864 if (N0.isUndef()) 8865 return DAG.getUNDEF(VT); 8866 8867 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 8868 // Only do this before legalize, since afterward the target may be depending 8869 // on the bitconvert. 8870 // First check to see if this is all constant. 8871 if (!LegalTypes && 8872 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 8873 VT.isVector()) { 8874 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 8875 8876 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 8877 assert(!DestEltVT.isVector() && 8878 "Element type of vector ValueType must not be vector!"); 8879 if (isSimple) 8880 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 8881 } 8882 8883 // If the input is a constant, let getNode fold it. 8884 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 8885 // If we can't allow illegal operations, we need to check that this is just 8886 // a fp -> int or int -> conversion and that the resulting operation will 8887 // be legal. 8888 if (!LegalOperations || 8889 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 8890 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 8891 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 8892 TLI.isOperationLegal(ISD::Constant, VT))) 8893 return DAG.getBitcast(VT, N0); 8894 } 8895 8896 // (conv (conv x, t1), t2) -> (conv x, t2) 8897 if (N0.getOpcode() == ISD::BITCAST) 8898 return DAG.getBitcast(VT, N0.getOperand(0)); 8899 8900 // fold (conv (load x)) -> (load (conv*)x) 8901 // If the resultant load doesn't need a higher alignment than the original! 8902 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8903 // Do not change the width of a volatile load. 8904 !cast<LoadSDNode>(N0)->isVolatile() && 8905 // Do not remove the cast if the types differ in endian layout. 8906 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 8907 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 8908 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 8909 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 8910 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8911 unsigned OrigAlign = LN0->getAlignment(); 8912 8913 bool Fast = false; 8914 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 8915 LN0->getAddressSpace(), OrigAlign, &Fast) && 8916 Fast) { 8917 SDValue Load = 8918 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 8919 LN0->getPointerInfo(), OrigAlign, 8920 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8921 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 8922 return Load; 8923 } 8924 } 8925 8926 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 8927 return V; 8928 8929 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8930 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8931 // 8932 // For ppc_fp128: 8933 // fold (bitcast (fneg x)) -> 8934 // flipbit = signbit 8935 // (xor (bitcast x) (build_pair flipbit, flipbit)) 8936 // 8937 // fold (bitcast (fabs x)) -> 8938 // flipbit = (and (extract_element (bitcast x), 0), signbit) 8939 // (xor (bitcast x) (build_pair flipbit, flipbit)) 8940 // This often reduces constant pool loads. 8941 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 8942 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 8943 N0.getNode()->hasOneUse() && VT.isInteger() && 8944 !VT.isVector() && !N0.getValueType().isVector()) { 8945 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 8946 AddToWorklist(NewConv.getNode()); 8947 8948 SDLoc DL(N); 8949 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 8950 assert(VT.getSizeInBits() == 128); 8951 SDValue SignBit = DAG.getConstant( 8952 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 8953 SDValue FlipBit; 8954 if (N0.getOpcode() == ISD::FNEG) { 8955 FlipBit = SignBit; 8956 AddToWorklist(FlipBit.getNode()); 8957 } else { 8958 assert(N0.getOpcode() == ISD::FABS); 8959 SDValue Hi = 8960 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 8961 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 8962 SDLoc(NewConv))); 8963 AddToWorklist(Hi.getNode()); 8964 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 8965 AddToWorklist(FlipBit.getNode()); 8966 } 8967 SDValue FlipBits = 8968 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 8969 AddToWorklist(FlipBits.getNode()); 8970 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 8971 } 8972 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 8973 if (N0.getOpcode() == ISD::FNEG) 8974 return DAG.getNode(ISD::XOR, DL, VT, 8975 NewConv, DAG.getConstant(SignBit, DL, VT)); 8976 assert(N0.getOpcode() == ISD::FABS); 8977 return DAG.getNode(ISD::AND, DL, VT, 8978 NewConv, DAG.getConstant(~SignBit, DL, VT)); 8979 } 8980 8981 // fold (bitconvert (fcopysign cst, x)) -> 8982 // (or (and (bitconvert x), sign), (and cst, (not sign))) 8983 // Note that we don't handle (copysign x, cst) because this can always be 8984 // folded to an fneg or fabs. 8985 // 8986 // For ppc_fp128: 8987 // fold (bitcast (fcopysign cst, x)) -> 8988 // flipbit = (and (extract_element 8989 // (xor (bitcast cst), (bitcast x)), 0), 8990 // signbit) 8991 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 8992 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 8993 isa<ConstantFPSDNode>(N0.getOperand(0)) && 8994 VT.isInteger() && !VT.isVector()) { 8995 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits(); 8996 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 8997 if (isTypeLegal(IntXVT)) { 8998 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 8999 AddToWorklist(X.getNode()); 9000 9001 // If X has a different width than the result/lhs, sext it or truncate it. 9002 unsigned VTWidth = VT.getSizeInBits(); 9003 if (OrigXWidth < VTWidth) { 9004 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 9005 AddToWorklist(X.getNode()); 9006 } else if (OrigXWidth > VTWidth) { 9007 // To get the sign bit in the right place, we have to shift it right 9008 // before truncating. 9009 SDLoc DL(X); 9010 X = DAG.getNode(ISD::SRL, DL, 9011 X.getValueType(), X, 9012 DAG.getConstant(OrigXWidth-VTWidth, DL, 9013 X.getValueType())); 9014 AddToWorklist(X.getNode()); 9015 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 9016 AddToWorklist(X.getNode()); 9017 } 9018 9019 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 9020 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2); 9021 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 9022 AddToWorklist(Cst.getNode()); 9023 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 9024 AddToWorklist(X.getNode()); 9025 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 9026 AddToWorklist(XorResult.getNode()); 9027 SDValue XorResult64 = DAG.getNode( 9028 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 9029 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 9030 SDLoc(XorResult))); 9031 AddToWorklist(XorResult64.getNode()); 9032 SDValue FlipBit = 9033 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 9034 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 9035 AddToWorklist(FlipBit.getNode()); 9036 SDValue FlipBits = 9037 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 9038 AddToWorklist(FlipBits.getNode()); 9039 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 9040 } 9041 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 9042 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 9043 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 9044 AddToWorklist(X.getNode()); 9045 9046 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 9047 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 9048 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 9049 AddToWorklist(Cst.getNode()); 9050 9051 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 9052 } 9053 } 9054 9055 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 9056 if (N0.getOpcode() == ISD::BUILD_PAIR) 9057 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 9058 return CombineLD; 9059 9060 // Remove double bitcasts from shuffles - this is often a legacy of 9061 // XformToShuffleWithZero being used to combine bitmaskings (of 9062 // float vectors bitcast to integer vectors) into shuffles. 9063 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 9064 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 9065 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 9066 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 9067 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 9068 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 9069 9070 // If operands are a bitcast, peek through if it casts the original VT. 9071 // If operands are a constant, just bitcast back to original VT. 9072 auto PeekThroughBitcast = [&](SDValue Op) { 9073 if (Op.getOpcode() == ISD::BITCAST && 9074 Op.getOperand(0).getValueType() == VT) 9075 return SDValue(Op.getOperand(0)); 9076 if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 9077 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 9078 return DAG.getBitcast(VT, Op); 9079 return SDValue(); 9080 }; 9081 9082 // FIXME: If either input vector is bitcast, try to convert the shuffle to 9083 // the result type of this bitcast. This would eliminate at least one 9084 // bitcast. See the transform in InstCombine. 9085 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 9086 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 9087 if (!(SV0 && SV1)) 9088 return SDValue(); 9089 9090 int MaskScale = 9091 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 9092 SmallVector<int, 8> NewMask; 9093 for (int M : SVN->getMask()) 9094 for (int i = 0; i != MaskScale; ++i) 9095 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 9096 9097 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 9098 if (!LegalMask) { 9099 std::swap(SV0, SV1); 9100 ShuffleVectorSDNode::commuteMask(NewMask); 9101 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 9102 } 9103 9104 if (LegalMask) 9105 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 9106 } 9107 9108 return SDValue(); 9109 } 9110 9111 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 9112 EVT VT = N->getValueType(0); 9113 return CombineConsecutiveLoads(N, VT); 9114 } 9115 9116 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 9117 /// operands. DstEltVT indicates the destination element value type. 9118 SDValue DAGCombiner:: 9119 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 9120 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 9121 9122 // If this is already the right type, we're done. 9123 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 9124 9125 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 9126 unsigned DstBitSize = DstEltVT.getSizeInBits(); 9127 9128 // If this is a conversion of N elements of one type to N elements of another 9129 // type, convert each element. This handles FP<->INT cases. 9130 if (SrcBitSize == DstBitSize) { 9131 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 9132 BV->getValueType(0).getVectorNumElements()); 9133 9134 // Due to the FP element handling below calling this routine recursively, 9135 // we can end up with a scalar-to-vector node here. 9136 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 9137 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 9138 DAG.getBitcast(DstEltVT, BV->getOperand(0))); 9139 9140 SmallVector<SDValue, 8> Ops; 9141 for (SDValue Op : BV->op_values()) { 9142 // If the vector element type is not legal, the BUILD_VECTOR operands 9143 // are promoted and implicitly truncated. Make that explicit here. 9144 if (Op.getValueType() != SrcEltVT) 9145 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 9146 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 9147 AddToWorklist(Ops.back().getNode()); 9148 } 9149 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 9150 } 9151 9152 // Otherwise, we're growing or shrinking the elements. To avoid having to 9153 // handle annoying details of growing/shrinking FP values, we convert them to 9154 // int first. 9155 if (SrcEltVT.isFloatingPoint()) { 9156 // Convert the input float vector to a int vector where the elements are the 9157 // same sizes. 9158 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 9159 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 9160 SrcEltVT = IntVT; 9161 } 9162 9163 // Now we know the input is an integer vector. If the output is a FP type, 9164 // convert to integer first, then to FP of the right size. 9165 if (DstEltVT.isFloatingPoint()) { 9166 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 9167 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 9168 9169 // Next, convert to FP elements of the same size. 9170 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 9171 } 9172 9173 SDLoc DL(BV); 9174 9175 // Okay, we know the src/dst types are both integers of differing types. 9176 // Handling growing first. 9177 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 9178 if (SrcBitSize < DstBitSize) { 9179 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 9180 9181 SmallVector<SDValue, 8> Ops; 9182 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 9183 i += NumInputsPerOutput) { 9184 bool isLE = DAG.getDataLayout().isLittleEndian(); 9185 APInt NewBits = APInt(DstBitSize, 0); 9186 bool EltIsUndef = true; 9187 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 9188 // Shift the previously computed bits over. 9189 NewBits <<= SrcBitSize; 9190 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 9191 if (Op.isUndef()) continue; 9192 EltIsUndef = false; 9193 9194 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 9195 zextOrTrunc(SrcBitSize).zext(DstBitSize); 9196 } 9197 9198 if (EltIsUndef) 9199 Ops.push_back(DAG.getUNDEF(DstEltVT)); 9200 else 9201 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 9202 } 9203 9204 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 9205 return DAG.getBuildVector(VT, DL, Ops); 9206 } 9207 9208 // Finally, this must be the case where we are shrinking elements: each input 9209 // turns into multiple outputs. 9210 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 9211 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 9212 NumOutputsPerInput*BV->getNumOperands()); 9213 SmallVector<SDValue, 8> Ops; 9214 9215 for (const SDValue &Op : BV->op_values()) { 9216 if (Op.isUndef()) { 9217 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 9218 continue; 9219 } 9220 9221 APInt OpVal = cast<ConstantSDNode>(Op)-> 9222 getAPIntValue().zextOrTrunc(SrcBitSize); 9223 9224 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 9225 APInt ThisVal = OpVal.trunc(DstBitSize); 9226 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 9227 OpVal.lshrInPlace(DstBitSize); 9228 } 9229 9230 // For big endian targets, swap the order of the pieces of each element. 9231 if (DAG.getDataLayout().isBigEndian()) 9232 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 9233 } 9234 9235 return DAG.getBuildVector(VT, DL, Ops); 9236 } 9237 9238 static bool isContractable(SDNode *N) { 9239 SDNodeFlags F = N->getFlags(); 9240 return F.hasAllowContract() || F.hasUnsafeAlgebra(); 9241 } 9242 9243 /// Try to perform FMA combining on a given FADD node. 9244 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 9245 SDValue N0 = N->getOperand(0); 9246 SDValue N1 = N->getOperand(1); 9247 EVT VT = N->getValueType(0); 9248 SDLoc SL(N); 9249 9250 const TargetOptions &Options = DAG.getTarget().Options; 9251 9252 // Floating-point multiply-add with intermediate rounding. 9253 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9254 9255 // Floating-point multiply-add without intermediate rounding. 9256 bool HasFMA = 9257 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9258 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9259 9260 // No valid opcode, do not combine. 9261 if (!HasFMAD && !HasFMA) 9262 return SDValue(); 9263 9264 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 9265 Options.UnsafeFPMath || HasFMAD); 9266 // If the addition is not contractable, do not combine. 9267 if (!AllowFusionGlobally && !isContractable(N)) 9268 return SDValue(); 9269 9270 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 9271 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 9272 return SDValue(); 9273 9274 // Always prefer FMAD to FMA for precision. 9275 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9276 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9277 9278 // Is the node an FMUL and contractable either due to global flags or 9279 // SDNodeFlags. 9280 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 9281 if (N.getOpcode() != ISD::FMUL) 9282 return false; 9283 return AllowFusionGlobally || isContractable(N.getNode()); 9284 }; 9285 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 9286 // prefer to fold the multiply with fewer uses. 9287 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) { 9288 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 9289 std::swap(N0, N1); 9290 } 9291 9292 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 9293 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 9294 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9295 N0.getOperand(0), N0.getOperand(1), N1); 9296 } 9297 9298 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 9299 // Note: Commutes FADD operands. 9300 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) { 9301 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9302 N1.getOperand(0), N1.getOperand(1), N0); 9303 } 9304 9305 // Look through FP_EXTEND nodes to do more combining. 9306 9307 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 9308 if (N0.getOpcode() == ISD::FP_EXTEND) { 9309 SDValue N00 = N0.getOperand(0); 9310 if (isContractableFMUL(N00) && 9311 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 9312 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9313 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9314 N00.getOperand(0)), 9315 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9316 N00.getOperand(1)), N1); 9317 } 9318 } 9319 9320 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 9321 // Note: Commutes FADD operands. 9322 if (N1.getOpcode() == ISD::FP_EXTEND) { 9323 SDValue N10 = N1.getOperand(0); 9324 if (isContractableFMUL(N10) && 9325 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 9326 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9327 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9328 N10.getOperand(0)), 9329 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9330 N10.getOperand(1)), N0); 9331 } 9332 } 9333 9334 // More folding opportunities when target permits. 9335 if (Aggressive) { 9336 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 9337 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9338 // are currently only supported on binary nodes. 9339 if (Options.UnsafeFPMath && 9340 N0.getOpcode() == PreferredFusedOpcode && 9341 N0.getOperand(2).getOpcode() == ISD::FMUL && 9342 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) { 9343 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9344 N0.getOperand(0), N0.getOperand(1), 9345 DAG.getNode(PreferredFusedOpcode, SL, VT, 9346 N0.getOperand(2).getOperand(0), 9347 N0.getOperand(2).getOperand(1), 9348 N1)); 9349 } 9350 9351 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 9352 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9353 // are currently only supported on binary nodes. 9354 if (Options.UnsafeFPMath && 9355 N1->getOpcode() == PreferredFusedOpcode && 9356 N1.getOperand(2).getOpcode() == ISD::FMUL && 9357 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) { 9358 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9359 N1.getOperand(0), N1.getOperand(1), 9360 DAG.getNode(PreferredFusedOpcode, SL, VT, 9361 N1.getOperand(2).getOperand(0), 9362 N1.getOperand(2).getOperand(1), 9363 N0)); 9364 } 9365 9366 9367 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 9368 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 9369 auto FoldFAddFMAFPExtFMul = [&] ( 9370 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 9371 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 9372 DAG.getNode(PreferredFusedOpcode, SL, VT, 9373 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 9374 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 9375 Z)); 9376 }; 9377 if (N0.getOpcode() == PreferredFusedOpcode) { 9378 SDValue N02 = N0.getOperand(2); 9379 if (N02.getOpcode() == ISD::FP_EXTEND) { 9380 SDValue N020 = N02.getOperand(0); 9381 if (isContractableFMUL(N020) && 9382 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) { 9383 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 9384 N020.getOperand(0), N020.getOperand(1), 9385 N1); 9386 } 9387 } 9388 } 9389 9390 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 9391 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 9392 // FIXME: This turns two single-precision and one double-precision 9393 // operation into two double-precision operations, which might not be 9394 // interesting for all targets, especially GPUs. 9395 auto FoldFAddFPExtFMAFMul = [&] ( 9396 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 9397 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9398 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 9399 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 9400 DAG.getNode(PreferredFusedOpcode, SL, VT, 9401 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 9402 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 9403 Z)); 9404 }; 9405 if (N0.getOpcode() == ISD::FP_EXTEND) { 9406 SDValue N00 = N0.getOperand(0); 9407 if (N00.getOpcode() == PreferredFusedOpcode) { 9408 SDValue N002 = N00.getOperand(2); 9409 if (isContractableFMUL(N002) && 9410 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 9411 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 9412 N002.getOperand(0), N002.getOperand(1), 9413 N1); 9414 } 9415 } 9416 } 9417 9418 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 9419 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 9420 if (N1.getOpcode() == PreferredFusedOpcode) { 9421 SDValue N12 = N1.getOperand(2); 9422 if (N12.getOpcode() == ISD::FP_EXTEND) { 9423 SDValue N120 = N12.getOperand(0); 9424 if (isContractableFMUL(N120) && 9425 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) { 9426 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 9427 N120.getOperand(0), N120.getOperand(1), 9428 N0); 9429 } 9430 } 9431 } 9432 9433 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 9434 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 9435 // FIXME: This turns two single-precision and one double-precision 9436 // operation into two double-precision operations, which might not be 9437 // interesting for all targets, especially GPUs. 9438 if (N1.getOpcode() == ISD::FP_EXTEND) { 9439 SDValue N10 = N1.getOperand(0); 9440 if (N10.getOpcode() == PreferredFusedOpcode) { 9441 SDValue N102 = N10.getOperand(2); 9442 if (isContractableFMUL(N102) && 9443 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 9444 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 9445 N102.getOperand(0), N102.getOperand(1), 9446 N0); 9447 } 9448 } 9449 } 9450 } 9451 9452 return SDValue(); 9453 } 9454 9455 /// Try to perform FMA combining on a given FSUB node. 9456 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 9457 SDValue N0 = N->getOperand(0); 9458 SDValue N1 = N->getOperand(1); 9459 EVT VT = N->getValueType(0); 9460 SDLoc SL(N); 9461 9462 const TargetOptions &Options = DAG.getTarget().Options; 9463 // Floating-point multiply-add with intermediate rounding. 9464 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9465 9466 // Floating-point multiply-add without intermediate rounding. 9467 bool HasFMA = 9468 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9469 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9470 9471 // No valid opcode, do not combine. 9472 if (!HasFMAD && !HasFMA) 9473 return SDValue(); 9474 9475 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 9476 Options.UnsafeFPMath || HasFMAD); 9477 // If the subtraction is not contractable, do not combine. 9478 if (!AllowFusionGlobally && !isContractable(N)) 9479 return SDValue(); 9480 9481 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 9482 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 9483 return SDValue(); 9484 9485 // Always prefer FMAD to FMA for precision. 9486 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9487 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9488 9489 // Is the node an FMUL and contractable either due to global flags or 9490 // SDNodeFlags. 9491 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 9492 if (N.getOpcode() != ISD::FMUL) 9493 return false; 9494 return AllowFusionGlobally || isContractable(N.getNode()); 9495 }; 9496 9497 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 9498 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 9499 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9500 N0.getOperand(0), N0.getOperand(1), 9501 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9502 } 9503 9504 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 9505 // Note: Commutes FSUB operands. 9506 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) 9507 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9508 DAG.getNode(ISD::FNEG, SL, VT, 9509 N1.getOperand(0)), 9510 N1.getOperand(1), N0); 9511 9512 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 9513 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) && 9514 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 9515 SDValue N00 = N0.getOperand(0).getOperand(0); 9516 SDValue N01 = N0.getOperand(0).getOperand(1); 9517 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9518 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 9519 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9520 } 9521 9522 // Look through FP_EXTEND nodes to do more combining. 9523 9524 // fold (fsub (fpext (fmul x, y)), z) 9525 // -> (fma (fpext x), (fpext y), (fneg z)) 9526 if (N0.getOpcode() == ISD::FP_EXTEND) { 9527 SDValue N00 = N0.getOperand(0); 9528 if (isContractableFMUL(N00) && 9529 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 9530 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9531 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9532 N00.getOperand(0)), 9533 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9534 N00.getOperand(1)), 9535 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9536 } 9537 } 9538 9539 // fold (fsub x, (fpext (fmul y, z))) 9540 // -> (fma (fneg (fpext y)), (fpext z), x) 9541 // Note: Commutes FSUB operands. 9542 if (N1.getOpcode() == ISD::FP_EXTEND) { 9543 SDValue N10 = N1.getOperand(0); 9544 if (isContractableFMUL(N10) && 9545 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 9546 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9547 DAG.getNode(ISD::FNEG, SL, VT, 9548 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9549 N10.getOperand(0))), 9550 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9551 N10.getOperand(1)), 9552 N0); 9553 } 9554 } 9555 9556 // fold (fsub (fpext (fneg (fmul, x, y))), z) 9557 // -> (fneg (fma (fpext x), (fpext y), z)) 9558 // Note: This could be removed with appropriate canonicalization of the 9559 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 9560 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 9561 // from implementing the canonicalization in visitFSUB. 9562 if (N0.getOpcode() == ISD::FP_EXTEND) { 9563 SDValue N00 = N0.getOperand(0); 9564 if (N00.getOpcode() == ISD::FNEG) { 9565 SDValue N000 = N00.getOperand(0); 9566 if (isContractableFMUL(N000) && 9567 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 9568 return DAG.getNode(ISD::FNEG, SL, VT, 9569 DAG.getNode(PreferredFusedOpcode, SL, VT, 9570 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9571 N000.getOperand(0)), 9572 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9573 N000.getOperand(1)), 9574 N1)); 9575 } 9576 } 9577 } 9578 9579 // fold (fsub (fneg (fpext (fmul, x, y))), z) 9580 // -> (fneg (fma (fpext x)), (fpext y), z) 9581 // Note: This could be removed with appropriate canonicalization of the 9582 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 9583 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 9584 // from implementing the canonicalization in visitFSUB. 9585 if (N0.getOpcode() == ISD::FNEG) { 9586 SDValue N00 = N0.getOperand(0); 9587 if (N00.getOpcode() == ISD::FP_EXTEND) { 9588 SDValue N000 = N00.getOperand(0); 9589 if (isContractableFMUL(N000) && 9590 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N000.getValueType())) { 9591 return DAG.getNode(ISD::FNEG, SL, VT, 9592 DAG.getNode(PreferredFusedOpcode, SL, VT, 9593 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9594 N000.getOperand(0)), 9595 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9596 N000.getOperand(1)), 9597 N1)); 9598 } 9599 } 9600 } 9601 9602 // More folding opportunities when target permits. 9603 if (Aggressive) { 9604 // fold (fsub (fma x, y, (fmul u, v)), z) 9605 // -> (fma x, y (fma u, v, (fneg z))) 9606 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9607 // are currently only supported on binary nodes. 9608 if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode && 9609 isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() && 9610 N0.getOperand(2)->hasOneUse()) { 9611 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9612 N0.getOperand(0), N0.getOperand(1), 9613 DAG.getNode(PreferredFusedOpcode, SL, VT, 9614 N0.getOperand(2).getOperand(0), 9615 N0.getOperand(2).getOperand(1), 9616 DAG.getNode(ISD::FNEG, SL, VT, 9617 N1))); 9618 } 9619 9620 // fold (fsub x, (fma y, z, (fmul u, v))) 9621 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 9622 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9623 // are currently only supported on binary nodes. 9624 if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode && 9625 isContractableFMUL(N1.getOperand(2))) { 9626 SDValue N20 = N1.getOperand(2).getOperand(0); 9627 SDValue N21 = N1.getOperand(2).getOperand(1); 9628 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9629 DAG.getNode(ISD::FNEG, SL, VT, 9630 N1.getOperand(0)), 9631 N1.getOperand(1), 9632 DAG.getNode(PreferredFusedOpcode, SL, VT, 9633 DAG.getNode(ISD::FNEG, SL, VT, N20), 9634 9635 N21, N0)); 9636 } 9637 9638 9639 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 9640 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 9641 if (N0.getOpcode() == PreferredFusedOpcode) { 9642 SDValue N02 = N0.getOperand(2); 9643 if (N02.getOpcode() == ISD::FP_EXTEND) { 9644 SDValue N020 = N02.getOperand(0); 9645 if (isContractableFMUL(N020) && 9646 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) { 9647 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9648 N0.getOperand(0), N0.getOperand(1), 9649 DAG.getNode(PreferredFusedOpcode, SL, VT, 9650 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9651 N020.getOperand(0)), 9652 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9653 N020.getOperand(1)), 9654 DAG.getNode(ISD::FNEG, SL, VT, 9655 N1))); 9656 } 9657 } 9658 } 9659 9660 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 9661 // -> (fma (fpext x), (fpext y), 9662 // (fma (fpext u), (fpext v), (fneg z))) 9663 // FIXME: This turns two single-precision and one double-precision 9664 // operation into two double-precision operations, which might not be 9665 // interesting for all targets, especially GPUs. 9666 if (N0.getOpcode() == ISD::FP_EXTEND) { 9667 SDValue N00 = N0.getOperand(0); 9668 if (N00.getOpcode() == PreferredFusedOpcode) { 9669 SDValue N002 = N00.getOperand(2); 9670 if (isContractableFMUL(N002) && 9671 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 9672 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9673 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9674 N00.getOperand(0)), 9675 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9676 N00.getOperand(1)), 9677 DAG.getNode(PreferredFusedOpcode, SL, VT, 9678 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9679 N002.getOperand(0)), 9680 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9681 N002.getOperand(1)), 9682 DAG.getNode(ISD::FNEG, SL, VT, 9683 N1))); 9684 } 9685 } 9686 } 9687 9688 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 9689 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 9690 if (N1.getOpcode() == PreferredFusedOpcode && 9691 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 9692 SDValue N120 = N1.getOperand(2).getOperand(0); 9693 if (isContractableFMUL(N120) && 9694 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) { 9695 SDValue N1200 = N120.getOperand(0); 9696 SDValue N1201 = N120.getOperand(1); 9697 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9698 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 9699 N1.getOperand(1), 9700 DAG.getNode(PreferredFusedOpcode, SL, VT, 9701 DAG.getNode(ISD::FNEG, SL, VT, 9702 DAG.getNode(ISD::FP_EXTEND, SL, 9703 VT, N1200)), 9704 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9705 N1201), 9706 N0)); 9707 } 9708 } 9709 9710 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 9711 // -> (fma (fneg (fpext y)), (fpext z), 9712 // (fma (fneg (fpext u)), (fpext v), x)) 9713 // FIXME: This turns two single-precision and one double-precision 9714 // operation into two double-precision operations, which might not be 9715 // interesting for all targets, especially GPUs. 9716 if (N1.getOpcode() == ISD::FP_EXTEND && 9717 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 9718 SDValue CvtSrc = N1.getOperand(0); 9719 SDValue N100 = CvtSrc.getOperand(0); 9720 SDValue N101 = CvtSrc.getOperand(1); 9721 SDValue N102 = CvtSrc.getOperand(2); 9722 if (isContractableFMUL(N102) && 9723 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, CvtSrc.getValueType())) { 9724 SDValue N1020 = N102.getOperand(0); 9725 SDValue N1021 = N102.getOperand(1); 9726 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9727 DAG.getNode(ISD::FNEG, SL, VT, 9728 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9729 N100)), 9730 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 9731 DAG.getNode(PreferredFusedOpcode, SL, VT, 9732 DAG.getNode(ISD::FNEG, SL, VT, 9733 DAG.getNode(ISD::FP_EXTEND, SL, 9734 VT, N1020)), 9735 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9736 N1021), 9737 N0)); 9738 } 9739 } 9740 } 9741 9742 return SDValue(); 9743 } 9744 9745 /// Try to perform FMA combining on a given FMUL node based on the distributive 9746 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions, 9747 /// subtraction instead of addition). 9748 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) { 9749 SDValue N0 = N->getOperand(0); 9750 SDValue N1 = N->getOperand(1); 9751 EVT VT = N->getValueType(0); 9752 SDLoc SL(N); 9753 9754 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 9755 9756 const TargetOptions &Options = DAG.getTarget().Options; 9757 9758 // The transforms below are incorrect when x == 0 and y == inf, because the 9759 // intermediate multiplication produces a nan. 9760 if (!Options.NoInfsFPMath) 9761 return SDValue(); 9762 9763 // Floating-point multiply-add without intermediate rounding. 9764 bool HasFMA = 9765 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 9766 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9767 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9768 9769 // Floating-point multiply-add with intermediate rounding. This can result 9770 // in a less precise result due to the changed rounding order. 9771 bool HasFMAD = Options.UnsafeFPMath && 9772 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9773 9774 // No valid opcode, do not combine. 9775 if (!HasFMAD && !HasFMA) 9776 return SDValue(); 9777 9778 // Always prefer FMAD to FMA for precision. 9779 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9780 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9781 9782 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 9783 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 9784 auto FuseFADD = [&](SDValue X, SDValue Y) { 9785 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 9786 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 9787 if (XC1 && XC1->isExactlyValue(+1.0)) 9788 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 9789 if (XC1 && XC1->isExactlyValue(-1.0)) 9790 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 9791 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9792 } 9793 return SDValue(); 9794 }; 9795 9796 if (SDValue FMA = FuseFADD(N0, N1)) 9797 return FMA; 9798 if (SDValue FMA = FuseFADD(N1, N0)) 9799 return FMA; 9800 9801 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 9802 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 9803 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 9804 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 9805 auto FuseFSUB = [&](SDValue X, SDValue Y) { 9806 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 9807 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 9808 if (XC0 && XC0->isExactlyValue(+1.0)) 9809 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9810 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 9811 Y); 9812 if (XC0 && XC0->isExactlyValue(-1.0)) 9813 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9814 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 9815 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9816 9817 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 9818 if (XC1 && XC1->isExactlyValue(+1.0)) 9819 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 9820 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9821 if (XC1 && XC1->isExactlyValue(-1.0)) 9822 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 9823 } 9824 return SDValue(); 9825 }; 9826 9827 if (SDValue FMA = FuseFSUB(N0, N1)) 9828 return FMA; 9829 if (SDValue FMA = FuseFSUB(N1, N0)) 9830 return FMA; 9831 9832 return SDValue(); 9833 } 9834 9835 static bool isFMulNegTwo(SDValue &N) { 9836 if (N.getOpcode() != ISD::FMUL) 9837 return false; 9838 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1))) 9839 return CFP->isExactlyValue(-2.0); 9840 return false; 9841 } 9842 9843 SDValue DAGCombiner::visitFADD(SDNode *N) { 9844 SDValue N0 = N->getOperand(0); 9845 SDValue N1 = N->getOperand(1); 9846 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 9847 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 9848 EVT VT = N->getValueType(0); 9849 SDLoc DL(N); 9850 const TargetOptions &Options = DAG.getTarget().Options; 9851 const SDNodeFlags Flags = N->getFlags(); 9852 9853 // fold vector ops 9854 if (VT.isVector()) 9855 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9856 return FoldedVOp; 9857 9858 // fold (fadd c1, c2) -> c1 + c2 9859 if (N0CFP && N1CFP) 9860 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 9861 9862 // canonicalize constant to RHS 9863 if (N0CFP && !N1CFP) 9864 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 9865 9866 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9867 return NewSel; 9868 9869 // fold (fadd A, (fneg B)) -> (fsub A, B) 9870 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 9871 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 9872 return DAG.getNode(ISD::FSUB, DL, VT, N0, 9873 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 9874 9875 // fold (fadd (fneg A), B) -> (fsub B, A) 9876 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 9877 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 9878 return DAG.getNode(ISD::FSUB, DL, VT, N1, 9879 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 9880 9881 // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B)) 9882 // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B)) 9883 if ((isFMulNegTwo(N0) && N0.hasOneUse()) || 9884 (isFMulNegTwo(N1) && N1.hasOneUse())) { 9885 bool N1IsFMul = isFMulNegTwo(N1); 9886 SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0); 9887 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags); 9888 return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags); 9889 } 9890 9891 // FIXME: Auto-upgrade the target/function-level option. 9892 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) { 9893 // fold (fadd A, 0) -> A 9894 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 9895 if (N1C->isZero()) 9896 return N0; 9897 } 9898 9899 // If 'unsafe math' is enabled, fold lots of things. 9900 if (Options.UnsafeFPMath) { 9901 // No FP constant should be created after legalization as Instruction 9902 // Selection pass has a hard time dealing with FP constants. 9903 bool AllowNewConst = (Level < AfterLegalizeDAG); 9904 9905 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 9906 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 9907 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 9908 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 9909 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 9910 Flags), 9911 Flags); 9912 9913 // If allowed, fold (fadd (fneg x), x) -> 0.0 9914 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 9915 return DAG.getConstantFP(0.0, DL, VT); 9916 9917 // If allowed, fold (fadd x, (fneg x)) -> 0.0 9918 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 9919 return DAG.getConstantFP(0.0, DL, VT); 9920 9921 // We can fold chains of FADD's of the same value into multiplications. 9922 // This transform is not safe in general because we are reducing the number 9923 // of rounding steps. 9924 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 9925 if (N0.getOpcode() == ISD::FMUL) { 9926 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 9927 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 9928 9929 // (fadd (fmul x, c), x) -> (fmul x, c+1) 9930 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 9931 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 9932 DAG.getConstantFP(1.0, DL, VT), Flags); 9933 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 9934 } 9935 9936 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 9937 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 9938 N1.getOperand(0) == N1.getOperand(1) && 9939 N0.getOperand(0) == N1.getOperand(0)) { 9940 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 9941 DAG.getConstantFP(2.0, DL, VT), Flags); 9942 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 9943 } 9944 } 9945 9946 if (N1.getOpcode() == ISD::FMUL) { 9947 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 9948 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 9949 9950 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 9951 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 9952 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 9953 DAG.getConstantFP(1.0, DL, VT), Flags); 9954 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 9955 } 9956 9957 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 9958 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 9959 N0.getOperand(0) == N0.getOperand(1) && 9960 N1.getOperand(0) == N0.getOperand(0)) { 9961 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 9962 DAG.getConstantFP(2.0, DL, VT), Flags); 9963 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 9964 } 9965 } 9966 9967 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 9968 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 9969 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 9970 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 9971 (N0.getOperand(0) == N1)) { 9972 return DAG.getNode(ISD::FMUL, DL, VT, 9973 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 9974 } 9975 } 9976 9977 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 9978 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 9979 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 9980 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 9981 N1.getOperand(0) == N0) { 9982 return DAG.getNode(ISD::FMUL, DL, VT, 9983 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 9984 } 9985 } 9986 9987 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 9988 if (AllowNewConst && 9989 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 9990 N0.getOperand(0) == N0.getOperand(1) && 9991 N1.getOperand(0) == N1.getOperand(1) && 9992 N0.getOperand(0) == N1.getOperand(0)) { 9993 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 9994 DAG.getConstantFP(4.0, DL, VT), Flags); 9995 } 9996 } 9997 } // enable-unsafe-fp-math 9998 9999 // FADD -> FMA combines: 10000 if (SDValue Fused = visitFADDForFMACombine(N)) { 10001 AddToWorklist(Fused.getNode()); 10002 return Fused; 10003 } 10004 return SDValue(); 10005 } 10006 10007 SDValue DAGCombiner::visitFSUB(SDNode *N) { 10008 SDValue N0 = N->getOperand(0); 10009 SDValue N1 = N->getOperand(1); 10010 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10011 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10012 EVT VT = N->getValueType(0); 10013 SDLoc DL(N); 10014 const TargetOptions &Options = DAG.getTarget().Options; 10015 const SDNodeFlags Flags = N->getFlags(); 10016 10017 // fold vector ops 10018 if (VT.isVector()) 10019 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 10020 return FoldedVOp; 10021 10022 // fold (fsub c1, c2) -> c1-c2 10023 if (N0CFP && N1CFP) 10024 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags); 10025 10026 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10027 return NewSel; 10028 10029 // fold (fsub A, (fneg B)) -> (fadd A, B) 10030 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 10031 return DAG.getNode(ISD::FADD, DL, VT, N0, 10032 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 10033 10034 // FIXME: Auto-upgrade the target/function-level option. 10035 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) { 10036 // (fsub 0, B) -> -B 10037 if (N0CFP && N0CFP->isZero()) { 10038 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 10039 return GetNegatedExpression(N1, DAG, LegalOperations); 10040 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 10041 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags); 10042 } 10043 } 10044 10045 // If 'unsafe math' is enabled, fold lots of things. 10046 if (Options.UnsafeFPMath) { 10047 // (fsub A, 0) -> A 10048 if (N1CFP && N1CFP->isZero()) 10049 return N0; 10050 10051 // (fsub x, x) -> 0.0 10052 if (N0 == N1) 10053 return DAG.getConstantFP(0.0f, DL, VT); 10054 10055 // (fsub x, (fadd x, y)) -> (fneg y) 10056 // (fsub x, (fadd y, x)) -> (fneg y) 10057 if (N1.getOpcode() == ISD::FADD) { 10058 SDValue N10 = N1->getOperand(0); 10059 SDValue N11 = N1->getOperand(1); 10060 10061 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 10062 return GetNegatedExpression(N11, DAG, LegalOperations); 10063 10064 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 10065 return GetNegatedExpression(N10, DAG, LegalOperations); 10066 } 10067 } 10068 10069 // FSUB -> FMA combines: 10070 if (SDValue Fused = visitFSUBForFMACombine(N)) { 10071 AddToWorklist(Fused.getNode()); 10072 return Fused; 10073 } 10074 10075 return SDValue(); 10076 } 10077 10078 SDValue DAGCombiner::visitFMUL(SDNode *N) { 10079 SDValue N0 = N->getOperand(0); 10080 SDValue N1 = N->getOperand(1); 10081 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10082 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10083 EVT VT = N->getValueType(0); 10084 SDLoc DL(N); 10085 const TargetOptions &Options = DAG.getTarget().Options; 10086 const SDNodeFlags Flags = N->getFlags(); 10087 10088 // fold vector ops 10089 if (VT.isVector()) { 10090 // This just handles C1 * C2 for vectors. Other vector folds are below. 10091 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 10092 return FoldedVOp; 10093 } 10094 10095 // fold (fmul c1, c2) -> c1*c2 10096 if (N0CFP && N1CFP) 10097 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 10098 10099 // canonicalize constant to RHS 10100 if (isConstantFPBuildVectorOrConstantFP(N0) && 10101 !isConstantFPBuildVectorOrConstantFP(N1)) 10102 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 10103 10104 // fold (fmul A, 1.0) -> A 10105 if (N1CFP && N1CFP->isExactlyValue(1.0)) 10106 return N0; 10107 10108 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10109 return NewSel; 10110 10111 if (Options.UnsafeFPMath) { 10112 // fold (fmul A, 0) -> 0 10113 if (N1CFP && N1CFP->isZero()) 10114 return N1; 10115 10116 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 10117 if (N0.getOpcode() == ISD::FMUL) { 10118 // Fold scalars or any vector constants (not just splats). 10119 // This fold is done in general by InstCombine, but extra fmul insts 10120 // may have been generated during lowering. 10121 SDValue N00 = N0.getOperand(0); 10122 SDValue N01 = N0.getOperand(1); 10123 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 10124 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 10125 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 10126 10127 // Check 1: Make sure that the first operand of the inner multiply is NOT 10128 // a constant. Otherwise, we may induce infinite looping. 10129 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 10130 // Check 2: Make sure that the second operand of the inner multiply and 10131 // the second operand of the outer multiply are constants. 10132 if ((N1CFP && isConstOrConstSplatFP(N01)) || 10133 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 10134 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 10135 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 10136 } 10137 } 10138 } 10139 10140 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 10141 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 10142 // during an early run of DAGCombiner can prevent folding with fmuls 10143 // inserted during lowering. 10144 if (N0.getOpcode() == ISD::FADD && 10145 (N0.getOperand(0) == N0.getOperand(1)) && 10146 N0.hasOneUse()) { 10147 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 10148 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 10149 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 10150 } 10151 } 10152 10153 // fold (fmul X, 2.0) -> (fadd X, X) 10154 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 10155 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 10156 10157 // fold (fmul X, -1.0) -> (fneg X) 10158 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 10159 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 10160 return DAG.getNode(ISD::FNEG, DL, VT, N0); 10161 10162 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 10163 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 10164 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 10165 // Both can be negated for free, check to see if at least one is cheaper 10166 // negated. 10167 if (LHSNeg == 2 || RHSNeg == 2) 10168 return DAG.getNode(ISD::FMUL, DL, VT, 10169 GetNegatedExpression(N0, DAG, LegalOperations), 10170 GetNegatedExpression(N1, DAG, LegalOperations), 10171 Flags); 10172 } 10173 } 10174 10175 // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X)) 10176 // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X) 10177 if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() && 10178 (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) && 10179 TLI.isOperationLegal(ISD::FABS, VT)) { 10180 SDValue Select = N0, X = N1; 10181 if (Select.getOpcode() != ISD::SELECT) 10182 std::swap(Select, X); 10183 10184 SDValue Cond = Select.getOperand(0); 10185 auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1)); 10186 auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2)); 10187 10188 if (TrueOpnd && FalseOpnd && 10189 Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X && 10190 isa<ConstantFPSDNode>(Cond.getOperand(1)) && 10191 cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) { 10192 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 10193 switch (CC) { 10194 default: break; 10195 case ISD::SETOLT: 10196 case ISD::SETULT: 10197 case ISD::SETOLE: 10198 case ISD::SETULE: 10199 case ISD::SETLT: 10200 case ISD::SETLE: 10201 std::swap(TrueOpnd, FalseOpnd); 10202 LLVM_FALLTHROUGH; 10203 case ISD::SETOGT: 10204 case ISD::SETUGT: 10205 case ISD::SETOGE: 10206 case ISD::SETUGE: 10207 case ISD::SETGT: 10208 case ISD::SETGE: 10209 if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) && 10210 TLI.isOperationLegal(ISD::FNEG, VT)) 10211 return DAG.getNode(ISD::FNEG, DL, VT, 10212 DAG.getNode(ISD::FABS, DL, VT, X)); 10213 if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0)) 10214 return DAG.getNode(ISD::FABS, DL, VT, X); 10215 10216 break; 10217 } 10218 } 10219 } 10220 10221 // FMUL -> FMA combines: 10222 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) { 10223 AddToWorklist(Fused.getNode()); 10224 return Fused; 10225 } 10226 10227 return SDValue(); 10228 } 10229 10230 SDValue DAGCombiner::visitFMA(SDNode *N) { 10231 SDValue N0 = N->getOperand(0); 10232 SDValue N1 = N->getOperand(1); 10233 SDValue N2 = N->getOperand(2); 10234 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10235 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10236 EVT VT = N->getValueType(0); 10237 SDLoc DL(N); 10238 const TargetOptions &Options = DAG.getTarget().Options; 10239 10240 // Constant fold FMA. 10241 if (isa<ConstantFPSDNode>(N0) && 10242 isa<ConstantFPSDNode>(N1) && 10243 isa<ConstantFPSDNode>(N2)) { 10244 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2); 10245 } 10246 10247 if (Options.UnsafeFPMath) { 10248 if (N0CFP && N0CFP->isZero()) 10249 return N2; 10250 if (N1CFP && N1CFP->isZero()) 10251 return N2; 10252 } 10253 // TODO: The FMA node should have flags that propagate to these nodes. 10254 if (N0CFP && N0CFP->isExactlyValue(1.0)) 10255 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 10256 if (N1CFP && N1CFP->isExactlyValue(1.0)) 10257 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 10258 10259 // Canonicalize (fma c, x, y) -> (fma x, c, y) 10260 if (isConstantFPBuildVectorOrConstantFP(N0) && 10261 !isConstantFPBuildVectorOrConstantFP(N1)) 10262 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 10263 10264 // TODO: FMA nodes should have flags that propagate to the created nodes. 10265 // For now, create a Flags object for use with all unsafe math transforms. 10266 SDNodeFlags Flags; 10267 Flags.setUnsafeAlgebra(true); 10268 10269 if (Options.UnsafeFPMath) { 10270 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 10271 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 10272 isConstantFPBuildVectorOrConstantFP(N1) && 10273 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 10274 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10275 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1), 10276 Flags), Flags); 10277 } 10278 10279 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 10280 if (N0.getOpcode() == ISD::FMUL && 10281 isConstantFPBuildVectorOrConstantFP(N1) && 10282 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 10283 return DAG.getNode(ISD::FMA, DL, VT, 10284 N0.getOperand(0), 10285 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1), 10286 Flags), 10287 N2); 10288 } 10289 } 10290 10291 // (fma x, 1, y) -> (fadd x, y) 10292 // (fma x, -1, y) -> (fadd (fneg x), y) 10293 if (N1CFP) { 10294 if (N1CFP->isExactlyValue(1.0)) 10295 // TODO: The FMA node should have flags that propagate to this node. 10296 return DAG.getNode(ISD::FADD, DL, VT, N0, N2); 10297 10298 if (N1CFP->isExactlyValue(-1.0) && 10299 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 10300 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0); 10301 AddToWorklist(RHSNeg.getNode()); 10302 // TODO: The FMA node should have flags that propagate to this node. 10303 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg); 10304 } 10305 10306 // fma (fneg x), K, y -> fma x -K, y 10307 if (N0.getOpcode() == ISD::FNEG && 10308 (TLI.isOperationLegal(ISD::ConstantFP, VT) || 10309 (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT)))) { 10310 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0), 10311 DAG.getNode(ISD::FNEG, DL, VT, N1, Flags), N2); 10312 } 10313 } 10314 10315 if (Options.UnsafeFPMath) { 10316 // (fma x, c, x) -> (fmul x, (c+1)) 10317 if (N1CFP && N0 == N2) { 10318 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10319 DAG.getNode(ISD::FADD, DL, VT, N1, 10320 DAG.getConstantFP(1.0, DL, VT), Flags), 10321 Flags); 10322 } 10323 10324 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 10325 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 10326 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10327 DAG.getNode(ISD::FADD, DL, VT, N1, 10328 DAG.getConstantFP(-1.0, DL, VT), Flags), 10329 Flags); 10330 } 10331 } 10332 10333 return SDValue(); 10334 } 10335 10336 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10337 // reciprocal. 10338 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 10339 // Notice that this is not always beneficial. One reason is different targets 10340 // may have different costs for FDIV and FMUL, so sometimes the cost of two 10341 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 10342 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 10343 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 10344 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 10345 const SDNodeFlags Flags = N->getFlags(); 10346 if (!UnsafeMath && !Flags.hasAllowReciprocal()) 10347 return SDValue(); 10348 10349 // Skip if current node is a reciprocal. 10350 SDValue N0 = N->getOperand(0); 10351 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10352 if (N0CFP && N0CFP->isExactlyValue(1.0)) 10353 return SDValue(); 10354 10355 // Exit early if the target does not want this transform or if there can't 10356 // possibly be enough uses of the divisor to make the transform worthwhile. 10357 SDValue N1 = N->getOperand(1); 10358 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 10359 if (!MinUses || N1->use_size() < MinUses) 10360 return SDValue(); 10361 10362 // Find all FDIV users of the same divisor. 10363 // Use a set because duplicates may be present in the user list. 10364 SetVector<SDNode *> Users; 10365 for (auto *U : N1->uses()) { 10366 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 10367 // This division is eligible for optimization only if global unsafe math 10368 // is enabled or if this division allows reciprocal formation. 10369 if (UnsafeMath || U->getFlags().hasAllowReciprocal()) 10370 Users.insert(U); 10371 } 10372 } 10373 10374 // Now that we have the actual number of divisor uses, make sure it meets 10375 // the minimum threshold specified by the target. 10376 if (Users.size() < MinUses) 10377 return SDValue(); 10378 10379 EVT VT = N->getValueType(0); 10380 SDLoc DL(N); 10381 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 10382 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 10383 10384 // Dividend / Divisor -> Dividend * Reciprocal 10385 for (auto *U : Users) { 10386 SDValue Dividend = U->getOperand(0); 10387 if (Dividend != FPOne) { 10388 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 10389 Reciprocal, Flags); 10390 CombineTo(U, NewNode); 10391 } else if (U != Reciprocal.getNode()) { 10392 // In the absence of fast-math-flags, this user node is always the 10393 // same node as Reciprocal, but with FMF they may be different nodes. 10394 CombineTo(U, Reciprocal); 10395 } 10396 } 10397 return SDValue(N, 0); // N was replaced. 10398 } 10399 10400 SDValue DAGCombiner::visitFDIV(SDNode *N) { 10401 SDValue N0 = N->getOperand(0); 10402 SDValue N1 = N->getOperand(1); 10403 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10404 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10405 EVT VT = N->getValueType(0); 10406 SDLoc DL(N); 10407 const TargetOptions &Options = DAG.getTarget().Options; 10408 SDNodeFlags Flags = N->getFlags(); 10409 10410 // fold vector ops 10411 if (VT.isVector()) 10412 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 10413 return FoldedVOp; 10414 10415 // fold (fdiv c1, c2) -> c1/c2 10416 if (N0CFP && N1CFP) 10417 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 10418 10419 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10420 return NewSel; 10421 10422 if (Options.UnsafeFPMath) { 10423 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 10424 if (N1CFP) { 10425 // Compute the reciprocal 1.0 / c2. 10426 const APFloat &N1APF = N1CFP->getValueAPF(); 10427 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 10428 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 10429 // Only do the transform if the reciprocal is a legal fp immediate that 10430 // isn't too nasty (eg NaN, denormal, ...). 10431 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 10432 (!LegalOperations || 10433 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 10434 // backend)... we should handle this gracefully after Legalize. 10435 // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) || 10436 TLI.isOperationLegal(ISD::ConstantFP, VT) || 10437 TLI.isFPImmLegal(Recip, VT))) 10438 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10439 DAG.getConstantFP(Recip, DL, VT), Flags); 10440 } 10441 10442 // If this FDIV is part of a reciprocal square root, it may be folded 10443 // into a target-specific square root estimate instruction. 10444 if (N1.getOpcode() == ISD::FSQRT) { 10445 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) { 10446 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10447 } 10448 } else if (N1.getOpcode() == ISD::FP_EXTEND && 10449 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10450 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 10451 Flags)) { 10452 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 10453 AddToWorklist(RV.getNode()); 10454 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10455 } 10456 } else if (N1.getOpcode() == ISD::FP_ROUND && 10457 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10458 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 10459 Flags)) { 10460 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 10461 AddToWorklist(RV.getNode()); 10462 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10463 } 10464 } else if (N1.getOpcode() == ISD::FMUL) { 10465 // Look through an FMUL. Even though this won't remove the FDIV directly, 10466 // it's still worthwhile to get rid of the FSQRT if possible. 10467 SDValue SqrtOp; 10468 SDValue OtherOp; 10469 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10470 SqrtOp = N1.getOperand(0); 10471 OtherOp = N1.getOperand(1); 10472 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 10473 SqrtOp = N1.getOperand(1); 10474 OtherOp = N1.getOperand(0); 10475 } 10476 if (SqrtOp.getNode()) { 10477 // We found a FSQRT, so try to make this fold: 10478 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 10479 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 10480 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 10481 AddToWorklist(RV.getNode()); 10482 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10483 } 10484 } 10485 } 10486 10487 // Fold into a reciprocal estimate and multiply instead of a real divide. 10488 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 10489 AddToWorklist(RV.getNode()); 10490 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10491 } 10492 } 10493 10494 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 10495 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 10496 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 10497 // Both can be negated for free, check to see if at least one is cheaper 10498 // negated. 10499 if (LHSNeg == 2 || RHSNeg == 2) 10500 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 10501 GetNegatedExpression(N0, DAG, LegalOperations), 10502 GetNegatedExpression(N1, DAG, LegalOperations), 10503 Flags); 10504 } 10505 } 10506 10507 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 10508 return CombineRepeatedDivisors; 10509 10510 return SDValue(); 10511 } 10512 10513 SDValue DAGCombiner::visitFREM(SDNode *N) { 10514 SDValue N0 = N->getOperand(0); 10515 SDValue N1 = N->getOperand(1); 10516 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10517 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10518 EVT VT = N->getValueType(0); 10519 10520 // fold (frem c1, c2) -> fmod(c1,c2) 10521 if (N0CFP && N1CFP) 10522 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags()); 10523 10524 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10525 return NewSel; 10526 10527 return SDValue(); 10528 } 10529 10530 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 10531 if (!DAG.getTarget().Options.UnsafeFPMath) 10532 return SDValue(); 10533 10534 SDValue N0 = N->getOperand(0); 10535 if (TLI.isFsqrtCheap(N0, DAG)) 10536 return SDValue(); 10537 10538 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 10539 // For now, create a Flags object for use with all unsafe math transforms. 10540 SDNodeFlags Flags; 10541 Flags.setUnsafeAlgebra(true); 10542 return buildSqrtEstimate(N0, Flags); 10543 } 10544 10545 /// copysign(x, fp_extend(y)) -> copysign(x, y) 10546 /// copysign(x, fp_round(y)) -> copysign(x, y) 10547 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 10548 SDValue N1 = N->getOperand(1); 10549 if ((N1.getOpcode() == ISD::FP_EXTEND || 10550 N1.getOpcode() == ISD::FP_ROUND)) { 10551 // Do not optimize out type conversion of f128 type yet. 10552 // For some targets like x86_64, configuration is changed to keep one f128 10553 // value in one SSE register, but instruction selection cannot handle 10554 // FCOPYSIGN on SSE registers yet. 10555 EVT N1VT = N1->getValueType(0); 10556 EVT N1Op0VT = N1->getOperand(0).getValueType(); 10557 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 10558 } 10559 return false; 10560 } 10561 10562 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 10563 SDValue N0 = N->getOperand(0); 10564 SDValue N1 = N->getOperand(1); 10565 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10566 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10567 EVT VT = N->getValueType(0); 10568 10569 if (N0CFP && N1CFP) // Constant fold 10570 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 10571 10572 if (N1CFP) { 10573 const APFloat &V = N1CFP->getValueAPF(); 10574 // copysign(x, c1) -> fabs(x) iff ispos(c1) 10575 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 10576 if (!V.isNegative()) { 10577 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 10578 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10579 } else { 10580 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 10581 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 10582 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 10583 } 10584 } 10585 10586 // copysign(fabs(x), y) -> copysign(x, y) 10587 // copysign(fneg(x), y) -> copysign(x, y) 10588 // copysign(copysign(x,z), y) -> copysign(x, y) 10589 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 10590 N0.getOpcode() == ISD::FCOPYSIGN) 10591 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1); 10592 10593 // copysign(x, abs(y)) -> abs(x) 10594 if (N1.getOpcode() == ISD::FABS) 10595 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10596 10597 // copysign(x, copysign(y,z)) -> copysign(x, z) 10598 if (N1.getOpcode() == ISD::FCOPYSIGN) 10599 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1)); 10600 10601 // copysign(x, fp_extend(y)) -> copysign(x, y) 10602 // copysign(x, fp_round(y)) -> copysign(x, y) 10603 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 10604 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0)); 10605 10606 return SDValue(); 10607 } 10608 10609 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 10610 SDValue N0 = N->getOperand(0); 10611 EVT VT = N->getValueType(0); 10612 EVT OpVT = N0.getValueType(); 10613 10614 // fold (sint_to_fp c1) -> c1fp 10615 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 10616 // ...but only if the target supports immediate floating-point values 10617 (!LegalOperations || 10618 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) 10619 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 10620 10621 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 10622 // but UINT_TO_FP is legal on this target, try to convert. 10623 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 10624 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 10625 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 10626 if (DAG.SignBitIsZero(N0)) 10627 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 10628 } 10629 10630 // The next optimizations are desirable only if SELECT_CC can be lowered. 10631 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 10632 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 10633 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 10634 !VT.isVector() && 10635 (!LegalOperations || 10636 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 10637 SDLoc DL(N); 10638 SDValue Ops[] = 10639 { N0.getOperand(0), N0.getOperand(1), 10640 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10641 N0.getOperand(2) }; 10642 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10643 } 10644 10645 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 10646 // (select_cc x, y, 1.0, 0.0,, cc) 10647 if (N0.getOpcode() == ISD::ZERO_EXTEND && 10648 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 10649 (!LegalOperations || 10650 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 10651 SDLoc DL(N); 10652 SDValue Ops[] = 10653 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 10654 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10655 N0.getOperand(0).getOperand(2) }; 10656 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10657 } 10658 } 10659 10660 return SDValue(); 10661 } 10662 10663 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 10664 SDValue N0 = N->getOperand(0); 10665 EVT VT = N->getValueType(0); 10666 EVT OpVT = N0.getValueType(); 10667 10668 // fold (uint_to_fp c1) -> c1fp 10669 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 10670 // ...but only if the target supports immediate floating-point values 10671 (!LegalOperations || 10672 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) 10673 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 10674 10675 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 10676 // but SINT_TO_FP is legal on this target, try to convert. 10677 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 10678 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 10679 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 10680 if (DAG.SignBitIsZero(N0)) 10681 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 10682 } 10683 10684 // The next optimizations are desirable only if SELECT_CC can be lowered. 10685 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 10686 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 10687 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 10688 (!LegalOperations || 10689 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 10690 SDLoc DL(N); 10691 SDValue Ops[] = 10692 { N0.getOperand(0), N0.getOperand(1), 10693 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10694 N0.getOperand(2) }; 10695 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10696 } 10697 } 10698 10699 return SDValue(); 10700 } 10701 10702 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 10703 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 10704 SDValue N0 = N->getOperand(0); 10705 EVT VT = N->getValueType(0); 10706 10707 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 10708 return SDValue(); 10709 10710 SDValue Src = N0.getOperand(0); 10711 EVT SrcVT = Src.getValueType(); 10712 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 10713 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 10714 10715 // We can safely assume the conversion won't overflow the output range, 10716 // because (for example) (uint8_t)18293.f is undefined behavior. 10717 10718 // Since we can assume the conversion won't overflow, our decision as to 10719 // whether the input will fit in the float should depend on the minimum 10720 // of the input range and output range. 10721 10722 // This means this is also safe for a signed input and unsigned output, since 10723 // a negative input would lead to undefined behavior. 10724 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 10725 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 10726 unsigned ActualSize = std::min(InputSize, OutputSize); 10727 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 10728 10729 // We can only fold away the float conversion if the input range can be 10730 // represented exactly in the float range. 10731 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 10732 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 10733 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 10734 : ISD::ZERO_EXTEND; 10735 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 10736 } 10737 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 10738 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 10739 return DAG.getBitcast(VT, Src); 10740 } 10741 return SDValue(); 10742 } 10743 10744 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 10745 SDValue N0 = N->getOperand(0); 10746 EVT VT = N->getValueType(0); 10747 10748 // fold (fp_to_sint c1fp) -> c1 10749 if (isConstantFPBuildVectorOrConstantFP(N0)) 10750 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 10751 10752 return FoldIntToFPToInt(N, DAG); 10753 } 10754 10755 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 10756 SDValue N0 = N->getOperand(0); 10757 EVT VT = N->getValueType(0); 10758 10759 // fold (fp_to_uint c1fp) -> c1 10760 if (isConstantFPBuildVectorOrConstantFP(N0)) 10761 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 10762 10763 return FoldIntToFPToInt(N, DAG); 10764 } 10765 10766 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 10767 SDValue N0 = N->getOperand(0); 10768 SDValue N1 = N->getOperand(1); 10769 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10770 EVT VT = N->getValueType(0); 10771 10772 // fold (fp_round c1fp) -> c1fp 10773 if (N0CFP) 10774 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 10775 10776 // fold (fp_round (fp_extend x)) -> x 10777 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 10778 return N0.getOperand(0); 10779 10780 // fold (fp_round (fp_round x)) -> (fp_round x) 10781 if (N0.getOpcode() == ISD::FP_ROUND) { 10782 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 10783 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1; 10784 10785 // Skip this folding if it results in an fp_round from f80 to f16. 10786 // 10787 // f80 to f16 always generates an expensive (and as yet, unimplemented) 10788 // libcall to __truncxfhf2 instead of selecting native f16 conversion 10789 // instructions from f32 or f64. Moreover, the first (value-preserving) 10790 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 10791 // x86. 10792 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 10793 return SDValue(); 10794 10795 // If the first fp_round isn't a value preserving truncation, it might 10796 // introduce a tie in the second fp_round, that wouldn't occur in the 10797 // single-step fp_round we want to fold to. 10798 // In other words, double rounding isn't the same as rounding. 10799 // Also, this is a value preserving truncation iff both fp_round's are. 10800 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 10801 SDLoc DL(N); 10802 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 10803 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 10804 } 10805 } 10806 10807 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 10808 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 10809 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 10810 N0.getOperand(0), N1); 10811 AddToWorklist(Tmp.getNode()); 10812 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 10813 Tmp, N0.getOperand(1)); 10814 } 10815 10816 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 10817 return NewVSel; 10818 10819 return SDValue(); 10820 } 10821 10822 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 10823 SDValue N0 = N->getOperand(0); 10824 EVT VT = N->getValueType(0); 10825 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 10826 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10827 10828 // fold (fp_round_inreg c1fp) -> c1fp 10829 if (N0CFP && isTypeLegal(EVT)) { 10830 SDLoc DL(N); 10831 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 10832 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 10833 } 10834 10835 return SDValue(); 10836 } 10837 10838 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 10839 SDValue N0 = N->getOperand(0); 10840 EVT VT = N->getValueType(0); 10841 10842 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 10843 if (N->hasOneUse() && 10844 N->use_begin()->getOpcode() == ISD::FP_ROUND) 10845 return SDValue(); 10846 10847 // fold (fp_extend c1fp) -> c1fp 10848 if (isConstantFPBuildVectorOrConstantFP(N0)) 10849 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 10850 10851 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 10852 if (N0.getOpcode() == ISD::FP16_TO_FP && 10853 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 10854 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 10855 10856 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 10857 // value of X. 10858 if (N0.getOpcode() == ISD::FP_ROUND 10859 && N0.getConstantOperandVal(1) == 1) { 10860 SDValue In = N0.getOperand(0); 10861 if (In.getValueType() == VT) return In; 10862 if (VT.bitsLT(In.getValueType())) 10863 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 10864 In, N0.getOperand(1)); 10865 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 10866 } 10867 10868 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 10869 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10870 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 10871 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10872 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 10873 LN0->getChain(), 10874 LN0->getBasePtr(), N0.getValueType(), 10875 LN0->getMemOperand()); 10876 CombineTo(N, ExtLoad); 10877 CombineTo(N0.getNode(), 10878 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 10879 N0.getValueType(), ExtLoad, 10880 DAG.getIntPtrConstant(1, SDLoc(N0))), 10881 ExtLoad.getValue(1)); 10882 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10883 } 10884 10885 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 10886 return NewVSel; 10887 10888 return SDValue(); 10889 } 10890 10891 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 10892 SDValue N0 = N->getOperand(0); 10893 EVT VT = N->getValueType(0); 10894 10895 // fold (fceil c1) -> fceil(c1) 10896 if (isConstantFPBuildVectorOrConstantFP(N0)) 10897 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 10898 10899 return SDValue(); 10900 } 10901 10902 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 10903 SDValue N0 = N->getOperand(0); 10904 EVT VT = N->getValueType(0); 10905 10906 // fold (ftrunc c1) -> ftrunc(c1) 10907 if (isConstantFPBuildVectorOrConstantFP(N0)) 10908 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 10909 10910 // fold ftrunc (known rounded int x) -> x 10911 // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is 10912 // likely to be generated to extract integer from a rounded floating value. 10913 switch (N0.getOpcode()) { 10914 default: break; 10915 case ISD::FRINT: 10916 case ISD::FTRUNC: 10917 case ISD::FNEARBYINT: 10918 case ISD::FFLOOR: 10919 case ISD::FCEIL: 10920 return N0; 10921 } 10922 10923 return SDValue(); 10924 } 10925 10926 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 10927 SDValue N0 = N->getOperand(0); 10928 EVT VT = N->getValueType(0); 10929 10930 // fold (ffloor c1) -> ffloor(c1) 10931 if (isConstantFPBuildVectorOrConstantFP(N0)) 10932 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 10933 10934 return SDValue(); 10935 } 10936 10937 // FIXME: FNEG and FABS have a lot in common; refactor. 10938 SDValue DAGCombiner::visitFNEG(SDNode *N) { 10939 SDValue N0 = N->getOperand(0); 10940 EVT VT = N->getValueType(0); 10941 10942 // Constant fold FNEG. 10943 if (isConstantFPBuildVectorOrConstantFP(N0)) 10944 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 10945 10946 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 10947 &DAG.getTarget().Options)) 10948 return GetNegatedExpression(N0, DAG, LegalOperations); 10949 10950 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 10951 // constant pool values. 10952 if (!TLI.isFNegFree(VT) && 10953 N0.getOpcode() == ISD::BITCAST && 10954 N0.getNode()->hasOneUse()) { 10955 SDValue Int = N0.getOperand(0); 10956 EVT IntVT = Int.getValueType(); 10957 if (IntVT.isInteger() && !IntVT.isVector()) { 10958 APInt SignMask; 10959 if (N0.getValueType().isVector()) { 10960 // For a vector, get a mask such as 0x80... per scalar element 10961 // and splat it. 10962 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits()); 10963 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 10964 } else { 10965 // For a scalar, just generate 0x80... 10966 SignMask = APInt::getSignMask(IntVT.getSizeInBits()); 10967 } 10968 SDLoc DL0(N0); 10969 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 10970 DAG.getConstant(SignMask, DL0, IntVT)); 10971 AddToWorklist(Int.getNode()); 10972 return DAG.getBitcast(VT, Int); 10973 } 10974 } 10975 10976 // (fneg (fmul c, x)) -> (fmul -c, x) 10977 if (N0.getOpcode() == ISD::FMUL && 10978 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 10979 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10980 if (CFP1) { 10981 APFloat CVal = CFP1->getValueAPF(); 10982 CVal.changeSign(); 10983 if (Level >= AfterLegalizeDAG && 10984 (TLI.isFPImmLegal(CVal, VT) || 10985 TLI.isOperationLegal(ISD::ConstantFP, VT))) 10986 return DAG.getNode( 10987 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 10988 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)), 10989 N0->getFlags()); 10990 } 10991 } 10992 10993 return SDValue(); 10994 } 10995 10996 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 10997 SDValue N0 = N->getOperand(0); 10998 SDValue N1 = N->getOperand(1); 10999 EVT VT = N->getValueType(0); 11000 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 11001 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 11002 11003 if (N0CFP && N1CFP) { 11004 const APFloat &C0 = N0CFP->getValueAPF(); 11005 const APFloat &C1 = N1CFP->getValueAPF(); 11006 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 11007 } 11008 11009 // Canonicalize to constant on RHS. 11010 if (isConstantFPBuildVectorOrConstantFP(N0) && 11011 !isConstantFPBuildVectorOrConstantFP(N1)) 11012 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 11013 11014 return SDValue(); 11015 } 11016 11017 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 11018 SDValue N0 = N->getOperand(0); 11019 SDValue N1 = N->getOperand(1); 11020 EVT VT = N->getValueType(0); 11021 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 11022 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 11023 11024 if (N0CFP && N1CFP) { 11025 const APFloat &C0 = N0CFP->getValueAPF(); 11026 const APFloat &C1 = N1CFP->getValueAPF(); 11027 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 11028 } 11029 11030 // Canonicalize to constant on RHS. 11031 if (isConstantFPBuildVectorOrConstantFP(N0) && 11032 !isConstantFPBuildVectorOrConstantFP(N1)) 11033 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 11034 11035 return SDValue(); 11036 } 11037 11038 SDValue DAGCombiner::visitFABS(SDNode *N) { 11039 SDValue N0 = N->getOperand(0); 11040 EVT VT = N->getValueType(0); 11041 11042 // fold (fabs c1) -> fabs(c1) 11043 if (isConstantFPBuildVectorOrConstantFP(N0)) 11044 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 11045 11046 // fold (fabs (fabs x)) -> (fabs x) 11047 if (N0.getOpcode() == ISD::FABS) 11048 return N->getOperand(0); 11049 11050 // fold (fabs (fneg x)) -> (fabs x) 11051 // fold (fabs (fcopysign x, y)) -> (fabs x) 11052 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 11053 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 11054 11055 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 11056 // constant pool values. 11057 if (!TLI.isFAbsFree(VT) && 11058 N0.getOpcode() == ISD::BITCAST && 11059 N0.getNode()->hasOneUse()) { 11060 SDValue Int = N0.getOperand(0); 11061 EVT IntVT = Int.getValueType(); 11062 if (IntVT.isInteger() && !IntVT.isVector()) { 11063 APInt SignMask; 11064 if (N0.getValueType().isVector()) { 11065 // For a vector, get a mask such as 0x7f... per scalar element 11066 // and splat it. 11067 SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits()); 11068 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 11069 } else { 11070 // For a scalar, just generate 0x7f... 11071 SignMask = ~APInt::getSignMask(IntVT.getSizeInBits()); 11072 } 11073 SDLoc DL(N0); 11074 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 11075 DAG.getConstant(SignMask, DL, IntVT)); 11076 AddToWorklist(Int.getNode()); 11077 return DAG.getBitcast(N->getValueType(0), Int); 11078 } 11079 } 11080 11081 return SDValue(); 11082 } 11083 11084 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 11085 SDValue Chain = N->getOperand(0); 11086 SDValue N1 = N->getOperand(1); 11087 SDValue N2 = N->getOperand(2); 11088 11089 // If N is a constant we could fold this into a fallthrough or unconditional 11090 // branch. However that doesn't happen very often in normal code, because 11091 // Instcombine/SimplifyCFG should have handled the available opportunities. 11092 // If we did this folding here, it would be necessary to update the 11093 // MachineBasicBlock CFG, which is awkward. 11094 11095 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 11096 // on the target. 11097 if (N1.getOpcode() == ISD::SETCC && 11098 TLI.isOperationLegalOrCustom(ISD::BR_CC, 11099 N1.getOperand(0).getValueType())) { 11100 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 11101 Chain, N1.getOperand(2), 11102 N1.getOperand(0), N1.getOperand(1), N2); 11103 } 11104 11105 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 11106 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 11107 (N1.getOperand(0).hasOneUse() && 11108 N1.getOperand(0).getOpcode() == ISD::SRL))) { 11109 SDNode *Trunc = nullptr; 11110 if (N1.getOpcode() == ISD::TRUNCATE) { 11111 // Look pass the truncate. 11112 Trunc = N1.getNode(); 11113 N1 = N1.getOperand(0); 11114 } 11115 11116 // Match this pattern so that we can generate simpler code: 11117 // 11118 // %a = ... 11119 // %b = and i32 %a, 2 11120 // %c = srl i32 %b, 1 11121 // brcond i32 %c ... 11122 // 11123 // into 11124 // 11125 // %a = ... 11126 // %b = and i32 %a, 2 11127 // %c = setcc eq %b, 0 11128 // brcond %c ... 11129 // 11130 // This applies only when the AND constant value has one bit set and the 11131 // SRL constant is equal to the log2 of the AND constant. The back-end is 11132 // smart enough to convert the result into a TEST/JMP sequence. 11133 SDValue Op0 = N1.getOperand(0); 11134 SDValue Op1 = N1.getOperand(1); 11135 11136 if (Op0.getOpcode() == ISD::AND && 11137 Op1.getOpcode() == ISD::Constant) { 11138 SDValue AndOp1 = Op0.getOperand(1); 11139 11140 if (AndOp1.getOpcode() == ISD::Constant) { 11141 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 11142 11143 if (AndConst.isPowerOf2() && 11144 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 11145 SDLoc DL(N); 11146 SDValue SetCC = 11147 DAG.getSetCC(DL, 11148 getSetCCResultType(Op0.getValueType()), 11149 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 11150 ISD::SETNE); 11151 11152 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 11153 MVT::Other, Chain, SetCC, N2); 11154 // Don't add the new BRCond into the worklist or else SimplifySelectCC 11155 // will convert it back to (X & C1) >> C2. 11156 CombineTo(N, NewBRCond, false); 11157 // Truncate is dead. 11158 if (Trunc) 11159 deleteAndRecombine(Trunc); 11160 // Replace the uses of SRL with SETCC 11161 WorklistRemover DeadNodes(*this); 11162 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 11163 deleteAndRecombine(N1.getNode()); 11164 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11165 } 11166 } 11167 } 11168 11169 if (Trunc) 11170 // Restore N1 if the above transformation doesn't match. 11171 N1 = N->getOperand(1); 11172 } 11173 11174 // Transform br(xor(x, y)) -> br(x != y) 11175 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 11176 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 11177 SDNode *TheXor = N1.getNode(); 11178 SDValue Op0 = TheXor->getOperand(0); 11179 SDValue Op1 = TheXor->getOperand(1); 11180 if (Op0.getOpcode() == Op1.getOpcode()) { 11181 // Avoid missing important xor optimizations. 11182 if (SDValue Tmp = visitXOR(TheXor)) { 11183 if (Tmp.getNode() != TheXor) { 11184 DEBUG(dbgs() << "\nReplacing.8 "; 11185 TheXor->dump(&DAG); 11186 dbgs() << "\nWith: "; 11187 Tmp.getNode()->dump(&DAG); 11188 dbgs() << '\n'); 11189 WorklistRemover DeadNodes(*this); 11190 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 11191 deleteAndRecombine(TheXor); 11192 return DAG.getNode(ISD::BRCOND, SDLoc(N), 11193 MVT::Other, Chain, Tmp, N2); 11194 } 11195 11196 // visitXOR has changed XOR's operands or replaced the XOR completely, 11197 // bail out. 11198 return SDValue(N, 0); 11199 } 11200 } 11201 11202 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 11203 bool Equal = false; 11204 if (isOneConstant(Op0) && Op0.hasOneUse() && 11205 Op0.getOpcode() == ISD::XOR) { 11206 TheXor = Op0.getNode(); 11207 Equal = true; 11208 } 11209 11210 EVT SetCCVT = N1.getValueType(); 11211 if (LegalTypes) 11212 SetCCVT = getSetCCResultType(SetCCVT); 11213 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 11214 SetCCVT, 11215 Op0, Op1, 11216 Equal ? ISD::SETEQ : ISD::SETNE); 11217 // Replace the uses of XOR with SETCC 11218 WorklistRemover DeadNodes(*this); 11219 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 11220 deleteAndRecombine(N1.getNode()); 11221 return DAG.getNode(ISD::BRCOND, SDLoc(N), 11222 MVT::Other, Chain, SetCC, N2); 11223 } 11224 } 11225 11226 return SDValue(); 11227 } 11228 11229 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 11230 // 11231 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 11232 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 11233 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 11234 11235 // If N is a constant we could fold this into a fallthrough or unconditional 11236 // branch. However that doesn't happen very often in normal code, because 11237 // Instcombine/SimplifyCFG should have handled the available opportunities. 11238 // If we did this folding here, it would be necessary to update the 11239 // MachineBasicBlock CFG, which is awkward. 11240 11241 // Use SimplifySetCC to simplify SETCC's. 11242 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 11243 CondLHS, CondRHS, CC->get(), SDLoc(N), 11244 false); 11245 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 11246 11247 // fold to a simpler setcc 11248 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 11249 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 11250 N->getOperand(0), Simp.getOperand(2), 11251 Simp.getOperand(0), Simp.getOperand(1), 11252 N->getOperand(4)); 11253 11254 return SDValue(); 11255 } 11256 11257 /// Return true if 'Use' is a load or a store that uses N as its base pointer 11258 /// and that N may be folded in the load / store addressing mode. 11259 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 11260 SelectionDAG &DAG, 11261 const TargetLowering &TLI) { 11262 EVT VT; 11263 unsigned AS; 11264 11265 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 11266 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 11267 return false; 11268 VT = LD->getMemoryVT(); 11269 AS = LD->getAddressSpace(); 11270 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 11271 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 11272 return false; 11273 VT = ST->getMemoryVT(); 11274 AS = ST->getAddressSpace(); 11275 } else 11276 return false; 11277 11278 TargetLowering::AddrMode AM; 11279 if (N->getOpcode() == ISD::ADD) { 11280 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11281 if (Offset) 11282 // [reg +/- imm] 11283 AM.BaseOffs = Offset->getSExtValue(); 11284 else 11285 // [reg +/- reg] 11286 AM.Scale = 1; 11287 } else if (N->getOpcode() == ISD::SUB) { 11288 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11289 if (Offset) 11290 // [reg +/- imm] 11291 AM.BaseOffs = -Offset->getSExtValue(); 11292 else 11293 // [reg +/- reg] 11294 AM.Scale = 1; 11295 } else 11296 return false; 11297 11298 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 11299 VT.getTypeForEVT(*DAG.getContext()), AS); 11300 } 11301 11302 /// Try turning a load/store into a pre-indexed load/store when the base 11303 /// pointer is an add or subtract and it has other uses besides the load/store. 11304 /// After the transformation, the new indexed load/store has effectively folded 11305 /// the add/subtract in and all of its other uses are redirected to the 11306 /// new load/store. 11307 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 11308 if (Level < AfterLegalizeDAG) 11309 return false; 11310 11311 bool isLoad = true; 11312 SDValue Ptr; 11313 EVT VT; 11314 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11315 if (LD->isIndexed()) 11316 return false; 11317 VT = LD->getMemoryVT(); 11318 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 11319 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 11320 return false; 11321 Ptr = LD->getBasePtr(); 11322 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11323 if (ST->isIndexed()) 11324 return false; 11325 VT = ST->getMemoryVT(); 11326 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 11327 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 11328 return false; 11329 Ptr = ST->getBasePtr(); 11330 isLoad = false; 11331 } else { 11332 return false; 11333 } 11334 11335 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 11336 // out. There is no reason to make this a preinc/predec. 11337 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 11338 Ptr.getNode()->hasOneUse()) 11339 return false; 11340 11341 // Ask the target to do addressing mode selection. 11342 SDValue BasePtr; 11343 SDValue Offset; 11344 ISD::MemIndexedMode AM = ISD::UNINDEXED; 11345 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 11346 return false; 11347 11348 // Backends without true r+i pre-indexed forms may need to pass a 11349 // constant base with a variable offset so that constant coercion 11350 // will work with the patterns in canonical form. 11351 bool Swapped = false; 11352 if (isa<ConstantSDNode>(BasePtr)) { 11353 std::swap(BasePtr, Offset); 11354 Swapped = true; 11355 } 11356 11357 // Don't create a indexed load / store with zero offset. 11358 if (isNullConstant(Offset)) 11359 return false; 11360 11361 // Try turning it into a pre-indexed load / store except when: 11362 // 1) The new base ptr is a frame index. 11363 // 2) If N is a store and the new base ptr is either the same as or is a 11364 // predecessor of the value being stored. 11365 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 11366 // that would create a cycle. 11367 // 4) All uses are load / store ops that use it as old base ptr. 11368 11369 // Check #1. Preinc'ing a frame index would require copying the stack pointer 11370 // (plus the implicit offset) to a register to preinc anyway. 11371 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 11372 return false; 11373 11374 // Check #2. 11375 if (!isLoad) { 11376 SDValue Val = cast<StoreSDNode>(N)->getValue(); 11377 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 11378 return false; 11379 } 11380 11381 // Caches for hasPredecessorHelper. 11382 SmallPtrSet<const SDNode *, 32> Visited; 11383 SmallVector<const SDNode *, 16> Worklist; 11384 Worklist.push_back(N); 11385 11386 // If the offset is a constant, there may be other adds of constants that 11387 // can be folded with this one. We should do this to avoid having to keep 11388 // a copy of the original base pointer. 11389 SmallVector<SDNode *, 16> OtherUses; 11390 if (isa<ConstantSDNode>(Offset)) 11391 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 11392 UE = BasePtr.getNode()->use_end(); 11393 UI != UE; ++UI) { 11394 SDUse &Use = UI.getUse(); 11395 // Skip the use that is Ptr and uses of other results from BasePtr's 11396 // node (important for nodes that return multiple results). 11397 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 11398 continue; 11399 11400 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 11401 continue; 11402 11403 if (Use.getUser()->getOpcode() != ISD::ADD && 11404 Use.getUser()->getOpcode() != ISD::SUB) { 11405 OtherUses.clear(); 11406 break; 11407 } 11408 11409 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 11410 if (!isa<ConstantSDNode>(Op1)) { 11411 OtherUses.clear(); 11412 break; 11413 } 11414 11415 // FIXME: In some cases, we can be smarter about this. 11416 if (Op1.getValueType() != Offset.getValueType()) { 11417 OtherUses.clear(); 11418 break; 11419 } 11420 11421 OtherUses.push_back(Use.getUser()); 11422 } 11423 11424 if (Swapped) 11425 std::swap(BasePtr, Offset); 11426 11427 // Now check for #3 and #4. 11428 bool RealUse = false; 11429 11430 for (SDNode *Use : Ptr.getNode()->uses()) { 11431 if (Use == N) 11432 continue; 11433 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 11434 return false; 11435 11436 // If Ptr may be folded in addressing mode of other use, then it's 11437 // not profitable to do this transformation. 11438 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 11439 RealUse = true; 11440 } 11441 11442 if (!RealUse) 11443 return false; 11444 11445 SDValue Result; 11446 if (isLoad) 11447 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 11448 BasePtr, Offset, AM); 11449 else 11450 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 11451 BasePtr, Offset, AM); 11452 ++PreIndexedNodes; 11453 ++NodesCombined; 11454 DEBUG(dbgs() << "\nReplacing.4 "; 11455 N->dump(&DAG); 11456 dbgs() << "\nWith: "; 11457 Result.getNode()->dump(&DAG); 11458 dbgs() << '\n'); 11459 WorklistRemover DeadNodes(*this); 11460 if (isLoad) { 11461 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 11462 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 11463 } else { 11464 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 11465 } 11466 11467 // Finally, since the node is now dead, remove it from the graph. 11468 deleteAndRecombine(N); 11469 11470 if (Swapped) 11471 std::swap(BasePtr, Offset); 11472 11473 // Replace other uses of BasePtr that can be updated to use Ptr 11474 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 11475 unsigned OffsetIdx = 1; 11476 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 11477 OffsetIdx = 0; 11478 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 11479 BasePtr.getNode() && "Expected BasePtr operand"); 11480 11481 // We need to replace ptr0 in the following expression: 11482 // x0 * offset0 + y0 * ptr0 = t0 11483 // knowing that 11484 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 11485 // 11486 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 11487 // indexed load/store and the expression that needs to be re-written. 11488 // 11489 // Therefore, we have: 11490 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 11491 11492 ConstantSDNode *CN = 11493 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 11494 int X0, X1, Y0, Y1; 11495 const APInt &Offset0 = CN->getAPIntValue(); 11496 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 11497 11498 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 11499 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 11500 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 11501 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 11502 11503 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 11504 11505 APInt CNV = Offset0; 11506 if (X0 < 0) CNV = -CNV; 11507 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 11508 else CNV = CNV - Offset1; 11509 11510 SDLoc DL(OtherUses[i]); 11511 11512 // We can now generate the new expression. 11513 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 11514 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 11515 11516 SDValue NewUse = DAG.getNode(Opcode, 11517 DL, 11518 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 11519 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 11520 deleteAndRecombine(OtherUses[i]); 11521 } 11522 11523 // Replace the uses of Ptr with uses of the updated base value. 11524 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 11525 deleteAndRecombine(Ptr.getNode()); 11526 AddToWorklist(Result.getNode()); 11527 11528 return true; 11529 } 11530 11531 /// Try to combine a load/store with a add/sub of the base pointer node into a 11532 /// post-indexed load/store. The transformation folded the add/subtract into the 11533 /// new indexed load/store effectively and all of its uses are redirected to the 11534 /// new load/store. 11535 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 11536 if (Level < AfterLegalizeDAG) 11537 return false; 11538 11539 bool isLoad = true; 11540 SDValue Ptr; 11541 EVT VT; 11542 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11543 if (LD->isIndexed()) 11544 return false; 11545 VT = LD->getMemoryVT(); 11546 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 11547 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 11548 return false; 11549 Ptr = LD->getBasePtr(); 11550 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11551 if (ST->isIndexed()) 11552 return false; 11553 VT = ST->getMemoryVT(); 11554 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 11555 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 11556 return false; 11557 Ptr = ST->getBasePtr(); 11558 isLoad = false; 11559 } else { 11560 return false; 11561 } 11562 11563 if (Ptr.getNode()->hasOneUse()) 11564 return false; 11565 11566 for (SDNode *Op : Ptr.getNode()->uses()) { 11567 if (Op == N || 11568 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 11569 continue; 11570 11571 SDValue BasePtr; 11572 SDValue Offset; 11573 ISD::MemIndexedMode AM = ISD::UNINDEXED; 11574 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 11575 // Don't create a indexed load / store with zero offset. 11576 if (isNullConstant(Offset)) 11577 continue; 11578 11579 // Try turning it into a post-indexed load / store except when 11580 // 1) All uses are load / store ops that use it as base ptr (and 11581 // it may be folded as addressing mmode). 11582 // 2) Op must be independent of N, i.e. Op is neither a predecessor 11583 // nor a successor of N. Otherwise, if Op is folded that would 11584 // create a cycle. 11585 11586 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 11587 continue; 11588 11589 // Check for #1. 11590 bool TryNext = false; 11591 for (SDNode *Use : BasePtr.getNode()->uses()) { 11592 if (Use == Ptr.getNode()) 11593 continue; 11594 11595 // If all the uses are load / store addresses, then don't do the 11596 // transformation. 11597 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 11598 bool RealUse = false; 11599 for (SDNode *UseUse : Use->uses()) { 11600 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 11601 RealUse = true; 11602 } 11603 11604 if (!RealUse) { 11605 TryNext = true; 11606 break; 11607 } 11608 } 11609 } 11610 11611 if (TryNext) 11612 continue; 11613 11614 // Check for #2 11615 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 11616 SDValue Result = isLoad 11617 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 11618 BasePtr, Offset, AM) 11619 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 11620 BasePtr, Offset, AM); 11621 ++PostIndexedNodes; 11622 ++NodesCombined; 11623 DEBUG(dbgs() << "\nReplacing.5 "; 11624 N->dump(&DAG); 11625 dbgs() << "\nWith: "; 11626 Result.getNode()->dump(&DAG); 11627 dbgs() << '\n'); 11628 WorklistRemover DeadNodes(*this); 11629 if (isLoad) { 11630 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 11631 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 11632 } else { 11633 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 11634 } 11635 11636 // Finally, since the node is now dead, remove it from the graph. 11637 deleteAndRecombine(N); 11638 11639 // Replace the uses of Use with uses of the updated base value. 11640 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 11641 Result.getValue(isLoad ? 1 : 0)); 11642 deleteAndRecombine(Op); 11643 return true; 11644 } 11645 } 11646 } 11647 11648 return false; 11649 } 11650 11651 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 11652 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 11653 ISD::MemIndexedMode AM = LD->getAddressingMode(); 11654 assert(AM != ISD::UNINDEXED); 11655 SDValue BP = LD->getOperand(1); 11656 SDValue Inc = LD->getOperand(2); 11657 11658 // Some backends use TargetConstants for load offsets, but don't expect 11659 // TargetConstants in general ADD nodes. We can convert these constants into 11660 // regular Constants (if the constant is not opaque). 11661 assert((Inc.getOpcode() != ISD::TargetConstant || 11662 !cast<ConstantSDNode>(Inc)->isOpaque()) && 11663 "Cannot split out indexing using opaque target constants"); 11664 if (Inc.getOpcode() == ISD::TargetConstant) { 11665 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 11666 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 11667 ConstInc->getValueType(0)); 11668 } 11669 11670 unsigned Opc = 11671 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 11672 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 11673 } 11674 11675 SDValue DAGCombiner::visitLOAD(SDNode *N) { 11676 LoadSDNode *LD = cast<LoadSDNode>(N); 11677 SDValue Chain = LD->getChain(); 11678 SDValue Ptr = LD->getBasePtr(); 11679 11680 // If load is not volatile and there are no uses of the loaded value (and 11681 // the updated indexed value in case of indexed loads), change uses of the 11682 // chain value into uses of the chain input (i.e. delete the dead load). 11683 if (!LD->isVolatile()) { 11684 if (N->getValueType(1) == MVT::Other) { 11685 // Unindexed loads. 11686 if (!N->hasAnyUseOfValue(0)) { 11687 // It's not safe to use the two value CombineTo variant here. e.g. 11688 // v1, chain2 = load chain1, loc 11689 // v2, chain3 = load chain2, loc 11690 // v3 = add v2, c 11691 // Now we replace use of chain2 with chain1. This makes the second load 11692 // isomorphic to the one we are deleting, and thus makes this load live. 11693 DEBUG(dbgs() << "\nReplacing.6 "; 11694 N->dump(&DAG); 11695 dbgs() << "\nWith chain: "; 11696 Chain.getNode()->dump(&DAG); 11697 dbgs() << "\n"); 11698 WorklistRemover DeadNodes(*this); 11699 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 11700 AddUsersToWorklist(Chain.getNode()); 11701 if (N->use_empty()) 11702 deleteAndRecombine(N); 11703 11704 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11705 } 11706 } else { 11707 // Indexed loads. 11708 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 11709 11710 // If this load has an opaque TargetConstant offset, then we cannot split 11711 // the indexing into an add/sub directly (that TargetConstant may not be 11712 // valid for a different type of node, and we cannot convert an opaque 11713 // target constant into a regular constant). 11714 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 11715 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 11716 11717 if (!N->hasAnyUseOfValue(0) && 11718 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 11719 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 11720 SDValue Index; 11721 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 11722 Index = SplitIndexingFromLoad(LD); 11723 // Try to fold the base pointer arithmetic into subsequent loads and 11724 // stores. 11725 AddUsersToWorklist(N); 11726 } else 11727 Index = DAG.getUNDEF(N->getValueType(1)); 11728 DEBUG(dbgs() << "\nReplacing.7 "; 11729 N->dump(&DAG); 11730 dbgs() << "\nWith: "; 11731 Undef.getNode()->dump(&DAG); 11732 dbgs() << " and 2 other values\n"); 11733 WorklistRemover DeadNodes(*this); 11734 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 11735 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 11736 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 11737 deleteAndRecombine(N); 11738 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11739 } 11740 } 11741 } 11742 11743 // If this load is directly stored, replace the load value with the stored 11744 // value. 11745 // TODO: Handle store large -> read small portion. 11746 // TODO: Handle TRUNCSTORE/LOADEXT 11747 if (OptLevel != CodeGenOpt::None && 11748 ISD::isNormalLoad(N) && !LD->isVolatile()) { 11749 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 11750 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 11751 if (PrevST->getBasePtr() == Ptr && 11752 PrevST->getValue().getValueType() == N->getValueType(0)) 11753 return CombineTo(N, PrevST->getOperand(1), Chain); 11754 } 11755 } 11756 11757 // Try to infer better alignment information than the load already has. 11758 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 11759 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 11760 if (Align > LD->getMemOperand()->getBaseAlignment()) { 11761 SDValue NewLoad = DAG.getExtLoad( 11762 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 11763 LD->getPointerInfo(), LD->getMemoryVT(), Align, 11764 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 11765 if (NewLoad.getNode() != N) 11766 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 11767 } 11768 } 11769 } 11770 11771 if (LD->isUnindexed()) { 11772 // Walk up chain skipping non-aliasing memory nodes. 11773 SDValue BetterChain = FindBetterChain(N, Chain); 11774 11775 // If there is a better chain. 11776 if (Chain != BetterChain) { 11777 SDValue ReplLoad; 11778 11779 // Replace the chain to void dependency. 11780 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 11781 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 11782 BetterChain, Ptr, LD->getMemOperand()); 11783 } else { 11784 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 11785 LD->getValueType(0), 11786 BetterChain, Ptr, LD->getMemoryVT(), 11787 LD->getMemOperand()); 11788 } 11789 11790 // Create token factor to keep old chain connected. 11791 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 11792 MVT::Other, Chain, ReplLoad.getValue(1)); 11793 11794 // Replace uses with load result and token factor 11795 return CombineTo(N, ReplLoad.getValue(0), Token); 11796 } 11797 } 11798 11799 // Try transforming N to an indexed load. 11800 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 11801 return SDValue(N, 0); 11802 11803 // Try to slice up N to more direct loads if the slices are mapped to 11804 // different register banks or pairing can take place. 11805 if (SliceUpLoad(N)) 11806 return SDValue(N, 0); 11807 11808 return SDValue(); 11809 } 11810 11811 namespace { 11812 11813 /// \brief Helper structure used to slice a load in smaller loads. 11814 /// Basically a slice is obtained from the following sequence: 11815 /// Origin = load Ty1, Base 11816 /// Shift = srl Ty1 Origin, CstTy Amount 11817 /// Inst = trunc Shift to Ty2 11818 /// 11819 /// Then, it will be rewritten into: 11820 /// Slice = load SliceTy, Base + SliceOffset 11821 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 11822 /// 11823 /// SliceTy is deduced from the number of bits that are actually used to 11824 /// build Inst. 11825 struct LoadedSlice { 11826 /// \brief Helper structure used to compute the cost of a slice. 11827 struct Cost { 11828 /// Are we optimizing for code size. 11829 bool ForCodeSize; 11830 11831 /// Various cost. 11832 unsigned Loads = 0; 11833 unsigned Truncates = 0; 11834 unsigned CrossRegisterBanksCopies = 0; 11835 unsigned ZExts = 0; 11836 unsigned Shift = 0; 11837 11838 Cost(bool ForCodeSize = false) : ForCodeSize(ForCodeSize) {} 11839 11840 /// \brief Get the cost of one isolated slice. 11841 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 11842 : ForCodeSize(ForCodeSize), Loads(1) { 11843 EVT TruncType = LS.Inst->getValueType(0); 11844 EVT LoadedType = LS.getLoadedType(); 11845 if (TruncType != LoadedType && 11846 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 11847 ZExts = 1; 11848 } 11849 11850 /// \brief Account for slicing gain in the current cost. 11851 /// Slicing provide a few gains like removing a shift or a 11852 /// truncate. This method allows to grow the cost of the original 11853 /// load with the gain from this slice. 11854 void addSliceGain(const LoadedSlice &LS) { 11855 // Each slice saves a truncate. 11856 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 11857 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 11858 LS.Inst->getValueType(0))) 11859 ++Truncates; 11860 // If there is a shift amount, this slice gets rid of it. 11861 if (LS.Shift) 11862 ++Shift; 11863 // If this slice can merge a cross register bank copy, account for it. 11864 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 11865 ++CrossRegisterBanksCopies; 11866 } 11867 11868 Cost &operator+=(const Cost &RHS) { 11869 Loads += RHS.Loads; 11870 Truncates += RHS.Truncates; 11871 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 11872 ZExts += RHS.ZExts; 11873 Shift += RHS.Shift; 11874 return *this; 11875 } 11876 11877 bool operator==(const Cost &RHS) const { 11878 return Loads == RHS.Loads && Truncates == RHS.Truncates && 11879 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 11880 ZExts == RHS.ZExts && Shift == RHS.Shift; 11881 } 11882 11883 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 11884 11885 bool operator<(const Cost &RHS) const { 11886 // Assume cross register banks copies are as expensive as loads. 11887 // FIXME: Do we want some more target hooks? 11888 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 11889 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 11890 // Unless we are optimizing for code size, consider the 11891 // expensive operation first. 11892 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 11893 return ExpensiveOpsLHS < ExpensiveOpsRHS; 11894 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 11895 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 11896 } 11897 11898 bool operator>(const Cost &RHS) const { return RHS < *this; } 11899 11900 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 11901 11902 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 11903 }; 11904 11905 // The last instruction that represent the slice. This should be a 11906 // truncate instruction. 11907 SDNode *Inst; 11908 11909 // The original load instruction. 11910 LoadSDNode *Origin; 11911 11912 // The right shift amount in bits from the original load. 11913 unsigned Shift; 11914 11915 // The DAG from which Origin came from. 11916 // This is used to get some contextual information about legal types, etc. 11917 SelectionDAG *DAG; 11918 11919 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 11920 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 11921 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 11922 11923 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 11924 /// \return Result is \p BitWidth and has used bits set to 1 and 11925 /// not used bits set to 0. 11926 APInt getUsedBits() const { 11927 // Reproduce the trunc(lshr) sequence: 11928 // - Start from the truncated value. 11929 // - Zero extend to the desired bit width. 11930 // - Shift left. 11931 assert(Origin && "No original load to compare against."); 11932 unsigned BitWidth = Origin->getValueSizeInBits(0); 11933 assert(Inst && "This slice is not bound to an instruction"); 11934 assert(Inst->getValueSizeInBits(0) <= BitWidth && 11935 "Extracted slice is bigger than the whole type!"); 11936 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 11937 UsedBits.setAllBits(); 11938 UsedBits = UsedBits.zext(BitWidth); 11939 UsedBits <<= Shift; 11940 return UsedBits; 11941 } 11942 11943 /// \brief Get the size of the slice to be loaded in bytes. 11944 unsigned getLoadedSize() const { 11945 unsigned SliceSize = getUsedBits().countPopulation(); 11946 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 11947 return SliceSize / 8; 11948 } 11949 11950 /// \brief Get the type that will be loaded for this slice. 11951 /// Note: This may not be the final type for the slice. 11952 EVT getLoadedType() const { 11953 assert(DAG && "Missing context"); 11954 LLVMContext &Ctxt = *DAG->getContext(); 11955 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 11956 } 11957 11958 /// \brief Get the alignment of the load used for this slice. 11959 unsigned getAlignment() const { 11960 unsigned Alignment = Origin->getAlignment(); 11961 unsigned Offset = getOffsetFromBase(); 11962 if (Offset != 0) 11963 Alignment = MinAlign(Alignment, Alignment + Offset); 11964 return Alignment; 11965 } 11966 11967 /// \brief Check if this slice can be rewritten with legal operations. 11968 bool isLegal() const { 11969 // An invalid slice is not legal. 11970 if (!Origin || !Inst || !DAG) 11971 return false; 11972 11973 // Offsets are for indexed load only, we do not handle that. 11974 if (!Origin->getOffset().isUndef()) 11975 return false; 11976 11977 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 11978 11979 // Check that the type is legal. 11980 EVT SliceType = getLoadedType(); 11981 if (!TLI.isTypeLegal(SliceType)) 11982 return false; 11983 11984 // Check that the load is legal for this type. 11985 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 11986 return false; 11987 11988 // Check that the offset can be computed. 11989 // 1. Check its type. 11990 EVT PtrType = Origin->getBasePtr().getValueType(); 11991 if (PtrType == MVT::Untyped || PtrType.isExtended()) 11992 return false; 11993 11994 // 2. Check that it fits in the immediate. 11995 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 11996 return false; 11997 11998 // 3. Check that the computation is legal. 11999 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 12000 return false; 12001 12002 // Check that the zext is legal if it needs one. 12003 EVT TruncateType = Inst->getValueType(0); 12004 if (TruncateType != SliceType && 12005 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 12006 return false; 12007 12008 return true; 12009 } 12010 12011 /// \brief Get the offset in bytes of this slice in the original chunk of 12012 /// bits. 12013 /// \pre DAG != nullptr. 12014 uint64_t getOffsetFromBase() const { 12015 assert(DAG && "Missing context."); 12016 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 12017 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 12018 uint64_t Offset = Shift / 8; 12019 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 12020 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 12021 "The size of the original loaded type is not a multiple of a" 12022 " byte."); 12023 // If Offset is bigger than TySizeInBytes, it means we are loading all 12024 // zeros. This should have been optimized before in the process. 12025 assert(TySizeInBytes > Offset && 12026 "Invalid shift amount for given loaded size"); 12027 if (IsBigEndian) 12028 Offset = TySizeInBytes - Offset - getLoadedSize(); 12029 return Offset; 12030 } 12031 12032 /// \brief Generate the sequence of instructions to load the slice 12033 /// represented by this object and redirect the uses of this slice to 12034 /// this new sequence of instructions. 12035 /// \pre this->Inst && this->Origin are valid Instructions and this 12036 /// object passed the legal check: LoadedSlice::isLegal returned true. 12037 /// \return The last instruction of the sequence used to load the slice. 12038 SDValue loadSlice() const { 12039 assert(Inst && Origin && "Unable to replace a non-existing slice."); 12040 const SDValue &OldBaseAddr = Origin->getBasePtr(); 12041 SDValue BaseAddr = OldBaseAddr; 12042 // Get the offset in that chunk of bytes w.r.t. the endianness. 12043 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 12044 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 12045 if (Offset) { 12046 // BaseAddr = BaseAddr + Offset. 12047 EVT ArithType = BaseAddr.getValueType(); 12048 SDLoc DL(Origin); 12049 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 12050 DAG->getConstant(Offset, DL, ArithType)); 12051 } 12052 12053 // Create the type of the loaded slice according to its size. 12054 EVT SliceType = getLoadedType(); 12055 12056 // Create the load for the slice. 12057 SDValue LastInst = 12058 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 12059 Origin->getPointerInfo().getWithOffset(Offset), 12060 getAlignment(), Origin->getMemOperand()->getFlags()); 12061 // If the final type is not the same as the loaded type, this means that 12062 // we have to pad with zero. Create a zero extend for that. 12063 EVT FinalType = Inst->getValueType(0); 12064 if (SliceType != FinalType) 12065 LastInst = 12066 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 12067 return LastInst; 12068 } 12069 12070 /// \brief Check if this slice can be merged with an expensive cross register 12071 /// bank copy. E.g., 12072 /// i = load i32 12073 /// f = bitcast i32 i to float 12074 bool canMergeExpensiveCrossRegisterBankCopy() const { 12075 if (!Inst || !Inst->hasOneUse()) 12076 return false; 12077 SDNode *Use = *Inst->use_begin(); 12078 if (Use->getOpcode() != ISD::BITCAST) 12079 return false; 12080 assert(DAG && "Missing context"); 12081 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 12082 EVT ResVT = Use->getValueType(0); 12083 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 12084 const TargetRegisterClass *ArgRC = 12085 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 12086 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 12087 return false; 12088 12089 // At this point, we know that we perform a cross-register-bank copy. 12090 // Check if it is expensive. 12091 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 12092 // Assume bitcasts are cheap, unless both register classes do not 12093 // explicitly share a common sub class. 12094 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 12095 return false; 12096 12097 // Check if it will be merged with the load. 12098 // 1. Check the alignment constraint. 12099 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 12100 ResVT.getTypeForEVT(*DAG->getContext())); 12101 12102 if (RequiredAlignment > getAlignment()) 12103 return false; 12104 12105 // 2. Check that the load is a legal operation for that type. 12106 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 12107 return false; 12108 12109 // 3. Check that we do not have a zext in the way. 12110 if (Inst->getValueType(0) != getLoadedType()) 12111 return false; 12112 12113 return true; 12114 } 12115 }; 12116 12117 } // end anonymous namespace 12118 12119 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 12120 /// \p UsedBits looks like 0..0 1..1 0..0. 12121 static bool areUsedBitsDense(const APInt &UsedBits) { 12122 // If all the bits are one, this is dense! 12123 if (UsedBits.isAllOnesValue()) 12124 return true; 12125 12126 // Get rid of the unused bits on the right. 12127 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 12128 // Get rid of the unused bits on the left. 12129 if (NarrowedUsedBits.countLeadingZeros()) 12130 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 12131 // Check that the chunk of bits is completely used. 12132 return NarrowedUsedBits.isAllOnesValue(); 12133 } 12134 12135 /// \brief Check whether or not \p First and \p Second are next to each other 12136 /// in memory. This means that there is no hole between the bits loaded 12137 /// by \p First and the bits loaded by \p Second. 12138 static bool areSlicesNextToEachOther(const LoadedSlice &First, 12139 const LoadedSlice &Second) { 12140 assert(First.Origin == Second.Origin && First.Origin && 12141 "Unable to match different memory origins."); 12142 APInt UsedBits = First.getUsedBits(); 12143 assert((UsedBits & Second.getUsedBits()) == 0 && 12144 "Slices are not supposed to overlap."); 12145 UsedBits |= Second.getUsedBits(); 12146 return areUsedBitsDense(UsedBits); 12147 } 12148 12149 /// \brief Adjust the \p GlobalLSCost according to the target 12150 /// paring capabilities and the layout of the slices. 12151 /// \pre \p GlobalLSCost should account for at least as many loads as 12152 /// there is in the slices in \p LoadedSlices. 12153 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 12154 LoadedSlice::Cost &GlobalLSCost) { 12155 unsigned NumberOfSlices = LoadedSlices.size(); 12156 // If there is less than 2 elements, no pairing is possible. 12157 if (NumberOfSlices < 2) 12158 return; 12159 12160 // Sort the slices so that elements that are likely to be next to each 12161 // other in memory are next to each other in the list. 12162 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 12163 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 12164 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 12165 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 12166 }); 12167 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 12168 // First (resp. Second) is the first (resp. Second) potentially candidate 12169 // to be placed in a paired load. 12170 const LoadedSlice *First = nullptr; 12171 const LoadedSlice *Second = nullptr; 12172 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 12173 // Set the beginning of the pair. 12174 First = Second) { 12175 Second = &LoadedSlices[CurrSlice]; 12176 12177 // If First is NULL, it means we start a new pair. 12178 // Get to the next slice. 12179 if (!First) 12180 continue; 12181 12182 EVT LoadedType = First->getLoadedType(); 12183 12184 // If the types of the slices are different, we cannot pair them. 12185 if (LoadedType != Second->getLoadedType()) 12186 continue; 12187 12188 // Check if the target supplies paired loads for this type. 12189 unsigned RequiredAlignment = 0; 12190 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 12191 // move to the next pair, this type is hopeless. 12192 Second = nullptr; 12193 continue; 12194 } 12195 // Check if we meet the alignment requirement. 12196 if (RequiredAlignment > First->getAlignment()) 12197 continue; 12198 12199 // Check that both loads are next to each other in memory. 12200 if (!areSlicesNextToEachOther(*First, *Second)) 12201 continue; 12202 12203 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 12204 --GlobalLSCost.Loads; 12205 // Move to the next pair. 12206 Second = nullptr; 12207 } 12208 } 12209 12210 /// \brief Check the profitability of all involved LoadedSlice. 12211 /// Currently, it is considered profitable if there is exactly two 12212 /// involved slices (1) which are (2) next to each other in memory, and 12213 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 12214 /// 12215 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 12216 /// the elements themselves. 12217 /// 12218 /// FIXME: When the cost model will be mature enough, we can relax 12219 /// constraints (1) and (2). 12220 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 12221 const APInt &UsedBits, bool ForCodeSize) { 12222 unsigned NumberOfSlices = LoadedSlices.size(); 12223 if (StressLoadSlicing) 12224 return NumberOfSlices > 1; 12225 12226 // Check (1). 12227 if (NumberOfSlices != 2) 12228 return false; 12229 12230 // Check (2). 12231 if (!areUsedBitsDense(UsedBits)) 12232 return false; 12233 12234 // Check (3). 12235 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 12236 // The original code has one big load. 12237 OrigCost.Loads = 1; 12238 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 12239 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 12240 // Accumulate the cost of all the slices. 12241 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 12242 GlobalSlicingCost += SliceCost; 12243 12244 // Account as cost in the original configuration the gain obtained 12245 // with the current slices. 12246 OrigCost.addSliceGain(LS); 12247 } 12248 12249 // If the target supports paired load, adjust the cost accordingly. 12250 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 12251 return OrigCost > GlobalSlicingCost; 12252 } 12253 12254 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 12255 /// operations, split it in the various pieces being extracted. 12256 /// 12257 /// This sort of thing is introduced by SROA. 12258 /// This slicing takes care not to insert overlapping loads. 12259 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 12260 bool DAGCombiner::SliceUpLoad(SDNode *N) { 12261 if (Level < AfterLegalizeDAG) 12262 return false; 12263 12264 LoadSDNode *LD = cast<LoadSDNode>(N); 12265 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 12266 !LD->getValueType(0).isInteger()) 12267 return false; 12268 12269 // Keep track of already used bits to detect overlapping values. 12270 // In that case, we will just abort the transformation. 12271 APInt UsedBits(LD->getValueSizeInBits(0), 0); 12272 12273 SmallVector<LoadedSlice, 4> LoadedSlices; 12274 12275 // Check if this load is used as several smaller chunks of bits. 12276 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 12277 // of computation for each trunc. 12278 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 12279 UI != UIEnd; ++UI) { 12280 // Skip the uses of the chain. 12281 if (UI.getUse().getResNo() != 0) 12282 continue; 12283 12284 SDNode *User = *UI; 12285 unsigned Shift = 0; 12286 12287 // Check if this is a trunc(lshr). 12288 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 12289 isa<ConstantSDNode>(User->getOperand(1))) { 12290 Shift = User->getConstantOperandVal(1); 12291 User = *User->use_begin(); 12292 } 12293 12294 // At this point, User is a Truncate, iff we encountered, trunc or 12295 // trunc(lshr). 12296 if (User->getOpcode() != ISD::TRUNCATE) 12297 return false; 12298 12299 // The width of the type must be a power of 2 and greater than 8-bits. 12300 // Otherwise the load cannot be represented in LLVM IR. 12301 // Moreover, if we shifted with a non-8-bits multiple, the slice 12302 // will be across several bytes. We do not support that. 12303 unsigned Width = User->getValueSizeInBits(0); 12304 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 12305 return false; 12306 12307 // Build the slice for this chain of computations. 12308 LoadedSlice LS(User, LD, Shift, &DAG); 12309 APInt CurrentUsedBits = LS.getUsedBits(); 12310 12311 // Check if this slice overlaps with another. 12312 if ((CurrentUsedBits & UsedBits) != 0) 12313 return false; 12314 // Update the bits used globally. 12315 UsedBits |= CurrentUsedBits; 12316 12317 // Check if the new slice would be legal. 12318 if (!LS.isLegal()) 12319 return false; 12320 12321 // Record the slice. 12322 LoadedSlices.push_back(LS); 12323 } 12324 12325 // Abort slicing if it does not seem to be profitable. 12326 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 12327 return false; 12328 12329 ++SlicedLoads; 12330 12331 // Rewrite each chain to use an independent load. 12332 // By construction, each chain can be represented by a unique load. 12333 12334 // Prepare the argument for the new token factor for all the slices. 12335 SmallVector<SDValue, 8> ArgChains; 12336 for (SmallVectorImpl<LoadedSlice>::const_iterator 12337 LSIt = LoadedSlices.begin(), 12338 LSItEnd = LoadedSlices.end(); 12339 LSIt != LSItEnd; ++LSIt) { 12340 SDValue SliceInst = LSIt->loadSlice(); 12341 CombineTo(LSIt->Inst, SliceInst, true); 12342 if (SliceInst.getOpcode() != ISD::LOAD) 12343 SliceInst = SliceInst.getOperand(0); 12344 assert(SliceInst->getOpcode() == ISD::LOAD && 12345 "It takes more than a zext to get to the loaded slice!!"); 12346 ArgChains.push_back(SliceInst.getValue(1)); 12347 } 12348 12349 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 12350 ArgChains); 12351 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 12352 AddToWorklist(Chain.getNode()); 12353 return true; 12354 } 12355 12356 /// Check to see if V is (and load (ptr), imm), where the load is having 12357 /// specific bytes cleared out. If so, return the byte size being masked out 12358 /// and the shift amount. 12359 static std::pair<unsigned, unsigned> 12360 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 12361 std::pair<unsigned, unsigned> Result(0, 0); 12362 12363 // Check for the structure we're looking for. 12364 if (V->getOpcode() != ISD::AND || 12365 !isa<ConstantSDNode>(V->getOperand(1)) || 12366 !ISD::isNormalLoad(V->getOperand(0).getNode())) 12367 return Result; 12368 12369 // Check the chain and pointer. 12370 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 12371 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 12372 12373 // The store should be chained directly to the load or be an operand of a 12374 // tokenfactor. 12375 if (LD == Chain.getNode()) 12376 ; // ok. 12377 else if (Chain->getOpcode() != ISD::TokenFactor) 12378 return Result; // Fail. 12379 else { 12380 bool isOk = false; 12381 for (const SDValue &ChainOp : Chain->op_values()) 12382 if (ChainOp.getNode() == LD) { 12383 isOk = true; 12384 break; 12385 } 12386 if (!isOk) return Result; 12387 } 12388 12389 // This only handles simple types. 12390 if (V.getValueType() != MVT::i16 && 12391 V.getValueType() != MVT::i32 && 12392 V.getValueType() != MVT::i64) 12393 return Result; 12394 12395 // Check the constant mask. Invert it so that the bits being masked out are 12396 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 12397 // follow the sign bit for uniformity. 12398 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 12399 unsigned NotMaskLZ = countLeadingZeros(NotMask); 12400 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 12401 unsigned NotMaskTZ = countTrailingZeros(NotMask); 12402 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 12403 if (NotMaskLZ == 64) return Result; // All zero mask. 12404 12405 // See if we have a continuous run of bits. If so, we have 0*1+0* 12406 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 12407 return Result; 12408 12409 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 12410 if (V.getValueType() != MVT::i64 && NotMaskLZ) 12411 NotMaskLZ -= 64-V.getValueSizeInBits(); 12412 12413 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 12414 switch (MaskedBytes) { 12415 case 1: 12416 case 2: 12417 case 4: break; 12418 default: return Result; // All one mask, or 5-byte mask. 12419 } 12420 12421 // Verify that the first bit starts at a multiple of mask so that the access 12422 // is aligned the same as the access width. 12423 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 12424 12425 Result.first = MaskedBytes; 12426 Result.second = NotMaskTZ/8; 12427 return Result; 12428 } 12429 12430 /// Check to see if IVal is something that provides a value as specified by 12431 /// MaskInfo. If so, replace the specified store with a narrower store of 12432 /// truncated IVal. 12433 static SDNode * 12434 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 12435 SDValue IVal, StoreSDNode *St, 12436 DAGCombiner *DC) { 12437 unsigned NumBytes = MaskInfo.first; 12438 unsigned ByteShift = MaskInfo.second; 12439 SelectionDAG &DAG = DC->getDAG(); 12440 12441 // Check to see if IVal is all zeros in the part being masked in by the 'or' 12442 // that uses this. If not, this is not a replacement. 12443 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 12444 ByteShift*8, (ByteShift+NumBytes)*8); 12445 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 12446 12447 // Check that it is legal on the target to do this. It is legal if the new 12448 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 12449 // legalization. 12450 MVT VT = MVT::getIntegerVT(NumBytes*8); 12451 if (!DC->isTypeLegal(VT)) 12452 return nullptr; 12453 12454 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 12455 // shifted by ByteShift and truncated down to NumBytes. 12456 if (ByteShift) { 12457 SDLoc DL(IVal); 12458 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 12459 DAG.getConstant(ByteShift*8, DL, 12460 DC->getShiftAmountTy(IVal.getValueType()))); 12461 } 12462 12463 // Figure out the offset for the store and the alignment of the access. 12464 unsigned StOffset; 12465 unsigned NewAlign = St->getAlignment(); 12466 12467 if (DAG.getDataLayout().isLittleEndian()) 12468 StOffset = ByteShift; 12469 else 12470 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 12471 12472 SDValue Ptr = St->getBasePtr(); 12473 if (StOffset) { 12474 SDLoc DL(IVal); 12475 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 12476 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 12477 NewAlign = MinAlign(NewAlign, StOffset); 12478 } 12479 12480 // Truncate down to the new size. 12481 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 12482 12483 ++OpsNarrowed; 12484 return DAG 12485 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 12486 St->getPointerInfo().getWithOffset(StOffset), NewAlign) 12487 .getNode(); 12488 } 12489 12490 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 12491 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 12492 /// narrowing the load and store if it would end up being a win for performance 12493 /// or code size. 12494 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 12495 StoreSDNode *ST = cast<StoreSDNode>(N); 12496 if (ST->isVolatile()) 12497 return SDValue(); 12498 12499 SDValue Chain = ST->getChain(); 12500 SDValue Value = ST->getValue(); 12501 SDValue Ptr = ST->getBasePtr(); 12502 EVT VT = Value.getValueType(); 12503 12504 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 12505 return SDValue(); 12506 12507 unsigned Opc = Value.getOpcode(); 12508 12509 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 12510 // is a byte mask indicating a consecutive number of bytes, check to see if 12511 // Y is known to provide just those bytes. If so, we try to replace the 12512 // load + replace + store sequence with a single (narrower) store, which makes 12513 // the load dead. 12514 if (Opc == ISD::OR) { 12515 std::pair<unsigned, unsigned> MaskedLoad; 12516 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 12517 if (MaskedLoad.first) 12518 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 12519 Value.getOperand(1), ST,this)) 12520 return SDValue(NewST, 0); 12521 12522 // Or is commutative, so try swapping X and Y. 12523 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 12524 if (MaskedLoad.first) 12525 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 12526 Value.getOperand(0), ST,this)) 12527 return SDValue(NewST, 0); 12528 } 12529 12530 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 12531 Value.getOperand(1).getOpcode() != ISD::Constant) 12532 return SDValue(); 12533 12534 SDValue N0 = Value.getOperand(0); 12535 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 12536 Chain == SDValue(N0.getNode(), 1)) { 12537 LoadSDNode *LD = cast<LoadSDNode>(N0); 12538 if (LD->getBasePtr() != Ptr || 12539 LD->getPointerInfo().getAddrSpace() != 12540 ST->getPointerInfo().getAddrSpace()) 12541 return SDValue(); 12542 12543 // Find the type to narrow it the load / op / store to. 12544 SDValue N1 = Value.getOperand(1); 12545 unsigned BitWidth = N1.getValueSizeInBits(); 12546 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 12547 if (Opc == ISD::AND) 12548 Imm ^= APInt::getAllOnesValue(BitWidth); 12549 if (Imm == 0 || Imm.isAllOnesValue()) 12550 return SDValue(); 12551 unsigned ShAmt = Imm.countTrailingZeros(); 12552 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 12553 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 12554 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 12555 // The narrowing should be profitable, the load/store operation should be 12556 // legal (or custom) and the store size should be equal to the NewVT width. 12557 while (NewBW < BitWidth && 12558 (NewVT.getStoreSizeInBits() != NewBW || 12559 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 12560 !TLI.isNarrowingProfitable(VT, NewVT))) { 12561 NewBW = NextPowerOf2(NewBW); 12562 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 12563 } 12564 if (NewBW >= BitWidth) 12565 return SDValue(); 12566 12567 // If the lsb changed does not start at the type bitwidth boundary, 12568 // start at the previous one. 12569 if (ShAmt % NewBW) 12570 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 12571 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 12572 std::min(BitWidth, ShAmt + NewBW)); 12573 if ((Imm & Mask) == Imm) { 12574 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 12575 if (Opc == ISD::AND) 12576 NewImm ^= APInt::getAllOnesValue(NewBW); 12577 uint64_t PtrOff = ShAmt / 8; 12578 // For big endian targets, we need to adjust the offset to the pointer to 12579 // load the correct bytes. 12580 if (DAG.getDataLayout().isBigEndian()) 12581 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 12582 12583 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 12584 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 12585 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 12586 return SDValue(); 12587 12588 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 12589 Ptr.getValueType(), Ptr, 12590 DAG.getConstant(PtrOff, SDLoc(LD), 12591 Ptr.getValueType())); 12592 SDValue NewLD = 12593 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 12594 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 12595 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 12596 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 12597 DAG.getConstant(NewImm, SDLoc(Value), 12598 NewVT)); 12599 SDValue NewST = 12600 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 12601 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 12602 12603 AddToWorklist(NewPtr.getNode()); 12604 AddToWorklist(NewLD.getNode()); 12605 AddToWorklist(NewVal.getNode()); 12606 WorklistRemover DeadNodes(*this); 12607 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 12608 ++OpsNarrowed; 12609 return NewST; 12610 } 12611 } 12612 12613 return SDValue(); 12614 } 12615 12616 /// For a given floating point load / store pair, if the load value isn't used 12617 /// by any other operations, then consider transforming the pair to integer 12618 /// load / store operations if the target deems the transformation profitable. 12619 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 12620 StoreSDNode *ST = cast<StoreSDNode>(N); 12621 SDValue Chain = ST->getChain(); 12622 SDValue Value = ST->getValue(); 12623 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 12624 Value.hasOneUse() && 12625 Chain == SDValue(Value.getNode(), 1)) { 12626 LoadSDNode *LD = cast<LoadSDNode>(Value); 12627 EVT VT = LD->getMemoryVT(); 12628 if (!VT.isFloatingPoint() || 12629 VT != ST->getMemoryVT() || 12630 LD->isNonTemporal() || 12631 ST->isNonTemporal() || 12632 LD->getPointerInfo().getAddrSpace() != 0 || 12633 ST->getPointerInfo().getAddrSpace() != 0) 12634 return SDValue(); 12635 12636 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 12637 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 12638 !TLI.isOperationLegal(ISD::STORE, IntVT) || 12639 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 12640 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 12641 return SDValue(); 12642 12643 unsigned LDAlign = LD->getAlignment(); 12644 unsigned STAlign = ST->getAlignment(); 12645 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 12646 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 12647 if (LDAlign < ABIAlign || STAlign < ABIAlign) 12648 return SDValue(); 12649 12650 SDValue NewLD = 12651 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 12652 LD->getPointerInfo(), LDAlign); 12653 12654 SDValue NewST = 12655 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(), 12656 ST->getPointerInfo(), STAlign); 12657 12658 AddToWorklist(NewLD.getNode()); 12659 AddToWorklist(NewST.getNode()); 12660 WorklistRemover DeadNodes(*this); 12661 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 12662 ++LdStFP2Int; 12663 return NewST; 12664 } 12665 12666 return SDValue(); 12667 } 12668 12669 // This is a helper function for visitMUL to check the profitability 12670 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 12671 // MulNode is the original multiply, AddNode is (add x, c1), 12672 // and ConstNode is c2. 12673 // 12674 // If the (add x, c1) has multiple uses, we could increase 12675 // the number of adds if we make this transformation. 12676 // It would only be worth doing this if we can remove a 12677 // multiply in the process. Check for that here. 12678 // To illustrate: 12679 // (A + c1) * c3 12680 // (A + c2) * c3 12681 // We're checking for cases where we have common "c3 * A" expressions. 12682 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 12683 SDValue &AddNode, 12684 SDValue &ConstNode) { 12685 APInt Val; 12686 12687 // If the add only has one use, this would be OK to do. 12688 if (AddNode.getNode()->hasOneUse()) 12689 return true; 12690 12691 // Walk all the users of the constant with which we're multiplying. 12692 for (SDNode *Use : ConstNode->uses()) { 12693 if (Use == MulNode) // This use is the one we're on right now. Skip it. 12694 continue; 12695 12696 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 12697 SDNode *OtherOp; 12698 SDNode *MulVar = AddNode.getOperand(0).getNode(); 12699 12700 // OtherOp is what we're multiplying against the constant. 12701 if (Use->getOperand(0) == ConstNode) 12702 OtherOp = Use->getOperand(1).getNode(); 12703 else 12704 OtherOp = Use->getOperand(0).getNode(); 12705 12706 // Check to see if multiply is with the same operand of our "add". 12707 // 12708 // ConstNode = CONST 12709 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 12710 // ... 12711 // AddNode = (A + c1) <-- MulVar is A. 12712 // = AddNode * ConstNode <-- current visiting instruction. 12713 // 12714 // If we make this transformation, we will have a common 12715 // multiply (ConstNode * A) that we can save. 12716 if (OtherOp == MulVar) 12717 return true; 12718 12719 // Now check to see if a future expansion will give us a common 12720 // multiply. 12721 // 12722 // ConstNode = CONST 12723 // AddNode = (A + c1) 12724 // ... = AddNode * ConstNode <-- current visiting instruction. 12725 // ... 12726 // OtherOp = (A + c2) 12727 // Use = OtherOp * ConstNode <-- visiting Use. 12728 // 12729 // If we make this transformation, we will have a common 12730 // multiply (CONST * A) after we also do the same transformation 12731 // to the "t2" instruction. 12732 if (OtherOp->getOpcode() == ISD::ADD && 12733 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 12734 OtherOp->getOperand(0).getNode() == MulVar) 12735 return true; 12736 } 12737 } 12738 12739 // Didn't find a case where this would be profitable. 12740 return false; 12741 } 12742 12743 static SDValue peekThroughBitcast(SDValue V) { 12744 while (V.getOpcode() == ISD::BITCAST) 12745 V = V.getOperand(0); 12746 return V; 12747 } 12748 12749 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 12750 unsigned NumStores) { 12751 SmallVector<SDValue, 8> Chains; 12752 SmallPtrSet<const SDNode *, 8> Visited; 12753 SDLoc StoreDL(StoreNodes[0].MemNode); 12754 12755 for (unsigned i = 0; i < NumStores; ++i) { 12756 Visited.insert(StoreNodes[i].MemNode); 12757 } 12758 12759 // don't include nodes that are children 12760 for (unsigned i = 0; i < NumStores; ++i) { 12761 if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0) 12762 Chains.push_back(StoreNodes[i].MemNode->getChain()); 12763 } 12764 12765 assert(Chains.size() > 0 && "Chain should have generated a chain"); 12766 return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains); 12767 } 12768 12769 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 12770 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores, 12771 bool IsConstantSrc, bool UseVector, bool UseTrunc) { 12772 // Make sure we have something to merge. 12773 if (NumStores < 2) 12774 return false; 12775 12776 // The latest Node in the DAG. 12777 SDLoc DL(StoreNodes[0].MemNode); 12778 12779 int64_t ElementSizeBits = MemVT.getStoreSizeInBits(); 12780 unsigned SizeInBits = NumStores * ElementSizeBits; 12781 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 12782 12783 EVT StoreTy; 12784 if (UseVector) { 12785 unsigned Elts = NumStores * NumMemElts; 12786 // Get the type for the merged vector store. 12787 StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 12788 } else 12789 StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 12790 12791 SDValue StoredVal; 12792 if (UseVector) { 12793 if (IsConstantSrc) { 12794 SmallVector<SDValue, 8> BuildVector; 12795 for (unsigned I = 0; I != NumStores; ++I) { 12796 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode); 12797 SDValue Val = St->getValue(); 12798 // If constant is of the wrong type, convert it now. 12799 if (MemVT != Val.getValueType()) { 12800 Val = peekThroughBitcast(Val); 12801 // Deal with constants of wrong size. 12802 if (ElementSizeBits != Val.getValueSizeInBits()) { 12803 EVT IntMemVT = 12804 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 12805 if (isa<ConstantFPSDNode>(Val)) { 12806 // Not clear how to truncate FP values. 12807 return false; 12808 } else if (auto *C = dyn_cast<ConstantSDNode>(Val)) 12809 Val = DAG.getConstant(C->getAPIntValue() 12810 .zextOrTrunc(Val.getValueSizeInBits()) 12811 .zextOrTrunc(ElementSizeBits), 12812 SDLoc(C), IntMemVT); 12813 } 12814 // Make sure correctly size type is the correct type. 12815 Val = DAG.getBitcast(MemVT, Val); 12816 } 12817 BuildVector.push_back(Val); 12818 } 12819 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS 12820 : ISD::BUILD_VECTOR, 12821 DL, StoreTy, BuildVector); 12822 } else { 12823 SmallVector<SDValue, 8> Ops; 12824 for (unsigned i = 0; i < NumStores; ++i) { 12825 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12826 SDValue Val = peekThroughBitcast(St->getValue()); 12827 // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of 12828 // type MemVT. If the underlying value is not the correct 12829 // type, but it is an extraction of an appropriate vector we 12830 // can recast Val to be of the correct type. This may require 12831 // converting between EXTRACT_VECTOR_ELT and 12832 // EXTRACT_SUBVECTOR. 12833 if ((MemVT != Val.getValueType()) && 12834 (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12835 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) { 12836 SDValue Vec = Val.getOperand(0); 12837 EVT MemVTScalarTy = MemVT.getScalarType(); 12838 // We may need to add a bitcast here to get types to line up. 12839 if (MemVTScalarTy != Vec.getValueType()) { 12840 unsigned Elts = Vec.getValueType().getSizeInBits() / 12841 MemVTScalarTy.getSizeInBits(); 12842 EVT NewVecTy = 12843 EVT::getVectorVT(*DAG.getContext(), MemVTScalarTy, Elts); 12844 Vec = DAG.getBitcast(NewVecTy, Vec); 12845 } 12846 auto OpC = (MemVT.isVector()) ? ISD::EXTRACT_SUBVECTOR 12847 : ISD::EXTRACT_VECTOR_ELT; 12848 Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Val.getOperand(1)); 12849 } 12850 Ops.push_back(Val); 12851 } 12852 12853 // Build the extracted vector elements back into a vector. 12854 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS 12855 : ISD::BUILD_VECTOR, 12856 DL, StoreTy, Ops); 12857 } 12858 } else { 12859 // We should always use a vector store when merging extracted vector 12860 // elements, so this path implies a store of constants. 12861 assert(IsConstantSrc && "Merged vector elements should use vector store"); 12862 12863 APInt StoreInt(SizeInBits, 0); 12864 12865 // Construct a single integer constant which is made of the smaller 12866 // constant inputs. 12867 bool IsLE = DAG.getDataLayout().isLittleEndian(); 12868 for (unsigned i = 0; i < NumStores; ++i) { 12869 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 12870 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 12871 12872 SDValue Val = St->getValue(); 12873 StoreInt <<= ElementSizeBits; 12874 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 12875 StoreInt |= C->getAPIntValue() 12876 .zextOrTrunc(ElementSizeBits) 12877 .zextOrTrunc(SizeInBits); 12878 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 12879 StoreInt |= C->getValueAPF() 12880 .bitcastToAPInt() 12881 .zextOrTrunc(ElementSizeBits) 12882 .zextOrTrunc(SizeInBits); 12883 // If fp truncation is necessary give up for now. 12884 if (MemVT.getSizeInBits() != ElementSizeBits) 12885 return false; 12886 } else { 12887 llvm_unreachable("Invalid constant element type"); 12888 } 12889 } 12890 12891 // Create the new Load and Store operations. 12892 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 12893 } 12894 12895 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12896 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores); 12897 12898 // make sure we use trunc store if it's necessary to be legal. 12899 SDValue NewStore; 12900 if (!UseTrunc) { 12901 NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(), 12902 FirstInChain->getPointerInfo(), 12903 FirstInChain->getAlignment()); 12904 } else { // Must be realized as a trunc store 12905 EVT LegalizedStoredValueTy = 12906 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 12907 unsigned LegalizedStoreSize = LegalizedStoredValueTy.getSizeInBits(); 12908 ConstantSDNode *C = cast<ConstantSDNode>(StoredVal); 12909 SDValue ExtendedStoreVal = 12910 DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL, 12911 LegalizedStoredValueTy); 12912 NewStore = DAG.getTruncStore( 12913 NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(), 12914 FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/, 12915 FirstInChain->getAlignment(), 12916 FirstInChain->getMemOperand()->getFlags()); 12917 } 12918 12919 // Replace all merged stores with the new store. 12920 for (unsigned i = 0; i < NumStores; ++i) 12921 CombineTo(StoreNodes[i].MemNode, NewStore); 12922 12923 AddToWorklist(NewChain.getNode()); 12924 return true; 12925 } 12926 12927 void DAGCombiner::getStoreMergeCandidates( 12928 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) { 12929 // This holds the base pointer, index, and the offset in bytes from the base 12930 // pointer. 12931 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 12932 EVT MemVT = St->getMemoryVT(); 12933 12934 SDValue Val = peekThroughBitcast(St->getValue()); 12935 // We must have a base and an offset. 12936 if (!BasePtr.getBase().getNode()) 12937 return; 12938 12939 // Do not handle stores to undef base pointers. 12940 if (BasePtr.getBase().isUndef()) 12941 return; 12942 12943 bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val); 12944 bool IsExtractVecSrc = (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12945 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR); 12946 bool IsLoadSrc = isa<LoadSDNode>(Val); 12947 BaseIndexOffset LBasePtr; 12948 // Match on loadbaseptr if relevant. 12949 EVT LoadVT; 12950 if (IsLoadSrc) { 12951 auto *Ld = cast<LoadSDNode>(Val); 12952 LBasePtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 12953 LoadVT = Ld->getMemoryVT(); 12954 // Load and store should be the same type. 12955 if (MemVT != LoadVT) 12956 return; 12957 } 12958 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr, 12959 int64_t &Offset) -> bool { 12960 if (Other->isVolatile() || Other->isIndexed()) 12961 return false; 12962 SDValue Val = peekThroughBitcast(Other->getValue()); 12963 // Allow merging constants of different types as integers. 12964 bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT()) 12965 : Other->getMemoryVT() != MemVT; 12966 if (IsLoadSrc) { 12967 if (NoTypeMatch) 12968 return false; 12969 // The Load's Base Ptr must also match 12970 if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Val)) { 12971 auto LPtr = BaseIndexOffset::match(OtherLd->getBasePtr(), DAG); 12972 if (LoadVT != OtherLd->getMemoryVT()) 12973 return false; 12974 if (!(LBasePtr.equalBaseIndex(LPtr, DAG))) 12975 return false; 12976 } else 12977 return false; 12978 } 12979 if (IsConstantSrc) { 12980 if (NoTypeMatch) 12981 return false; 12982 if (!(isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val))) 12983 return false; 12984 } 12985 if (IsExtractVecSrc) { 12986 // Do not merge truncated stores here. 12987 if (Other->isTruncatingStore()) 12988 return false; 12989 if (!MemVT.bitsEq(Val.getValueType())) 12990 return false; 12991 if (Val.getOpcode() != ISD::EXTRACT_VECTOR_ELT && 12992 Val.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12993 return false; 12994 } 12995 Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG); 12996 return (BasePtr.equalBaseIndex(Ptr, DAG, Offset)); 12997 }; 12998 12999 // We looking for a root node which is an ancestor to all mergable 13000 // stores. We search up through a load, to our root and then down 13001 // through all children. For instance we will find Store{1,2,3} if 13002 // St is Store1, Store2. or Store3 where the root is not a load 13003 // which always true for nonvolatile ops. TODO: Expand 13004 // the search to find all valid candidates through multiple layers of loads. 13005 // 13006 // Root 13007 // |-------|-------| 13008 // Load Load Store3 13009 // | | 13010 // Store1 Store2 13011 // 13012 // FIXME: We should be able to climb and 13013 // descend TokenFactors to find candidates as well. 13014 13015 SDNode *RootNode = (St->getChain()).getNode(); 13016 13017 if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) { 13018 RootNode = Ldn->getChain().getNode(); 13019 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 13020 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain 13021 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2) 13022 if (I2.getOperandNo() == 0) 13023 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) { 13024 BaseIndexOffset Ptr; 13025 int64_t PtrDiff; 13026 if (CandidateMatch(OtherST, Ptr, PtrDiff)) 13027 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff)); 13028 } 13029 } else 13030 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 13031 if (I.getOperandNo() == 0) 13032 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 13033 BaseIndexOffset Ptr; 13034 int64_t PtrDiff; 13035 if (CandidateMatch(OtherST, Ptr, PtrDiff)) 13036 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff)); 13037 } 13038 } 13039 13040 // We need to check that merging these stores does not cause a loop in 13041 // the DAG. Any store candidate may depend on another candidate 13042 // indirectly through its operand (we already consider dependencies 13043 // through the chain). Check in parallel by searching up from 13044 // non-chain operands of candidates. 13045 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 13046 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) { 13047 // FIXME: We should be able to truncate a full search of 13048 // predecessors by doing a BFS and keeping tabs the originating 13049 // stores from which worklist nodes come from in a similar way to 13050 // TokenFactor simplfication. 13051 13052 SmallPtrSet<const SDNode *, 16> Visited; 13053 SmallVector<const SDNode *, 8> Worklist; 13054 unsigned int Max = 8192; 13055 // Search Ops of store candidates. 13056 for (unsigned i = 0; i < NumStores; ++i) { 13057 SDNode *n = StoreNodes[i].MemNode; 13058 // Potential loops may happen only through non-chain operands 13059 for (unsigned j = 1; j < n->getNumOperands(); ++j) 13060 Worklist.push_back(n->getOperand(j).getNode()); 13061 } 13062 // Search through DAG. We can stop early if we find a store node. 13063 for (unsigned i = 0; i < NumStores; ++i) { 13064 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist, 13065 Max)) 13066 return false; 13067 // Check if we ended early, failing conservatively if so. 13068 if (Visited.size() >= Max) 13069 return false; 13070 } 13071 return true; 13072 } 13073 13074 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) { 13075 if (OptLevel == CodeGenOpt::None) 13076 return false; 13077 13078 EVT MemVT = St->getMemoryVT(); 13079 int64_t ElementSizeBytes = MemVT.getStoreSize(); 13080 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 13081 13082 if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits) 13083 return false; 13084 13085 bool NoVectors = DAG.getMachineFunction().getFunction().hasFnAttribute( 13086 Attribute::NoImplicitFloat); 13087 13088 // This function cannot currently deal with non-byte-sized memory sizes. 13089 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 13090 return false; 13091 13092 if (!MemVT.isSimple()) 13093 return false; 13094 13095 // Perform an early exit check. Do not bother looking at stored values that 13096 // are not constants, loads, or extracted vector elements. 13097 SDValue StoredVal = peekThroughBitcast(St->getValue()); 13098 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 13099 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 13100 isa<ConstantFPSDNode>(StoredVal); 13101 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 13102 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 13103 13104 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 13105 return false; 13106 13107 SmallVector<MemOpLink, 8> StoreNodes; 13108 // Find potential store merge candidates by searching through chain sub-DAG 13109 getStoreMergeCandidates(St, StoreNodes); 13110 13111 // Check if there is anything to merge. 13112 if (StoreNodes.size() < 2) 13113 return false; 13114 13115 // Sort the memory operands according to their distance from the 13116 // base pointer. 13117 std::sort(StoreNodes.begin(), StoreNodes.end(), 13118 [](MemOpLink LHS, MemOpLink RHS) { 13119 return LHS.OffsetFromBase < RHS.OffsetFromBase; 13120 }); 13121 13122 // Store Merge attempts to merge the lowest stores. This generally 13123 // works out as if successful, as the remaining stores are checked 13124 // after the first collection of stores is merged. However, in the 13125 // case that a non-mergeable store is found first, e.g., {p[-2], 13126 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent 13127 // mergeable cases. To prevent this, we prune such stores from the 13128 // front of StoreNodes here. 13129 13130 bool RV = false; 13131 while (StoreNodes.size() > 1) { 13132 unsigned StartIdx = 0; 13133 while ((StartIdx + 1 < StoreNodes.size()) && 13134 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes != 13135 StoreNodes[StartIdx + 1].OffsetFromBase) 13136 ++StartIdx; 13137 13138 // Bail if we don't have enough candidates to merge. 13139 if (StartIdx + 1 >= StoreNodes.size()) 13140 return RV; 13141 13142 if (StartIdx) 13143 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx); 13144 13145 // Scan the memory operations on the chain and find the first 13146 // non-consecutive store memory address. 13147 unsigned NumConsecutiveStores = 1; 13148 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 13149 // Check that the addresses are consecutive starting from the second 13150 // element in the list of stores. 13151 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) { 13152 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 13153 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 13154 break; 13155 NumConsecutiveStores = i + 1; 13156 } 13157 13158 if (NumConsecutiveStores < 2) { 13159 StoreNodes.erase(StoreNodes.begin(), 13160 StoreNodes.begin() + NumConsecutiveStores); 13161 continue; 13162 } 13163 13164 // Check that we can merge these candidates without causing a cycle 13165 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, 13166 NumConsecutiveStores)) { 13167 StoreNodes.erase(StoreNodes.begin(), 13168 StoreNodes.begin() + NumConsecutiveStores); 13169 continue; 13170 } 13171 13172 // The node with the lowest store address. 13173 LLVMContext &Context = *DAG.getContext(); 13174 const DataLayout &DL = DAG.getDataLayout(); 13175 13176 // Store the constants into memory as one consecutive store. 13177 if (IsConstantSrc) { 13178 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 13179 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 13180 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 13181 unsigned LastLegalType = 1; 13182 unsigned LastLegalVectorType = 1; 13183 bool LastIntegerTrunc = false; 13184 bool NonZero = false; 13185 unsigned FirstZeroAfterNonZero = NumConsecutiveStores; 13186 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 13187 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode); 13188 SDValue StoredVal = ST->getValue(); 13189 bool IsElementZero = false; 13190 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) 13191 IsElementZero = C->isNullValue(); 13192 else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) 13193 IsElementZero = C->getConstantFPValue()->isNullValue(); 13194 if (IsElementZero) { 13195 if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores) 13196 FirstZeroAfterNonZero = i; 13197 } 13198 NonZero |= !IsElementZero; 13199 13200 // Find a legal type for the constant store. 13201 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 13202 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 13203 bool IsFast = false; 13204 if (TLI.isTypeLegal(StoreTy) && 13205 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 13206 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13207 FirstStoreAlign, &IsFast) && 13208 IsFast) { 13209 LastIntegerTrunc = false; 13210 LastLegalType = i + 1; 13211 // Or check whether a truncstore is legal. 13212 } else if (TLI.getTypeAction(Context, StoreTy) == 13213 TargetLowering::TypePromoteInteger) { 13214 EVT LegalizedStoredValueTy = 13215 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 13216 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 13217 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) && 13218 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13219 FirstStoreAlign, &IsFast) && 13220 IsFast) { 13221 LastIntegerTrunc = true; 13222 LastLegalType = i + 1; 13223 } 13224 } 13225 13226 // We only use vectors if the constant is known to be zero or the target 13227 // allows it and the function is not marked with the noimplicitfloat 13228 // attribute. 13229 if ((!NonZero || 13230 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) && 13231 !NoVectors) { 13232 // Find a legal type for the vector store. 13233 unsigned Elts = (i + 1) * NumMemElts; 13234 EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 13235 if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) && 13236 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && 13237 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 13238 FirstStoreAlign, &IsFast) && 13239 IsFast) 13240 LastLegalVectorType = i + 1; 13241 } 13242 } 13243 13244 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 13245 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType; 13246 13247 // Check if we found a legal integer type that creates a meaningful merge. 13248 if (NumElem < 2) { 13249 // We know that candidate stores are in order and of correct 13250 // shape. While there is no mergeable sequence from the 13251 // beginning one may start later in the sequence. The only 13252 // reason a merge of size N could have failed where another of 13253 // the same size would not have, is if the alignment has 13254 // improved or we've dropped a non-zero value. Drop as many 13255 // candidates as we can here. 13256 unsigned NumSkip = 1; 13257 while ( 13258 (NumSkip < NumConsecutiveStores) && 13259 (NumSkip < FirstZeroAfterNonZero) && 13260 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) { 13261 NumSkip++; 13262 } 13263 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 13264 continue; 13265 } 13266 13267 bool Merged = MergeStoresOfConstantsOrVecElts( 13268 StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc); 13269 RV |= Merged; 13270 13271 // Remove merged stores for next iteration. 13272 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 13273 continue; 13274 } 13275 13276 // When extracting multiple vector elements, try to store them 13277 // in one vector store rather than a sequence of scalar stores. 13278 if (IsExtractVecSrc) { 13279 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 13280 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 13281 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 13282 unsigned NumStoresToMerge = 1; 13283 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 13284 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 13285 SDValue StVal = peekThroughBitcast(St->getValue()); 13286 // This restriction could be loosened. 13287 // Bail out if any stored values are not elements extracted from a 13288 // vector. It should be possible to handle mixed sources, but load 13289 // sources need more careful handling (see the block of code below that 13290 // handles consecutive loads). 13291 if (StVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT && 13292 StVal.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13293 return RV; 13294 13295 // Find a legal type for the vector store. 13296 unsigned Elts = (i + 1) * NumMemElts; 13297 EVT Ty = 13298 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 13299 bool IsFast; 13300 if (TLI.isTypeLegal(Ty) && 13301 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && 13302 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 13303 FirstStoreAlign, &IsFast) && 13304 IsFast) 13305 NumStoresToMerge = i + 1; 13306 } 13307 13308 // Check if we found a legal integer type that creates a meaningful merge. 13309 if (NumStoresToMerge < 2) { 13310 // We know that candidate stores are in order and of correct 13311 // shape. While there is no mergeable sequence from the 13312 // beginning one may start later in the sequence. The only 13313 // reason a merge of size N could have failed where another of 13314 // the same size would not have, is if the alignment has 13315 // improved. Drop as many candidates as we can here. 13316 unsigned NumSkip = 1; 13317 while ((NumSkip < NumConsecutiveStores) && 13318 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 13319 NumSkip++; 13320 13321 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 13322 continue; 13323 } 13324 13325 bool Merged = MergeStoresOfConstantsOrVecElts( 13326 StoreNodes, MemVT, NumStoresToMerge, false, true, false); 13327 if (!Merged) { 13328 StoreNodes.erase(StoreNodes.begin(), 13329 StoreNodes.begin() + NumStoresToMerge); 13330 continue; 13331 } 13332 // Remove merged stores for next iteration. 13333 StoreNodes.erase(StoreNodes.begin(), 13334 StoreNodes.begin() + NumStoresToMerge); 13335 RV = true; 13336 continue; 13337 } 13338 13339 // Below we handle the case of multiple consecutive stores that 13340 // come from multiple consecutive loads. We merge them into a single 13341 // wide load and a single wide store. 13342 13343 // Look for load nodes which are used by the stored values. 13344 SmallVector<MemOpLink, 8> LoadNodes; 13345 13346 // Find acceptable loads. Loads need to have the same chain (token factor), 13347 // must not be zext, volatile, indexed, and they must be consecutive. 13348 BaseIndexOffset LdBasePtr; 13349 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 13350 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 13351 SDValue Val = peekThroughBitcast(St->getValue()); 13352 LoadSDNode *Ld = dyn_cast<LoadSDNode>(Val); 13353 if (!Ld) 13354 break; 13355 13356 // Loads must only have one use. 13357 if (!Ld->hasNUsesOfValue(1, 0)) 13358 break; 13359 13360 // The memory operands must not be volatile. 13361 if (Ld->isVolatile() || Ld->isIndexed()) 13362 break; 13363 13364 // The stored memory type must be the same. 13365 if (Ld->getMemoryVT() != MemVT) 13366 break; 13367 13368 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 13369 // If this is not the first ptr that we check. 13370 int64_t LdOffset = 0; 13371 if (LdBasePtr.getBase().getNode()) { 13372 // The base ptr must be the same. 13373 if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset)) 13374 break; 13375 } else { 13376 // Check that all other base pointers are the same as this one. 13377 LdBasePtr = LdPtr; 13378 } 13379 13380 // We found a potential memory operand to merge. 13381 LoadNodes.push_back(MemOpLink(Ld, LdOffset)); 13382 } 13383 13384 if (LoadNodes.size() < 2) { 13385 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1); 13386 continue; 13387 } 13388 13389 // If we have load/store pair instructions and we only have two values, 13390 // don't bother merging. 13391 unsigned RequiredAlignment; 13392 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 13393 StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) { 13394 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2); 13395 continue; 13396 } 13397 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 13398 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 13399 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 13400 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 13401 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 13402 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 13403 13404 // Scan the memory operations on the chain and find the first 13405 // non-consecutive load memory address. These variables hold the index in 13406 // the store node array. 13407 unsigned LastConsecutiveLoad = 1; 13408 // This variable refers to the size and not index in the array. 13409 unsigned LastLegalVectorType = 1; 13410 unsigned LastLegalIntegerType = 1; 13411 bool isDereferenceable = true; 13412 bool DoIntegerTruncate = false; 13413 StartAddress = LoadNodes[0].OffsetFromBase; 13414 SDValue FirstChain = FirstLoad->getChain(); 13415 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 13416 // All loads must share the same chain. 13417 if (LoadNodes[i].MemNode->getChain() != FirstChain) 13418 break; 13419 13420 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 13421 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 13422 break; 13423 LastConsecutiveLoad = i; 13424 13425 if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable()) 13426 isDereferenceable = false; 13427 13428 // Find a legal type for the vector store. 13429 unsigned Elts = (i + 1) * NumMemElts; 13430 EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 13431 13432 bool IsFastSt, IsFastLd; 13433 if (TLI.isTypeLegal(StoreTy) && 13434 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 13435 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13436 FirstStoreAlign, &IsFastSt) && 13437 IsFastSt && 13438 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 13439 FirstLoadAlign, &IsFastLd) && 13440 IsFastLd) { 13441 LastLegalVectorType = i + 1; 13442 } 13443 13444 // Find a legal type for the integer store. 13445 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 13446 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 13447 if (TLI.isTypeLegal(StoreTy) && 13448 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 13449 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13450 FirstStoreAlign, &IsFastSt) && 13451 IsFastSt && 13452 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 13453 FirstLoadAlign, &IsFastLd) && 13454 IsFastLd) { 13455 LastLegalIntegerType = i + 1; 13456 DoIntegerTruncate = false; 13457 // Or check whether a truncstore and extload is legal. 13458 } else if (TLI.getTypeAction(Context, StoreTy) == 13459 TargetLowering::TypePromoteInteger) { 13460 EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy); 13461 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 13462 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) && 13463 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, 13464 StoreTy) && 13465 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, 13466 StoreTy) && 13467 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 13468 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13469 FirstStoreAlign, &IsFastSt) && 13470 IsFastSt && 13471 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 13472 FirstLoadAlign, &IsFastLd) && 13473 IsFastLd) { 13474 LastLegalIntegerType = i + 1; 13475 DoIntegerTruncate = true; 13476 } 13477 } 13478 } 13479 13480 // Only use vector types if the vector type is larger than the integer type. 13481 // If they are the same, use integers. 13482 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 13483 unsigned LastLegalType = 13484 std::max(LastLegalVectorType, LastLegalIntegerType); 13485 13486 // We add +1 here because the LastXXX variables refer to location while 13487 // the NumElem refers to array/index size. 13488 unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1); 13489 NumElem = std::min(LastLegalType, NumElem); 13490 13491 if (NumElem < 2) { 13492 // We know that candidate stores are in order and of correct 13493 // shape. While there is no mergeable sequence from the 13494 // beginning one may start later in the sequence. The only 13495 // reason a merge of size N could have failed where another of 13496 // the same size would not have is if the alignment or either 13497 // the load or store has improved. Drop as many candidates as we 13498 // can here. 13499 unsigned NumSkip = 1; 13500 while ((NumSkip < LoadNodes.size()) && 13501 (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) && 13502 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 13503 NumSkip++; 13504 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 13505 continue; 13506 } 13507 13508 // Find if it is better to use vectors or integers to load and store 13509 // to memory. 13510 EVT JointMemOpVT; 13511 if (UseVectorTy) { 13512 // Find a legal type for the vector store. 13513 unsigned Elts = NumElem * NumMemElts; 13514 JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 13515 } else { 13516 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 13517 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 13518 } 13519 13520 SDLoc LoadDL(LoadNodes[0].MemNode); 13521 SDLoc StoreDL(StoreNodes[0].MemNode); 13522 13523 // The merged loads are required to have the same incoming chain, so 13524 // using the first's chain is acceptable. 13525 13526 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem); 13527 AddToWorklist(NewStoreChain.getNode()); 13528 13529 MachineMemOperand::Flags MMOFlags = isDereferenceable ? 13530 MachineMemOperand::MODereferenceable: 13531 MachineMemOperand::MONone; 13532 13533 SDValue NewLoad, NewStore; 13534 if (UseVectorTy || !DoIntegerTruncate) { 13535 NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(), 13536 FirstLoad->getBasePtr(), 13537 FirstLoad->getPointerInfo(), FirstLoadAlign, 13538 MMOFlags); 13539 NewStore = DAG.getStore(NewStoreChain, StoreDL, NewLoad, 13540 FirstInChain->getBasePtr(), 13541 FirstInChain->getPointerInfo(), FirstStoreAlign); 13542 } else { // This must be the truncstore/extload case 13543 EVT ExtendedTy = 13544 TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT); 13545 NewLoad = 13546 DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, FirstLoad->getChain(), 13547 FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(), 13548 JointMemOpVT, FirstLoadAlign, MMOFlags); 13549 NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad, 13550 FirstInChain->getBasePtr(), 13551 FirstInChain->getPointerInfo(), JointMemOpVT, 13552 FirstInChain->getAlignment(), 13553 FirstInChain->getMemOperand()->getFlags()); 13554 } 13555 13556 // Transfer chain users from old loads to the new load. 13557 for (unsigned i = 0; i < NumElem; ++i) { 13558 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 13559 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 13560 SDValue(NewLoad.getNode(), 1)); 13561 } 13562 13563 // Replace the all stores with the new store. Recursively remove 13564 // corresponding value if its no longer used. 13565 for (unsigned i = 0; i < NumElem; ++i) { 13566 SDValue Val = StoreNodes[i].MemNode->getOperand(1); 13567 CombineTo(StoreNodes[i].MemNode, NewStore); 13568 if (Val.getNode()->use_empty()) 13569 recursivelyDeleteUnusedNodes(Val.getNode()); 13570 } 13571 13572 RV = true; 13573 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 13574 } 13575 return RV; 13576 } 13577 13578 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 13579 SDLoc SL(ST); 13580 SDValue ReplStore; 13581 13582 // Replace the chain to avoid dependency. 13583 if (ST->isTruncatingStore()) { 13584 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 13585 ST->getBasePtr(), ST->getMemoryVT(), 13586 ST->getMemOperand()); 13587 } else { 13588 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 13589 ST->getMemOperand()); 13590 } 13591 13592 // Create token to keep both nodes around. 13593 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 13594 MVT::Other, ST->getChain(), ReplStore); 13595 13596 // Make sure the new and old chains are cleaned up. 13597 AddToWorklist(Token.getNode()); 13598 13599 // Don't add users to work list. 13600 return CombineTo(ST, Token, false); 13601 } 13602 13603 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 13604 SDValue Value = ST->getValue(); 13605 if (Value.getOpcode() == ISD::TargetConstantFP) 13606 return SDValue(); 13607 13608 SDLoc DL(ST); 13609 13610 SDValue Chain = ST->getChain(); 13611 SDValue Ptr = ST->getBasePtr(); 13612 13613 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 13614 13615 // NOTE: If the original store is volatile, this transform must not increase 13616 // the number of stores. For example, on x86-32 an f64 can be stored in one 13617 // processor operation but an i64 (which is not legal) requires two. So the 13618 // transform should not be done in this case. 13619 13620 SDValue Tmp; 13621 switch (CFP->getSimpleValueType(0).SimpleTy) { 13622 default: 13623 llvm_unreachable("Unknown FP type"); 13624 case MVT::f16: // We don't do this for these yet. 13625 case MVT::f80: 13626 case MVT::f128: 13627 case MVT::ppcf128: 13628 return SDValue(); 13629 case MVT::f32: 13630 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 13631 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 13632 ; 13633 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 13634 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 13635 MVT::i32); 13636 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 13637 } 13638 13639 return SDValue(); 13640 case MVT::f64: 13641 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 13642 !ST->isVolatile()) || 13643 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 13644 ; 13645 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 13646 getZExtValue(), SDLoc(CFP), MVT::i64); 13647 return DAG.getStore(Chain, DL, Tmp, 13648 Ptr, ST->getMemOperand()); 13649 } 13650 13651 if (!ST->isVolatile() && 13652 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 13653 // Many FP stores are not made apparent until after legalize, e.g. for 13654 // argument passing. Since this is so common, custom legalize the 13655 // 64-bit integer store into two 32-bit stores. 13656 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 13657 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 13658 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 13659 if (DAG.getDataLayout().isBigEndian()) 13660 std::swap(Lo, Hi); 13661 13662 unsigned Alignment = ST->getAlignment(); 13663 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 13664 AAMDNodes AAInfo = ST->getAAInfo(); 13665 13666 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 13667 ST->getAlignment(), MMOFlags, AAInfo); 13668 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 13669 DAG.getConstant(4, DL, Ptr.getValueType())); 13670 Alignment = MinAlign(Alignment, 4U); 13671 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 13672 ST->getPointerInfo().getWithOffset(4), 13673 Alignment, MMOFlags, AAInfo); 13674 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 13675 St0, St1); 13676 } 13677 13678 return SDValue(); 13679 } 13680 } 13681 13682 SDValue DAGCombiner::visitSTORE(SDNode *N) { 13683 StoreSDNode *ST = cast<StoreSDNode>(N); 13684 SDValue Chain = ST->getChain(); 13685 SDValue Value = ST->getValue(); 13686 SDValue Ptr = ST->getBasePtr(); 13687 13688 // If this is a store of a bit convert, store the input value if the 13689 // resultant store does not need a higher alignment than the original. 13690 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 13691 ST->isUnindexed()) { 13692 EVT SVT = Value.getOperand(0).getValueType(); 13693 if (((!LegalOperations && !ST->isVolatile()) || 13694 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) && 13695 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 13696 unsigned OrigAlign = ST->getAlignment(); 13697 bool Fast = false; 13698 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 13699 ST->getAddressSpace(), OrigAlign, &Fast) && 13700 Fast) { 13701 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 13702 ST->getPointerInfo(), OrigAlign, 13703 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 13704 } 13705 } 13706 } 13707 13708 // Turn 'store undef, Ptr' -> nothing. 13709 if (Value.isUndef() && ST->isUnindexed()) 13710 return Chain; 13711 13712 // Try to infer better alignment information than the store already has. 13713 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 13714 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 13715 if (Align > ST->getAlignment()) { 13716 SDValue NewStore = 13717 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 13718 ST->getMemoryVT(), Align, 13719 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 13720 if (NewStore.getNode() != N) 13721 return CombineTo(ST, NewStore, true); 13722 } 13723 } 13724 } 13725 13726 // Try transforming a pair floating point load / store ops to integer 13727 // load / store ops. 13728 if (SDValue NewST = TransformFPLoadStorePair(N)) 13729 return NewST; 13730 13731 if (ST->isUnindexed()) { 13732 // Walk up chain skipping non-aliasing memory nodes, on this store and any 13733 // adjacent stores. 13734 if (findBetterNeighborChains(ST)) { 13735 // replaceStoreChain uses CombineTo, which handled all of the worklist 13736 // manipulation. Return the original node to not do anything else. 13737 return SDValue(ST, 0); 13738 } 13739 Chain = ST->getChain(); 13740 } 13741 13742 // FIXME: is there such a thing as a truncating indexed store? 13743 if (ST->isTruncatingStore() && ST->isUnindexed() && 13744 Value.getValueType().isInteger()) { 13745 // See if we can simplify the input to this truncstore with knowledge that 13746 // only the low bits are being used. For example: 13747 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 13748 SDValue Shorter = DAG.GetDemandedBits( 13749 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 13750 ST->getMemoryVT().getScalarSizeInBits())); 13751 AddToWorklist(Value.getNode()); 13752 if (Shorter.getNode()) 13753 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 13754 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 13755 13756 // Otherwise, see if we can simplify the operation with 13757 // SimplifyDemandedBits, which only works if the value has a single use. 13758 if (SimplifyDemandedBits( 13759 Value, 13760 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 13761 ST->getMemoryVT().getScalarSizeInBits()))) { 13762 // Re-visit the store if anything changed and the store hasn't been merged 13763 // with another node (N is deleted) SimplifyDemandedBits will add Value's 13764 // node back to the worklist if necessary, but we also need to re-visit 13765 // the Store node itself. 13766 if (N->getOpcode() != ISD::DELETED_NODE) 13767 AddToWorklist(N); 13768 return SDValue(N, 0); 13769 } 13770 } 13771 13772 // If this is a load followed by a store to the same location, then the store 13773 // is dead/noop. 13774 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 13775 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 13776 ST->isUnindexed() && !ST->isVolatile() && 13777 // There can't be any side effects between the load and store, such as 13778 // a call or store. 13779 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 13780 // The store is dead, remove it. 13781 return Chain; 13782 } 13783 } 13784 13785 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 13786 if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() && 13787 !ST1->isVolatile() && ST1->getBasePtr() == Ptr && 13788 ST->getMemoryVT() == ST1->getMemoryVT()) { 13789 // If this is a store followed by a store with the same value to the same 13790 // location, then the store is dead/noop. 13791 if (ST1->getValue() == Value) { 13792 // The store is dead, remove it. 13793 return Chain; 13794 } 13795 13796 // If this is a store who's preceeding store to the same location 13797 // and no one other node is chained to that store we can effectively 13798 // drop the store. Do not remove stores to undef as they may be used as 13799 // data sinks. 13800 if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() && 13801 !ST1->getBasePtr().isUndef()) { 13802 // ST1 is fully overwritten and can be elided. Combine with it's chain 13803 // value. 13804 CombineTo(ST1, ST1->getChain()); 13805 return SDValue(); 13806 } 13807 } 13808 } 13809 13810 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 13811 // truncating store. We can do this even if this is already a truncstore. 13812 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 13813 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 13814 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 13815 ST->getMemoryVT())) { 13816 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 13817 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 13818 } 13819 13820 // Always perform this optimization before types are legal. If the target 13821 // prefers, also try this after legalization to catch stores that were created 13822 // by intrinsics or other nodes. 13823 if (!LegalTypes || (TLI.mergeStoresAfterLegalization())) { 13824 while (true) { 13825 // There can be multiple store sequences on the same chain. 13826 // Keep trying to merge store sequences until we are unable to do so 13827 // or until we merge the last store on the chain. 13828 bool Changed = MergeConsecutiveStores(ST); 13829 if (!Changed) break; 13830 // Return N as merge only uses CombineTo and no worklist clean 13831 // up is necessary. 13832 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N)) 13833 return SDValue(N, 0); 13834 } 13835 } 13836 13837 // Try transforming N to an indexed store. 13838 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 13839 return SDValue(N, 0); 13840 13841 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 13842 // 13843 // Make sure to do this only after attempting to merge stores in order to 13844 // avoid changing the types of some subset of stores due to visit order, 13845 // preventing their merging. 13846 if (isa<ConstantFPSDNode>(ST->getValue())) { 13847 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 13848 return NewSt; 13849 } 13850 13851 if (SDValue NewSt = splitMergedValStore(ST)) 13852 return NewSt; 13853 13854 return ReduceLoadOpStoreWidth(N); 13855 } 13856 13857 /// For the instruction sequence of store below, F and I values 13858 /// are bundled together as an i64 value before being stored into memory. 13859 /// Sometimes it is more efficent to generate separate stores for F and I, 13860 /// which can remove the bitwise instructions or sink them to colder places. 13861 /// 13862 /// (store (or (zext (bitcast F to i32) to i64), 13863 /// (shl (zext I to i64), 32)), addr) --> 13864 /// (store F, addr) and (store I, addr+4) 13865 /// 13866 /// Similarly, splitting for other merged store can also be beneficial, like: 13867 /// For pair of {i32, i32}, i64 store --> two i32 stores. 13868 /// For pair of {i32, i16}, i64 store --> two i32 stores. 13869 /// For pair of {i16, i16}, i32 store --> two i16 stores. 13870 /// For pair of {i16, i8}, i32 store --> two i16 stores. 13871 /// For pair of {i8, i8}, i16 store --> two i8 stores. 13872 /// 13873 /// We allow each target to determine specifically which kind of splitting is 13874 /// supported. 13875 /// 13876 /// The store patterns are commonly seen from the simple code snippet below 13877 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 13878 /// void goo(const std::pair<int, float> &); 13879 /// hoo() { 13880 /// ... 13881 /// goo(std::make_pair(tmp, ftmp)); 13882 /// ... 13883 /// } 13884 /// 13885 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) { 13886 if (OptLevel == CodeGenOpt::None) 13887 return SDValue(); 13888 13889 SDValue Val = ST->getValue(); 13890 SDLoc DL(ST); 13891 13892 // Match OR operand. 13893 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR) 13894 return SDValue(); 13895 13896 // Match SHL operand and get Lower and Higher parts of Val. 13897 SDValue Op1 = Val.getOperand(0); 13898 SDValue Op2 = Val.getOperand(1); 13899 SDValue Lo, Hi; 13900 if (Op1.getOpcode() != ISD::SHL) { 13901 std::swap(Op1, Op2); 13902 if (Op1.getOpcode() != ISD::SHL) 13903 return SDValue(); 13904 } 13905 Lo = Op2; 13906 Hi = Op1.getOperand(0); 13907 if (!Op1.hasOneUse()) 13908 return SDValue(); 13909 13910 // Match shift amount to HalfValBitSize. 13911 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2; 13912 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1)); 13913 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize) 13914 return SDValue(); 13915 13916 // Lo and Hi are zero-extended from int with size less equal than 32 13917 // to i64. 13918 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() || 13919 !Lo.getOperand(0).getValueType().isScalarInteger() || 13920 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize || 13921 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() || 13922 !Hi.getOperand(0).getValueType().isScalarInteger() || 13923 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize) 13924 return SDValue(); 13925 13926 // Use the EVT of low and high parts before bitcast as the input 13927 // of target query. 13928 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST) 13929 ? Lo.getOperand(0).getValueType() 13930 : Lo.getValueType(); 13931 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST) 13932 ? Hi.getOperand(0).getValueType() 13933 : Hi.getValueType(); 13934 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) 13935 return SDValue(); 13936 13937 // Start to split store. 13938 unsigned Alignment = ST->getAlignment(); 13939 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 13940 AAMDNodes AAInfo = ST->getAAInfo(); 13941 13942 // Change the sizes of Lo and Hi's value types to HalfValBitSize. 13943 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize); 13944 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0)); 13945 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0)); 13946 13947 SDValue Chain = ST->getChain(); 13948 SDValue Ptr = ST->getBasePtr(); 13949 // Lower value store. 13950 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 13951 ST->getAlignment(), MMOFlags, AAInfo); 13952 Ptr = 13953 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 13954 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType())); 13955 // Higher value store. 13956 SDValue St1 = 13957 DAG.getStore(St0, DL, Hi, Ptr, 13958 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8), 13959 Alignment / 2, MMOFlags, AAInfo); 13960 return St1; 13961 } 13962 13963 /// Convert a disguised subvector insertion into a shuffle: 13964 /// insert_vector_elt V, (bitcast X from vector type), IdxC --> 13965 /// bitcast(shuffle (bitcast V), (extended X), Mask) 13966 /// Note: We do not use an insert_subvector node because that requires a legal 13967 /// subvector type. 13968 SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) { 13969 SDValue InsertVal = N->getOperand(1); 13970 if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() || 13971 !InsertVal.getOperand(0).getValueType().isVector()) 13972 return SDValue(); 13973 13974 SDValue SubVec = InsertVal.getOperand(0); 13975 SDValue DestVec = N->getOperand(0); 13976 EVT SubVecVT = SubVec.getValueType(); 13977 EVT VT = DestVec.getValueType(); 13978 unsigned NumSrcElts = SubVecVT.getVectorNumElements(); 13979 unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits(); 13980 unsigned NumMaskVals = ExtendRatio * NumSrcElts; 13981 13982 // Step 1: Create a shuffle mask that implements this insert operation. The 13983 // vector that we are inserting into will be operand 0 of the shuffle, so 13984 // those elements are just 'i'. The inserted subvector is in the first 13985 // positions of operand 1 of the shuffle. Example: 13986 // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7} 13987 SmallVector<int, 16> Mask(NumMaskVals); 13988 for (unsigned i = 0; i != NumMaskVals; ++i) { 13989 if (i / NumSrcElts == InsIndex) 13990 Mask[i] = (i % NumSrcElts) + NumMaskVals; 13991 else 13992 Mask[i] = i; 13993 } 13994 13995 // Bail out if the target can not handle the shuffle we want to create. 13996 EVT SubVecEltVT = SubVecVT.getVectorElementType(); 13997 EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals); 13998 if (!TLI.isShuffleMaskLegal(Mask, ShufVT)) 13999 return SDValue(); 14000 14001 // Step 2: Create a wide vector from the inserted source vector by appending 14002 // undefined elements. This is the same size as our destination vector. 14003 SDLoc DL(N); 14004 SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT)); 14005 ConcatOps[0] = SubVec; 14006 SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps); 14007 14008 // Step 3: Shuffle in the padded subvector. 14009 SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec); 14010 SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask); 14011 AddToWorklist(PaddedSubV.getNode()); 14012 AddToWorklist(DestVecBC.getNode()); 14013 AddToWorklist(Shuf.getNode()); 14014 return DAG.getBitcast(VT, Shuf); 14015 } 14016 14017 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 14018 SDValue InVec = N->getOperand(0); 14019 SDValue InVal = N->getOperand(1); 14020 SDValue EltNo = N->getOperand(2); 14021 SDLoc DL(N); 14022 14023 // If the inserted element is an UNDEF, just use the input vector. 14024 if (InVal.isUndef()) 14025 return InVec; 14026 14027 EVT VT = InVec.getValueType(); 14028 14029 // Remove redundant insertions: 14030 // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x 14031 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 14032 InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1)) 14033 return InVec; 14034 14035 // We must know which element is being inserted for folds below here. 14036 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo); 14037 if (!IndexC) 14038 return SDValue(); 14039 unsigned Elt = IndexC->getZExtValue(); 14040 14041 if (SDValue Shuf = combineInsertEltToShuffle(N, Elt)) 14042 return Shuf; 14043 14044 // Canonicalize insert_vector_elt dag nodes. 14045 // Example: 14046 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 14047 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 14048 // 14049 // Do this only if the child insert_vector node has one use; also 14050 // do this only if indices are both constants and Idx1 < Idx0. 14051 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 14052 && isa<ConstantSDNode>(InVec.getOperand(2))) { 14053 unsigned OtherElt = InVec.getConstantOperandVal(2); 14054 if (Elt < OtherElt) { 14055 // Swap nodes. 14056 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, 14057 InVec.getOperand(0), InVal, EltNo); 14058 AddToWorklist(NewOp.getNode()); 14059 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 14060 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 14061 } 14062 } 14063 14064 // If we can't generate a legal BUILD_VECTOR, exit 14065 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 14066 return SDValue(); 14067 14068 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 14069 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 14070 // vector elements. 14071 SmallVector<SDValue, 8> Ops; 14072 // Do not combine these two vectors if the output vector will not replace 14073 // the input vector. 14074 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 14075 Ops.append(InVec.getNode()->op_begin(), 14076 InVec.getNode()->op_end()); 14077 } else if (InVec.isUndef()) { 14078 unsigned NElts = VT.getVectorNumElements(); 14079 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 14080 } else { 14081 return SDValue(); 14082 } 14083 14084 // Insert the element 14085 if (Elt < Ops.size()) { 14086 // All the operands of BUILD_VECTOR must have the same type; 14087 // we enforce that here. 14088 EVT OpVT = Ops[0].getValueType(); 14089 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal; 14090 } 14091 14092 // Return the new vector 14093 return DAG.getBuildVector(VT, DL, Ops); 14094 } 14095 14096 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 14097 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 14098 assert(!OriginalLoad->isVolatile()); 14099 14100 EVT ResultVT = EVE->getValueType(0); 14101 EVT VecEltVT = InVecVT.getVectorElementType(); 14102 unsigned Align = OriginalLoad->getAlignment(); 14103 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 14104 VecEltVT.getTypeForEVT(*DAG.getContext())); 14105 14106 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 14107 return SDValue(); 14108 14109 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ? 14110 ISD::NON_EXTLOAD : ISD::EXTLOAD; 14111 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT)) 14112 return SDValue(); 14113 14114 Align = NewAlign; 14115 14116 SDValue NewPtr = OriginalLoad->getBasePtr(); 14117 SDValue Offset; 14118 EVT PtrType = NewPtr.getValueType(); 14119 MachinePointerInfo MPI; 14120 SDLoc DL(EVE); 14121 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 14122 int Elt = ConstEltNo->getZExtValue(); 14123 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 14124 Offset = DAG.getConstant(PtrOff, DL, PtrType); 14125 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 14126 } else { 14127 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 14128 Offset = DAG.getNode( 14129 ISD::MUL, DL, PtrType, Offset, 14130 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 14131 MPI = OriginalLoad->getPointerInfo(); 14132 } 14133 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 14134 14135 // The replacement we need to do here is a little tricky: we need to 14136 // replace an extractelement of a load with a load. 14137 // Use ReplaceAllUsesOfValuesWith to do the replacement. 14138 // Note that this replacement assumes that the extractvalue is the only 14139 // use of the load; that's okay because we don't want to perform this 14140 // transformation in other cases anyway. 14141 SDValue Load; 14142 SDValue Chain; 14143 if (ResultVT.bitsGT(VecEltVT)) { 14144 // If the result type of vextract is wider than the load, then issue an 14145 // extending load instead. 14146 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 14147 VecEltVT) 14148 ? ISD::ZEXTLOAD 14149 : ISD::EXTLOAD; 14150 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 14151 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 14152 Align, OriginalLoad->getMemOperand()->getFlags(), 14153 OriginalLoad->getAAInfo()); 14154 Chain = Load.getValue(1); 14155 } else { 14156 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, 14157 MPI, Align, OriginalLoad->getMemOperand()->getFlags(), 14158 OriginalLoad->getAAInfo()); 14159 Chain = Load.getValue(1); 14160 if (ResultVT.bitsLT(VecEltVT)) 14161 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 14162 else 14163 Load = DAG.getBitcast(ResultVT, Load); 14164 } 14165 WorklistRemover DeadNodes(*this); 14166 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 14167 SDValue To[] = { Load, Chain }; 14168 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 14169 // Since we're explicitly calling ReplaceAllUses, add the new node to the 14170 // worklist explicitly as well. 14171 AddToWorklist(Load.getNode()); 14172 AddUsersToWorklist(Load.getNode()); // Add users too 14173 // Make sure to revisit this node to clean it up; it will usually be dead. 14174 AddToWorklist(EVE); 14175 ++OpsNarrowed; 14176 return SDValue(EVE, 0); 14177 } 14178 14179 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 14180 // (vextract (scalar_to_vector val, 0) -> val 14181 SDValue InVec = N->getOperand(0); 14182 EVT VT = InVec.getValueType(); 14183 EVT NVT = N->getValueType(0); 14184 14185 if (InVec.isUndef()) 14186 return DAG.getUNDEF(NVT); 14187 14188 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 14189 // Check if the result type doesn't match the inserted element type. A 14190 // SCALAR_TO_VECTOR may truncate the inserted element and the 14191 // EXTRACT_VECTOR_ELT may widen the extracted vector. 14192 SDValue InOp = InVec.getOperand(0); 14193 if (InOp.getValueType() != NVT) { 14194 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 14195 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 14196 } 14197 return InOp; 14198 } 14199 14200 SDValue EltNo = N->getOperand(1); 14201 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 14202 14203 // extract_vector_elt (build_vector x, y), 1 -> y 14204 if (ConstEltNo && 14205 InVec.getOpcode() == ISD::BUILD_VECTOR && 14206 TLI.isTypeLegal(VT) && 14207 (InVec.hasOneUse() || 14208 TLI.aggressivelyPreferBuildVectorSources(VT))) { 14209 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 14210 EVT InEltVT = Elt.getValueType(); 14211 14212 // Sometimes build_vector's scalar input types do not match result type. 14213 if (NVT == InEltVT) 14214 return Elt; 14215 14216 // TODO: It may be useful to truncate if free if the build_vector implicitly 14217 // converts. 14218 } 14219 14220 // extract_vector_elt (v2i32 (bitcast i64:x)), EltTrunc -> i32 (trunc i64:x) 14221 bool isLE = DAG.getDataLayout().isLittleEndian(); 14222 unsigned EltTrunc = isLE ? 0 : VT.getVectorNumElements() - 1; 14223 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 14224 ConstEltNo->getZExtValue() == EltTrunc && VT.isInteger()) { 14225 SDValue BCSrc = InVec.getOperand(0); 14226 if (BCSrc.getValueType().isScalarInteger()) 14227 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 14228 } 14229 14230 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 14231 // 14232 // This only really matters if the index is non-constant since other combines 14233 // on the constant elements already work. 14234 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && 14235 EltNo == InVec.getOperand(2)) { 14236 SDValue Elt = InVec.getOperand(1); 14237 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt; 14238 } 14239 14240 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 14241 // We only perform this optimization before the op legalization phase because 14242 // we may introduce new vector instructions which are not backed by TD 14243 // patterns. For example on AVX, extracting elements from a wide vector 14244 // without using extract_subvector. However, if we can find an underlying 14245 // scalar value, then we can always use that. 14246 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 14247 int NumElem = VT.getVectorNumElements(); 14248 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 14249 // Find the new index to extract from. 14250 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 14251 14252 // Extracting an undef index is undef. 14253 if (OrigElt == -1) 14254 return DAG.getUNDEF(NVT); 14255 14256 // Select the right vector half to extract from. 14257 SDValue SVInVec; 14258 if (OrigElt < NumElem) { 14259 SVInVec = InVec->getOperand(0); 14260 } else { 14261 SVInVec = InVec->getOperand(1); 14262 OrigElt -= NumElem; 14263 } 14264 14265 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 14266 SDValue InOp = SVInVec.getOperand(OrigElt); 14267 if (InOp.getValueType() != NVT) { 14268 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 14269 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 14270 } 14271 14272 return InOp; 14273 } 14274 14275 // FIXME: We should handle recursing on other vector shuffles and 14276 // scalar_to_vector here as well. 14277 14278 if (!LegalOperations || 14279 // FIXME: Should really be just isOperationLegalOrCustom. 14280 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VT) || 14281 TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VT)) { 14282 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 14283 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 14284 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 14285 } 14286 } 14287 14288 bool BCNumEltsChanged = false; 14289 EVT ExtVT = VT.getVectorElementType(); 14290 EVT LVT = ExtVT; 14291 14292 // If the result of load has to be truncated, then it's not necessarily 14293 // profitable. 14294 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 14295 return SDValue(); 14296 14297 if (InVec.getOpcode() == ISD::BITCAST) { 14298 // Don't duplicate a load with other uses. 14299 if (!InVec.hasOneUse()) 14300 return SDValue(); 14301 14302 EVT BCVT = InVec.getOperand(0).getValueType(); 14303 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 14304 return SDValue(); 14305 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 14306 BCNumEltsChanged = true; 14307 InVec = InVec.getOperand(0); 14308 ExtVT = BCVT.getVectorElementType(); 14309 } 14310 14311 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 14312 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 14313 ISD::isNormalLoad(InVec.getNode()) && 14314 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 14315 SDValue Index = N->getOperand(1); 14316 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) { 14317 if (!OrigLoad->isVolatile()) { 14318 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 14319 OrigLoad); 14320 } 14321 } 14322 } 14323 14324 // Perform only after legalization to ensure build_vector / vector_shuffle 14325 // optimizations have already been done. 14326 if (!LegalOperations) return SDValue(); 14327 14328 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 14329 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 14330 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 14331 14332 if (ConstEltNo) { 14333 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 14334 14335 LoadSDNode *LN0 = nullptr; 14336 const ShuffleVectorSDNode *SVN = nullptr; 14337 if (ISD::isNormalLoad(InVec.getNode())) { 14338 LN0 = cast<LoadSDNode>(InVec); 14339 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 14340 InVec.getOperand(0).getValueType() == ExtVT && 14341 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 14342 // Don't duplicate a load with other uses. 14343 if (!InVec.hasOneUse()) 14344 return SDValue(); 14345 14346 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 14347 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 14348 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 14349 // => 14350 // (load $addr+1*size) 14351 14352 // Don't duplicate a load with other uses. 14353 if (!InVec.hasOneUse()) 14354 return SDValue(); 14355 14356 // If the bit convert changed the number of elements, it is unsafe 14357 // to examine the mask. 14358 if (BCNumEltsChanged) 14359 return SDValue(); 14360 14361 // Select the input vector, guarding against out of range extract vector. 14362 unsigned NumElems = VT.getVectorNumElements(); 14363 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 14364 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 14365 14366 if (InVec.getOpcode() == ISD::BITCAST) { 14367 // Don't duplicate a load with other uses. 14368 if (!InVec.hasOneUse()) 14369 return SDValue(); 14370 14371 InVec = InVec.getOperand(0); 14372 } 14373 if (ISD::isNormalLoad(InVec.getNode())) { 14374 LN0 = cast<LoadSDNode>(InVec); 14375 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 14376 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 14377 } 14378 } 14379 14380 // Make sure we found a non-volatile load and the extractelement is 14381 // the only use. 14382 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 14383 return SDValue(); 14384 14385 // If Idx was -1 above, Elt is going to be -1, so just return undef. 14386 if (Elt == -1) 14387 return DAG.getUNDEF(LVT); 14388 14389 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 14390 } 14391 14392 return SDValue(); 14393 } 14394 14395 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 14396 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 14397 // We perform this optimization post type-legalization because 14398 // the type-legalizer often scalarizes integer-promoted vectors. 14399 // Performing this optimization before may create bit-casts which 14400 // will be type-legalized to complex code sequences. 14401 // We perform this optimization only before the operation legalizer because we 14402 // may introduce illegal operations. 14403 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 14404 return SDValue(); 14405 14406 unsigned NumInScalars = N->getNumOperands(); 14407 SDLoc DL(N); 14408 EVT VT = N->getValueType(0); 14409 14410 // Check to see if this is a BUILD_VECTOR of a bunch of values 14411 // which come from any_extend or zero_extend nodes. If so, we can create 14412 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 14413 // optimizations. We do not handle sign-extend because we can't fill the sign 14414 // using shuffles. 14415 EVT SourceType = MVT::Other; 14416 bool AllAnyExt = true; 14417 14418 for (unsigned i = 0; i != NumInScalars; ++i) { 14419 SDValue In = N->getOperand(i); 14420 // Ignore undef inputs. 14421 if (In.isUndef()) continue; 14422 14423 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 14424 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 14425 14426 // Abort if the element is not an extension. 14427 if (!ZeroExt && !AnyExt) { 14428 SourceType = MVT::Other; 14429 break; 14430 } 14431 14432 // The input is a ZeroExt or AnyExt. Check the original type. 14433 EVT InTy = In.getOperand(0).getValueType(); 14434 14435 // Check that all of the widened source types are the same. 14436 if (SourceType == MVT::Other) 14437 // First time. 14438 SourceType = InTy; 14439 else if (InTy != SourceType) { 14440 // Multiple income types. Abort. 14441 SourceType = MVT::Other; 14442 break; 14443 } 14444 14445 // Check if all of the extends are ANY_EXTENDs. 14446 AllAnyExt &= AnyExt; 14447 } 14448 14449 // In order to have valid types, all of the inputs must be extended from the 14450 // same source type and all of the inputs must be any or zero extend. 14451 // Scalar sizes must be a power of two. 14452 EVT OutScalarTy = VT.getScalarType(); 14453 bool ValidTypes = SourceType != MVT::Other && 14454 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 14455 isPowerOf2_32(SourceType.getSizeInBits()); 14456 14457 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 14458 // turn into a single shuffle instruction. 14459 if (!ValidTypes) 14460 return SDValue(); 14461 14462 bool isLE = DAG.getDataLayout().isLittleEndian(); 14463 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 14464 assert(ElemRatio > 1 && "Invalid element size ratio"); 14465 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 14466 DAG.getConstant(0, DL, SourceType); 14467 14468 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 14469 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 14470 14471 // Populate the new build_vector 14472 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 14473 SDValue Cast = N->getOperand(i); 14474 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 14475 Cast.getOpcode() == ISD::ZERO_EXTEND || 14476 Cast.isUndef()) && "Invalid cast opcode"); 14477 SDValue In; 14478 if (Cast.isUndef()) 14479 In = DAG.getUNDEF(SourceType); 14480 else 14481 In = Cast->getOperand(0); 14482 unsigned Index = isLE ? (i * ElemRatio) : 14483 (i * ElemRatio + (ElemRatio - 1)); 14484 14485 assert(Index < Ops.size() && "Invalid index"); 14486 Ops[Index] = In; 14487 } 14488 14489 // The type of the new BUILD_VECTOR node. 14490 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 14491 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 14492 "Invalid vector size"); 14493 // Check if the new vector type is legal. 14494 if (!isTypeLegal(VecVT)) return SDValue(); 14495 14496 // Make the new BUILD_VECTOR. 14497 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops); 14498 14499 // The new BUILD_VECTOR node has the potential to be further optimized. 14500 AddToWorklist(BV.getNode()); 14501 // Bitcast to the desired type. 14502 return DAG.getBitcast(VT, BV); 14503 } 14504 14505 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 14506 EVT VT = N->getValueType(0); 14507 14508 unsigned NumInScalars = N->getNumOperands(); 14509 SDLoc DL(N); 14510 14511 EVT SrcVT = MVT::Other; 14512 unsigned Opcode = ISD::DELETED_NODE; 14513 unsigned NumDefs = 0; 14514 14515 for (unsigned i = 0; i != NumInScalars; ++i) { 14516 SDValue In = N->getOperand(i); 14517 unsigned Opc = In.getOpcode(); 14518 14519 if (Opc == ISD::UNDEF) 14520 continue; 14521 14522 // If all scalar values are floats and converted from integers. 14523 if (Opcode == ISD::DELETED_NODE && 14524 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 14525 Opcode = Opc; 14526 } 14527 14528 if (Opc != Opcode) 14529 return SDValue(); 14530 14531 EVT InVT = In.getOperand(0).getValueType(); 14532 14533 // If all scalar values are typed differently, bail out. It's chosen to 14534 // simplify BUILD_VECTOR of integer types. 14535 if (SrcVT == MVT::Other) 14536 SrcVT = InVT; 14537 if (SrcVT != InVT) 14538 return SDValue(); 14539 NumDefs++; 14540 } 14541 14542 // If the vector has just one element defined, it's not worth to fold it into 14543 // a vectorized one. 14544 if (NumDefs < 2) 14545 return SDValue(); 14546 14547 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 14548 && "Should only handle conversion from integer to float."); 14549 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 14550 14551 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 14552 14553 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 14554 return SDValue(); 14555 14556 // Just because the floating-point vector type is legal does not necessarily 14557 // mean that the corresponding integer vector type is. 14558 if (!isTypeLegal(NVT)) 14559 return SDValue(); 14560 14561 SmallVector<SDValue, 8> Opnds; 14562 for (unsigned i = 0; i != NumInScalars; ++i) { 14563 SDValue In = N->getOperand(i); 14564 14565 if (In.isUndef()) 14566 Opnds.push_back(DAG.getUNDEF(SrcVT)); 14567 else 14568 Opnds.push_back(In.getOperand(0)); 14569 } 14570 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds); 14571 AddToWorklist(BV.getNode()); 14572 14573 return DAG.getNode(Opcode, DL, VT, BV); 14574 } 14575 14576 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N, 14577 ArrayRef<int> VectorMask, 14578 SDValue VecIn1, SDValue VecIn2, 14579 unsigned LeftIdx) { 14580 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 14581 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy); 14582 14583 EVT VT = N->getValueType(0); 14584 EVT InVT1 = VecIn1.getValueType(); 14585 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1; 14586 14587 unsigned Vec2Offset = 0; 14588 unsigned NumElems = VT.getVectorNumElements(); 14589 unsigned ShuffleNumElems = NumElems; 14590 14591 // In case both the input vectors are extracted from same base 14592 // vector we do not need extra addend (Vec2Offset) while 14593 // computing shuffle mask. 14594 if (!VecIn2 || !(VecIn1.getOpcode() == ISD::EXTRACT_SUBVECTOR) || 14595 !(VecIn2.getOpcode() == ISD::EXTRACT_SUBVECTOR) || 14596 !(VecIn1.getOperand(0) == VecIn2.getOperand(0))) 14597 Vec2Offset = InVT1.getVectorNumElements(); 14598 14599 // We can't generate a shuffle node with mismatched input and output types. 14600 // Try to make the types match the type of the output. 14601 if (InVT1 != VT || InVT2 != VT) { 14602 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) { 14603 // If the output vector length is a multiple of both input lengths, 14604 // we can concatenate them and pad the rest with undefs. 14605 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits(); 14606 assert(NumConcats >= 2 && "Concat needs at least two inputs!"); 14607 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1)); 14608 ConcatOps[0] = VecIn1; 14609 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1); 14610 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 14611 VecIn2 = SDValue(); 14612 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) { 14613 if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems)) 14614 return SDValue(); 14615 14616 if (!VecIn2.getNode()) { 14617 // If we only have one input vector, and it's twice the size of the 14618 // output, split it in two. 14619 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, 14620 DAG.getConstant(NumElems, DL, IdxTy)); 14621 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx); 14622 // Since we now have shorter input vectors, adjust the offset of the 14623 // second vector's start. 14624 Vec2Offset = NumElems; 14625 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) { 14626 // VecIn1 is wider than the output, and we have another, possibly 14627 // smaller input. Pad the smaller input with undefs, shuffle at the 14628 // input vector width, and extract the output. 14629 // The shuffle type is different than VT, so check legality again. 14630 if (LegalOperations && 14631 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1)) 14632 return SDValue(); 14633 14634 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to 14635 // lower it back into a BUILD_VECTOR. So if the inserted type is 14636 // illegal, don't even try. 14637 if (InVT1 != InVT2) { 14638 if (!TLI.isTypeLegal(InVT2)) 14639 return SDValue(); 14640 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1, 14641 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx); 14642 } 14643 ShuffleNumElems = NumElems * 2; 14644 } else { 14645 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider 14646 // than VecIn1. We can't handle this for now - this case will disappear 14647 // when we start sorting the vectors by type. 14648 return SDValue(); 14649 } 14650 } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() && 14651 InVT1.getSizeInBits() == VT.getSizeInBits()) { 14652 SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2)); 14653 ConcatOps[0] = VecIn2; 14654 VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 14655 } else { 14656 // TODO: Support cases where the length mismatch isn't exactly by a 14657 // factor of 2. 14658 // TODO: Move this check upwards, so that if we have bad type 14659 // mismatches, we don't create any DAG nodes. 14660 return SDValue(); 14661 } 14662 } 14663 14664 // Initialize mask to undef. 14665 SmallVector<int, 8> Mask(ShuffleNumElems, -1); 14666 14667 // Only need to run up to the number of elements actually used, not the 14668 // total number of elements in the shuffle - if we are shuffling a wider 14669 // vector, the high lanes should be set to undef. 14670 for (unsigned i = 0; i != NumElems; ++i) { 14671 if (VectorMask[i] <= 0) 14672 continue; 14673 14674 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1); 14675 if (VectorMask[i] == (int)LeftIdx) { 14676 Mask[i] = ExtIndex; 14677 } else if (VectorMask[i] == (int)LeftIdx + 1) { 14678 Mask[i] = Vec2Offset + ExtIndex; 14679 } 14680 } 14681 14682 // The type the input vectors may have changed above. 14683 InVT1 = VecIn1.getValueType(); 14684 14685 // If we already have a VecIn2, it should have the same type as VecIn1. 14686 // If we don't, get an undef/zero vector of the appropriate type. 14687 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1); 14688 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type."); 14689 14690 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask); 14691 if (ShuffleNumElems > NumElems) 14692 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx); 14693 14694 return Shuffle; 14695 } 14696 14697 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 14698 // operations. If the types of the vectors we're extracting from allow it, 14699 // turn this into a vector_shuffle node. 14700 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) { 14701 SDLoc DL(N); 14702 EVT VT = N->getValueType(0); 14703 14704 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 14705 if (!isTypeLegal(VT)) 14706 return SDValue(); 14707 14708 // May only combine to shuffle after legalize if shuffle is legal. 14709 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 14710 return SDValue(); 14711 14712 bool UsesZeroVector = false; 14713 unsigned NumElems = N->getNumOperands(); 14714 14715 // Record, for each element of the newly built vector, which input vector 14716 // that element comes from. -1 stands for undef, 0 for the zero vector, 14717 // and positive values for the input vectors. 14718 // VectorMask maps each element to its vector number, and VecIn maps vector 14719 // numbers to their initial SDValues. 14720 14721 SmallVector<int, 8> VectorMask(NumElems, -1); 14722 SmallVector<SDValue, 8> VecIn; 14723 VecIn.push_back(SDValue()); 14724 14725 for (unsigned i = 0; i != NumElems; ++i) { 14726 SDValue Op = N->getOperand(i); 14727 14728 if (Op.isUndef()) 14729 continue; 14730 14731 // See if we can use a blend with a zero vector. 14732 // TODO: Should we generalize this to a blend with an arbitrary constant 14733 // vector? 14734 if (isNullConstant(Op) || isNullFPConstant(Op)) { 14735 UsesZeroVector = true; 14736 VectorMask[i] = 0; 14737 continue; 14738 } 14739 14740 // Not an undef or zero. If the input is something other than an 14741 // EXTRACT_VECTOR_ELT with a constant index, bail out. 14742 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14743 !isa<ConstantSDNode>(Op.getOperand(1))) 14744 return SDValue(); 14745 SDValue ExtractedFromVec = Op.getOperand(0); 14746 14747 // All inputs must have the same element type as the output. 14748 if (VT.getVectorElementType() != 14749 ExtractedFromVec.getValueType().getVectorElementType()) 14750 return SDValue(); 14751 14752 // Have we seen this input vector before? 14753 // The vectors are expected to be tiny (usually 1 or 2 elements), so using 14754 // a map back from SDValues to numbers isn't worth it. 14755 unsigned Idx = std::distance( 14756 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec)); 14757 if (Idx == VecIn.size()) 14758 VecIn.push_back(ExtractedFromVec); 14759 14760 VectorMask[i] = Idx; 14761 } 14762 14763 // If we didn't find at least one input vector, bail out. 14764 if (VecIn.size() < 2) 14765 return SDValue(); 14766 14767 // If all the Operands of BUILD_VECTOR extract from same 14768 // vector, then split the vector efficiently based on the maximum 14769 // vector access index and adjust the VectorMask and 14770 // VecIn accordingly. 14771 if (VecIn.size() == 2) { 14772 unsigned MaxIndex = 0; 14773 unsigned NearestPow2 = 0; 14774 SDValue Vec = VecIn.back(); 14775 EVT InVT = Vec.getValueType(); 14776 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 14777 SmallVector<unsigned, 8> IndexVec(NumElems, 0); 14778 14779 for (unsigned i = 0; i < NumElems; i++) { 14780 if (VectorMask[i] <= 0) 14781 continue; 14782 unsigned Index = N->getOperand(i).getConstantOperandVal(1); 14783 IndexVec[i] = Index; 14784 MaxIndex = std::max(MaxIndex, Index); 14785 } 14786 14787 NearestPow2 = PowerOf2Ceil(MaxIndex); 14788 if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 && 14789 NumElems * 2 < NearestPow2) { 14790 unsigned SplitSize = NearestPow2 / 2; 14791 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), 14792 InVT.getVectorElementType(), SplitSize); 14793 if (TLI.isTypeLegal(SplitVT)) { 14794 SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, 14795 DAG.getConstant(SplitSize, DL, IdxTy)); 14796 SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, 14797 DAG.getConstant(0, DL, IdxTy)); 14798 VecIn.pop_back(); 14799 VecIn.push_back(VecIn1); 14800 VecIn.push_back(VecIn2); 14801 14802 for (unsigned i = 0; i < NumElems; i++) { 14803 if (VectorMask[i] <= 0) 14804 continue; 14805 VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2; 14806 } 14807 } 14808 } 14809 } 14810 14811 // TODO: We want to sort the vectors by descending length, so that adjacent 14812 // pairs have similar length, and the longer vector is always first in the 14813 // pair. 14814 14815 // TODO: Should this fire if some of the input vectors has illegal type (like 14816 // it does now), or should we let legalization run its course first? 14817 14818 // Shuffle phase: 14819 // Take pairs of vectors, and shuffle them so that the result has elements 14820 // from these vectors in the correct places. 14821 // For example, given: 14822 // t10: i32 = extract_vector_elt t1, Constant:i64<0> 14823 // t11: i32 = extract_vector_elt t2, Constant:i64<0> 14824 // t12: i32 = extract_vector_elt t3, Constant:i64<0> 14825 // t13: i32 = extract_vector_elt t1, Constant:i64<1> 14826 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13 14827 // We will generate: 14828 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2 14829 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef 14830 SmallVector<SDValue, 4> Shuffles; 14831 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) { 14832 unsigned LeftIdx = 2 * In + 1; 14833 SDValue VecLeft = VecIn[LeftIdx]; 14834 SDValue VecRight = 14835 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue(); 14836 14837 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft, 14838 VecRight, LeftIdx)) 14839 Shuffles.push_back(Shuffle); 14840 else 14841 return SDValue(); 14842 } 14843 14844 // If we need the zero vector as an "ingredient" in the blend tree, add it 14845 // to the list of shuffles. 14846 if (UsesZeroVector) 14847 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT) 14848 : DAG.getConstantFP(0.0, DL, VT)); 14849 14850 // If we only have one shuffle, we're done. 14851 if (Shuffles.size() == 1) 14852 return Shuffles[0]; 14853 14854 // Update the vector mask to point to the post-shuffle vectors. 14855 for (int &Vec : VectorMask) 14856 if (Vec == 0) 14857 Vec = Shuffles.size() - 1; 14858 else 14859 Vec = (Vec - 1) / 2; 14860 14861 // More than one shuffle. Generate a binary tree of blends, e.g. if from 14862 // the previous step we got the set of shuffles t10, t11, t12, t13, we will 14863 // generate: 14864 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2 14865 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4 14866 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6 14867 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8 14868 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11 14869 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13 14870 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21 14871 14872 // Make sure the initial size of the shuffle list is even. 14873 if (Shuffles.size() % 2) 14874 Shuffles.push_back(DAG.getUNDEF(VT)); 14875 14876 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) { 14877 if (CurSize % 2) { 14878 Shuffles[CurSize] = DAG.getUNDEF(VT); 14879 CurSize++; 14880 } 14881 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) { 14882 int Left = 2 * In; 14883 int Right = 2 * In + 1; 14884 SmallVector<int, 8> Mask(NumElems, -1); 14885 for (unsigned i = 0; i != NumElems; ++i) { 14886 if (VectorMask[i] == Left) { 14887 Mask[i] = i; 14888 VectorMask[i] = In; 14889 } else if (VectorMask[i] == Right) { 14890 Mask[i] = i + NumElems; 14891 VectorMask[i] = In; 14892 } 14893 } 14894 14895 Shuffles[In] = 14896 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask); 14897 } 14898 } 14899 return Shuffles[0]; 14900 } 14901 14902 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 14903 EVT VT = N->getValueType(0); 14904 14905 // A vector built entirely of undefs is undef. 14906 if (ISD::allOperandsUndef(N)) 14907 return DAG.getUNDEF(VT); 14908 14909 // Check if we can express BUILD VECTOR via subvector extract. 14910 if (!LegalTypes && (N->getNumOperands() > 1)) { 14911 SDValue Op0 = N->getOperand(0); 14912 auto checkElem = [&](SDValue Op) -> uint64_t { 14913 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) && 14914 (Op0.getOperand(0) == Op.getOperand(0))) 14915 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 14916 return CNode->getZExtValue(); 14917 return -1; 14918 }; 14919 14920 int Offset = checkElem(Op0); 14921 for (unsigned i = 0; i < N->getNumOperands(); ++i) { 14922 if (Offset + i != checkElem(N->getOperand(i))) { 14923 Offset = -1; 14924 break; 14925 } 14926 } 14927 14928 if ((Offset == 0) && 14929 (Op0.getOperand(0).getValueType() == N->getValueType(0))) 14930 return Op0.getOperand(0); 14931 if ((Offset != -1) && 14932 ((Offset % N->getValueType(0).getVectorNumElements()) == 14933 0)) // IDX must be multiple of output size. 14934 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0), 14935 Op0.getOperand(0), Op0.getOperand(1)); 14936 } 14937 14938 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 14939 return V; 14940 14941 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 14942 return V; 14943 14944 if (SDValue V = reduceBuildVecToShuffle(N)) 14945 return V; 14946 14947 return SDValue(); 14948 } 14949 14950 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 14951 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14952 EVT OpVT = N->getOperand(0).getValueType(); 14953 14954 // If the operands are legal vectors, leave them alone. 14955 if (TLI.isTypeLegal(OpVT)) 14956 return SDValue(); 14957 14958 SDLoc DL(N); 14959 EVT VT = N->getValueType(0); 14960 SmallVector<SDValue, 8> Ops; 14961 14962 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 14963 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 14964 14965 // Keep track of what we encounter. 14966 bool AnyInteger = false; 14967 bool AnyFP = false; 14968 for (const SDValue &Op : N->ops()) { 14969 if (ISD::BITCAST == Op.getOpcode() && 14970 !Op.getOperand(0).getValueType().isVector()) 14971 Ops.push_back(Op.getOperand(0)); 14972 else if (ISD::UNDEF == Op.getOpcode()) 14973 Ops.push_back(ScalarUndef); 14974 else 14975 return SDValue(); 14976 14977 // Note whether we encounter an integer or floating point scalar. 14978 // If it's neither, bail out, it could be something weird like x86mmx. 14979 EVT LastOpVT = Ops.back().getValueType(); 14980 if (LastOpVT.isFloatingPoint()) 14981 AnyFP = true; 14982 else if (LastOpVT.isInteger()) 14983 AnyInteger = true; 14984 else 14985 return SDValue(); 14986 } 14987 14988 // If any of the operands is a floating point scalar bitcast to a vector, 14989 // use floating point types throughout, and bitcast everything. 14990 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 14991 if (AnyFP) { 14992 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 14993 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 14994 if (AnyInteger) { 14995 for (SDValue &Op : Ops) { 14996 if (Op.getValueType() == SVT) 14997 continue; 14998 if (Op.isUndef()) 14999 Op = ScalarUndef; 15000 else 15001 Op = DAG.getBitcast(SVT, Op); 15002 } 15003 } 15004 } 15005 15006 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 15007 VT.getSizeInBits() / SVT.getSizeInBits()); 15008 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 15009 } 15010 15011 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 15012 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 15013 // most two distinct vectors the same size as the result, attempt to turn this 15014 // into a legal shuffle. 15015 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 15016 EVT VT = N->getValueType(0); 15017 EVT OpVT = N->getOperand(0).getValueType(); 15018 int NumElts = VT.getVectorNumElements(); 15019 int NumOpElts = OpVT.getVectorNumElements(); 15020 15021 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 15022 SmallVector<int, 8> Mask; 15023 15024 for (SDValue Op : N->ops()) { 15025 // Peek through any bitcast. 15026 Op = peekThroughBitcast(Op); 15027 15028 // UNDEF nodes convert to UNDEF shuffle mask values. 15029 if (Op.isUndef()) { 15030 Mask.append((unsigned)NumOpElts, -1); 15031 continue; 15032 } 15033 15034 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 15035 return SDValue(); 15036 15037 // What vector are we extracting the subvector from and at what index? 15038 SDValue ExtVec = Op.getOperand(0); 15039 15040 // We want the EVT of the original extraction to correctly scale the 15041 // extraction index. 15042 EVT ExtVT = ExtVec.getValueType(); 15043 15044 // Peek through any bitcast. 15045 ExtVec = peekThroughBitcast(ExtVec); 15046 15047 // UNDEF nodes convert to UNDEF shuffle mask values. 15048 if (ExtVec.isUndef()) { 15049 Mask.append((unsigned)NumOpElts, -1); 15050 continue; 15051 } 15052 15053 if (!isa<ConstantSDNode>(Op.getOperand(1))) 15054 return SDValue(); 15055 int ExtIdx = Op.getConstantOperandVal(1); 15056 15057 // Ensure that we are extracting a subvector from a vector the same 15058 // size as the result. 15059 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 15060 return SDValue(); 15061 15062 // Scale the subvector index to account for any bitcast. 15063 int NumExtElts = ExtVT.getVectorNumElements(); 15064 if (0 == (NumExtElts % NumElts)) 15065 ExtIdx /= (NumExtElts / NumElts); 15066 else if (0 == (NumElts % NumExtElts)) 15067 ExtIdx *= (NumElts / NumExtElts); 15068 else 15069 return SDValue(); 15070 15071 // At most we can reference 2 inputs in the final shuffle. 15072 if (SV0.isUndef() || SV0 == ExtVec) { 15073 SV0 = ExtVec; 15074 for (int i = 0; i != NumOpElts; ++i) 15075 Mask.push_back(i + ExtIdx); 15076 } else if (SV1.isUndef() || SV1 == ExtVec) { 15077 SV1 = ExtVec; 15078 for (int i = 0; i != NumOpElts; ++i) 15079 Mask.push_back(i + ExtIdx + NumElts); 15080 } else { 15081 return SDValue(); 15082 } 15083 } 15084 15085 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 15086 return SDValue(); 15087 15088 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 15089 DAG.getBitcast(VT, SV1), Mask); 15090 } 15091 15092 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 15093 // If we only have one input vector, we don't need to do any concatenation. 15094 if (N->getNumOperands() == 1) 15095 return N->getOperand(0); 15096 15097 // Check if all of the operands are undefs. 15098 EVT VT = N->getValueType(0); 15099 if (ISD::allOperandsUndef(N)) 15100 return DAG.getUNDEF(VT); 15101 15102 // Optimize concat_vectors where all but the first of the vectors are undef. 15103 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 15104 return Op.isUndef(); 15105 })) { 15106 SDValue In = N->getOperand(0); 15107 assert(In.getValueType().isVector() && "Must concat vectors"); 15108 15109 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 15110 if (In->getOpcode() == ISD::BITCAST && 15111 !In->getOperand(0).getValueType().isVector()) { 15112 SDValue Scalar = In->getOperand(0); 15113 15114 // If the bitcast type isn't legal, it might be a trunc of a legal type; 15115 // look through the trunc so we can still do the transform: 15116 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 15117 if (Scalar->getOpcode() == ISD::TRUNCATE && 15118 !TLI.isTypeLegal(Scalar.getValueType()) && 15119 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 15120 Scalar = Scalar->getOperand(0); 15121 15122 EVT SclTy = Scalar->getValueType(0); 15123 15124 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 15125 return SDValue(); 15126 15127 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits(); 15128 if (VNTNumElms < 2) 15129 return SDValue(); 15130 15131 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms); 15132 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 15133 return SDValue(); 15134 15135 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar); 15136 return DAG.getBitcast(VT, Res); 15137 } 15138 } 15139 15140 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 15141 // We have already tested above for an UNDEF only concatenation. 15142 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 15143 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 15144 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 15145 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 15146 }; 15147 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 15148 SmallVector<SDValue, 8> Opnds; 15149 EVT SVT = VT.getScalarType(); 15150 15151 EVT MinVT = SVT; 15152 if (!SVT.isFloatingPoint()) { 15153 // If BUILD_VECTOR are from built from integer, they may have different 15154 // operand types. Get the smallest type and truncate all operands to it. 15155 bool FoundMinVT = false; 15156 for (const SDValue &Op : N->ops()) 15157 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 15158 EVT OpSVT = Op.getOperand(0).getValueType(); 15159 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 15160 FoundMinVT = true; 15161 } 15162 assert(FoundMinVT && "Concat vector type mismatch"); 15163 } 15164 15165 for (const SDValue &Op : N->ops()) { 15166 EVT OpVT = Op.getValueType(); 15167 unsigned NumElts = OpVT.getVectorNumElements(); 15168 15169 if (ISD::UNDEF == Op.getOpcode()) 15170 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 15171 15172 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 15173 if (SVT.isFloatingPoint()) { 15174 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 15175 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 15176 } else { 15177 for (unsigned i = 0; i != NumElts; ++i) 15178 Opnds.push_back( 15179 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 15180 } 15181 } 15182 } 15183 15184 assert(VT.getVectorNumElements() == Opnds.size() && 15185 "Concat vector type mismatch"); 15186 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 15187 } 15188 15189 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 15190 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 15191 return V; 15192 15193 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 15194 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 15195 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 15196 return V; 15197 15198 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 15199 // nodes often generate nop CONCAT_VECTOR nodes. 15200 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 15201 // place the incoming vectors at the exact same location. 15202 SDValue SingleSource = SDValue(); 15203 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 15204 15205 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 15206 SDValue Op = N->getOperand(i); 15207 15208 if (Op.isUndef()) 15209 continue; 15210 15211 // Check if this is the identity extract: 15212 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 15213 return SDValue(); 15214 15215 // Find the single incoming vector for the extract_subvector. 15216 if (SingleSource.getNode()) { 15217 if (Op.getOperand(0) != SingleSource) 15218 return SDValue(); 15219 } else { 15220 SingleSource = Op.getOperand(0); 15221 15222 // Check the source type is the same as the type of the result. 15223 // If not, this concat may extend the vector, so we can not 15224 // optimize it away. 15225 if (SingleSource.getValueType() != N->getValueType(0)) 15226 return SDValue(); 15227 } 15228 15229 unsigned IdentityIndex = i * PartNumElem; 15230 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 15231 // The extract index must be constant. 15232 if (!CS) 15233 return SDValue(); 15234 15235 // Check that we are reading from the identity index. 15236 if (CS->getZExtValue() != IdentityIndex) 15237 return SDValue(); 15238 } 15239 15240 if (SingleSource.getNode()) 15241 return SingleSource; 15242 15243 return SDValue(); 15244 } 15245 15246 /// If we are extracting a subvector produced by a wide binary operator with at 15247 /// at least one operand that was the result of a vector concatenation, then try 15248 /// to use the narrow vector operands directly to avoid the concatenation and 15249 /// extraction. 15250 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) { 15251 // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share 15252 // some of these bailouts with other transforms. 15253 15254 // The extract index must be a constant, so we can map it to a concat operand. 15255 auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 15256 if (!ExtractIndex) 15257 return SDValue(); 15258 15259 // Only handle the case where we are doubling and then halving. A larger ratio 15260 // may require more than two narrow binops to replace the wide binop. 15261 EVT VT = Extract->getValueType(0); 15262 unsigned NumElems = VT.getVectorNumElements(); 15263 assert((ExtractIndex->getZExtValue() % NumElems) == 0 && 15264 "Extract index is not a multiple of the vector length."); 15265 if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2) 15266 return SDValue(); 15267 15268 // We are looking for an optionally bitcasted wide vector binary operator 15269 // feeding an extract subvector. 15270 SDValue BinOp = peekThroughBitcast(Extract->getOperand(0)); 15271 15272 // TODO: The motivating case for this transform is an x86 AVX1 target. That 15273 // target has temptingly almost legal versions of bitwise logic ops in 256-bit 15274 // flavors, but no other 256-bit integer support. This could be extended to 15275 // handle any binop, but that may require fixing/adding other folds to avoid 15276 // codegen regressions. 15277 unsigned BOpcode = BinOp.getOpcode(); 15278 if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR) 15279 return SDValue(); 15280 15281 // The binop must be a vector type, so we can chop it in half. 15282 EVT WideBVT = BinOp.getValueType(); 15283 if (!WideBVT.isVector()) 15284 return SDValue(); 15285 15286 // Bail out if the target does not support a narrower version of the binop. 15287 EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(), 15288 WideBVT.getVectorNumElements() / 2); 15289 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15290 if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT)) 15291 return SDValue(); 15292 15293 // Peek through bitcasts of the binary operator operands if needed. 15294 SDValue LHS = peekThroughBitcast(BinOp.getOperand(0)); 15295 SDValue RHS = peekThroughBitcast(BinOp.getOperand(1)); 15296 15297 // We need at least one concatenation operation of a binop operand to make 15298 // this transform worthwhile. The concat must double the input vector sizes. 15299 // TODO: Should we also handle INSERT_SUBVECTOR patterns? 15300 bool ConcatL = 15301 LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2; 15302 bool ConcatR = 15303 RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2; 15304 if (!ConcatL && !ConcatR) 15305 return SDValue(); 15306 15307 // If one of the binop operands was not the result of a concat, we must 15308 // extract a half-sized operand for our new narrow binop. We can't just reuse 15309 // the original extract index operand because we may have bitcasted. 15310 unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems; 15311 unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements(); 15312 EVT ExtBOIdxVT = Extract->getOperand(1).getValueType(); 15313 SDLoc DL(Extract); 15314 15315 // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN 15316 // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N) 15317 // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN 15318 SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum)) 15319 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 15320 BinOp.getOperand(0), 15321 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT)); 15322 15323 SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum)) 15324 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 15325 BinOp.getOperand(1), 15326 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT)); 15327 15328 SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y); 15329 return DAG.getBitcast(VT, NarrowBinOp); 15330 } 15331 15332 /// If we are extracting a subvector from a wide vector load, convert to a 15333 /// narrow load to eliminate the extraction: 15334 /// (extract_subvector (load wide vector)) --> (load narrow vector) 15335 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) { 15336 // TODO: Add support for big-endian. The offset calculation must be adjusted. 15337 if (DAG.getDataLayout().isBigEndian()) 15338 return SDValue(); 15339 15340 // TODO: The one-use check is overly conservative. Check the cost of the 15341 // extract instead or remove that condition entirely. 15342 auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0)); 15343 auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 15344 if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() || 15345 !ExtIdx) 15346 return SDValue(); 15347 15348 // The narrow load will be offset from the base address of the old load if 15349 // we are extracting from something besides index 0 (little-endian). 15350 EVT VT = Extract->getValueType(0); 15351 SDLoc DL(Extract); 15352 SDValue BaseAddr = Ld->getOperand(1); 15353 unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize(); 15354 15355 // TODO: Use "BaseIndexOffset" to make this more effective. 15356 SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL); 15357 MachineFunction &MF = DAG.getMachineFunction(); 15358 MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset, 15359 VT.getStoreSize()); 15360 SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO); 15361 DAG.makeEquivalentMemoryOrdering(Ld, NewLd); 15362 return NewLd; 15363 } 15364 15365 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 15366 EVT NVT = N->getValueType(0); 15367 SDValue V = N->getOperand(0); 15368 15369 // Extract from UNDEF is UNDEF. 15370 if (V.isUndef()) 15371 return DAG.getUNDEF(NVT); 15372 15373 if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT)) 15374 if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG)) 15375 return NarrowLoad; 15376 15377 // Combine: 15378 // (extract_subvec (concat V1, V2, ...), i) 15379 // Into: 15380 // Vi if possible 15381 // Only operand 0 is checked as 'concat' assumes all inputs of the same 15382 // type. 15383 if (V->getOpcode() == ISD::CONCAT_VECTORS && 15384 isa<ConstantSDNode>(N->getOperand(1)) && 15385 V->getOperand(0).getValueType() == NVT) { 15386 unsigned Idx = N->getConstantOperandVal(1); 15387 unsigned NumElems = NVT.getVectorNumElements(); 15388 assert((Idx % NumElems) == 0 && 15389 "IDX in concat is not a multiple of the result vector length."); 15390 return V->getOperand(Idx / NumElems); 15391 } 15392 15393 // Skip bitcasting 15394 V = peekThroughBitcast(V); 15395 15396 // If the input is a build vector. Try to make a smaller build vector. 15397 if (V->getOpcode() == ISD::BUILD_VECTOR) { 15398 if (auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))) { 15399 EVT InVT = V->getValueType(0); 15400 unsigned ExtractSize = NVT.getSizeInBits(); 15401 unsigned EltSize = InVT.getScalarSizeInBits(); 15402 // Only do this if we won't split any elements. 15403 if (ExtractSize % EltSize == 0) { 15404 unsigned NumElems = ExtractSize / EltSize; 15405 EVT ExtractVT = EVT::getVectorVT(*DAG.getContext(), 15406 InVT.getVectorElementType(), NumElems); 15407 if ((!LegalOperations || 15408 TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT)) && 15409 (!LegalTypes || TLI.isTypeLegal(ExtractVT))) { 15410 unsigned IdxVal = (Idx->getZExtValue() * NVT.getScalarSizeInBits()) / 15411 EltSize; 15412 15413 // Extract the pieces from the original build_vector. 15414 SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N), 15415 makeArrayRef(V->op_begin() + IdxVal, 15416 NumElems)); 15417 return DAG.getBitcast(NVT, BuildVec); 15418 } 15419 } 15420 } 15421 } 15422 15423 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 15424 // Handle only simple case where vector being inserted and vector 15425 // being extracted are of same size. 15426 EVT SmallVT = V->getOperand(1).getValueType(); 15427 if (!NVT.bitsEq(SmallVT)) 15428 return SDValue(); 15429 15430 // Only handle cases where both indexes are constants. 15431 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15432 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 15433 15434 if (InsIdx && ExtIdx) { 15435 // Combine: 15436 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 15437 // Into: 15438 // indices are equal or bit offsets are equal => V1 15439 // otherwise => (extract_subvec V1, ExtIdx) 15440 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() == 15441 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits()) 15442 return DAG.getBitcast(NVT, V->getOperand(1)); 15443 return DAG.getNode( 15444 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, 15445 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)), 15446 N->getOperand(1)); 15447 } 15448 } 15449 15450 if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG)) 15451 return NarrowBOp; 15452 15453 return SDValue(); 15454 } 15455 15456 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 15457 SDValue V, SelectionDAG &DAG) { 15458 SDLoc DL(V); 15459 EVT VT = V.getValueType(); 15460 15461 switch (V.getOpcode()) { 15462 default: 15463 return V; 15464 15465 case ISD::CONCAT_VECTORS: { 15466 EVT OpVT = V->getOperand(0).getValueType(); 15467 int OpSize = OpVT.getVectorNumElements(); 15468 SmallBitVector OpUsedElements(OpSize, false); 15469 bool FoundSimplification = false; 15470 SmallVector<SDValue, 4> NewOps; 15471 NewOps.reserve(V->getNumOperands()); 15472 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 15473 SDValue Op = V->getOperand(i); 15474 bool OpUsed = false; 15475 for (int j = 0; j < OpSize; ++j) 15476 if (UsedElements[i * OpSize + j]) { 15477 OpUsedElements[j] = true; 15478 OpUsed = true; 15479 } 15480 NewOps.push_back( 15481 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 15482 : DAG.getUNDEF(OpVT)); 15483 FoundSimplification |= Op == NewOps.back(); 15484 OpUsedElements.reset(); 15485 } 15486 if (FoundSimplification) 15487 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 15488 return V; 15489 } 15490 15491 case ISD::INSERT_SUBVECTOR: { 15492 SDValue BaseV = V->getOperand(0); 15493 SDValue SubV = V->getOperand(1); 15494 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 15495 if (!IdxN) 15496 return V; 15497 15498 int SubSize = SubV.getValueType().getVectorNumElements(); 15499 int Idx = IdxN->getZExtValue(); 15500 bool SubVectorUsed = false; 15501 SmallBitVector SubUsedElements(SubSize, false); 15502 for (int i = 0; i < SubSize; ++i) 15503 if (UsedElements[i + Idx]) { 15504 SubVectorUsed = true; 15505 SubUsedElements[i] = true; 15506 UsedElements[i + Idx] = false; 15507 } 15508 15509 // Now recurse on both the base and sub vectors. 15510 SDValue SimplifiedSubV = 15511 SubVectorUsed 15512 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 15513 : DAG.getUNDEF(SubV.getValueType()); 15514 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 15515 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 15516 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 15517 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 15518 return V; 15519 } 15520 } 15521 } 15522 15523 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 15524 SDValue N1, SelectionDAG &DAG) { 15525 EVT VT = SVN->getValueType(0); 15526 int NumElts = VT.getVectorNumElements(); 15527 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 15528 for (int M : SVN->getMask()) 15529 if (M >= 0 && M < NumElts) 15530 N0UsedElements[M] = true; 15531 else if (M >= NumElts) 15532 N1UsedElements[M - NumElts] = true; 15533 15534 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 15535 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 15536 if (S0 == N0 && S1 == N1) 15537 return SDValue(); 15538 15539 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 15540 } 15541 15542 static SDValue simplifyShuffleMask(ShuffleVectorSDNode *SVN, SDValue N0, 15543 SDValue N1, SelectionDAG &DAG) { 15544 auto isUndefElt = [](SDValue V, int Idx) { 15545 // TODO - handle more cases as required. 15546 if (V.getOpcode() == ISD::BUILD_VECTOR) 15547 return V.getOperand(Idx).isUndef(); 15548 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) 15549 return (Idx != 0) || V.getOperand(0).isUndef(); 15550 return false; 15551 }; 15552 15553 EVT VT = SVN->getValueType(0); 15554 unsigned NumElts = VT.getVectorNumElements(); 15555 15556 bool Changed = false; 15557 SmallVector<int, 8> NewMask; 15558 for (unsigned i = 0; i != NumElts; ++i) { 15559 int Idx = SVN->getMaskElt(i); 15560 if ((0 <= Idx && Idx < (int)NumElts && isUndefElt(N0, Idx)) || 15561 ((int)NumElts < Idx && isUndefElt(N1, Idx - NumElts))) { 15562 Changed = true; 15563 Idx = -1; 15564 } 15565 NewMask.push_back(Idx); 15566 } 15567 if (Changed) 15568 return DAG.getVectorShuffle(VT, SDLoc(SVN), N0, N1, NewMask); 15569 15570 return SDValue(); 15571 } 15572 15573 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 15574 // or turn a shuffle of a single concat into simpler shuffle then concat. 15575 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 15576 EVT VT = N->getValueType(0); 15577 unsigned NumElts = VT.getVectorNumElements(); 15578 15579 SDValue N0 = N->getOperand(0); 15580 SDValue N1 = N->getOperand(1); 15581 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 15582 15583 SmallVector<SDValue, 4> Ops; 15584 EVT ConcatVT = N0.getOperand(0).getValueType(); 15585 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 15586 unsigned NumConcats = NumElts / NumElemsPerConcat; 15587 15588 // Special case: shuffle(concat(A,B)) can be more efficiently represented 15589 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 15590 // half vector elements. 15591 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 15592 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 15593 SVN->getMask().end(), [](int i) { return i == -1; })) { 15594 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 15595 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 15596 N1 = DAG.getUNDEF(ConcatVT); 15597 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 15598 } 15599 15600 // Look at every vector that's inserted. We're looking for exact 15601 // subvector-sized copies from a concatenated vector 15602 for (unsigned I = 0; I != NumConcats; ++I) { 15603 // Make sure we're dealing with a copy. 15604 unsigned Begin = I * NumElemsPerConcat; 15605 bool AllUndef = true, NoUndef = true; 15606 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 15607 if (SVN->getMaskElt(J) >= 0) 15608 AllUndef = false; 15609 else 15610 NoUndef = false; 15611 } 15612 15613 if (NoUndef) { 15614 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 15615 return SDValue(); 15616 15617 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 15618 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 15619 return SDValue(); 15620 15621 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 15622 if (FirstElt < N0.getNumOperands()) 15623 Ops.push_back(N0.getOperand(FirstElt)); 15624 else 15625 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 15626 15627 } else if (AllUndef) { 15628 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 15629 } else { // Mixed with general masks and undefs, can't do optimization. 15630 return SDValue(); 15631 } 15632 } 15633 15634 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 15635 } 15636 15637 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 15638 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 15639 // 15640 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always 15641 // a simplification in some sense, but it isn't appropriate in general: some 15642 // BUILD_VECTORs are substantially cheaper than others. The general case 15643 // of a BUILD_VECTOR requires inserting each element individually (or 15644 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of 15645 // all constants is a single constant pool load. A BUILD_VECTOR where each 15646 // element is identical is a splat. A BUILD_VECTOR where most of the operands 15647 // are undef lowers to a small number of element insertions. 15648 // 15649 // To deal with this, we currently use a bunch of mostly arbitrary heuristics. 15650 // We don't fold shuffles where one side is a non-zero constant, and we don't 15651 // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate 15652 // non-constant operands. This seems to work out reasonably well in practice. 15653 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN, 15654 SelectionDAG &DAG, 15655 const TargetLowering &TLI) { 15656 EVT VT = SVN->getValueType(0); 15657 unsigned NumElts = VT.getVectorNumElements(); 15658 SDValue N0 = SVN->getOperand(0); 15659 SDValue N1 = SVN->getOperand(1); 15660 15661 if (!N0->hasOneUse() || !N1->hasOneUse()) 15662 return SDValue(); 15663 15664 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as 15665 // discussed above. 15666 if (!N1.isUndef()) { 15667 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode()); 15668 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode()); 15669 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode())) 15670 return SDValue(); 15671 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode())) 15672 return SDValue(); 15673 } 15674 15675 // If both inputs are splats of the same value then we can safely merge this 15676 // to a single BUILD_VECTOR with undef elements based on the shuffle mask. 15677 bool IsSplat = false; 15678 auto *BV0 = dyn_cast<BuildVectorSDNode>(N0); 15679 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 15680 if (BV0 && BV1) 15681 if (SDValue Splat0 = BV0->getSplatValue()) 15682 IsSplat = (Splat0 == BV1->getSplatValue()); 15683 15684 SmallVector<SDValue, 8> Ops; 15685 SmallSet<SDValue, 16> DuplicateOps; 15686 for (int M : SVN->getMask()) { 15687 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 15688 if (M >= 0) { 15689 int Idx = M < (int)NumElts ? M : M - NumElts; 15690 SDValue &S = (M < (int)NumElts ? N0 : N1); 15691 if (S.getOpcode() == ISD::BUILD_VECTOR) { 15692 Op = S.getOperand(Idx); 15693 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) { 15694 assert(Idx == 0 && "Unexpected SCALAR_TO_VECTOR operand index."); 15695 Op = S.getOperand(0); 15696 } else { 15697 // Operand can't be combined - bail out. 15698 return SDValue(); 15699 } 15700 } 15701 15702 // Don't duplicate a non-constant BUILD_VECTOR operand unless we're 15703 // generating a splat; semantically, this is fine, but it's likely to 15704 // generate low-quality code if the target can't reconstruct an appropriate 15705 // shuffle. 15706 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op)) 15707 if (!IsSplat && !DuplicateOps.insert(Op).second) 15708 return SDValue(); 15709 15710 Ops.push_back(Op); 15711 } 15712 15713 // BUILD_VECTOR requires all inputs to be of the same type, find the 15714 // maximum type and extend them all. 15715 EVT SVT = VT.getScalarType(); 15716 if (SVT.isInteger()) 15717 for (SDValue &Op : Ops) 15718 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 15719 if (SVT != VT.getScalarType()) 15720 for (SDValue &Op : Ops) 15721 Op = TLI.isZExtFree(Op.getValueType(), SVT) 15722 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT) 15723 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT); 15724 return DAG.getBuildVector(VT, SDLoc(SVN), Ops); 15725 } 15726 15727 // Match shuffles that can be converted to any_vector_extend_in_reg. 15728 // This is often generated during legalization. 15729 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src)) 15730 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case. 15731 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN, 15732 SelectionDAG &DAG, 15733 const TargetLowering &TLI, 15734 bool LegalOperations, 15735 bool LegalTypes) { 15736 EVT VT = SVN->getValueType(0); 15737 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 15738 15739 // TODO Add support for big-endian when we have a test case. 15740 if (!VT.isInteger() || IsBigEndian) 15741 return SDValue(); 15742 15743 unsigned NumElts = VT.getVectorNumElements(); 15744 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 15745 ArrayRef<int> Mask = SVN->getMask(); 15746 SDValue N0 = SVN->getOperand(0); 15747 15748 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32)) 15749 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) { 15750 for (unsigned i = 0; i != NumElts; ++i) { 15751 if (Mask[i] < 0) 15752 continue; 15753 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale)) 15754 continue; 15755 return false; 15756 } 15757 return true; 15758 }; 15759 15760 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for 15761 // power-of-2 extensions as they are the most likely. 15762 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) { 15763 // Check for non power of 2 vector sizes 15764 if (NumElts % Scale != 0) 15765 continue; 15766 if (!isAnyExtend(Scale)) 15767 continue; 15768 15769 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale); 15770 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale); 15771 if (!LegalTypes || TLI.isTypeLegal(OutVT)) 15772 if (!LegalOperations || 15773 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT)) 15774 return DAG.getBitcast(VT, 15775 DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT)); 15776 } 15777 15778 return SDValue(); 15779 } 15780 15781 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of 15782 // each source element of a large type into the lowest elements of a smaller 15783 // destination type. This is often generated during legalization. 15784 // If the source node itself was a '*_extend_vector_inreg' node then we should 15785 // then be able to remove it. 15786 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, 15787 SelectionDAG &DAG) { 15788 EVT VT = SVN->getValueType(0); 15789 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 15790 15791 // TODO Add support for big-endian when we have a test case. 15792 if (!VT.isInteger() || IsBigEndian) 15793 return SDValue(); 15794 15795 SDValue N0 = peekThroughBitcast(SVN->getOperand(0)); 15796 15797 unsigned Opcode = N0.getOpcode(); 15798 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG && 15799 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG && 15800 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG) 15801 return SDValue(); 15802 15803 SDValue N00 = N0.getOperand(0); 15804 ArrayRef<int> Mask = SVN->getMask(); 15805 unsigned NumElts = VT.getVectorNumElements(); 15806 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 15807 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits(); 15808 unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits(); 15809 15810 if (ExtDstSizeInBits % ExtSrcSizeInBits != 0) 15811 return SDValue(); 15812 unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits; 15813 15814 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1> 15815 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1> 15816 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1> 15817 auto isTruncate = [&Mask, &NumElts](unsigned Scale) { 15818 for (unsigned i = 0; i != NumElts; ++i) { 15819 if (Mask[i] < 0) 15820 continue; 15821 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale)) 15822 continue; 15823 return false; 15824 } 15825 return true; 15826 }; 15827 15828 // At the moment we just handle the case where we've truncated back to the 15829 // same size as before the extension. 15830 // TODO: handle more extension/truncation cases as cases arise. 15831 if (EltSizeInBits != ExtSrcSizeInBits) 15832 return SDValue(); 15833 15834 // We can remove *extend_vector_inreg only if the truncation happens at 15835 // the same scale as the extension. 15836 if (isTruncate(ExtScale)) 15837 return DAG.getBitcast(VT, N00); 15838 15839 return SDValue(); 15840 } 15841 15842 // Combine shuffles of splat-shuffles of the form: 15843 // shuffle (shuffle V, undef, splat-mask), undef, M 15844 // If splat-mask contains undef elements, we need to be careful about 15845 // introducing undef's in the folded mask which are not the result of composing 15846 // the masks of the shuffles. 15847 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask, 15848 ShuffleVectorSDNode *Splat, 15849 SelectionDAG &DAG) { 15850 ArrayRef<int> SplatMask = Splat->getMask(); 15851 assert(UserMask.size() == SplatMask.size() && "Mask length mismatch"); 15852 15853 // Prefer simplifying to the splat-shuffle, if possible. This is legal if 15854 // every undef mask element in the splat-shuffle has a corresponding undef 15855 // element in the user-shuffle's mask or if the composition of mask elements 15856 // would result in undef. 15857 // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask): 15858 // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u] 15859 // In this case it is not legal to simplify to the splat-shuffle because we 15860 // may be exposing the users of the shuffle an undef element at index 1 15861 // which was not there before the combine. 15862 // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u] 15863 // In this case the composition of masks yields SplatMask, so it's ok to 15864 // simplify to the splat-shuffle. 15865 // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u] 15866 // In this case the composed mask includes all undef elements of SplatMask 15867 // and in addition sets element zero to undef. It is safe to simplify to 15868 // the splat-shuffle. 15869 auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask, 15870 ArrayRef<int> SplatMask) { 15871 for (unsigned i = 0, e = UserMask.size(); i != e; ++i) 15872 if (UserMask[i] != -1 && SplatMask[i] == -1 && 15873 SplatMask[UserMask[i]] != -1) 15874 return false; 15875 return true; 15876 }; 15877 if (CanSimplifyToExistingSplat(UserMask, SplatMask)) 15878 return SDValue(Splat, 0); 15879 15880 // Create a new shuffle with a mask that is composed of the two shuffles' 15881 // masks. 15882 SmallVector<int, 32> NewMask; 15883 for (int Idx : UserMask) 15884 NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]); 15885 15886 return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat), 15887 Splat->getOperand(0), Splat->getOperand(1), 15888 NewMask); 15889 } 15890 15891 /// If the shuffle mask is taking exactly one element from the first vector 15892 /// operand and passing through all other elements from the second vector 15893 /// operand, return the index of the mask element that is choosing an element 15894 /// from the first operand. Otherwise, return -1. 15895 static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) { 15896 int MaskSize = Mask.size(); 15897 int EltFromOp0 = -1; 15898 // TODO: This does not match if there are undef elements in the shuffle mask. 15899 // Should we ignore undefs in the shuffle mask instead? The trade-off is 15900 // removing an instruction (a shuffle), but losing the knowledge that some 15901 // vector lanes are not needed. 15902 for (int i = 0; i != MaskSize; ++i) { 15903 if (Mask[i] >= 0 && Mask[i] < MaskSize) { 15904 // We're looking for a shuffle of exactly one element from operand 0. 15905 if (EltFromOp0 != -1) 15906 return -1; 15907 EltFromOp0 = i; 15908 } else if (Mask[i] != i + MaskSize) { 15909 // Nothing from operand 1 can change lanes. 15910 return -1; 15911 } 15912 } 15913 return EltFromOp0; 15914 } 15915 15916 /// If a shuffle inserts exactly one element from a source vector operand into 15917 /// another vector operand and we can access the specified element as a scalar, 15918 /// then we can eliminate the shuffle. 15919 static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf, 15920 SelectionDAG &DAG) { 15921 // First, check if we are taking one element of a vector and shuffling that 15922 // element into another vector. 15923 ArrayRef<int> Mask = Shuf->getMask(); 15924 SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end()); 15925 SDValue Op0 = Shuf->getOperand(0); 15926 SDValue Op1 = Shuf->getOperand(1); 15927 int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask); 15928 if (ShufOp0Index == -1) { 15929 // Commute mask and check again. 15930 ShuffleVectorSDNode::commuteMask(CommutedMask); 15931 ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask); 15932 if (ShufOp0Index == -1) 15933 return SDValue(); 15934 // Commute operands to match the commuted shuffle mask. 15935 std::swap(Op0, Op1); 15936 Mask = CommutedMask; 15937 } 15938 15939 // The shuffle inserts exactly one element from operand 0 into operand 1. 15940 // Now see if we can access that element as a scalar via a real insert element 15941 // instruction. 15942 // TODO: We can try harder to locate the element as a scalar. Examples: it 15943 // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant. 15944 assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() && 15945 "Shuffle mask value must be from operand 0"); 15946 if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT) 15947 return SDValue(); 15948 15949 auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2)); 15950 if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index]) 15951 return SDValue(); 15952 15953 // There's an existing insertelement with constant insertion index, so we 15954 // don't need to check the legality/profitability of a replacement operation 15955 // that differs at most in the constant value. The target should be able to 15956 // lower any of those in a similar way. If not, legalization will expand this 15957 // to a scalar-to-vector plus shuffle. 15958 // 15959 // Note that the shuffle may move the scalar from the position that the insert 15960 // element used. Therefore, our new insert element occurs at the shuffle's 15961 // mask index value, not the insert's index value. 15962 // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C' 15963 SDValue NewInsIndex = DAG.getConstant(ShufOp0Index, SDLoc(Shuf), 15964 Op0.getOperand(2).getValueType()); 15965 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(), 15966 Op1, Op0.getOperand(1), NewInsIndex); 15967 } 15968 15969 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 15970 EVT VT = N->getValueType(0); 15971 unsigned NumElts = VT.getVectorNumElements(); 15972 15973 SDValue N0 = N->getOperand(0); 15974 SDValue N1 = N->getOperand(1); 15975 15976 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 15977 15978 // Canonicalize shuffle undef, undef -> undef 15979 if (N0.isUndef() && N1.isUndef()) 15980 return DAG.getUNDEF(VT); 15981 15982 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 15983 15984 // Canonicalize shuffle v, v -> v, undef 15985 if (N0 == N1) { 15986 SmallVector<int, 8> NewMask; 15987 for (unsigned i = 0; i != NumElts; ++i) { 15988 int Idx = SVN->getMaskElt(i); 15989 if (Idx >= (int)NumElts) Idx -= NumElts; 15990 NewMask.push_back(Idx); 15991 } 15992 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 15993 } 15994 15995 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 15996 if (N0.isUndef()) 15997 return DAG.getCommutedVectorShuffle(*SVN); 15998 15999 // Remove references to rhs if it is undef 16000 if (N1.isUndef()) { 16001 bool Changed = false; 16002 SmallVector<int, 8> NewMask; 16003 for (unsigned i = 0; i != NumElts; ++i) { 16004 int Idx = SVN->getMaskElt(i); 16005 if (Idx >= (int)NumElts) { 16006 Idx = -1; 16007 Changed = true; 16008 } 16009 NewMask.push_back(Idx); 16010 } 16011 if (Changed) 16012 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 16013 } 16014 16015 // Simplify shuffle mask if a referenced element is UNDEF. 16016 if (SDValue V = simplifyShuffleMask(SVN, N0, N1, DAG)) 16017 return V; 16018 16019 if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG)) 16020 return InsElt; 16021 16022 // A shuffle of a single vector that is a splat can always be folded. 16023 if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0)) 16024 if (N1->isUndef() && N0Shuf->isSplat()) 16025 return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG); 16026 16027 // If it is a splat, check if the argument vector is another splat or a 16028 // build_vector. 16029 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 16030 SDNode *V = N0.getNode(); 16031 16032 // If this is a bit convert that changes the element type of the vector but 16033 // not the number of vector elements, look through it. Be careful not to 16034 // look though conversions that change things like v4f32 to v2f64. 16035 if (V->getOpcode() == ISD::BITCAST) { 16036 SDValue ConvInput = V->getOperand(0); 16037 if (ConvInput.getValueType().isVector() && 16038 ConvInput.getValueType().getVectorNumElements() == NumElts) 16039 V = ConvInput.getNode(); 16040 } 16041 16042 if (V->getOpcode() == ISD::BUILD_VECTOR) { 16043 assert(V->getNumOperands() == NumElts && 16044 "BUILD_VECTOR has wrong number of operands"); 16045 SDValue Base; 16046 bool AllSame = true; 16047 for (unsigned i = 0; i != NumElts; ++i) { 16048 if (!V->getOperand(i).isUndef()) { 16049 Base = V->getOperand(i); 16050 break; 16051 } 16052 } 16053 // Splat of <u, u, u, u>, return <u, u, u, u> 16054 if (!Base.getNode()) 16055 return N0; 16056 for (unsigned i = 0; i != NumElts; ++i) { 16057 if (V->getOperand(i) != Base) { 16058 AllSame = false; 16059 break; 16060 } 16061 } 16062 // Splat of <x, x, x, x>, return <x, x, x, x> 16063 if (AllSame) 16064 return N0; 16065 16066 // Canonicalize any other splat as a build_vector. 16067 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 16068 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 16069 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 16070 16071 // We may have jumped through bitcasts, so the type of the 16072 // BUILD_VECTOR may not match the type of the shuffle. 16073 if (V->getValueType(0) != VT) 16074 NewBV = DAG.getBitcast(VT, NewBV); 16075 return NewBV; 16076 } 16077 } 16078 16079 // There are various patterns used to build up a vector from smaller vectors, 16080 // subvectors, or elements. Scan chains of these and replace unused insertions 16081 // or components with undef. 16082 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 16083 return S; 16084 16085 // Match shuffles that can be converted to any_vector_extend_in_reg. 16086 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations, LegalTypes)) 16087 return V; 16088 16089 // Combine "truncate_vector_in_reg" style shuffles. 16090 if (SDValue V = combineTruncationShuffle(SVN, DAG)) 16091 return V; 16092 16093 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 16094 Level < AfterLegalizeVectorOps && 16095 (N1.isUndef() || 16096 (N1.getOpcode() == ISD::CONCAT_VECTORS && 16097 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 16098 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 16099 return V; 16100 } 16101 16102 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 16103 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 16104 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 16105 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI)) 16106 return Res; 16107 16108 // If this shuffle only has a single input that is a bitcasted shuffle, 16109 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 16110 // back to their original types. 16111 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 16112 N1.isUndef() && Level < AfterLegalizeVectorOps && 16113 TLI.isTypeLegal(VT)) { 16114 16115 // Peek through the bitcast only if there is one user. 16116 SDValue BC0 = N0; 16117 while (BC0.getOpcode() == ISD::BITCAST) { 16118 if (!BC0.hasOneUse()) 16119 break; 16120 BC0 = BC0.getOperand(0); 16121 } 16122 16123 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 16124 if (Scale == 1) 16125 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 16126 16127 SmallVector<int, 8> NewMask; 16128 for (int M : Mask) 16129 for (int s = 0; s != Scale; ++s) 16130 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 16131 return NewMask; 16132 }; 16133 16134 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 16135 EVT SVT = VT.getScalarType(); 16136 EVT InnerVT = BC0->getValueType(0); 16137 EVT InnerSVT = InnerVT.getScalarType(); 16138 16139 // Determine which shuffle works with the smaller scalar type. 16140 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 16141 EVT ScaleSVT = ScaleVT.getScalarType(); 16142 16143 if (TLI.isTypeLegal(ScaleVT) && 16144 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 16145 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 16146 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 16147 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 16148 16149 // Scale the shuffle masks to the smaller scalar type. 16150 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 16151 SmallVector<int, 8> InnerMask = 16152 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 16153 SmallVector<int, 8> OuterMask = 16154 ScaleShuffleMask(SVN->getMask(), OuterScale); 16155 16156 // Merge the shuffle masks. 16157 SmallVector<int, 8> NewMask; 16158 for (int M : OuterMask) 16159 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 16160 16161 // Test for shuffle mask legality over both commutations. 16162 SDValue SV0 = BC0->getOperand(0); 16163 SDValue SV1 = BC0->getOperand(1); 16164 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 16165 if (!LegalMask) { 16166 std::swap(SV0, SV1); 16167 ShuffleVectorSDNode::commuteMask(NewMask); 16168 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 16169 } 16170 16171 if (LegalMask) { 16172 SV0 = DAG.getBitcast(ScaleVT, SV0); 16173 SV1 = DAG.getBitcast(ScaleVT, SV1); 16174 return DAG.getBitcast( 16175 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 16176 } 16177 } 16178 } 16179 } 16180 16181 // Canonicalize shuffles according to rules: 16182 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 16183 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 16184 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 16185 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 16186 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 16187 TLI.isTypeLegal(VT)) { 16188 // The incoming shuffle must be of the same type as the result of the 16189 // current shuffle. 16190 assert(N1->getOperand(0).getValueType() == VT && 16191 "Shuffle types don't match"); 16192 16193 SDValue SV0 = N1->getOperand(0); 16194 SDValue SV1 = N1->getOperand(1); 16195 bool HasSameOp0 = N0 == SV0; 16196 bool IsSV1Undef = SV1.isUndef(); 16197 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 16198 // Commute the operands of this shuffle so that next rule 16199 // will trigger. 16200 return DAG.getCommutedVectorShuffle(*SVN); 16201 } 16202 16203 // Try to fold according to rules: 16204 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 16205 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 16206 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 16207 // Don't try to fold shuffles with illegal type. 16208 // Only fold if this shuffle is the only user of the other shuffle. 16209 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 16210 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 16211 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 16212 16213 // Don't try to fold splats; they're likely to simplify somehow, or they 16214 // might be free. 16215 if (OtherSV->isSplat()) 16216 return SDValue(); 16217 16218 // The incoming shuffle must be of the same type as the result of the 16219 // current shuffle. 16220 assert(OtherSV->getOperand(0).getValueType() == VT && 16221 "Shuffle types don't match"); 16222 16223 SDValue SV0, SV1; 16224 SmallVector<int, 4> Mask; 16225 // Compute the combined shuffle mask for a shuffle with SV0 as the first 16226 // operand, and SV1 as the second operand. 16227 for (unsigned i = 0; i != NumElts; ++i) { 16228 int Idx = SVN->getMaskElt(i); 16229 if (Idx < 0) { 16230 // Propagate Undef. 16231 Mask.push_back(Idx); 16232 continue; 16233 } 16234 16235 SDValue CurrentVec; 16236 if (Idx < (int)NumElts) { 16237 // This shuffle index refers to the inner shuffle N0. Lookup the inner 16238 // shuffle mask to identify which vector is actually referenced. 16239 Idx = OtherSV->getMaskElt(Idx); 16240 if (Idx < 0) { 16241 // Propagate Undef. 16242 Mask.push_back(Idx); 16243 continue; 16244 } 16245 16246 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 16247 : OtherSV->getOperand(1); 16248 } else { 16249 // This shuffle index references an element within N1. 16250 CurrentVec = N1; 16251 } 16252 16253 // Simple case where 'CurrentVec' is UNDEF. 16254 if (CurrentVec.isUndef()) { 16255 Mask.push_back(-1); 16256 continue; 16257 } 16258 16259 // Canonicalize the shuffle index. We don't know yet if CurrentVec 16260 // will be the first or second operand of the combined shuffle. 16261 Idx = Idx % NumElts; 16262 if (!SV0.getNode() || SV0 == CurrentVec) { 16263 // Ok. CurrentVec is the left hand side. 16264 // Update the mask accordingly. 16265 SV0 = CurrentVec; 16266 Mask.push_back(Idx); 16267 continue; 16268 } 16269 16270 // Bail out if we cannot convert the shuffle pair into a single shuffle. 16271 if (SV1.getNode() && SV1 != CurrentVec) 16272 return SDValue(); 16273 16274 // Ok. CurrentVec is the right hand side. 16275 // Update the mask accordingly. 16276 SV1 = CurrentVec; 16277 Mask.push_back(Idx + NumElts); 16278 } 16279 16280 // Check if all indices in Mask are Undef. In case, propagate Undef. 16281 bool isUndefMask = true; 16282 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 16283 isUndefMask &= Mask[i] < 0; 16284 16285 if (isUndefMask) 16286 return DAG.getUNDEF(VT); 16287 16288 if (!SV0.getNode()) 16289 SV0 = DAG.getUNDEF(VT); 16290 if (!SV1.getNode()) 16291 SV1 = DAG.getUNDEF(VT); 16292 16293 // Avoid introducing shuffles with illegal mask. 16294 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 16295 ShuffleVectorSDNode::commuteMask(Mask); 16296 16297 if (!TLI.isShuffleMaskLegal(Mask, VT)) 16298 return SDValue(); 16299 16300 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 16301 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 16302 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 16303 std::swap(SV0, SV1); 16304 } 16305 16306 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 16307 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 16308 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 16309 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask); 16310 } 16311 16312 return SDValue(); 16313 } 16314 16315 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 16316 SDValue InVal = N->getOperand(0); 16317 EVT VT = N->getValueType(0); 16318 16319 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 16320 // with a VECTOR_SHUFFLE and possible truncate. 16321 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 16322 SDValue InVec = InVal->getOperand(0); 16323 SDValue EltNo = InVal->getOperand(1); 16324 auto InVecT = InVec.getValueType(); 16325 if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) { 16326 SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1); 16327 int Elt = C0->getZExtValue(); 16328 NewMask[0] = Elt; 16329 SDValue Val; 16330 // If we have an implict truncate do truncate here as long as it's legal. 16331 // if it's not legal, this should 16332 if (VT.getScalarType() != InVal.getValueType() && 16333 InVal.getValueType().isScalarInteger() && 16334 isTypeLegal(VT.getScalarType())) { 16335 Val = 16336 DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal); 16337 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val); 16338 } 16339 if (VT.getScalarType() == InVecT.getScalarType() && 16340 VT.getVectorNumElements() <= InVecT.getVectorNumElements() && 16341 TLI.isShuffleMaskLegal(NewMask, VT)) { 16342 Val = DAG.getVectorShuffle(InVecT, SDLoc(N), InVec, 16343 DAG.getUNDEF(InVecT), NewMask); 16344 // If the initial vector is the correct size this shuffle is a 16345 // valid result. 16346 if (VT == InVecT) 16347 return Val; 16348 // If not we must truncate the vector. 16349 if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) { 16350 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 16351 SDValue ZeroIdx = DAG.getConstant(0, SDLoc(N), IdxTy); 16352 EVT SubVT = 16353 EVT::getVectorVT(*DAG.getContext(), InVecT.getVectorElementType(), 16354 VT.getVectorNumElements()); 16355 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, Val, 16356 ZeroIdx); 16357 return Val; 16358 } 16359 } 16360 } 16361 } 16362 16363 return SDValue(); 16364 } 16365 16366 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 16367 EVT VT = N->getValueType(0); 16368 SDValue N0 = N->getOperand(0); 16369 SDValue N1 = N->getOperand(1); 16370 SDValue N2 = N->getOperand(2); 16371 16372 // If inserting an UNDEF, just return the original vector. 16373 if (N1.isUndef()) 16374 return N0; 16375 16376 // For nested INSERT_SUBVECTORs, attempt to combine inner node first to allow 16377 // us to pull BITCASTs from input to output. 16378 if (N0.hasOneUse() && N0->getOpcode() == ISD::INSERT_SUBVECTOR) 16379 if (SDValue NN0 = visitINSERT_SUBVECTOR(N0.getNode())) 16380 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, NN0, N1, N2); 16381 16382 // If this is an insert of an extracted vector into an undef vector, we can 16383 // just use the input to the extract. 16384 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 16385 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT) 16386 return N1.getOperand(0); 16387 16388 // If we are inserting a bitcast value into an undef, with the same 16389 // number of elements, just use the bitcast input of the extract. 16390 // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 -> 16391 // BITCAST (INSERT_SUBVECTOR UNDEF N1 N2) 16392 if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST && 16393 N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR && 16394 N1.getOperand(0).getOperand(1) == N2 && 16395 N1.getOperand(0).getOperand(0).getValueType().getVectorNumElements() == 16396 VT.getVectorNumElements()) { 16397 return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0)); 16398 } 16399 16400 // If both N1 and N2 are bitcast values on which insert_subvector 16401 // would makes sense, pull the bitcast through. 16402 // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 -> 16403 // BITCAST (INSERT_SUBVECTOR N0 N1 N2) 16404 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) { 16405 SDValue CN0 = N0.getOperand(0); 16406 SDValue CN1 = N1.getOperand(0); 16407 if (CN0.getValueType().getVectorElementType() == 16408 CN1.getValueType().getVectorElementType() && 16409 CN0.getValueType().getVectorNumElements() == 16410 VT.getVectorNumElements()) { 16411 SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), 16412 CN0.getValueType(), CN0, CN1, N2); 16413 return DAG.getBitcast(VT, NewINSERT); 16414 } 16415 } 16416 16417 // Combine INSERT_SUBVECTORs where we are inserting to the same index. 16418 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) 16419 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) 16420 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && 16421 N0.getOperand(1).getValueType() == N1.getValueType() && 16422 N0.getOperand(2) == N2) 16423 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), 16424 N1, N2); 16425 16426 if (!isa<ConstantSDNode>(N2)) 16427 return SDValue(); 16428 16429 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue(); 16430 16431 // Canonicalize insert_subvector dag nodes. 16432 // Example: 16433 // (insert_subvector (insert_subvector A, Idx0), Idx1) 16434 // -> (insert_subvector (insert_subvector A, Idx1), Idx0) 16435 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() && 16436 N1.getValueType() == N0.getOperand(1).getValueType() && 16437 isa<ConstantSDNode>(N0.getOperand(2))) { 16438 unsigned OtherIdx = N0.getConstantOperandVal(2); 16439 if (InsIdx < OtherIdx) { 16440 // Swap nodes. 16441 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, 16442 N0.getOperand(0), N1, N2); 16443 AddToWorklist(NewOp.getNode()); 16444 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()), 16445 VT, NewOp, N0.getOperand(1), N0.getOperand(2)); 16446 } 16447 } 16448 16449 // If the input vector is a concatenation, and the insert replaces 16450 // one of the pieces, we can optimize into a single concat_vectors. 16451 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() && 16452 N0.getOperand(0).getValueType() == N1.getValueType()) { 16453 unsigned Factor = N1.getValueType().getVectorNumElements(); 16454 16455 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end()); 16456 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1; 16457 16458 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 16459 } 16460 16461 return SDValue(); 16462 } 16463 16464 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 16465 SDValue N0 = N->getOperand(0); 16466 16467 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 16468 if (N0->getOpcode() == ISD::FP16_TO_FP) 16469 return N0->getOperand(0); 16470 16471 return SDValue(); 16472 } 16473 16474 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 16475 SDValue N0 = N->getOperand(0); 16476 16477 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 16478 if (N0->getOpcode() == ISD::AND) { 16479 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 16480 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 16481 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 16482 N0.getOperand(0)); 16483 } 16484 } 16485 16486 return SDValue(); 16487 } 16488 16489 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 16490 /// with the destination vector and a zero vector. 16491 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 16492 /// vector_shuffle V, Zero, <0, 4, 2, 4> 16493 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 16494 assert(N->getOpcode() == ISD::AND && "Unexpected opcode!"); 16495 16496 EVT VT = N->getValueType(0); 16497 SDValue LHS = N->getOperand(0); 16498 SDValue RHS = peekThroughBitcast(N->getOperand(1)); 16499 SDLoc DL(N); 16500 16501 // Make sure we're not running after operation legalization where it 16502 // may have custom lowered the vector shuffles. 16503 if (LegalOperations) 16504 return SDValue(); 16505 16506 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 16507 return SDValue(); 16508 16509 EVT RVT = RHS.getValueType(); 16510 unsigned NumElts = RHS.getNumOperands(); 16511 16512 // Attempt to create a valid clear mask, splitting the mask into 16513 // sub elements and checking to see if each is 16514 // all zeros or all ones - suitable for shuffle masking. 16515 auto BuildClearMask = [&](int Split) { 16516 int NumSubElts = NumElts * Split; 16517 int NumSubBits = RVT.getScalarSizeInBits() / Split; 16518 16519 SmallVector<int, 8> Indices; 16520 for (int i = 0; i != NumSubElts; ++i) { 16521 int EltIdx = i / Split; 16522 int SubIdx = i % Split; 16523 SDValue Elt = RHS.getOperand(EltIdx); 16524 if (Elt.isUndef()) { 16525 Indices.push_back(-1); 16526 continue; 16527 } 16528 16529 APInt Bits; 16530 if (isa<ConstantSDNode>(Elt)) 16531 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 16532 else if (isa<ConstantFPSDNode>(Elt)) 16533 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 16534 else 16535 return SDValue(); 16536 16537 // Extract the sub element from the constant bit mask. 16538 if (DAG.getDataLayout().isBigEndian()) { 16539 Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits); 16540 } else { 16541 Bits.lshrInPlace(SubIdx * NumSubBits); 16542 } 16543 16544 if (Split > 1) 16545 Bits = Bits.trunc(NumSubBits); 16546 16547 if (Bits.isAllOnesValue()) 16548 Indices.push_back(i); 16549 else if (Bits == 0) 16550 Indices.push_back(i + NumSubElts); 16551 else 16552 return SDValue(); 16553 } 16554 16555 // Let's see if the target supports this vector_shuffle. 16556 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 16557 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 16558 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 16559 return SDValue(); 16560 16561 SDValue Zero = DAG.getConstant(0, DL, ClearVT); 16562 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL, 16563 DAG.getBitcast(ClearVT, LHS), 16564 Zero, Indices)); 16565 }; 16566 16567 // Determine maximum split level (byte level masking). 16568 int MaxSplit = 1; 16569 if (RVT.getScalarSizeInBits() % 8 == 0) 16570 MaxSplit = RVT.getScalarSizeInBits() / 8; 16571 16572 for (int Split = 1; Split <= MaxSplit; ++Split) 16573 if (RVT.getScalarSizeInBits() % Split == 0) 16574 if (SDValue S = BuildClearMask(Split)) 16575 return S; 16576 16577 return SDValue(); 16578 } 16579 16580 /// Visit a binary vector operation, like ADD. 16581 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 16582 assert(N->getValueType(0).isVector() && 16583 "SimplifyVBinOp only works on vectors!"); 16584 16585 SDValue LHS = N->getOperand(0); 16586 SDValue RHS = N->getOperand(1); 16587 SDValue Ops[] = {LHS, RHS}; 16588 16589 // See if we can constant fold the vector operation. 16590 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 16591 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 16592 return Fold; 16593 16594 // Type legalization might introduce new shuffles in the DAG. 16595 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 16596 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 16597 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 16598 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 16599 LHS.getOperand(1).isUndef() && 16600 RHS.getOperand(1).isUndef()) { 16601 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 16602 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 16603 16604 if (SVN0->getMask().equals(SVN1->getMask())) { 16605 EVT VT = N->getValueType(0); 16606 SDValue UndefVector = LHS.getOperand(1); 16607 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 16608 LHS.getOperand(0), RHS.getOperand(0), 16609 N->getFlags()); 16610 AddUsersToWorklist(N); 16611 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 16612 SVN0->getMask()); 16613 } 16614 } 16615 16616 return SDValue(); 16617 } 16618 16619 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 16620 SDValue N2) { 16621 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 16622 16623 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 16624 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 16625 16626 // If we got a simplified select_cc node back from SimplifySelectCC, then 16627 // break it down into a new SETCC node, and a new SELECT node, and then return 16628 // the SELECT node, since we were called with a SELECT node. 16629 if (SCC.getNode()) { 16630 // Check to see if we got a select_cc back (to turn into setcc/select). 16631 // Otherwise, just return whatever node we got back, like fabs. 16632 if (SCC.getOpcode() == ISD::SELECT_CC) { 16633 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 16634 N0.getValueType(), 16635 SCC.getOperand(0), SCC.getOperand(1), 16636 SCC.getOperand(4)); 16637 AddToWorklist(SETCC.getNode()); 16638 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 16639 SCC.getOperand(2), SCC.getOperand(3)); 16640 } 16641 16642 return SCC; 16643 } 16644 return SDValue(); 16645 } 16646 16647 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 16648 /// being selected between, see if we can simplify the select. Callers of this 16649 /// should assume that TheSelect is deleted if this returns true. As such, they 16650 /// should return the appropriate thing (e.g. the node) back to the top-level of 16651 /// the DAG combiner loop to avoid it being looked at. 16652 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 16653 SDValue RHS) { 16654 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 16655 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 16656 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 16657 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 16658 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 16659 SDValue Sqrt = RHS; 16660 ISD::CondCode CC; 16661 SDValue CmpLHS; 16662 const ConstantFPSDNode *Zero = nullptr; 16663 16664 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 16665 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 16666 CmpLHS = TheSelect->getOperand(0); 16667 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 16668 } else { 16669 // SELECT or VSELECT 16670 SDValue Cmp = TheSelect->getOperand(0); 16671 if (Cmp.getOpcode() == ISD::SETCC) { 16672 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 16673 CmpLHS = Cmp.getOperand(0); 16674 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 16675 } 16676 } 16677 if (Zero && Zero->isZero() && 16678 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 16679 CC == ISD::SETULT || CC == ISD::SETLT)) { 16680 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 16681 CombineTo(TheSelect, Sqrt); 16682 return true; 16683 } 16684 } 16685 } 16686 // Cannot simplify select with vector condition 16687 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 16688 16689 // If this is a select from two identical things, try to pull the operation 16690 // through the select. 16691 if (LHS.getOpcode() != RHS.getOpcode() || 16692 !LHS.hasOneUse() || !RHS.hasOneUse()) 16693 return false; 16694 16695 // If this is a load and the token chain is identical, replace the select 16696 // of two loads with a load through a select of the address to load from. 16697 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 16698 // constants have been dropped into the constant pool. 16699 if (LHS.getOpcode() == ISD::LOAD) { 16700 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 16701 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 16702 16703 // Token chains must be identical. 16704 if (LHS.getOperand(0) != RHS.getOperand(0) || 16705 // Do not let this transformation reduce the number of volatile loads. 16706 LLD->isVolatile() || RLD->isVolatile() || 16707 // FIXME: If either is a pre/post inc/dec load, 16708 // we'd need to split out the address adjustment. 16709 LLD->isIndexed() || RLD->isIndexed() || 16710 // If this is an EXTLOAD, the VT's must match. 16711 LLD->getMemoryVT() != RLD->getMemoryVT() || 16712 // If this is an EXTLOAD, the kind of extension must match. 16713 (LLD->getExtensionType() != RLD->getExtensionType() && 16714 // The only exception is if one of the extensions is anyext. 16715 LLD->getExtensionType() != ISD::EXTLOAD && 16716 RLD->getExtensionType() != ISD::EXTLOAD) || 16717 // FIXME: this discards src value information. This is 16718 // over-conservative. It would be beneficial to be able to remember 16719 // both potential memory locations. Since we are discarding 16720 // src value info, don't do the transformation if the memory 16721 // locations are not in the default address space. 16722 LLD->getPointerInfo().getAddrSpace() != 0 || 16723 RLD->getPointerInfo().getAddrSpace() != 0 || 16724 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 16725 LLD->getBasePtr().getValueType())) 16726 return false; 16727 16728 // Check that the select condition doesn't reach either load. If so, 16729 // folding this will induce a cycle into the DAG. If not, this is safe to 16730 // xform, so create a select of the addresses. 16731 SDValue Addr; 16732 if (TheSelect->getOpcode() == ISD::SELECT) { 16733 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 16734 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 16735 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 16736 return false; 16737 // The loads must not depend on one another. 16738 if (LLD->isPredecessorOf(RLD) || 16739 RLD->isPredecessorOf(LLD)) 16740 return false; 16741 Addr = DAG.getSelect(SDLoc(TheSelect), 16742 LLD->getBasePtr().getValueType(), 16743 TheSelect->getOperand(0), LLD->getBasePtr(), 16744 RLD->getBasePtr()); 16745 } else { // Otherwise SELECT_CC 16746 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 16747 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 16748 16749 if ((LLD->hasAnyUseOfValue(1) && 16750 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 16751 (RLD->hasAnyUseOfValue(1) && 16752 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 16753 return false; 16754 16755 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 16756 LLD->getBasePtr().getValueType(), 16757 TheSelect->getOperand(0), 16758 TheSelect->getOperand(1), 16759 LLD->getBasePtr(), RLD->getBasePtr(), 16760 TheSelect->getOperand(4)); 16761 } 16762 16763 SDValue Load; 16764 // It is safe to replace the two loads if they have different alignments, 16765 // but the new load must be the minimum (most restrictive) alignment of the 16766 // inputs. 16767 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 16768 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 16769 if (!RLD->isInvariant()) 16770 MMOFlags &= ~MachineMemOperand::MOInvariant; 16771 if (!RLD->isDereferenceable()) 16772 MMOFlags &= ~MachineMemOperand::MODereferenceable; 16773 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 16774 // FIXME: Discards pointer and AA info. 16775 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 16776 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 16777 MMOFlags); 16778 } else { 16779 // FIXME: Discards pointer and AA info. 16780 Load = DAG.getExtLoad( 16781 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 16782 : LLD->getExtensionType(), 16783 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 16784 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 16785 } 16786 16787 // Users of the select now use the result of the load. 16788 CombineTo(TheSelect, Load); 16789 16790 // Users of the old loads now use the new load's chain. We know the 16791 // old-load value is dead now. 16792 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 16793 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 16794 return true; 16795 } 16796 16797 return false; 16798 } 16799 16800 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and 16801 /// bitwise 'and'. 16802 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, 16803 SDValue N1, SDValue N2, SDValue N3, 16804 ISD::CondCode CC) { 16805 // If this is a select where the false operand is zero and the compare is a 16806 // check of the sign bit, see if we can perform the "gzip trick": 16807 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A 16808 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A 16809 EVT XType = N0.getValueType(); 16810 EVT AType = N2.getValueType(); 16811 if (!isNullConstant(N3) || !XType.bitsGE(AType)) 16812 return SDValue(); 16813 16814 // If the comparison is testing for a positive value, we have to invert 16815 // the sign bit mask, so only do that transform if the target has a bitwise 16816 // 'and not' instruction (the invert is free). 16817 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) { 16818 // (X > -1) ? A : 0 16819 // (X > 0) ? X : 0 <-- This is canonical signed max. 16820 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2))) 16821 return SDValue(); 16822 } else if (CC == ISD::SETLT) { 16823 // (X < 0) ? A : 0 16824 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min. 16825 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2))) 16826 return SDValue(); 16827 } else { 16828 return SDValue(); 16829 } 16830 16831 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit 16832 // constant. 16833 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 16834 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 16835 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 16836 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1; 16837 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); 16838 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt); 16839 AddToWorklist(Shift.getNode()); 16840 16841 if (XType.bitsGT(AType)) { 16842 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 16843 AddToWorklist(Shift.getNode()); 16844 } 16845 16846 if (CC == ISD::SETGT) 16847 Shift = DAG.getNOT(DL, Shift, AType); 16848 16849 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 16850 } 16851 16852 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy); 16853 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt); 16854 AddToWorklist(Shift.getNode()); 16855 16856 if (XType.bitsGT(AType)) { 16857 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 16858 AddToWorklist(Shift.getNode()); 16859 } 16860 16861 if (CC == ISD::SETGT) 16862 Shift = DAG.getNOT(DL, Shift, AType); 16863 16864 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 16865 } 16866 16867 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 16868 /// where 'cond' is the comparison specified by CC. 16869 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 16870 SDValue N2, SDValue N3, ISD::CondCode CC, 16871 bool NotExtCompare) { 16872 // (x ? y : y) -> y. 16873 if (N2 == N3) return N2; 16874 16875 EVT VT = N2.getValueType(); 16876 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 16877 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 16878 16879 // Determine if the condition we're dealing with is constant 16880 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 16881 N0, N1, CC, DL, false); 16882 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 16883 16884 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 16885 // fold select_cc true, x, y -> x 16886 // fold select_cc false, x, y -> y 16887 return !SCCC->isNullValue() ? N2 : N3; 16888 } 16889 16890 // Check to see if we can simplify the select into an fabs node 16891 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 16892 // Allow either -0.0 or 0.0 16893 if (CFP->isZero()) { 16894 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 16895 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 16896 N0 == N2 && N3.getOpcode() == ISD::FNEG && 16897 N2 == N3.getOperand(0)) 16898 return DAG.getNode(ISD::FABS, DL, VT, N0); 16899 16900 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 16901 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 16902 N0 == N3 && N2.getOpcode() == ISD::FNEG && 16903 N2.getOperand(0) == N3) 16904 return DAG.getNode(ISD::FABS, DL, VT, N3); 16905 } 16906 } 16907 16908 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 16909 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 16910 // in it. This is a win when the constant is not otherwise available because 16911 // it replaces two constant pool loads with one. We only do this if the FP 16912 // type is known to be legal, because if it isn't, then we are before legalize 16913 // types an we want the other legalization to happen first (e.g. to avoid 16914 // messing with soft float) and if the ConstantFP is not legal, because if 16915 // it is legal, we may not need to store the FP constant in a constant pool. 16916 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 16917 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 16918 if (TLI.isTypeLegal(N2.getValueType()) && 16919 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 16920 TargetLowering::Legal && 16921 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 16922 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 16923 // If both constants have multiple uses, then we won't need to do an 16924 // extra load, they are likely around in registers for other users. 16925 (TV->hasOneUse() || FV->hasOneUse())) { 16926 Constant *Elts[] = { 16927 const_cast<ConstantFP*>(FV->getConstantFPValue()), 16928 const_cast<ConstantFP*>(TV->getConstantFPValue()) 16929 }; 16930 Type *FPTy = Elts[0]->getType(); 16931 const DataLayout &TD = DAG.getDataLayout(); 16932 16933 // Create a ConstantArray of the two constants. 16934 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 16935 SDValue CPIdx = 16936 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 16937 TD.getPrefTypeAlignment(FPTy)); 16938 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 16939 16940 // Get the offsets to the 0 and 1 element of the array so that we can 16941 // select between them. 16942 SDValue Zero = DAG.getIntPtrConstant(0, DL); 16943 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 16944 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 16945 16946 SDValue Cond = DAG.getSetCC(DL, 16947 getSetCCResultType(N0.getValueType()), 16948 N0, N1, CC); 16949 AddToWorklist(Cond.getNode()); 16950 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 16951 Cond, One, Zero); 16952 AddToWorklist(CstOffset.getNode()); 16953 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 16954 CstOffset); 16955 AddToWorklist(CPIdx.getNode()); 16956 return DAG.getLoad( 16957 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 16958 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 16959 Alignment); 16960 } 16961 } 16962 16963 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC)) 16964 return V; 16965 16966 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 16967 // where y is has a single bit set. 16968 // A plaintext description would be, we can turn the SELECT_CC into an AND 16969 // when the condition can be materialized as an all-ones register. Any 16970 // single bit-test can be materialized as an all-ones register with 16971 // shift-left and shift-right-arith. 16972 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 16973 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 16974 SDValue AndLHS = N0->getOperand(0); 16975 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 16976 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 16977 // Shift the tested bit over the sign bit. 16978 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 16979 SDValue ShlAmt = 16980 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 16981 getShiftAmountTy(AndLHS.getValueType())); 16982 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 16983 16984 // Now arithmetic right shift it all the way over, so the result is either 16985 // all-ones, or zero. 16986 SDValue ShrAmt = 16987 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 16988 getShiftAmountTy(Shl.getValueType())); 16989 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 16990 16991 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 16992 } 16993 } 16994 16995 // fold select C, 16, 0 -> shl C, 4 16996 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 16997 TLI.getBooleanContents(N0.getValueType()) == 16998 TargetLowering::ZeroOrOneBooleanContent) { 16999 17000 // If the caller doesn't want us to simplify this into a zext of a compare, 17001 // don't do it. 17002 if (NotExtCompare && N2C->isOne()) 17003 return SDValue(); 17004 17005 // Get a SetCC of the condition 17006 // NOTE: Don't create a SETCC if it's not legal on this target. 17007 if (!LegalOperations || 17008 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 17009 SDValue Temp, SCC; 17010 // cast from setcc result type to select result type 17011 if (LegalTypes) { 17012 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 17013 N0, N1, CC); 17014 if (N2.getValueType().bitsLT(SCC.getValueType())) 17015 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 17016 N2.getValueType()); 17017 else 17018 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 17019 N2.getValueType(), SCC); 17020 } else { 17021 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 17022 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 17023 N2.getValueType(), SCC); 17024 } 17025 17026 AddToWorklist(SCC.getNode()); 17027 AddToWorklist(Temp.getNode()); 17028 17029 if (N2C->isOne()) 17030 return Temp; 17031 17032 // shl setcc result by log2 n2c 17033 return DAG.getNode( 17034 ISD::SHL, DL, N2.getValueType(), Temp, 17035 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 17036 getShiftAmountTy(Temp.getValueType()))); 17037 } 17038 } 17039 17040 // Check to see if this is an integer abs. 17041 // select_cc setg[te] X, 0, X, -X -> 17042 // select_cc setgt X, -1, X, -X -> 17043 // select_cc setl[te] X, 0, -X, X -> 17044 // select_cc setlt X, 1, -X, X -> 17045 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 17046 if (N1C) { 17047 ConstantSDNode *SubC = nullptr; 17048 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 17049 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 17050 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 17051 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 17052 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 17053 (N1C->isOne() && CC == ISD::SETLT)) && 17054 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 17055 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 17056 17057 EVT XType = N0.getValueType(); 17058 if (SubC && SubC->isNullValue() && XType.isInteger()) { 17059 SDLoc DL(N0); 17060 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 17061 N0, 17062 DAG.getConstant(XType.getSizeInBits() - 1, DL, 17063 getShiftAmountTy(N0.getValueType()))); 17064 SDValue Add = DAG.getNode(ISD::ADD, DL, 17065 XType, N0, Shift); 17066 AddToWorklist(Shift.getNode()); 17067 AddToWorklist(Add.getNode()); 17068 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 17069 } 17070 } 17071 17072 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 17073 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 17074 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 17075 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 17076 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 17077 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 17078 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 17079 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 17080 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 17081 SDValue ValueOnZero = N2; 17082 SDValue Count = N3; 17083 // If the condition is NE instead of E, swap the operands. 17084 if (CC == ISD::SETNE) 17085 std::swap(ValueOnZero, Count); 17086 // Check if the value on zero is a constant equal to the bits in the type. 17087 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 17088 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 17089 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 17090 // legal, combine to just cttz. 17091 if ((Count.getOpcode() == ISD::CTTZ || 17092 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 17093 N0 == Count.getOperand(0) && 17094 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 17095 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 17096 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 17097 // legal, combine to just ctlz. 17098 if ((Count.getOpcode() == ISD::CTLZ || 17099 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 17100 N0 == Count.getOperand(0) && 17101 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 17102 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 17103 } 17104 } 17105 } 17106 17107 return SDValue(); 17108 } 17109 17110 /// This is a stub for TargetLowering::SimplifySetCC. 17111 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 17112 ISD::CondCode Cond, const SDLoc &DL, 17113 bool foldBooleans) { 17114 TargetLowering::DAGCombinerInfo 17115 DagCombineInfo(DAG, Level, false, this); 17116 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 17117 } 17118 17119 /// Given an ISD::SDIV node expressing a divide by constant, return 17120 /// a DAG expression to select that will generate the same value by multiplying 17121 /// by a magic number. 17122 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 17123 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 17124 // when optimising for minimum size, we don't want to expand a div to a mul 17125 // and a shift. 17126 if (DAG.getMachineFunction().getFunction().optForMinSize()) 17127 return SDValue(); 17128 17129 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 17130 if (!C) 17131 return SDValue(); 17132 17133 // Avoid division by zero. 17134 if (C->isNullValue()) 17135 return SDValue(); 17136 17137 std::vector<SDNode *> Built; 17138 SDValue S = 17139 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 17140 17141 for (SDNode *N : Built) 17142 AddToWorklist(N); 17143 return S; 17144 } 17145 17146 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 17147 /// DAG expression that will generate the same value by right shifting. 17148 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 17149 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 17150 if (!C) 17151 return SDValue(); 17152 17153 // Avoid division by zero. 17154 if (C->isNullValue()) 17155 return SDValue(); 17156 17157 std::vector<SDNode *> Built; 17158 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 17159 17160 for (SDNode *N : Built) 17161 AddToWorklist(N); 17162 return S; 17163 } 17164 17165 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 17166 /// expression that will generate the same value by multiplying by a magic 17167 /// number. 17168 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 17169 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 17170 // when optimising for minimum size, we don't want to expand a div to a mul 17171 // and a shift. 17172 if (DAG.getMachineFunction().getFunction().optForMinSize()) 17173 return SDValue(); 17174 17175 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 17176 if (!C) 17177 return SDValue(); 17178 17179 // Avoid division by zero. 17180 if (C->isNullValue()) 17181 return SDValue(); 17182 17183 std::vector<SDNode *> Built; 17184 SDValue S = 17185 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 17186 17187 for (SDNode *N : Built) 17188 AddToWorklist(N); 17189 return S; 17190 } 17191 17192 /// Determines the LogBase2 value for a non-null input value using the 17193 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V). 17194 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) { 17195 EVT VT = V.getValueType(); 17196 unsigned EltBits = VT.getScalarSizeInBits(); 17197 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V); 17198 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT); 17199 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz); 17200 return LogBase2; 17201 } 17202 17203 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 17204 /// For the reciprocal, we need to find the zero of the function: 17205 /// F(X) = A X - 1 [which has a zero at X = 1/A] 17206 /// => 17207 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 17208 /// does not require additional intermediate precision] 17209 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) { 17210 if (Level >= AfterLegalizeDAG) 17211 return SDValue(); 17212 17213 // TODO: Handle half and/or extended types? 17214 EVT VT = Op.getValueType(); 17215 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 17216 return SDValue(); 17217 17218 // If estimates are explicitly disabled for this function, we're done. 17219 MachineFunction &MF = DAG.getMachineFunction(); 17220 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF); 17221 if (Enabled == TLI.ReciprocalEstimate::Disabled) 17222 return SDValue(); 17223 17224 // Estimates may be explicitly enabled for this type with a custom number of 17225 // refinement steps. 17226 int Iterations = TLI.getDivRefinementSteps(VT, MF); 17227 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) { 17228 AddToWorklist(Est.getNode()); 17229 17230 if (Iterations) { 17231 EVT VT = Op.getValueType(); 17232 SDLoc DL(Op); 17233 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 17234 17235 // Newton iterations: Est = Est + Est (1 - Arg * Est) 17236 for (int i = 0; i < Iterations; ++i) { 17237 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 17238 AddToWorklist(NewEst.getNode()); 17239 17240 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 17241 AddToWorklist(NewEst.getNode()); 17242 17243 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 17244 AddToWorklist(NewEst.getNode()); 17245 17246 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 17247 AddToWorklist(Est.getNode()); 17248 } 17249 } 17250 return Est; 17251 } 17252 17253 return SDValue(); 17254 } 17255 17256 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 17257 /// For the reciprocal sqrt, we need to find the zero of the function: 17258 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 17259 /// => 17260 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 17261 /// As a result, we precompute A/2 prior to the iteration loop. 17262 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 17263 unsigned Iterations, 17264 SDNodeFlags Flags, bool Reciprocal) { 17265 EVT VT = Arg.getValueType(); 17266 SDLoc DL(Arg); 17267 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 17268 17269 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 17270 // this entire sequence requires only one FP constant. 17271 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 17272 AddToWorklist(HalfArg.getNode()); 17273 17274 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 17275 AddToWorklist(HalfArg.getNode()); 17276 17277 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 17278 for (unsigned i = 0; i < Iterations; ++i) { 17279 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 17280 AddToWorklist(NewEst.getNode()); 17281 17282 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 17283 AddToWorklist(NewEst.getNode()); 17284 17285 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 17286 AddToWorklist(NewEst.getNode()); 17287 17288 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 17289 AddToWorklist(Est.getNode()); 17290 } 17291 17292 // If non-reciprocal square root is requested, multiply the result by Arg. 17293 if (!Reciprocal) { 17294 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 17295 AddToWorklist(Est.getNode()); 17296 } 17297 17298 return Est; 17299 } 17300 17301 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 17302 /// For the reciprocal sqrt, we need to find the zero of the function: 17303 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 17304 /// => 17305 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 17306 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 17307 unsigned Iterations, 17308 SDNodeFlags Flags, bool Reciprocal) { 17309 EVT VT = Arg.getValueType(); 17310 SDLoc DL(Arg); 17311 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 17312 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 17313 17314 // This routine must enter the loop below to work correctly 17315 // when (Reciprocal == false). 17316 assert(Iterations > 0); 17317 17318 // Newton iterations for reciprocal square root: 17319 // E = (E * -0.5) * ((A * E) * E + -3.0) 17320 for (unsigned i = 0; i < Iterations; ++i) { 17321 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 17322 AddToWorklist(AE.getNode()); 17323 17324 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 17325 AddToWorklist(AEE.getNode()); 17326 17327 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 17328 AddToWorklist(RHS.getNode()); 17329 17330 // When calculating a square root at the last iteration build: 17331 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 17332 // (notice a common subexpression) 17333 SDValue LHS; 17334 if (Reciprocal || (i + 1) < Iterations) { 17335 // RSQRT: LHS = (E * -0.5) 17336 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 17337 } else { 17338 // SQRT: LHS = (A * E) * -0.5 17339 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 17340 } 17341 AddToWorklist(LHS.getNode()); 17342 17343 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 17344 AddToWorklist(Est.getNode()); 17345 } 17346 17347 return Est; 17348 } 17349 17350 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 17351 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 17352 /// Op can be zero. 17353 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, 17354 bool Reciprocal) { 17355 if (Level >= AfterLegalizeDAG) 17356 return SDValue(); 17357 17358 // TODO: Handle half and/or extended types? 17359 EVT VT = Op.getValueType(); 17360 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 17361 return SDValue(); 17362 17363 // If estimates are explicitly disabled for this function, we're done. 17364 MachineFunction &MF = DAG.getMachineFunction(); 17365 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF); 17366 if (Enabled == TLI.ReciprocalEstimate::Disabled) 17367 return SDValue(); 17368 17369 // Estimates may be explicitly enabled for this type with a custom number of 17370 // refinement steps. 17371 int Iterations = TLI.getSqrtRefinementSteps(VT, MF); 17372 17373 bool UseOneConstNR = false; 17374 if (SDValue Est = 17375 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR, 17376 Reciprocal)) { 17377 AddToWorklist(Est.getNode()); 17378 17379 if (Iterations) { 17380 Est = UseOneConstNR 17381 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 17382 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 17383 17384 if (!Reciprocal) { 17385 // Unfortunately, Est is now NaN if the input was exactly 0.0. 17386 // Select out this case and force the answer to 0.0. 17387 EVT VT = Op.getValueType(); 17388 SDLoc DL(Op); 17389 17390 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 17391 EVT CCVT = getSetCCResultType(VT); 17392 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 17393 AddToWorklist(ZeroCmp.getNode()); 17394 17395 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 17396 ZeroCmp, FPZero, Est); 17397 AddToWorklist(Est.getNode()); 17398 } 17399 } 17400 return Est; 17401 } 17402 17403 return SDValue(); 17404 } 17405 17406 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) { 17407 return buildSqrtEstimateImpl(Op, Flags, true); 17408 } 17409 17410 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) { 17411 return buildSqrtEstimateImpl(Op, Flags, false); 17412 } 17413 17414 /// Return true if there is any possibility that the two addresses overlap. 17415 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 17416 // If they are the same then they must be aliases. 17417 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 17418 17419 // If they are both volatile then they cannot be reordered. 17420 if (Op0->isVolatile() && Op1->isVolatile()) return true; 17421 17422 // If one operation reads from invariant memory, and the other may store, they 17423 // cannot alias. These should really be checking the equivalent of mayWrite, 17424 // but it only matters for memory nodes other than load /store. 17425 if (Op0->isInvariant() && Op1->writeMem()) 17426 return false; 17427 17428 if (Op1->isInvariant() && Op0->writeMem()) 17429 return false; 17430 17431 unsigned NumBytes0 = Op0->getMemoryVT().getStoreSize(); 17432 unsigned NumBytes1 = Op1->getMemoryVT().getStoreSize(); 17433 17434 // Check for BaseIndexOffset matching. 17435 BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG); 17436 BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG); 17437 int64_t PtrDiff; 17438 if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff)) 17439 return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0)); 17440 17441 // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be 17442 // able to calculate their relative offset if at least one arises 17443 // from an alloca. However, these allocas cannot overlap and we 17444 // can infer there is no alias. 17445 if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase())) 17446 if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) { 17447 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 17448 // If the base are the same frame index but the we couldn't find a 17449 // constant offset, (indices are different) be conservative. 17450 if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) || 17451 !MFI.isFixedObjectIndex(B->getIndex()))) 17452 return false; 17453 } 17454 17455 bool IsFI0 = isa<FrameIndexSDNode>(BasePtr0.getBase()); 17456 bool IsFI1 = isa<FrameIndexSDNode>(BasePtr1.getBase()); 17457 bool IsGV0 = isa<GlobalAddressSDNode>(BasePtr0.getBase()); 17458 bool IsGV1 = isa<GlobalAddressSDNode>(BasePtr1.getBase()); 17459 bool IsCV0 = isa<ConstantPoolSDNode>(BasePtr0.getBase()); 17460 bool IsCV1 = isa<ConstantPoolSDNode>(BasePtr1.getBase()); 17461 17462 // If of mismatched base types or checkable indices we can check 17463 // they do not alias. 17464 if ((BasePtr0.getIndex() == BasePtr1.getIndex() || (IsFI0 != IsFI1) || 17465 (IsGV0 != IsGV1) || (IsCV0 != IsCV1)) && 17466 (IsFI0 || IsGV0 || IsCV0) && (IsFI1 || IsGV1 || IsCV1)) 17467 return false; 17468 17469 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 17470 // compared to the size and offset of the access, we may be able to prove they 17471 // do not alias. This check is conservative for now to catch cases created by 17472 // splitting vector types. 17473 int64_t SrcValOffset0 = Op0->getSrcValueOffset(); 17474 int64_t SrcValOffset1 = Op1->getSrcValueOffset(); 17475 unsigned OrigAlignment0 = Op0->getOriginalAlignment(); 17476 unsigned OrigAlignment1 = Op1->getOriginalAlignment(); 17477 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 && 17478 NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) { 17479 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0; 17480 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1; 17481 17482 // There is no overlap between these relatively aligned accesses of similar 17483 // size. Return no alias. 17484 if ((OffAlign0 + NumBytes0) <= OffAlign1 || 17485 (OffAlign1 + NumBytes1) <= OffAlign0) 17486 return false; 17487 } 17488 17489 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 17490 ? CombinerGlobalAA 17491 : DAG.getSubtarget().useAA(); 17492 #ifndef NDEBUG 17493 if (CombinerAAOnlyFunc.getNumOccurrences() && 17494 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 17495 UseAA = false; 17496 #endif 17497 17498 if (UseAA && AA && 17499 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 17500 // Use alias analysis information. 17501 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1); 17502 int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset; 17503 int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset; 17504 AliasResult AAResult = 17505 AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0, 17506 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 17507 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1, 17508 UseTBAA ? Op1->getAAInfo() : AAMDNodes()) ); 17509 if (AAResult == NoAlias) 17510 return false; 17511 } 17512 17513 // Otherwise we have to assume they alias. 17514 return true; 17515 } 17516 17517 /// Walk up chain skipping non-aliasing memory nodes, 17518 /// looking for aliasing nodes and adding them to the Aliases vector. 17519 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 17520 SmallVectorImpl<SDValue> &Aliases) { 17521 SmallVector<SDValue, 8> Chains; // List of chains to visit. 17522 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 17523 17524 // Get alias information for node. 17525 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 17526 17527 // Starting off. 17528 Chains.push_back(OriginalChain); 17529 unsigned Depth = 0; 17530 17531 // Look at each chain and determine if it is an alias. If so, add it to the 17532 // aliases list. If not, then continue up the chain looking for the next 17533 // candidate. 17534 while (!Chains.empty()) { 17535 SDValue Chain = Chains.pop_back_val(); 17536 17537 // For TokenFactor nodes, look at each operand and only continue up the 17538 // chain until we reach the depth limit. 17539 // 17540 // FIXME: The depth check could be made to return the last non-aliasing 17541 // chain we found before we hit a tokenfactor rather than the original 17542 // chain. 17543 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 17544 Aliases.clear(); 17545 Aliases.push_back(OriginalChain); 17546 return; 17547 } 17548 17549 // Don't bother if we've been before. 17550 if (!Visited.insert(Chain.getNode()).second) 17551 continue; 17552 17553 switch (Chain.getOpcode()) { 17554 case ISD::EntryToken: 17555 // Entry token is ideal chain operand, but handled in FindBetterChain. 17556 break; 17557 17558 case ISD::LOAD: 17559 case ISD::STORE: { 17560 // Get alias information for Chain. 17561 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 17562 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 17563 17564 // If chain is alias then stop here. 17565 if (!(IsLoad && IsOpLoad) && 17566 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 17567 Aliases.push_back(Chain); 17568 } else { 17569 // Look further up the chain. 17570 Chains.push_back(Chain.getOperand(0)); 17571 ++Depth; 17572 } 17573 break; 17574 } 17575 17576 case ISD::TokenFactor: 17577 // We have to check each of the operands of the token factor for "small" 17578 // token factors, so we queue them up. Adding the operands to the queue 17579 // (stack) in reverse order maintains the original order and increases the 17580 // likelihood that getNode will find a matching token factor (CSE.) 17581 if (Chain.getNumOperands() > 16) { 17582 Aliases.push_back(Chain); 17583 break; 17584 } 17585 for (unsigned n = Chain.getNumOperands(); n;) 17586 Chains.push_back(Chain.getOperand(--n)); 17587 ++Depth; 17588 break; 17589 17590 case ISD::CopyFromReg: 17591 // Forward past CopyFromReg. 17592 Chains.push_back(Chain.getOperand(0)); 17593 ++Depth; 17594 break; 17595 17596 default: 17597 // For all other instructions we will just have to take what we can get. 17598 Aliases.push_back(Chain); 17599 break; 17600 } 17601 } 17602 } 17603 17604 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 17605 /// (aliasing node.) 17606 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 17607 if (OptLevel == CodeGenOpt::None) 17608 return OldChain; 17609 17610 // Ops for replacing token factor. 17611 SmallVector<SDValue, 8> Aliases; 17612 17613 // Accumulate all the aliases to this node. 17614 GatherAllAliases(N, OldChain, Aliases); 17615 17616 // If no operands then chain to entry token. 17617 if (Aliases.size() == 0) 17618 return DAG.getEntryNode(); 17619 17620 // If a single operand then chain to it. We don't need to revisit it. 17621 if (Aliases.size() == 1) 17622 return Aliases[0]; 17623 17624 // Construct a custom tailored token factor. 17625 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 17626 } 17627 17628 // This function tries to collect a bunch of potentially interesting 17629 // nodes to improve the chains of, all at once. This might seem 17630 // redundant, as this function gets called when visiting every store 17631 // node, so why not let the work be done on each store as it's visited? 17632 // 17633 // I believe this is mainly important because MergeConsecutiveStores 17634 // is unable to deal with merging stores of different sizes, so unless 17635 // we improve the chains of all the potential candidates up-front 17636 // before running MergeConsecutiveStores, it might only see some of 17637 // the nodes that will eventually be candidates, and then not be able 17638 // to go from a partially-merged state to the desired final 17639 // fully-merged state. 17640 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 17641 if (OptLevel == CodeGenOpt::None) 17642 return false; 17643 17644 // This holds the base pointer, index, and the offset in bytes from the base 17645 // pointer. 17646 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 17647 17648 // We must have a base and an offset. 17649 if (!BasePtr.getBase().getNode()) 17650 return false; 17651 17652 // Do not handle stores to undef base pointers. 17653 if (BasePtr.getBase().isUndef()) 17654 return false; 17655 17656 SmallVector<StoreSDNode *, 8> ChainedStores; 17657 ChainedStores.push_back(St); 17658 17659 // Walk up the chain and look for nodes with offsets from the same 17660 // base pointer. Stop when reaching an instruction with a different kind 17661 // or instruction which has a different base pointer. 17662 StoreSDNode *Index = St; 17663 while (Index) { 17664 // If the chain has more than one use, then we can't reorder the mem ops. 17665 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 17666 break; 17667 17668 if (Index->isVolatile() || Index->isIndexed()) 17669 break; 17670 17671 // Find the base pointer and offset for this memory node. 17672 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 17673 17674 // Check that the base pointer is the same as the original one. 17675 if (!BasePtr.equalBaseIndex(Ptr, DAG)) 17676 break; 17677 17678 // Walk up the chain to find the next store node, ignoring any 17679 // intermediate loads. Any other kind of node will halt the loop. 17680 SDNode *NextInChain = Index->getChain().getNode(); 17681 while (true) { 17682 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 17683 // We found a store node. Use it for the next iteration. 17684 if (STn->isVolatile() || STn->isIndexed()) { 17685 Index = nullptr; 17686 break; 17687 } 17688 ChainedStores.push_back(STn); 17689 Index = STn; 17690 break; 17691 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 17692 NextInChain = Ldn->getChain().getNode(); 17693 continue; 17694 } else { 17695 Index = nullptr; 17696 break; 17697 } 17698 } // end while 17699 } 17700 17701 // At this point, ChainedStores lists all of the Store nodes 17702 // reachable by iterating up through chain nodes matching the above 17703 // conditions. For each such store identified, try to find an 17704 // earlier chain to attach the store to which won't violate the 17705 // required ordering. 17706 bool MadeChangeToSt = false; 17707 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 17708 17709 for (StoreSDNode *ChainedStore : ChainedStores) { 17710 SDValue Chain = ChainedStore->getChain(); 17711 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 17712 17713 if (Chain != BetterChain) { 17714 if (ChainedStore == St) 17715 MadeChangeToSt = true; 17716 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 17717 } 17718 } 17719 17720 // Do all replacements after finding the replacements to make to avoid making 17721 // the chains more complicated by introducing new TokenFactors. 17722 for (auto Replacement : BetterChains) 17723 replaceStoreChain(Replacement.first, Replacement.second); 17724 17725 return MadeChangeToSt; 17726 } 17727 17728 /// This is the entry point for the file. 17729 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA, 17730 CodeGenOpt::Level OptLevel) { 17731 /// This is the main entry point to this class. 17732 DAGCombiner(*this, AA, OptLevel).Run(Level); 17733 } 17734