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 3846 // ZEXTLOAD is already small enough. 3847 if (Load->getExtensionType() == ISD::ZEXTLOAD && 3848 ExtVT.bitsGE(Load->getMemoryVT())) 3849 continue; 3850 3851 // Use LE to convert equal sized loads to zext. 3852 if (ExtVT.bitsLE(Load->getMemoryVT())) 3853 Loads.insert(Load); 3854 3855 continue; 3856 } 3857 return false; 3858 } 3859 case ISD::ZERO_EXTEND: 3860 case ISD::AssertZext: { 3861 unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes(); 3862 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3863 EVT VT = Op.getOpcode() == ISD::AssertZext ? 3864 cast<VTSDNode>(Op.getOperand(1))->getVT() : 3865 Op.getOperand(0).getValueType(); 3866 3867 // We can accept extending nodes if the mask is wider or an equal 3868 // width to the original type. 3869 if (ExtVT.bitsGE(VT)) 3870 continue; 3871 break; 3872 } 3873 case ISD::OR: 3874 case ISD::XOR: 3875 case ISD::AND: 3876 if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask, 3877 NodeToMask)) 3878 return false; 3879 continue; 3880 } 3881 3882 // Allow one node which will masked along with any loads found. 3883 if (NodeToMask) 3884 return false; 3885 NodeToMask = Op.getNode(); 3886 } 3887 return true; 3888 } 3889 3890 bool DAGCombiner::BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG) { 3891 auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1)); 3892 if (!Mask) 3893 return false; 3894 3895 if (!Mask->getAPIntValue().isMask()) 3896 return false; 3897 3898 // No need to do anything if the and directly uses a load. 3899 if (isa<LoadSDNode>(N->getOperand(0))) 3900 return false; 3901 3902 SmallPtrSet<LoadSDNode*, 8> Loads; 3903 SmallPtrSet<SDNode*, 2> NodesWithConsts; 3904 SDNode *FixupNode = nullptr; 3905 if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) { 3906 if (Loads.size() == 0) 3907 return false; 3908 3909 DEBUG(dbgs() << "Backwards propagate AND: "; N->dump()); 3910 SDValue MaskOp = N->getOperand(1); 3911 3912 // If it exists, fixup the single node we allow in the tree that needs 3913 // masking. 3914 if (FixupNode) { 3915 DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump()); 3916 SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode), 3917 FixupNode->getValueType(0), 3918 SDValue(FixupNode, 0), MaskOp); 3919 DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And); 3920 DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), 3921 MaskOp); 3922 } 3923 3924 // Narrow any constants that need it. 3925 for (auto *LogicN : NodesWithConsts) { 3926 SDValue Op0 = LogicN->getOperand(0); 3927 SDValue Op1 = LogicN->getOperand(1); 3928 3929 if (isa<ConstantSDNode>(Op0)) 3930 std::swap(Op0, Op1); 3931 3932 SDValue And = DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(), 3933 Op1, MaskOp); 3934 3935 DAG.UpdateNodeOperands(LogicN, Op0, And); 3936 } 3937 3938 // Create narrow loads. 3939 for (auto *Load : Loads) { 3940 DEBUG(dbgs() << "Propagate AND back to: "; Load->dump()); 3941 SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0), 3942 SDValue(Load, 0), MaskOp); 3943 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And); 3944 DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp); 3945 SDValue NewLoad = ReduceLoadWidth(And.getNode()); 3946 assert(NewLoad && 3947 "Shouldn't be masking the load if it can't be narrowed"); 3948 CombineTo(Load, NewLoad, NewLoad.getValue(1)); 3949 } 3950 DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode()); 3951 return true; 3952 } 3953 return false; 3954 } 3955 3956 SDValue DAGCombiner::visitAND(SDNode *N) { 3957 SDValue N0 = N->getOperand(0); 3958 SDValue N1 = N->getOperand(1); 3959 EVT VT = N1.getValueType(); 3960 3961 // x & x --> x 3962 if (N0 == N1) 3963 return N0; 3964 3965 // fold vector ops 3966 if (VT.isVector()) { 3967 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3968 return FoldedVOp; 3969 3970 // fold (and x, 0) -> 0, vector edition 3971 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3972 // do not return N0, because undef node may exist in N0 3973 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()), 3974 SDLoc(N), N0.getValueType()); 3975 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3976 // do not return N1, because undef node may exist in N1 3977 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()), 3978 SDLoc(N), N1.getValueType()); 3979 3980 // fold (and x, -1) -> x, vector edition 3981 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3982 return N1; 3983 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3984 return N0; 3985 } 3986 3987 // fold (and c1, c2) -> c1&c2 3988 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3989 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3990 if (N0C && N1C && !N1C->isOpaque()) 3991 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3992 // canonicalize constant to RHS 3993 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3994 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3995 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3996 // fold (and x, -1) -> x 3997 if (isAllOnesConstant(N1)) 3998 return N0; 3999 // if (and x, c) is known to be zero, return 0 4000 unsigned BitWidth = VT.getScalarSizeInBits(); 4001 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4002 APInt::getAllOnesValue(BitWidth))) 4003 return DAG.getConstant(0, SDLoc(N), VT); 4004 4005 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4006 return NewSel; 4007 4008 // reassociate and 4009 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 4010 return RAND; 4011 4012 // Try to convert a constant mask AND into a shuffle clear mask. 4013 if (VT.isVector()) 4014 if (SDValue Shuffle = XformToShuffleWithZero(N)) 4015 return Shuffle; 4016 4017 // fold (and (or x, C), D) -> D if (C & D) == D 4018 auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) { 4019 return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue()); 4020 }; 4021 if (N0.getOpcode() == ISD::OR && 4022 matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset)) 4023 return N1; 4024 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 4025 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4026 SDValue N0Op0 = N0.getOperand(0); 4027 APInt Mask = ~N1C->getAPIntValue(); 4028 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits()); 4029 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 4030 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 4031 N0.getValueType(), N0Op0); 4032 4033 // Replace uses of the AND with uses of the Zero extend node. 4034 CombineTo(N, Zext); 4035 4036 // We actually want to replace all uses of the any_extend with the 4037 // zero_extend, to avoid duplicating things. This will later cause this 4038 // AND to be folded. 4039 CombineTo(N0.getNode(), Zext); 4040 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4041 } 4042 } 4043 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 4044 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 4045 // already be zero by virtue of the width of the base type of the load. 4046 // 4047 // the 'X' node here can either be nothing or an extract_vector_elt to catch 4048 // more cases. 4049 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 4050 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 4051 N0.getOperand(0).getOpcode() == ISD::LOAD && 4052 N0.getOperand(0).getResNo() == 0) || 4053 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 4054 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 4055 N0 : N0.getOperand(0) ); 4056 4057 // Get the constant (if applicable) the zero'th operand is being ANDed with. 4058 // This can be a pure constant or a vector splat, in which case we treat the 4059 // vector as a scalar and use the splat value. 4060 APInt Constant = APInt::getNullValue(1); 4061 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 4062 Constant = C->getAPIntValue(); 4063 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 4064 APInt SplatValue, SplatUndef; 4065 unsigned SplatBitSize; 4066 bool HasAnyUndefs; 4067 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 4068 SplatBitSize, HasAnyUndefs); 4069 if (IsSplat) { 4070 // Undef bits can contribute to a possible optimisation if set, so 4071 // set them. 4072 SplatValue |= SplatUndef; 4073 4074 // The splat value may be something like "0x00FFFFFF", which means 0 for 4075 // the first vector value and FF for the rest, repeating. We need a mask 4076 // that will apply equally to all members of the vector, so AND all the 4077 // lanes of the constant together. 4078 EVT VT = Vector->getValueType(0); 4079 unsigned BitWidth = VT.getScalarSizeInBits(); 4080 4081 // If the splat value has been compressed to a bitlength lower 4082 // than the size of the vector lane, we need to re-expand it to 4083 // the lane size. 4084 if (BitWidth > SplatBitSize) 4085 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 4086 SplatBitSize < BitWidth; 4087 SplatBitSize = SplatBitSize * 2) 4088 SplatValue |= SplatValue.shl(SplatBitSize); 4089 4090 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 4091 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 4092 if (SplatBitSize % BitWidth == 0) { 4093 Constant = APInt::getAllOnesValue(BitWidth); 4094 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 4095 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 4096 } 4097 } 4098 } 4099 4100 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 4101 // actually legal and isn't going to get expanded, else this is a false 4102 // optimisation. 4103 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 4104 Load->getValueType(0), 4105 Load->getMemoryVT()); 4106 4107 // Resize the constant to the same size as the original memory access before 4108 // extension. If it is still the AllOnesValue then this AND is completely 4109 // unneeded. 4110 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits()); 4111 4112 bool B; 4113 switch (Load->getExtensionType()) { 4114 default: B = false; break; 4115 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 4116 case ISD::ZEXTLOAD: 4117 case ISD::NON_EXTLOAD: B = true; break; 4118 } 4119 4120 if (B && Constant.isAllOnesValue()) { 4121 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 4122 // preserve semantics once we get rid of the AND. 4123 SDValue NewLoad(Load, 0); 4124 4125 // Fold the AND away. NewLoad may get replaced immediately. 4126 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 4127 4128 if (Load->getExtensionType() == ISD::EXTLOAD) { 4129 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 4130 Load->getValueType(0), SDLoc(Load), 4131 Load->getChain(), Load->getBasePtr(), 4132 Load->getOffset(), Load->getMemoryVT(), 4133 Load->getMemOperand()); 4134 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 4135 if (Load->getNumValues() == 3) { 4136 // PRE/POST_INC loads have 3 values. 4137 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 4138 NewLoad.getValue(2) }; 4139 CombineTo(Load, To, 3, true); 4140 } else { 4141 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 4142 } 4143 } 4144 4145 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4146 } 4147 } 4148 4149 // fold (and (load x), 255) -> (zextload x, i8) 4150 // fold (and (extload x, i16), 255) -> (zextload x, i8) 4151 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 4152 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD || 4153 (N0.getOpcode() == ISD::ANY_EXTEND && 4154 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 4155 if (SDValue Res = ReduceLoadWidth(N)) { 4156 LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND 4157 ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0); 4158 4159 AddToWorklist(N); 4160 CombineTo(LN0, Res, Res.getValue(1)); 4161 return SDValue(N, 0); 4162 } 4163 } 4164 4165 if (Level >= AfterLegalizeTypes) { 4166 // Attempt to propagate the AND back up to the leaves which, if they're 4167 // loads, can be combined to narrow loads and the AND node can be removed. 4168 // Perform after legalization so that extend nodes will already be 4169 // combined into the loads. 4170 if (BackwardsPropagateMask(N, DAG)) { 4171 return SDValue(N, 0); 4172 } 4173 } 4174 4175 if (SDValue Combined = visitANDLike(N0, N1, N)) 4176 return Combined; 4177 4178 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 4179 if (N0.getOpcode() == N1.getOpcode()) 4180 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4181 return Tmp; 4182 4183 // Masking the negated extension of a boolean is just the zero-extended 4184 // boolean: 4185 // and (sub 0, zext(bool X)), 1 --> zext(bool X) 4186 // and (sub 0, sext(bool X)), 1 --> zext(bool X) 4187 // 4188 // Note: the SimplifyDemandedBits fold below can make an information-losing 4189 // transform, and then we have no way to find this better fold. 4190 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) { 4191 if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) { 4192 SDValue SubRHS = N0.getOperand(1); 4193 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND && 4194 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 4195 return SubRHS; 4196 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND && 4197 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 4198 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0)); 4199 } 4200 } 4201 4202 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 4203 // fold (and (sra)) -> (and (srl)) when possible. 4204 if (SimplifyDemandedBits(SDValue(N, 0))) 4205 return SDValue(N, 0); 4206 4207 // fold (zext_inreg (extload x)) -> (zextload x) 4208 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 4209 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4210 EVT MemVT = LN0->getMemoryVT(); 4211 // If we zero all the possible extended bits, then we can turn this into 4212 // a zextload if we are running before legalize or the operation is legal. 4213 unsigned BitWidth = N1.getScalarValueSizeInBits(); 4214 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 4215 BitWidth - MemVT.getScalarSizeInBits())) && 4216 ((!LegalOperations && !LN0->isVolatile()) || 4217 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 4218 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 4219 LN0->getChain(), LN0->getBasePtr(), 4220 MemVT, LN0->getMemOperand()); 4221 AddToWorklist(N); 4222 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 4223 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4224 } 4225 } 4226 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 4227 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 4228 N0.hasOneUse()) { 4229 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4230 EVT MemVT = LN0->getMemoryVT(); 4231 // If we zero all the possible extended bits, then we can turn this into 4232 // a zextload if we are running before legalize or the operation is legal. 4233 unsigned BitWidth = N1.getScalarValueSizeInBits(); 4234 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 4235 BitWidth - MemVT.getScalarSizeInBits())) && 4236 ((!LegalOperations && !LN0->isVolatile()) || 4237 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 4238 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 4239 LN0->getChain(), LN0->getBasePtr(), 4240 MemVT, LN0->getMemOperand()); 4241 AddToWorklist(N); 4242 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 4243 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4244 } 4245 } 4246 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 4247 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 4248 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 4249 N0.getOperand(1), false)) 4250 return BSwap; 4251 } 4252 4253 return SDValue(); 4254 } 4255 4256 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 4257 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 4258 bool DemandHighBits) { 4259 if (!LegalOperations) 4260 return SDValue(); 4261 4262 EVT VT = N->getValueType(0); 4263 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 4264 return SDValue(); 4265 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 4266 return SDValue(); 4267 4268 // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff) 4269 bool LookPassAnd0 = false; 4270 bool LookPassAnd1 = false; 4271 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 4272 std::swap(N0, N1); 4273 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 4274 std::swap(N0, N1); 4275 if (N0.getOpcode() == ISD::AND) { 4276 if (!N0.getNode()->hasOneUse()) 4277 return SDValue(); 4278 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4279 if (!N01C || N01C->getZExtValue() != 0xFF00) 4280 return SDValue(); 4281 N0 = N0.getOperand(0); 4282 LookPassAnd0 = true; 4283 } 4284 4285 if (N1.getOpcode() == ISD::AND) { 4286 if (!N1.getNode()->hasOneUse()) 4287 return SDValue(); 4288 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 4289 if (!N11C || N11C->getZExtValue() != 0xFF) 4290 return SDValue(); 4291 N1 = N1.getOperand(0); 4292 LookPassAnd1 = true; 4293 } 4294 4295 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 4296 std::swap(N0, N1); 4297 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 4298 return SDValue(); 4299 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse()) 4300 return SDValue(); 4301 4302 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4303 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 4304 if (!N01C || !N11C) 4305 return SDValue(); 4306 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 4307 return SDValue(); 4308 4309 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 4310 SDValue N00 = N0->getOperand(0); 4311 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 4312 if (!N00.getNode()->hasOneUse()) 4313 return SDValue(); 4314 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 4315 if (!N001C || N001C->getZExtValue() != 0xFF) 4316 return SDValue(); 4317 N00 = N00.getOperand(0); 4318 LookPassAnd0 = true; 4319 } 4320 4321 SDValue N10 = N1->getOperand(0); 4322 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 4323 if (!N10.getNode()->hasOneUse()) 4324 return SDValue(); 4325 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 4326 if (!N101C || N101C->getZExtValue() != 0xFF00) 4327 return SDValue(); 4328 N10 = N10.getOperand(0); 4329 LookPassAnd1 = true; 4330 } 4331 4332 if (N00 != N10) 4333 return SDValue(); 4334 4335 // Make sure everything beyond the low halfword gets set to zero since the SRL 4336 // 16 will clear the top bits. 4337 unsigned OpSizeInBits = VT.getSizeInBits(); 4338 if (DemandHighBits && OpSizeInBits > 16) { 4339 // If the left-shift isn't masked out then the only way this is a bswap is 4340 // if all bits beyond the low 8 are 0. In that case the entire pattern 4341 // reduces to a left shift anyway: leave it for other parts of the combiner. 4342 if (!LookPassAnd0) 4343 return SDValue(); 4344 4345 // However, if the right shift isn't masked out then it might be because 4346 // it's not needed. See if we can spot that too. 4347 if (!LookPassAnd1 && 4348 !DAG.MaskedValueIsZero( 4349 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 4350 return SDValue(); 4351 } 4352 4353 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 4354 if (OpSizeInBits > 16) { 4355 SDLoc DL(N); 4356 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 4357 DAG.getConstant(OpSizeInBits - 16, DL, 4358 getShiftAmountTy(VT))); 4359 } 4360 return Res; 4361 } 4362 4363 /// Return true if the specified node is an element that makes up a 32-bit 4364 /// packed halfword byteswap. 4365 /// ((x & 0x000000ff) << 8) | 4366 /// ((x & 0x0000ff00) >> 8) | 4367 /// ((x & 0x00ff0000) << 8) | 4368 /// ((x & 0xff000000) >> 8) 4369 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 4370 if (!N.getNode()->hasOneUse()) 4371 return false; 4372 4373 unsigned Opc = N.getOpcode(); 4374 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 4375 return false; 4376 4377 SDValue N0 = N.getOperand(0); 4378 unsigned Opc0 = N0.getOpcode(); 4379 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL) 4380 return false; 4381 4382 ConstantSDNode *N1C = nullptr; 4383 // SHL or SRL: look upstream for AND mask operand 4384 if (Opc == ISD::AND) 4385 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4386 else if (Opc0 == ISD::AND) 4387 N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4388 if (!N1C) 4389 return false; 4390 4391 unsigned MaskByteOffset; 4392 switch (N1C->getZExtValue()) { 4393 default: 4394 return false; 4395 case 0xFF: MaskByteOffset = 0; break; 4396 case 0xFF00: MaskByteOffset = 1; break; 4397 case 0xFF0000: MaskByteOffset = 2; break; 4398 case 0xFF000000: MaskByteOffset = 3; break; 4399 } 4400 4401 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 4402 if (Opc == ISD::AND) { 4403 if (MaskByteOffset == 0 || MaskByteOffset == 2) { 4404 // (x >> 8) & 0xff 4405 // (x >> 8) & 0xff0000 4406 if (Opc0 != ISD::SRL) 4407 return false; 4408 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4409 if (!C || C->getZExtValue() != 8) 4410 return false; 4411 } else { 4412 // (x << 8) & 0xff00 4413 // (x << 8) & 0xff000000 4414 if (Opc0 != ISD::SHL) 4415 return false; 4416 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4417 if (!C || C->getZExtValue() != 8) 4418 return false; 4419 } 4420 } else if (Opc == ISD::SHL) { 4421 // (x & 0xff) << 8 4422 // (x & 0xff0000) << 8 4423 if (MaskByteOffset != 0 && MaskByteOffset != 2) 4424 return false; 4425 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4426 if (!C || C->getZExtValue() != 8) 4427 return false; 4428 } else { // Opc == ISD::SRL 4429 // (x & 0xff00) >> 8 4430 // (x & 0xff000000) >> 8 4431 if (MaskByteOffset != 1 && MaskByteOffset != 3) 4432 return false; 4433 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4434 if (!C || C->getZExtValue() != 8) 4435 return false; 4436 } 4437 4438 if (Parts[MaskByteOffset]) 4439 return false; 4440 4441 Parts[MaskByteOffset] = N0.getOperand(0).getNode(); 4442 return true; 4443 } 4444 4445 /// Match a 32-bit packed halfword bswap. That is 4446 /// ((x & 0x000000ff) << 8) | 4447 /// ((x & 0x0000ff00) >> 8) | 4448 /// ((x & 0x00ff0000) << 8) | 4449 /// ((x & 0xff000000) >> 8) 4450 /// => (rotl (bswap x), 16) 4451 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 4452 if (!LegalOperations) 4453 return SDValue(); 4454 4455 EVT VT = N->getValueType(0); 4456 if (VT != MVT::i32) 4457 return SDValue(); 4458 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 4459 return SDValue(); 4460 4461 // Look for either 4462 // (or (or (and), (and)), (or (and), (and))) 4463 // (or (or (or (and), (and)), (and)), (and)) 4464 if (N0.getOpcode() != ISD::OR) 4465 return SDValue(); 4466 SDValue N00 = N0.getOperand(0); 4467 SDValue N01 = N0.getOperand(1); 4468 SDNode *Parts[4] = {}; 4469 4470 if (N1.getOpcode() == ISD::OR && 4471 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 4472 // (or (or (and), (and)), (or (and), (and))) 4473 if (!isBSwapHWordElement(N00, Parts)) 4474 return SDValue(); 4475 4476 if (!isBSwapHWordElement(N01, Parts)) 4477 return SDValue(); 4478 SDValue N10 = N1.getOperand(0); 4479 if (!isBSwapHWordElement(N10, Parts)) 4480 return SDValue(); 4481 SDValue N11 = N1.getOperand(1); 4482 if (!isBSwapHWordElement(N11, Parts)) 4483 return SDValue(); 4484 } else { 4485 // (or (or (or (and), (and)), (and)), (and)) 4486 if (!isBSwapHWordElement(N1, Parts)) 4487 return SDValue(); 4488 if (!isBSwapHWordElement(N01, Parts)) 4489 return SDValue(); 4490 if (N00.getOpcode() != ISD::OR) 4491 return SDValue(); 4492 SDValue N000 = N00.getOperand(0); 4493 if (!isBSwapHWordElement(N000, Parts)) 4494 return SDValue(); 4495 SDValue N001 = N00.getOperand(1); 4496 if (!isBSwapHWordElement(N001, Parts)) 4497 return SDValue(); 4498 } 4499 4500 // Make sure the parts are all coming from the same node. 4501 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 4502 return SDValue(); 4503 4504 SDLoc DL(N); 4505 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 4506 SDValue(Parts[0], 0)); 4507 4508 // Result of the bswap should be rotated by 16. If it's not legal, then 4509 // do (x << 16) | (x >> 16). 4510 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 4511 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 4512 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 4513 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 4514 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 4515 return DAG.getNode(ISD::OR, DL, VT, 4516 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 4517 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 4518 } 4519 4520 /// This contains all DAGCombine rules which reduce two values combined by 4521 /// an Or operation to a single value \see visitANDLike(). 4522 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) { 4523 EVT VT = N1.getValueType(); 4524 SDLoc DL(N); 4525 4526 // fold (or x, undef) -> -1 4527 if (!LegalOperations && (N0.isUndef() || N1.isUndef())) 4528 return DAG.getAllOnesConstant(DL, VT); 4529 4530 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL)) 4531 return V; 4532 4533 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 4534 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 4535 // Don't increase # computations. 4536 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 4537 // We can only do this xform if we know that bits from X that are set in C2 4538 // but not in C1 are already zero. Likewise for Y. 4539 if (const ConstantSDNode *N0O1C = 4540 getAsNonOpaqueConstant(N0.getOperand(1))) { 4541 if (const ConstantSDNode *N1O1C = 4542 getAsNonOpaqueConstant(N1.getOperand(1))) { 4543 // We can only do this xform if we know that bits from X that are set in 4544 // C2 but not in C1 are already zero. Likewise for Y. 4545 const APInt &LHSMask = N0O1C->getAPIntValue(); 4546 const APInt &RHSMask = N1O1C->getAPIntValue(); 4547 4548 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 4549 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 4550 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 4551 N0.getOperand(0), N1.getOperand(0)); 4552 return DAG.getNode(ISD::AND, DL, VT, X, 4553 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 4554 } 4555 } 4556 } 4557 } 4558 4559 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 4560 if (N0.getOpcode() == ISD::AND && 4561 N1.getOpcode() == ISD::AND && 4562 N0.getOperand(0) == N1.getOperand(0) && 4563 // Don't increase # computations. 4564 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 4565 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 4566 N0.getOperand(1), N1.getOperand(1)); 4567 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X); 4568 } 4569 4570 return SDValue(); 4571 } 4572 4573 SDValue DAGCombiner::visitOR(SDNode *N) { 4574 SDValue N0 = N->getOperand(0); 4575 SDValue N1 = N->getOperand(1); 4576 EVT VT = N1.getValueType(); 4577 4578 // x | x --> x 4579 if (N0 == N1) 4580 return N0; 4581 4582 // fold vector ops 4583 if (VT.isVector()) { 4584 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4585 return FoldedVOp; 4586 4587 // fold (or x, 0) -> x, vector edition 4588 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4589 return N1; 4590 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4591 return N0; 4592 4593 // fold (or x, -1) -> -1, vector edition 4594 if (ISD::isBuildVectorAllOnes(N0.getNode())) 4595 // do not return N0, because undef node may exist in N0 4596 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType()); 4597 if (ISD::isBuildVectorAllOnes(N1.getNode())) 4598 // do not return N1, because undef node may exist in N1 4599 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType()); 4600 4601 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 4602 // Do this only if the resulting shuffle is legal. 4603 if (isa<ShuffleVectorSDNode>(N0) && 4604 isa<ShuffleVectorSDNode>(N1) && 4605 // Avoid folding a node with illegal type. 4606 TLI.isTypeLegal(VT)) { 4607 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 4608 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 4609 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 4610 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 4611 // Ensure both shuffles have a zero input. 4612 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) { 4613 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 4614 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 4615 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 4616 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 4617 bool CanFold = true; 4618 int NumElts = VT.getVectorNumElements(); 4619 SmallVector<int, 4> Mask(NumElts); 4620 4621 for (int i = 0; i != NumElts; ++i) { 4622 int M0 = SV0->getMaskElt(i); 4623 int M1 = SV1->getMaskElt(i); 4624 4625 // Determine if either index is pointing to a zero vector. 4626 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 4627 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 4628 4629 // If one element is zero and the otherside is undef, keep undef. 4630 // This also handles the case that both are undef. 4631 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 4632 Mask[i] = -1; 4633 continue; 4634 } 4635 4636 // Make sure only one of the elements is zero. 4637 if (M0Zero == M1Zero) { 4638 CanFold = false; 4639 break; 4640 } 4641 4642 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 4643 4644 // We have a zero and non-zero element. If the non-zero came from 4645 // SV0 make the index a LHS index. If it came from SV1, make it 4646 // a RHS index. We need to mod by NumElts because we don't care 4647 // which operand it came from in the original shuffles. 4648 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 4649 } 4650 4651 if (CanFold) { 4652 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 4653 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 4654 4655 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 4656 if (!LegalMask) { 4657 std::swap(NewLHS, NewRHS); 4658 ShuffleVectorSDNode::commuteMask(Mask); 4659 LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 4660 } 4661 4662 if (LegalMask) 4663 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask); 4664 } 4665 } 4666 } 4667 } 4668 4669 // fold (or c1, c2) -> c1|c2 4670 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4671 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4672 if (N0C && N1C && !N1C->isOpaque()) 4673 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 4674 // canonicalize constant to RHS 4675 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4676 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4677 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 4678 // fold (or x, 0) -> x 4679 if (isNullConstant(N1)) 4680 return N0; 4681 // fold (or x, -1) -> -1 4682 if (isAllOnesConstant(N1)) 4683 return N1; 4684 4685 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4686 return NewSel; 4687 4688 // fold (or x, c) -> c iff (x & ~c) == 0 4689 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 4690 return N1; 4691 4692 if (SDValue Combined = visitORLike(N0, N1, N)) 4693 return Combined; 4694 4695 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 4696 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 4697 return BSwap; 4698 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 4699 return BSwap; 4700 4701 // reassociate or 4702 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 4703 return ROR; 4704 4705 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 4706 // iff (c1 & c2) != 0. 4707 auto MatchIntersect = [](ConstantSDNode *LHS, ConstantSDNode *RHS) { 4708 return LHS->getAPIntValue().intersects(RHS->getAPIntValue()); 4709 }; 4710 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4711 matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect)) { 4712 if (SDValue COR = DAG.FoldConstantArithmetic( 4713 ISD::OR, SDLoc(N1), VT, N1.getNode(), N0.getOperand(1).getNode())) { 4714 SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1); 4715 AddToWorklist(IOR.getNode()); 4716 return DAG.getNode(ISD::AND, SDLoc(N), VT, COR, IOR); 4717 } 4718 } 4719 4720 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 4721 if (N0.getOpcode() == N1.getOpcode()) 4722 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4723 return Tmp; 4724 4725 // See if this is some rotate idiom. 4726 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 4727 return SDValue(Rot, 0); 4728 4729 if (SDValue Load = MatchLoadCombine(N)) 4730 return Load; 4731 4732 // Simplify the operands using demanded-bits information. 4733 if (SimplifyDemandedBits(SDValue(N, 0))) 4734 return SDValue(N, 0); 4735 4736 return SDValue(); 4737 } 4738 4739 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 4740 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 4741 if (Op.getOpcode() == ISD::AND) { 4742 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 4743 Mask = Op.getOperand(1); 4744 Op = Op.getOperand(0); 4745 } else { 4746 return false; 4747 } 4748 } 4749 4750 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 4751 Shift = Op; 4752 return true; 4753 } 4754 4755 return false; 4756 } 4757 4758 // Return true if we can prove that, whenever Neg and Pos are both in the 4759 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 4760 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 4761 // 4762 // (or (shift1 X, Neg), (shift2 X, Pos)) 4763 // 4764 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 4765 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 4766 // to consider shift amounts with defined behavior. 4767 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 4768 // If EltSize is a power of 2 then: 4769 // 4770 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 4771 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 4772 // 4773 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 4774 // for the stronger condition: 4775 // 4776 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 4777 // 4778 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 4779 // we can just replace Neg with Neg' for the rest of the function. 4780 // 4781 // In other cases we check for the even stronger condition: 4782 // 4783 // Neg == EltSize - Pos [B] 4784 // 4785 // for all Neg and Pos. Note that the (or ...) then invokes undefined 4786 // behavior if Pos == 0 (and consequently Neg == EltSize). 4787 // 4788 // We could actually use [A] whenever EltSize is a power of 2, but the 4789 // only extra cases that it would match are those uninteresting ones 4790 // where Neg and Pos are never in range at the same time. E.g. for 4791 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 4792 // as well as (sub 32, Pos), but: 4793 // 4794 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 4795 // 4796 // always invokes undefined behavior for 32-bit X. 4797 // 4798 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 4799 unsigned MaskLoBits = 0; 4800 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 4801 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 4802 if (NegC->getAPIntValue() == EltSize - 1) { 4803 Neg = Neg.getOperand(0); 4804 MaskLoBits = Log2_64(EltSize); 4805 } 4806 } 4807 } 4808 4809 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 4810 if (Neg.getOpcode() != ISD::SUB) 4811 return false; 4812 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 4813 if (!NegC) 4814 return false; 4815 SDValue NegOp1 = Neg.getOperand(1); 4816 4817 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 4818 // Pos'. The truncation is redundant for the purpose of the equality. 4819 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 4820 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4821 if (PosC->getAPIntValue() == EltSize - 1) 4822 Pos = Pos.getOperand(0); 4823 4824 // The condition we need is now: 4825 // 4826 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 4827 // 4828 // If NegOp1 == Pos then we need: 4829 // 4830 // EltSize & Mask == NegC & Mask 4831 // 4832 // (because "x & Mask" is a truncation and distributes through subtraction). 4833 APInt Width; 4834 if (Pos == NegOp1) 4835 Width = NegC->getAPIntValue(); 4836 4837 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 4838 // Then the condition we want to prove becomes: 4839 // 4840 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 4841 // 4842 // which, again because "x & Mask" is a truncation, becomes: 4843 // 4844 // NegC & Mask == (EltSize - PosC) & Mask 4845 // EltSize & Mask == (NegC + PosC) & Mask 4846 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 4847 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4848 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 4849 else 4850 return false; 4851 } else 4852 return false; 4853 4854 // Now we just need to check that EltSize & Mask == Width & Mask. 4855 if (MaskLoBits) 4856 // EltSize & Mask is 0 since Mask is EltSize - 1. 4857 return Width.getLoBits(MaskLoBits) == 0; 4858 return Width == EltSize; 4859 } 4860 4861 // A subroutine of MatchRotate used once we have found an OR of two opposite 4862 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 4863 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 4864 // former being preferred if supported. InnerPos and InnerNeg are Pos and 4865 // Neg with outer conversions stripped away. 4866 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 4867 SDValue Neg, SDValue InnerPos, 4868 SDValue InnerNeg, unsigned PosOpcode, 4869 unsigned NegOpcode, const SDLoc &DL) { 4870 // fold (or (shl x, (*ext y)), 4871 // (srl x, (*ext (sub 32, y)))) -> 4872 // (rotl x, y) or (rotr x, (sub 32, y)) 4873 // 4874 // fold (or (shl x, (*ext (sub 32, y))), 4875 // (srl x, (*ext y))) -> 4876 // (rotr x, y) or (rotl x, (sub 32, y)) 4877 EVT VT = Shifted.getValueType(); 4878 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 4879 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 4880 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 4881 HasPos ? Pos : Neg).getNode(); 4882 } 4883 4884 return nullptr; 4885 } 4886 4887 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 4888 // idioms for rotate, and if the target supports rotation instructions, generate 4889 // a rot[lr]. 4890 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 4891 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 4892 EVT VT = LHS.getValueType(); 4893 if (!TLI.isTypeLegal(VT)) return nullptr; 4894 4895 // The target must have at least one rotate flavor. 4896 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 4897 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 4898 if (!HasROTL && !HasROTR) return nullptr; 4899 4900 // Check for truncated rotate. 4901 if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE && 4902 LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) { 4903 assert(LHS.getValueType() == RHS.getValueType()); 4904 if (SDNode *Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) { 4905 return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(), 4906 SDValue(Rot, 0)).getNode(); 4907 } 4908 } 4909 4910 // Match "(X shl/srl V1) & V2" where V2 may not be present. 4911 SDValue LHSShift; // The shift. 4912 SDValue LHSMask; // AND value if any. 4913 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 4914 return nullptr; // Not part of a rotate. 4915 4916 SDValue RHSShift; // The shift. 4917 SDValue RHSMask; // AND value if any. 4918 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 4919 return nullptr; // Not part of a rotate. 4920 4921 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 4922 return nullptr; // Not shifting the same value. 4923 4924 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 4925 return nullptr; // Shifts must disagree. 4926 4927 // Canonicalize shl to left side in a shl/srl pair. 4928 if (RHSShift.getOpcode() == ISD::SHL) { 4929 std::swap(LHS, RHS); 4930 std::swap(LHSShift, RHSShift); 4931 std::swap(LHSMask, RHSMask); 4932 } 4933 4934 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4935 SDValue LHSShiftArg = LHSShift.getOperand(0); 4936 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4937 SDValue RHSShiftArg = RHSShift.getOperand(0); 4938 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4939 4940 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4941 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4942 auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS, 4943 ConstantSDNode *RHS) { 4944 return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits; 4945 }; 4946 if (matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) { 4947 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4948 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4949 4950 // If there is an AND of either shifted operand, apply it to the result. 4951 if (LHSMask.getNode() || RHSMask.getNode()) { 4952 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT); 4953 SDValue Mask = AllOnes; 4954 4955 if (LHSMask.getNode()) { 4956 SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt); 4957 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4958 DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits)); 4959 } 4960 if (RHSMask.getNode()) { 4961 SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt); 4962 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4963 DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits)); 4964 } 4965 4966 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4967 } 4968 4969 return Rot.getNode(); 4970 } 4971 4972 // If there is a mask here, and we have a variable shift, we can't be sure 4973 // that we're masking out the right stuff. 4974 if (LHSMask.getNode() || RHSMask.getNode()) 4975 return nullptr; 4976 4977 // If the shift amount is sign/zext/any-extended just peel it off. 4978 SDValue LExtOp0 = LHSShiftAmt; 4979 SDValue RExtOp0 = RHSShiftAmt; 4980 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4981 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4982 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4983 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4984 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4985 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4986 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4987 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4988 LExtOp0 = LHSShiftAmt.getOperand(0); 4989 RExtOp0 = RHSShiftAmt.getOperand(0); 4990 } 4991 4992 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4993 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4994 if (TryL) 4995 return TryL; 4996 4997 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4998 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4999 if (TryR) 5000 return TryR; 5001 5002 return nullptr; 5003 } 5004 5005 namespace { 5006 5007 /// Represents known origin of an individual byte in load combine pattern. The 5008 /// value of the byte is either constant zero or comes from memory. 5009 struct ByteProvider { 5010 // For constant zero providers Load is set to nullptr. For memory providers 5011 // Load represents the node which loads the byte from memory. 5012 // ByteOffset is the offset of the byte in the value produced by the load. 5013 LoadSDNode *Load = nullptr; 5014 unsigned ByteOffset = 0; 5015 5016 ByteProvider() = default; 5017 5018 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) { 5019 return ByteProvider(Load, ByteOffset); 5020 } 5021 5022 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); } 5023 5024 bool isConstantZero() const { return !Load; } 5025 bool isMemory() const { return Load; } 5026 5027 bool operator==(const ByteProvider &Other) const { 5028 return Other.Load == Load && Other.ByteOffset == ByteOffset; 5029 } 5030 5031 private: 5032 ByteProvider(LoadSDNode *Load, unsigned ByteOffset) 5033 : Load(Load), ByteOffset(ByteOffset) {} 5034 }; 5035 5036 } // end anonymous namespace 5037 5038 /// Recursively traverses the expression calculating the origin of the requested 5039 /// byte of the given value. Returns None if the provider can't be calculated. 5040 /// 5041 /// For all the values except the root of the expression verifies that the value 5042 /// has exactly one use and if it's not true return None. This way if the origin 5043 /// of the byte is returned it's guaranteed that the values which contribute to 5044 /// the byte are not used outside of this expression. 5045 /// 5046 /// Because the parts of the expression are not allowed to have more than one 5047 /// use this function iterates over trees, not DAGs. So it never visits the same 5048 /// node more than once. 5049 static const Optional<ByteProvider> 5050 calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth, 5051 bool Root = false) { 5052 // Typical i64 by i8 pattern requires recursion up to 8 calls depth 5053 if (Depth == 10) 5054 return None; 5055 5056 if (!Root && !Op.hasOneUse()) 5057 return None; 5058 5059 assert(Op.getValueType().isScalarInteger() && "can't handle other types"); 5060 unsigned BitWidth = Op.getValueSizeInBits(); 5061 if (BitWidth % 8 != 0) 5062 return None; 5063 unsigned ByteWidth = BitWidth / 8; 5064 assert(Index < ByteWidth && "invalid index requested"); 5065 (void) ByteWidth; 5066 5067 switch (Op.getOpcode()) { 5068 case ISD::OR: { 5069 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1); 5070 if (!LHS) 5071 return None; 5072 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1); 5073 if (!RHS) 5074 return None; 5075 5076 if (LHS->isConstantZero()) 5077 return RHS; 5078 if (RHS->isConstantZero()) 5079 return LHS; 5080 return None; 5081 } 5082 case ISD::SHL: { 5083 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 5084 if (!ShiftOp) 5085 return None; 5086 5087 uint64_t BitShift = ShiftOp->getZExtValue(); 5088 if (BitShift % 8 != 0) 5089 return None; 5090 uint64_t ByteShift = BitShift / 8; 5091 5092 return Index < ByteShift 5093 ? ByteProvider::getConstantZero() 5094 : calculateByteProvider(Op->getOperand(0), Index - ByteShift, 5095 Depth + 1); 5096 } 5097 case ISD::ANY_EXTEND: 5098 case ISD::SIGN_EXTEND: 5099 case ISD::ZERO_EXTEND: { 5100 SDValue NarrowOp = Op->getOperand(0); 5101 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits(); 5102 if (NarrowBitWidth % 8 != 0) 5103 return None; 5104 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 5105 5106 if (Index >= NarrowByteWidth) 5107 return Op.getOpcode() == ISD::ZERO_EXTEND 5108 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 5109 : None; 5110 return calculateByteProvider(NarrowOp, Index, Depth + 1); 5111 } 5112 case ISD::BSWAP: 5113 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1, 5114 Depth + 1); 5115 case ISD::LOAD: { 5116 auto L = cast<LoadSDNode>(Op.getNode()); 5117 if (L->isVolatile() || L->isIndexed()) 5118 return None; 5119 5120 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits(); 5121 if (NarrowBitWidth % 8 != 0) 5122 return None; 5123 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 5124 5125 if (Index >= NarrowByteWidth) 5126 return L->getExtensionType() == ISD::ZEXTLOAD 5127 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 5128 : None; 5129 return ByteProvider::getMemory(L, Index); 5130 } 5131 } 5132 5133 return None; 5134 } 5135 5136 /// Match a pattern where a wide type scalar value is loaded by several narrow 5137 /// loads and combined by shifts and ors. Fold it into a single load or a load 5138 /// and a BSWAP if the targets supports it. 5139 /// 5140 /// Assuming little endian target: 5141 /// i8 *a = ... 5142 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24) 5143 /// => 5144 /// i32 val = *((i32)a) 5145 /// 5146 /// i8 *a = ... 5147 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3] 5148 /// => 5149 /// i32 val = BSWAP(*((i32)a)) 5150 /// 5151 /// TODO: This rule matches complex patterns with OR node roots and doesn't 5152 /// interact well with the worklist mechanism. When a part of the pattern is 5153 /// updated (e.g. one of the loads) its direct users are put into the worklist, 5154 /// but the root node of the pattern which triggers the load combine is not 5155 /// necessarily a direct user of the changed node. For example, once the address 5156 /// of t28 load is reassociated load combine won't be triggered: 5157 /// t25: i32 = add t4, Constant:i32<2> 5158 /// t26: i64 = sign_extend t25 5159 /// t27: i64 = add t2, t26 5160 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64 5161 /// t29: i32 = zero_extend t28 5162 /// t32: i32 = shl t29, Constant:i8<8> 5163 /// t33: i32 = or t23, t32 5164 /// As a possible fix visitLoad can check if the load can be a part of a load 5165 /// combine pattern and add corresponding OR roots to the worklist. 5166 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) { 5167 assert(N->getOpcode() == ISD::OR && 5168 "Can only match load combining against OR nodes"); 5169 5170 // Handles simple types only 5171 EVT VT = N->getValueType(0); 5172 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 5173 return SDValue(); 5174 unsigned ByteWidth = VT.getSizeInBits() / 8; 5175 5176 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5177 // Before legalize we can introduce too wide illegal loads which will be later 5178 // split into legal sized loads. This enables us to combine i64 load by i8 5179 // patterns to a couple of i32 loads on 32 bit targets. 5180 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT)) 5181 return SDValue(); 5182 5183 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = []( 5184 unsigned BW, unsigned i) { return i; }; 5185 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = []( 5186 unsigned BW, unsigned i) { return BW - i - 1; }; 5187 5188 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian(); 5189 auto MemoryByteOffset = [&] (ByteProvider P) { 5190 assert(P.isMemory() && "Must be a memory byte provider"); 5191 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits(); 5192 assert(LoadBitWidth % 8 == 0 && 5193 "can only analyze providers for individual bytes not bit"); 5194 unsigned LoadByteWidth = LoadBitWidth / 8; 5195 return IsBigEndianTarget 5196 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset) 5197 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset); 5198 }; 5199 5200 Optional<BaseIndexOffset> Base; 5201 SDValue Chain; 5202 5203 SmallSet<LoadSDNode *, 8> Loads; 5204 Optional<ByteProvider> FirstByteProvider; 5205 int64_t FirstOffset = INT64_MAX; 5206 5207 // Check if all the bytes of the OR we are looking at are loaded from the same 5208 // base address. Collect bytes offsets from Base address in ByteOffsets. 5209 SmallVector<int64_t, 4> ByteOffsets(ByteWidth); 5210 for (unsigned i = 0; i < ByteWidth; i++) { 5211 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true); 5212 if (!P || !P->isMemory()) // All the bytes must be loaded from memory 5213 return SDValue(); 5214 5215 LoadSDNode *L = P->Load; 5216 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() && 5217 "Must be enforced by calculateByteProvider"); 5218 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset"); 5219 5220 // All loads must share the same chain 5221 SDValue LChain = L->getChain(); 5222 if (!Chain) 5223 Chain = LChain; 5224 else if (Chain != LChain) 5225 return SDValue(); 5226 5227 // Loads must share the same base address 5228 BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG); 5229 int64_t ByteOffsetFromBase = 0; 5230 if (!Base) 5231 Base = Ptr; 5232 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase)) 5233 return SDValue(); 5234 5235 // Calculate the offset of the current byte from the base address 5236 ByteOffsetFromBase += MemoryByteOffset(*P); 5237 ByteOffsets[i] = ByteOffsetFromBase; 5238 5239 // Remember the first byte load 5240 if (ByteOffsetFromBase < FirstOffset) { 5241 FirstByteProvider = P; 5242 FirstOffset = ByteOffsetFromBase; 5243 } 5244 5245 Loads.insert(L); 5246 } 5247 assert(!Loads.empty() && "All the bytes of the value must be loaded from " 5248 "memory, so there must be at least one load which produces the value"); 5249 assert(Base && "Base address of the accessed memory location must be set"); 5250 assert(FirstOffset != INT64_MAX && "First byte offset must be set"); 5251 5252 // Check if the bytes of the OR we are looking at match with either big or 5253 // little endian value load 5254 bool BigEndian = true, LittleEndian = true; 5255 for (unsigned i = 0; i < ByteWidth; i++) { 5256 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset; 5257 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i); 5258 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i); 5259 if (!BigEndian && !LittleEndian) 5260 return SDValue(); 5261 } 5262 assert((BigEndian != LittleEndian) && "should be either or"); 5263 assert(FirstByteProvider && "must be set"); 5264 5265 // Ensure that the first byte is loaded from zero offset of the first load. 5266 // So the combined value can be loaded from the first load address. 5267 if (MemoryByteOffset(*FirstByteProvider) != 0) 5268 return SDValue(); 5269 LoadSDNode *FirstLoad = FirstByteProvider->Load; 5270 5271 // The node we are looking at matches with the pattern, check if we can 5272 // replace it with a single load and bswap if needed. 5273 5274 // If the load needs byte swap check if the target supports it 5275 bool NeedsBswap = IsBigEndianTarget != BigEndian; 5276 5277 // Before legalize we can introduce illegal bswaps which will be later 5278 // converted to an explicit bswap sequence. This way we end up with a single 5279 // load and byte shuffling instead of several loads and byte shuffling. 5280 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT)) 5281 return SDValue(); 5282 5283 // Check that a load of the wide type is both allowed and fast on the target 5284 bool Fast = false; 5285 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), 5286 VT, FirstLoad->getAddressSpace(), 5287 FirstLoad->getAlignment(), &Fast); 5288 if (!Allowed || !Fast) 5289 return SDValue(); 5290 5291 SDValue NewLoad = 5292 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(), 5293 FirstLoad->getPointerInfo(), FirstLoad->getAlignment()); 5294 5295 // Transfer chain users from old loads to the new load. 5296 for (LoadSDNode *L : Loads) 5297 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1)); 5298 5299 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad; 5300 } 5301 5302 SDValue DAGCombiner::visitXOR(SDNode *N) { 5303 SDValue N0 = N->getOperand(0); 5304 SDValue N1 = N->getOperand(1); 5305 EVT VT = N0.getValueType(); 5306 5307 // fold vector ops 5308 if (VT.isVector()) { 5309 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5310 return FoldedVOp; 5311 5312 // fold (xor x, 0) -> x, vector edition 5313 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5314 return N1; 5315 if (ISD::isBuildVectorAllZeros(N1.getNode())) 5316 return N0; 5317 } 5318 5319 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 5320 if (N0.isUndef() && N1.isUndef()) 5321 return DAG.getConstant(0, SDLoc(N), VT); 5322 // fold (xor x, undef) -> undef 5323 if (N0.isUndef()) 5324 return N0; 5325 if (N1.isUndef()) 5326 return N1; 5327 // fold (xor c1, c2) -> c1^c2 5328 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5329 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 5330 if (N0C && N1C) 5331 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 5332 // canonicalize constant to RHS 5333 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 5334 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 5335 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 5336 // fold (xor x, 0) -> x 5337 if (isNullConstant(N1)) 5338 return N0; 5339 5340 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5341 return NewSel; 5342 5343 // reassociate xor 5344 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 5345 return RXOR; 5346 5347 // fold !(x cc y) -> (x !cc y) 5348 SDValue LHS, RHS, CC; 5349 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 5350 bool isInt = LHS.getValueType().isInteger(); 5351 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 5352 isInt); 5353 5354 if (!LegalOperations || 5355 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 5356 switch (N0.getOpcode()) { 5357 default: 5358 llvm_unreachable("Unhandled SetCC Equivalent!"); 5359 case ISD::SETCC: 5360 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC); 5361 case ISD::SELECT_CC: 5362 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2), 5363 N0.getOperand(3), NotCC); 5364 } 5365 } 5366 } 5367 5368 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 5369 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 5370 N0.getNode()->hasOneUse() && 5371 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 5372 SDValue V = N0.getOperand(0); 5373 SDLoc DL(N0); 5374 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 5375 DAG.getConstant(1, DL, V.getValueType())); 5376 AddToWorklist(V.getNode()); 5377 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 5378 } 5379 5380 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 5381 if (isOneConstant(N1) && VT == MVT::i1 && 5382 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 5383 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5384 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 5385 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 5386 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 5387 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 5388 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 5389 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 5390 } 5391 } 5392 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 5393 if (isAllOnesConstant(N1) && 5394 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 5395 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5396 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 5397 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 5398 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 5399 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 5400 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 5401 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 5402 } 5403 } 5404 // fold (xor (and x, y), y) -> (and (not x), y) 5405 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 5406 N0->getOperand(1) == N1) { 5407 SDValue X = N0->getOperand(0); 5408 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 5409 AddToWorklist(NotX.getNode()); 5410 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 5411 } 5412 5413 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X) 5414 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5415 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && 5416 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) && 5417 TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { 5418 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1))) 5419 if (C->getAPIntValue() == (OpSizeInBits - 1)) 5420 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0)); 5421 } 5422 5423 // fold (xor x, x) -> 0 5424 if (N0 == N1) 5425 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 5426 5427 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 5428 // Here is a concrete example of this equivalence: 5429 // i16 x == 14 5430 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 5431 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 5432 // 5433 // => 5434 // 5435 // i16 ~1 == 0b1111111111111110 5436 // i16 rol(~1, 14) == 0b1011111111111111 5437 // 5438 // Some additional tips to help conceptualize this transform: 5439 // - Try to see the operation as placing a single zero in a value of all ones. 5440 // - There exists no value for x which would allow the result to contain zero. 5441 // - Values of x larger than the bitwidth are undefined and do not require a 5442 // consistent result. 5443 // - Pushing the zero left requires shifting one bits in from the right. 5444 // A rotate left of ~1 is a nice way of achieving the desired result. 5445 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 5446 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 5447 SDLoc DL(N); 5448 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 5449 N0.getOperand(1)); 5450 } 5451 5452 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 5453 if (N0.getOpcode() == N1.getOpcode()) 5454 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 5455 return Tmp; 5456 5457 // Simplify the expression using non-local knowledge. 5458 if (SimplifyDemandedBits(SDValue(N, 0))) 5459 return SDValue(N, 0); 5460 5461 return SDValue(); 5462 } 5463 5464 /// Handle transforms common to the three shifts, when the shift amount is a 5465 /// constant. 5466 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 5467 SDNode *LHS = N->getOperand(0).getNode(); 5468 if (!LHS->hasOneUse()) return SDValue(); 5469 5470 // We want to pull some binops through shifts, so that we have (and (shift)) 5471 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 5472 // thing happens with address calculations, so it's important to canonicalize 5473 // it. 5474 bool HighBitSet = false; // Can we transform this if the high bit is set? 5475 5476 switch (LHS->getOpcode()) { 5477 default: return SDValue(); 5478 case ISD::OR: 5479 case ISD::XOR: 5480 HighBitSet = false; // We can only transform sra if the high bit is clear. 5481 break; 5482 case ISD::AND: 5483 HighBitSet = true; // We can only transform sra if the high bit is set. 5484 break; 5485 case ISD::ADD: 5486 if (N->getOpcode() != ISD::SHL) 5487 return SDValue(); // only shl(add) not sr[al](add). 5488 HighBitSet = false; // We can only transform sra if the high bit is clear. 5489 break; 5490 } 5491 5492 // We require the RHS of the binop to be a constant and not opaque as well. 5493 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 5494 if (!BinOpCst) return SDValue(); 5495 5496 // FIXME: disable this unless the input to the binop is a shift by a constant 5497 // or is copy/select.Enable this in other cases when figure out it's exactly profitable. 5498 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 5499 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL || 5500 BinOpLHSVal->getOpcode() == ISD::SRA || 5501 BinOpLHSVal->getOpcode() == ISD::SRL; 5502 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg || 5503 BinOpLHSVal->getOpcode() == ISD::SELECT; 5504 5505 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) && 5506 !isCopyOrSelect) 5507 return SDValue(); 5508 5509 if (isCopyOrSelect && N->hasOneUse()) 5510 return SDValue(); 5511 5512 EVT VT = N->getValueType(0); 5513 5514 // If this is a signed shift right, and the high bit is modified by the 5515 // logical operation, do not perform the transformation. The highBitSet 5516 // boolean indicates the value of the high bit of the constant which would 5517 // cause it to be modified for this operation. 5518 if (N->getOpcode() == ISD::SRA) { 5519 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 5520 if (BinOpRHSSignSet != HighBitSet) 5521 return SDValue(); 5522 } 5523 5524 if (!TLI.isDesirableToCommuteWithShift(LHS)) 5525 return SDValue(); 5526 5527 // Fold the constants, shifting the binop RHS by the shift amount. 5528 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 5529 N->getValueType(0), 5530 LHS->getOperand(1), N->getOperand(1)); 5531 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 5532 5533 // Create the new shift. 5534 SDValue NewShift = DAG.getNode(N->getOpcode(), 5535 SDLoc(LHS->getOperand(0)), 5536 VT, LHS->getOperand(0), N->getOperand(1)); 5537 5538 // Create the new binop. 5539 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 5540 } 5541 5542 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 5543 assert(N->getOpcode() == ISD::TRUNCATE); 5544 assert(N->getOperand(0).getOpcode() == ISD::AND); 5545 5546 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 5547 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 5548 SDValue N01 = N->getOperand(0).getOperand(1); 5549 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) { 5550 SDLoc DL(N); 5551 EVT TruncVT = N->getValueType(0); 5552 SDValue N00 = N->getOperand(0).getOperand(0); 5553 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00); 5554 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01); 5555 AddToWorklist(Trunc00.getNode()); 5556 AddToWorklist(Trunc01.getNode()); 5557 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01); 5558 } 5559 } 5560 5561 return SDValue(); 5562 } 5563 5564 SDValue DAGCombiner::visitRotate(SDNode *N) { 5565 SDLoc dl(N); 5566 SDValue N0 = N->getOperand(0); 5567 SDValue N1 = N->getOperand(1); 5568 EVT VT = N->getValueType(0); 5569 unsigned Bitsize = VT.getScalarSizeInBits(); 5570 5571 // fold (rot x, 0) -> x 5572 if (isNullConstantOrNullSplatConstant(N1)) 5573 return N0; 5574 5575 // fold (rot x, c) -> (rot x, c % BitSize) 5576 if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) { 5577 if (Cst->getAPIntValue().uge(Bitsize)) { 5578 uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize); 5579 return DAG.getNode(N->getOpcode(), dl, VT, N0, 5580 DAG.getConstant(RotAmt, dl, N1.getValueType())); 5581 } 5582 } 5583 5584 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 5585 if (N1.getOpcode() == ISD::TRUNCATE && 5586 N1.getOperand(0).getOpcode() == ISD::AND) { 5587 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5588 return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1); 5589 } 5590 5591 unsigned NextOp = N0.getOpcode(); 5592 // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize) 5593 if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) { 5594 SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1); 5595 SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)); 5596 if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) { 5597 EVT ShiftVT = C1->getValueType(0); 5598 bool SameSide = (N->getOpcode() == NextOp); 5599 unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB; 5600 if (SDValue CombinedShift = 5601 DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) { 5602 SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT); 5603 SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic( 5604 ISD::SREM, dl, ShiftVT, CombinedShift.getNode(), 5605 BitsizeC.getNode()); 5606 return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0), 5607 CombinedShiftNorm); 5608 } 5609 } 5610 } 5611 return SDValue(); 5612 } 5613 5614 SDValue DAGCombiner::visitSHL(SDNode *N) { 5615 SDValue N0 = N->getOperand(0); 5616 SDValue N1 = N->getOperand(1); 5617 EVT VT = N0.getValueType(); 5618 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5619 5620 // fold vector ops 5621 if (VT.isVector()) { 5622 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5623 return FoldedVOp; 5624 5625 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 5626 // If setcc produces all-one true value then: 5627 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 5628 if (N1CV && N1CV->isConstant()) { 5629 if (N0.getOpcode() == ISD::AND) { 5630 SDValue N00 = N0->getOperand(0); 5631 SDValue N01 = N0->getOperand(1); 5632 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 5633 5634 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 5635 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 5636 TargetLowering::ZeroOrNegativeOneBooleanContent) { 5637 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 5638 N01CV, N1CV)) 5639 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 5640 } 5641 } 5642 } 5643 } 5644 5645 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5646 5647 // fold (shl c1, c2) -> c1<<c2 5648 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5649 if (N0C && N1C && !N1C->isOpaque()) 5650 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 5651 // fold (shl 0, x) -> 0 5652 if (isNullConstantOrNullSplatConstant(N0)) 5653 return N0; 5654 // fold (shl x, c >= size(x)) -> undef 5655 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 5656 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 5657 return Val->getAPIntValue().uge(OpSizeInBits); 5658 }; 5659 if (matchUnaryPredicate(N1, MatchShiftTooBig)) 5660 return DAG.getUNDEF(VT); 5661 // fold (shl x, 0) -> x 5662 if (N1C && N1C->isNullValue()) 5663 return N0; 5664 // fold (shl undef, x) -> 0 5665 if (N0.isUndef()) 5666 return DAG.getConstant(0, SDLoc(N), VT); 5667 5668 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5669 return NewSel; 5670 5671 // if (shl x, c) is known to be zero, return 0 5672 if (DAG.MaskedValueIsZero(SDValue(N, 0), 5673 APInt::getAllOnesValue(OpSizeInBits))) 5674 return DAG.getConstant(0, SDLoc(N), VT); 5675 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 5676 if (N1.getOpcode() == ISD::TRUNCATE && 5677 N1.getOperand(0).getOpcode() == ISD::AND) { 5678 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5679 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 5680 } 5681 5682 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5683 return SDValue(N, 0); 5684 5685 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 5686 if (N0.getOpcode() == ISD::SHL) { 5687 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 5688 ConstantSDNode *RHS) { 5689 APInt c1 = LHS->getAPIntValue(); 5690 APInt c2 = RHS->getAPIntValue(); 5691 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5692 return (c1 + c2).uge(OpSizeInBits); 5693 }; 5694 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 5695 return DAG.getConstant(0, SDLoc(N), VT); 5696 5697 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 5698 ConstantSDNode *RHS) { 5699 APInt c1 = LHS->getAPIntValue(); 5700 APInt c2 = RHS->getAPIntValue(); 5701 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5702 return (c1 + c2).ult(OpSizeInBits); 5703 }; 5704 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 5705 SDLoc DL(N); 5706 EVT ShiftVT = N1.getValueType(); 5707 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 5708 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum); 5709 } 5710 } 5711 5712 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 5713 // For this to be valid, the second form must not preserve any of the bits 5714 // that are shifted out by the inner shift in the first form. This means 5715 // the outer shift size must be >= the number of bits added by the ext. 5716 // As a corollary, we don't care what kind of ext it is. 5717 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 5718 N0.getOpcode() == ISD::ANY_EXTEND || 5719 N0.getOpcode() == ISD::SIGN_EXTEND) && 5720 N0.getOperand(0).getOpcode() == ISD::SHL) { 5721 SDValue N0Op0 = N0.getOperand(0); 5722 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5723 APInt c1 = N0Op0C1->getAPIntValue(); 5724 APInt c2 = N1C->getAPIntValue(); 5725 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5726 5727 EVT InnerShiftVT = N0Op0.getValueType(); 5728 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 5729 if (c2.uge(OpSizeInBits - InnerShiftSize)) { 5730 SDLoc DL(N0); 5731 APInt Sum = c1 + c2; 5732 if (Sum.uge(OpSizeInBits)) 5733 return DAG.getConstant(0, DL, VT); 5734 5735 return DAG.getNode( 5736 ISD::SHL, DL, VT, 5737 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)), 5738 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5739 } 5740 } 5741 } 5742 5743 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 5744 // Only fold this if the inner zext has no other uses to avoid increasing 5745 // the total number of instructions. 5746 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 5747 N0.getOperand(0).getOpcode() == ISD::SRL) { 5748 SDValue N0Op0 = N0.getOperand(0); 5749 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5750 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) { 5751 uint64_t c1 = N0Op0C1->getZExtValue(); 5752 uint64_t c2 = N1C->getZExtValue(); 5753 if (c1 == c2) { 5754 SDValue NewOp0 = N0.getOperand(0); 5755 EVT CountVT = NewOp0.getOperand(1).getValueType(); 5756 SDLoc DL(N); 5757 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 5758 NewOp0, 5759 DAG.getConstant(c2, DL, CountVT)); 5760 AddToWorklist(NewSHL.getNode()); 5761 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 5762 } 5763 } 5764 } 5765 } 5766 5767 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 5768 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 5769 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 5770 N0->getFlags().hasExact()) { 5771 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5772 uint64_t C1 = N0C1->getZExtValue(); 5773 uint64_t C2 = N1C->getZExtValue(); 5774 SDLoc DL(N); 5775 if (C1 <= C2) 5776 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5777 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 5778 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 5779 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 5780 } 5781 } 5782 5783 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 5784 // (and (srl x, (sub c1, c2), MASK) 5785 // Only fold this if the inner shift has no other uses -- if it does, folding 5786 // this will increase the total number of instructions. 5787 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5788 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5789 uint64_t c1 = N0C1->getZExtValue(); 5790 if (c1 < OpSizeInBits) { 5791 uint64_t c2 = N1C->getZExtValue(); 5792 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 5793 SDValue Shift; 5794 if (c2 > c1) { 5795 Mask <<= c2 - c1; 5796 SDLoc DL(N); 5797 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5798 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 5799 } else { 5800 Mask.lshrInPlace(c1 - c2); 5801 SDLoc DL(N); 5802 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 5803 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 5804 } 5805 SDLoc DL(N0); 5806 return DAG.getNode(ISD::AND, DL, VT, Shift, 5807 DAG.getConstant(Mask, DL, VT)); 5808 } 5809 } 5810 } 5811 5812 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 5813 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) && 5814 isConstantOrConstantVector(N1, /* No Opaques */ true)) { 5815 SDLoc DL(N); 5816 SDValue AllBits = DAG.getAllOnesConstant(DL, VT); 5817 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1); 5818 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask); 5819 } 5820 5821 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 5822 // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 5823 // Variant of version done on multiply, except mul by a power of 2 is turned 5824 // into a shift. 5825 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) && 5826 N0.getNode()->hasOneUse() && 5827 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5828 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5829 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 5830 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5831 AddToWorklist(Shl0.getNode()); 5832 AddToWorklist(Shl1.getNode()); 5833 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1); 5834 } 5835 5836 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 5837 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() && 5838 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5839 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5840 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5841 if (isConstantOrConstantVector(Shl)) 5842 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl); 5843 } 5844 5845 if (N1C && !N1C->isOpaque()) 5846 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 5847 return NewSHL; 5848 5849 return SDValue(); 5850 } 5851 5852 SDValue DAGCombiner::visitSRA(SDNode *N) { 5853 SDValue N0 = N->getOperand(0); 5854 SDValue N1 = N->getOperand(1); 5855 EVT VT = N0.getValueType(); 5856 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5857 5858 // Arithmetic shifting an all-sign-bit value is a no-op. 5859 // fold (sra 0, x) -> 0 5860 // fold (sra -1, x) -> -1 5861 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits) 5862 return N0; 5863 5864 // fold vector ops 5865 if (VT.isVector()) 5866 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5867 return FoldedVOp; 5868 5869 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5870 5871 // fold (sra c1, c2) -> (sra c1, c2) 5872 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5873 if (N0C && N1C && !N1C->isOpaque()) 5874 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 5875 // fold (sra x, c >= size(x)) -> undef 5876 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 5877 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 5878 return Val->getAPIntValue().uge(OpSizeInBits); 5879 }; 5880 if (matchUnaryPredicate(N1, MatchShiftTooBig)) 5881 return DAG.getUNDEF(VT); 5882 // fold (sra x, 0) -> x 5883 if (N1C && N1C->isNullValue()) 5884 return N0; 5885 5886 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5887 return NewSel; 5888 5889 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 5890 // sext_inreg. 5891 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 5892 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 5893 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 5894 if (VT.isVector()) 5895 ExtVT = EVT::getVectorVT(*DAG.getContext(), 5896 ExtVT, VT.getVectorNumElements()); 5897 if ((!LegalOperations || 5898 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 5899 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5900 N0.getOperand(0), DAG.getValueType(ExtVT)); 5901 } 5902 5903 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 5904 if (N0.getOpcode() == ISD::SRA) { 5905 SDLoc DL(N); 5906 EVT ShiftVT = N1.getValueType(); 5907 5908 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 5909 ConstantSDNode *RHS) { 5910 APInt c1 = LHS->getAPIntValue(); 5911 APInt c2 = RHS->getAPIntValue(); 5912 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5913 return (c1 + c2).uge(OpSizeInBits); 5914 }; 5915 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 5916 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), 5917 DAG.getConstant(OpSizeInBits - 1, DL, ShiftVT)); 5918 5919 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 5920 ConstantSDNode *RHS) { 5921 APInt c1 = LHS->getAPIntValue(); 5922 APInt c2 = RHS->getAPIntValue(); 5923 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5924 return (c1 + c2).ult(OpSizeInBits); 5925 }; 5926 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 5927 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 5928 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), Sum); 5929 } 5930 } 5931 5932 // fold (sra (shl X, m), (sub result_size, n)) 5933 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 5934 // result_size - n != m. 5935 // If truncate is free for the target sext(shl) is likely to result in better 5936 // code. 5937 if (N0.getOpcode() == ISD::SHL && N1C) { 5938 // Get the two constanst of the shifts, CN0 = m, CN = n. 5939 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 5940 if (N01C) { 5941 LLVMContext &Ctx = *DAG.getContext(); 5942 // Determine what the truncate's result bitsize and type would be. 5943 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 5944 5945 if (VT.isVector()) 5946 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 5947 5948 // Determine the residual right-shift amount. 5949 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 5950 5951 // If the shift is not a no-op (in which case this should be just a sign 5952 // extend already), the truncated to type is legal, sign_extend is legal 5953 // on that type, and the truncate to that type is both legal and free, 5954 // perform the transform. 5955 if ((ShiftAmt > 0) && 5956 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 5957 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 5958 TLI.isTruncateFree(VT, TruncVT)) { 5959 SDLoc DL(N); 5960 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 5961 getShiftAmountTy(N0.getOperand(0).getValueType())); 5962 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 5963 N0.getOperand(0), Amt); 5964 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 5965 Shift); 5966 return DAG.getNode(ISD::SIGN_EXTEND, DL, 5967 N->getValueType(0), Trunc); 5968 } 5969 } 5970 } 5971 5972 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 5973 if (N1.getOpcode() == ISD::TRUNCATE && 5974 N1.getOperand(0).getOpcode() == ISD::AND) { 5975 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5976 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 5977 } 5978 5979 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 5980 // if c1 is equal to the number of bits the trunc removes 5981 if (N0.getOpcode() == ISD::TRUNCATE && 5982 (N0.getOperand(0).getOpcode() == ISD::SRL || 5983 N0.getOperand(0).getOpcode() == ISD::SRA) && 5984 N0.getOperand(0).hasOneUse() && 5985 N0.getOperand(0).getOperand(1).hasOneUse() && 5986 N1C) { 5987 SDValue N0Op0 = N0.getOperand(0); 5988 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 5989 unsigned LargeShiftVal = LargeShift->getZExtValue(); 5990 EVT LargeVT = N0Op0.getValueType(); 5991 5992 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 5993 SDLoc DL(N); 5994 SDValue Amt = 5995 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 5996 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 5997 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 5998 N0Op0.getOperand(0), Amt); 5999 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 6000 } 6001 } 6002 } 6003 6004 // Simplify, based on bits shifted out of the LHS. 6005 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 6006 return SDValue(N, 0); 6007 6008 // If the sign bit is known to be zero, switch this to a SRL. 6009 if (DAG.SignBitIsZero(N0)) 6010 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 6011 6012 if (N1C && !N1C->isOpaque()) 6013 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 6014 return NewSRA; 6015 6016 return SDValue(); 6017 } 6018 6019 SDValue DAGCombiner::visitSRL(SDNode *N) { 6020 SDValue N0 = N->getOperand(0); 6021 SDValue N1 = N->getOperand(1); 6022 EVT VT = N0.getValueType(); 6023 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 6024 6025 // fold vector ops 6026 if (VT.isVector()) 6027 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 6028 return FoldedVOp; 6029 6030 ConstantSDNode *N1C = isConstOrConstSplat(N1); 6031 6032 // fold (srl c1, c2) -> c1 >>u c2 6033 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 6034 if (N0C && N1C && !N1C->isOpaque()) 6035 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 6036 // fold (srl 0, x) -> 0 6037 if (isNullConstantOrNullSplatConstant(N0)) 6038 return N0; 6039 // fold (srl x, c >= size(x)) -> undef 6040 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 6041 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 6042 return Val->getAPIntValue().uge(OpSizeInBits); 6043 }; 6044 if (matchUnaryPredicate(N1, MatchShiftTooBig)) 6045 return DAG.getUNDEF(VT); 6046 // fold (srl x, 0) -> x 6047 if (N1C && N1C->isNullValue()) 6048 return N0; 6049 6050 if (SDValue NewSel = foldBinOpIntoSelect(N)) 6051 return NewSel; 6052 6053 // if (srl x, c) is known to be zero, return 0 6054 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 6055 APInt::getAllOnesValue(OpSizeInBits))) 6056 return DAG.getConstant(0, SDLoc(N), VT); 6057 6058 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 6059 if (N0.getOpcode() == ISD::SRL) { 6060 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 6061 ConstantSDNode *RHS) { 6062 APInt c1 = LHS->getAPIntValue(); 6063 APInt c2 = RHS->getAPIntValue(); 6064 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6065 return (c1 + c2).uge(OpSizeInBits); 6066 }; 6067 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 6068 return DAG.getConstant(0, SDLoc(N), VT); 6069 6070 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 6071 ConstantSDNode *RHS) { 6072 APInt c1 = LHS->getAPIntValue(); 6073 APInt c2 = RHS->getAPIntValue(); 6074 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6075 return (c1 + c2).ult(OpSizeInBits); 6076 }; 6077 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 6078 SDLoc DL(N); 6079 EVT ShiftVT = N1.getValueType(); 6080 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 6081 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum); 6082 } 6083 } 6084 6085 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 6086 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 6087 N0.getOperand(0).getOpcode() == ISD::SRL) { 6088 if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) { 6089 uint64_t c1 = N001C->getZExtValue(); 6090 uint64_t c2 = N1C->getZExtValue(); 6091 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 6092 EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType(); 6093 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 6094 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 6095 if (c1 + OpSizeInBits == InnerShiftSize) { 6096 SDLoc DL(N0); 6097 if (c1 + c2 >= InnerShiftSize) 6098 return DAG.getConstant(0, DL, VT); 6099 return DAG.getNode(ISD::TRUNCATE, DL, VT, 6100 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 6101 N0.getOperand(0).getOperand(0), 6102 DAG.getConstant(c1 + c2, DL, 6103 ShiftCountVT))); 6104 } 6105 } 6106 } 6107 6108 // fold (srl (shl x, c), c) -> (and x, cst2) 6109 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 6110 isConstantOrConstantVector(N1, /* NoOpaques */ true)) { 6111 SDLoc DL(N); 6112 SDValue Mask = 6113 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1); 6114 AddToWorklist(Mask.getNode()); 6115 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask); 6116 } 6117 6118 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 6119 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 6120 // Shifting in all undef bits? 6121 EVT SmallVT = N0.getOperand(0).getValueType(); 6122 unsigned BitSize = SmallVT.getScalarSizeInBits(); 6123 if (N1C->getZExtValue() >= BitSize) 6124 return DAG.getUNDEF(VT); 6125 6126 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 6127 uint64_t ShiftAmt = N1C->getZExtValue(); 6128 SDLoc DL0(N0); 6129 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 6130 N0.getOperand(0), 6131 DAG.getConstant(ShiftAmt, DL0, 6132 getShiftAmountTy(SmallVT))); 6133 AddToWorklist(SmallShift.getNode()); 6134 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt); 6135 SDLoc DL(N); 6136 return DAG.getNode(ISD::AND, DL, VT, 6137 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 6138 DAG.getConstant(Mask, DL, VT)); 6139 } 6140 } 6141 6142 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 6143 // bit, which is unmodified by sra. 6144 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 6145 if (N0.getOpcode() == ISD::SRA) 6146 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 6147 } 6148 6149 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 6150 if (N1C && N0.getOpcode() == ISD::CTLZ && 6151 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 6152 KnownBits Known; 6153 DAG.computeKnownBits(N0.getOperand(0), Known); 6154 6155 // If any of the input bits are KnownOne, then the input couldn't be all 6156 // zeros, thus the result of the srl will always be zero. 6157 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 6158 6159 // If all of the bits input the to ctlz node are known to be zero, then 6160 // the result of the ctlz is "32" and the result of the shift is one. 6161 APInt UnknownBits = ~Known.Zero; 6162 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 6163 6164 // Otherwise, check to see if there is exactly one bit input to the ctlz. 6165 if (UnknownBits.isPowerOf2()) { 6166 // Okay, we know that only that the single bit specified by UnknownBits 6167 // could be set on input to the CTLZ node. If this bit is set, the SRL 6168 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 6169 // to an SRL/XOR pair, which is likely to simplify more. 6170 unsigned ShAmt = UnknownBits.countTrailingZeros(); 6171 SDValue Op = N0.getOperand(0); 6172 6173 if (ShAmt) { 6174 SDLoc DL(N0); 6175 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 6176 DAG.getConstant(ShAmt, DL, 6177 getShiftAmountTy(Op.getValueType()))); 6178 AddToWorklist(Op.getNode()); 6179 } 6180 6181 SDLoc DL(N); 6182 return DAG.getNode(ISD::XOR, DL, VT, 6183 Op, DAG.getConstant(1, DL, VT)); 6184 } 6185 } 6186 6187 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 6188 if (N1.getOpcode() == ISD::TRUNCATE && 6189 N1.getOperand(0).getOpcode() == ISD::AND) { 6190 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 6191 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 6192 } 6193 6194 // fold operands of srl based on knowledge that the low bits are not 6195 // demanded. 6196 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 6197 return SDValue(N, 0); 6198 6199 if (N1C && !N1C->isOpaque()) 6200 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 6201 return NewSRL; 6202 6203 // Attempt to convert a srl of a load into a narrower zero-extending load. 6204 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 6205 return NarrowLoad; 6206 6207 // Here is a common situation. We want to optimize: 6208 // 6209 // %a = ... 6210 // %b = and i32 %a, 2 6211 // %c = srl i32 %b, 1 6212 // brcond i32 %c ... 6213 // 6214 // into 6215 // 6216 // %a = ... 6217 // %b = and %a, 2 6218 // %c = setcc eq %b, 0 6219 // brcond %c ... 6220 // 6221 // However when after the source operand of SRL is optimized into AND, the SRL 6222 // itself may not be optimized further. Look for it and add the BRCOND into 6223 // the worklist. 6224 if (N->hasOneUse()) { 6225 SDNode *Use = *N->use_begin(); 6226 if (Use->getOpcode() == ISD::BRCOND) 6227 AddToWorklist(Use); 6228 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 6229 // Also look pass the truncate. 6230 Use = *Use->use_begin(); 6231 if (Use->getOpcode() == ISD::BRCOND) 6232 AddToWorklist(Use); 6233 } 6234 } 6235 6236 return SDValue(); 6237 } 6238 6239 SDValue DAGCombiner::visitABS(SDNode *N) { 6240 SDValue N0 = N->getOperand(0); 6241 EVT VT = N->getValueType(0); 6242 6243 // fold (abs c1) -> c2 6244 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6245 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0); 6246 // fold (abs (abs x)) -> (abs x) 6247 if (N0.getOpcode() == ISD::ABS) 6248 return N0; 6249 // fold (abs x) -> x iff not-negative 6250 if (DAG.SignBitIsZero(N0)) 6251 return N0; 6252 return SDValue(); 6253 } 6254 6255 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 6256 SDValue N0 = N->getOperand(0); 6257 EVT VT = N->getValueType(0); 6258 6259 // fold (bswap c1) -> c2 6260 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6261 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 6262 // fold (bswap (bswap x)) -> x 6263 if (N0.getOpcode() == ISD::BSWAP) 6264 return N0->getOperand(0); 6265 return SDValue(); 6266 } 6267 6268 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 6269 SDValue N0 = N->getOperand(0); 6270 EVT VT = N->getValueType(0); 6271 6272 // fold (bitreverse c1) -> c2 6273 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6274 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0); 6275 // fold (bitreverse (bitreverse x)) -> x 6276 if (N0.getOpcode() == ISD::BITREVERSE) 6277 return N0.getOperand(0); 6278 return SDValue(); 6279 } 6280 6281 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 6282 SDValue N0 = N->getOperand(0); 6283 EVT VT = N->getValueType(0); 6284 6285 // fold (ctlz c1) -> c2 6286 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6287 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 6288 return SDValue(); 6289 } 6290 6291 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 6292 SDValue N0 = N->getOperand(0); 6293 EVT VT = N->getValueType(0); 6294 6295 // fold (ctlz_zero_undef c1) -> c2 6296 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6297 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 6298 return SDValue(); 6299 } 6300 6301 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 6302 SDValue N0 = N->getOperand(0); 6303 EVT VT = N->getValueType(0); 6304 6305 // fold (cttz c1) -> c2 6306 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6307 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 6308 return SDValue(); 6309 } 6310 6311 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 6312 SDValue N0 = N->getOperand(0); 6313 EVT VT = N->getValueType(0); 6314 6315 // fold (cttz_zero_undef c1) -> c2 6316 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6317 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 6318 return SDValue(); 6319 } 6320 6321 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 6322 SDValue N0 = N->getOperand(0); 6323 EVT VT = N->getValueType(0); 6324 6325 // fold (ctpop c1) -> c2 6326 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6327 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 6328 return SDValue(); 6329 } 6330 6331 /// \brief Generate Min/Max node 6332 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 6333 SDValue RHS, SDValue True, SDValue False, 6334 ISD::CondCode CC, const TargetLowering &TLI, 6335 SelectionDAG &DAG) { 6336 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 6337 return SDValue(); 6338 6339 switch (CC) { 6340 case ISD::SETOLT: 6341 case ISD::SETOLE: 6342 case ISD::SETLT: 6343 case ISD::SETLE: 6344 case ISD::SETULT: 6345 case ISD::SETULE: { 6346 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 6347 if (TLI.isOperationLegal(Opcode, VT)) 6348 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 6349 return SDValue(); 6350 } 6351 case ISD::SETOGT: 6352 case ISD::SETOGE: 6353 case ISD::SETGT: 6354 case ISD::SETGE: 6355 case ISD::SETUGT: 6356 case ISD::SETUGE: { 6357 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 6358 if (TLI.isOperationLegal(Opcode, VT)) 6359 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 6360 return SDValue(); 6361 } 6362 default: 6363 return SDValue(); 6364 } 6365 } 6366 6367 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) { 6368 SDValue Cond = N->getOperand(0); 6369 SDValue N1 = N->getOperand(1); 6370 SDValue N2 = N->getOperand(2); 6371 EVT VT = N->getValueType(0); 6372 EVT CondVT = Cond.getValueType(); 6373 SDLoc DL(N); 6374 6375 if (!VT.isInteger()) 6376 return SDValue(); 6377 6378 auto *C1 = dyn_cast<ConstantSDNode>(N1); 6379 auto *C2 = dyn_cast<ConstantSDNode>(N2); 6380 if (!C1 || !C2) 6381 return SDValue(); 6382 6383 // Only do this before legalization to avoid conflicting with target-specific 6384 // transforms in the other direction (create a select from a zext/sext). There 6385 // is also a target-independent combine here in DAGCombiner in the other 6386 // direction for (select Cond, -1, 0) when the condition is not i1. 6387 if (CondVT == MVT::i1 && !LegalOperations) { 6388 if (C1->isNullValue() && C2->isOne()) { 6389 // select Cond, 0, 1 --> zext (!Cond) 6390 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 6391 if (VT != MVT::i1) 6392 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond); 6393 return NotCond; 6394 } 6395 if (C1->isNullValue() && C2->isAllOnesValue()) { 6396 // select Cond, 0, -1 --> sext (!Cond) 6397 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 6398 if (VT != MVT::i1) 6399 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond); 6400 return NotCond; 6401 } 6402 if (C1->isOne() && C2->isNullValue()) { 6403 // select Cond, 1, 0 --> zext (Cond) 6404 if (VT != MVT::i1) 6405 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 6406 return Cond; 6407 } 6408 if (C1->isAllOnesValue() && C2->isNullValue()) { 6409 // select Cond, -1, 0 --> sext (Cond) 6410 if (VT != MVT::i1) 6411 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 6412 return Cond; 6413 } 6414 6415 // For any constants that differ by 1, we can transform the select into an 6416 // extend and add. Use a target hook because some targets may prefer to 6417 // transform in the other direction. 6418 if (TLI.convertSelectOfConstantsToMath(VT)) { 6419 if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) { 6420 // select Cond, C1, C1-1 --> add (zext Cond), C1-1 6421 if (VT != MVT::i1) 6422 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 6423 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 6424 } 6425 if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) { 6426 // select Cond, C1, C1+1 --> add (sext Cond), C1+1 6427 if (VT != MVT::i1) 6428 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 6429 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 6430 } 6431 } 6432 6433 return SDValue(); 6434 } 6435 6436 // fold (select Cond, 0, 1) -> (xor Cond, 1) 6437 // We can't do this reliably if integer based booleans have different contents 6438 // to floating point based booleans. This is because we can't tell whether we 6439 // have an integer-based boolean or a floating-point-based boolean unless we 6440 // can find the SETCC that produced it and inspect its operands. This is 6441 // fairly easy if C is the SETCC node, but it can potentially be 6442 // undiscoverable (or not reasonably discoverable). For example, it could be 6443 // in another basic block or it could require searching a complicated 6444 // expression. 6445 if (CondVT.isInteger() && 6446 TLI.getBooleanContents(false, true) == 6447 TargetLowering::ZeroOrOneBooleanContent && 6448 TLI.getBooleanContents(false, false) == 6449 TargetLowering::ZeroOrOneBooleanContent && 6450 C1->isNullValue() && C2->isOne()) { 6451 SDValue NotCond = 6452 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT)); 6453 if (VT.bitsEq(CondVT)) 6454 return NotCond; 6455 return DAG.getZExtOrTrunc(NotCond, DL, VT); 6456 } 6457 6458 return SDValue(); 6459 } 6460 6461 SDValue DAGCombiner::visitSELECT(SDNode *N) { 6462 SDValue N0 = N->getOperand(0); 6463 SDValue N1 = N->getOperand(1); 6464 SDValue N2 = N->getOperand(2); 6465 EVT VT = N->getValueType(0); 6466 EVT VT0 = N0.getValueType(); 6467 SDLoc DL(N); 6468 6469 // fold (select C, X, X) -> X 6470 if (N1 == N2) 6471 return N1; 6472 6473 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 6474 // fold (select true, X, Y) -> X 6475 // fold (select false, X, Y) -> Y 6476 return !N0C->isNullValue() ? N1 : N2; 6477 } 6478 6479 // fold (select X, X, Y) -> (or X, Y) 6480 // fold (select X, 1, Y) -> (or C, Y) 6481 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 6482 return DAG.getNode(ISD::OR, DL, VT, N0, N2); 6483 6484 if (SDValue V = foldSelectOfConstants(N)) 6485 return V; 6486 6487 // fold (select C, 0, X) -> (and (not C), X) 6488 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 6489 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 6490 AddToWorklist(NOTNode.getNode()); 6491 return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2); 6492 } 6493 // fold (select C, X, 1) -> (or (not C), X) 6494 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 6495 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 6496 AddToWorklist(NOTNode.getNode()); 6497 return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1); 6498 } 6499 // fold (select X, Y, X) -> (and X, Y) 6500 // fold (select X, Y, 0) -> (and X, Y) 6501 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 6502 return DAG.getNode(ISD::AND, DL, VT, N0, N1); 6503 6504 // If we can fold this based on the true/false value, do so. 6505 if (SimplifySelectOps(N, N1, N2)) 6506 return SDValue(N, 0); // Don't revisit N. 6507 6508 if (VT0 == MVT::i1) { 6509 // The code in this block deals with the following 2 equivalences: 6510 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 6511 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 6512 // The target can specify its preferred form with the 6513 // shouldNormalizeToSelectSequence() callback. However we always transform 6514 // to the right anyway if we find the inner select exists in the DAG anyway 6515 // and we always transform to the left side if we know that we can further 6516 // optimize the combination of the conditions. 6517 bool normalizeToSequence = 6518 TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 6519 // select (and Cond0, Cond1), X, Y 6520 // -> select Cond0, (select Cond1, X, Y), Y 6521 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 6522 SDValue Cond0 = N0->getOperand(0); 6523 SDValue Cond1 = N0->getOperand(1); 6524 SDValue InnerSelect = 6525 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2); 6526 if (normalizeToSequence || !InnerSelect.use_empty()) 6527 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, 6528 InnerSelect, N2); 6529 } 6530 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 6531 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 6532 SDValue Cond0 = N0->getOperand(0); 6533 SDValue Cond1 = N0->getOperand(1); 6534 SDValue InnerSelect = 6535 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2); 6536 if (normalizeToSequence || !InnerSelect.use_empty()) 6537 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1, 6538 InnerSelect); 6539 } 6540 6541 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 6542 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 6543 SDValue N1_0 = N1->getOperand(0); 6544 SDValue N1_1 = N1->getOperand(1); 6545 SDValue N1_2 = N1->getOperand(2); 6546 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 6547 // Create the actual and node if we can generate good code for it. 6548 if (!normalizeToSequence) { 6549 SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0); 6550 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2); 6551 } 6552 // Otherwise see if we can optimize the "and" to a better pattern. 6553 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 6554 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1, 6555 N2); 6556 } 6557 } 6558 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 6559 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 6560 SDValue N2_0 = N2->getOperand(0); 6561 SDValue N2_1 = N2->getOperand(1); 6562 SDValue N2_2 = N2->getOperand(2); 6563 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 6564 // Create the actual or node if we can generate good code for it. 6565 if (!normalizeToSequence) { 6566 SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0); 6567 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2); 6568 } 6569 // Otherwise see if we can optimize to a better pattern. 6570 if (SDValue Combined = visitORLike(N0, N2_0, N)) 6571 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1, 6572 N2_2); 6573 } 6574 } 6575 } 6576 6577 // select (xor Cond, 1), X, Y -> select Cond, Y, X 6578 if (VT0 == MVT::i1) { 6579 if (N0->getOpcode() == ISD::XOR) { 6580 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) { 6581 SDValue Cond0 = N0->getOperand(0); 6582 if (C->isOne()) 6583 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N2, N1); 6584 } 6585 } 6586 } 6587 6588 // fold selects based on a setcc into other things, such as min/max/abs 6589 if (N0.getOpcode() == ISD::SETCC) { 6590 // select x, y (fcmp lt x, y) -> fminnum x, y 6591 // select x, y (fcmp gt x, y) -> fmaxnum x, y 6592 // 6593 // This is OK if we don't care about what happens if either operand is a 6594 // NaN. 6595 // 6596 6597 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 6598 // no signed zeros as well as no nans. 6599 const TargetOptions &Options = DAG.getTarget().Options; 6600 if (Options.UnsafeFPMath && VT.isFloatingPoint() && N0.hasOneUse() && 6601 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 6602 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6603 6604 if (SDValue FMinMax = combineMinNumMaxNum( 6605 DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG)) 6606 return FMinMax; 6607 } 6608 6609 if ((!LegalOperations && 6610 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 6611 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 6612 return DAG.getNode(ISD::SELECT_CC, DL, VT, N0.getOperand(0), 6613 N0.getOperand(1), N1, N2, N0.getOperand(2)); 6614 return SimplifySelect(DL, N0, N1, N2); 6615 } 6616 6617 return SDValue(); 6618 } 6619 6620 static 6621 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 6622 SDLoc DL(N); 6623 EVT LoVT, HiVT; 6624 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 6625 6626 // Split the inputs. 6627 SDValue Lo, Hi, LL, LH, RL, RH; 6628 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 6629 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 6630 6631 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 6632 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 6633 6634 return std::make_pair(Lo, Hi); 6635 } 6636 6637 // This function assumes all the vselect's arguments are CONCAT_VECTOR 6638 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 6639 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 6640 SDLoc DL(N); 6641 SDValue Cond = N->getOperand(0); 6642 SDValue LHS = N->getOperand(1); 6643 SDValue RHS = N->getOperand(2); 6644 EVT VT = N->getValueType(0); 6645 int NumElems = VT.getVectorNumElements(); 6646 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 6647 RHS.getOpcode() == ISD::CONCAT_VECTORS && 6648 Cond.getOpcode() == ISD::BUILD_VECTOR); 6649 6650 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 6651 // binary ones here. 6652 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 6653 return SDValue(); 6654 6655 // We're sure we have an even number of elements due to the 6656 // concat_vectors we have as arguments to vselect. 6657 // Skip BV elements until we find one that's not an UNDEF 6658 // After we find an UNDEF element, keep looping until we get to half the 6659 // length of the BV and see if all the non-undef nodes are the same. 6660 ConstantSDNode *BottomHalf = nullptr; 6661 for (int i = 0; i < NumElems / 2; ++i) { 6662 if (Cond->getOperand(i)->isUndef()) 6663 continue; 6664 6665 if (BottomHalf == nullptr) 6666 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 6667 else if (Cond->getOperand(i).getNode() != BottomHalf) 6668 return SDValue(); 6669 } 6670 6671 // Do the same for the second half of the BuildVector 6672 ConstantSDNode *TopHalf = nullptr; 6673 for (int i = NumElems / 2; i < NumElems; ++i) { 6674 if (Cond->getOperand(i)->isUndef()) 6675 continue; 6676 6677 if (TopHalf == nullptr) 6678 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 6679 else if (Cond->getOperand(i).getNode() != TopHalf) 6680 return SDValue(); 6681 } 6682 6683 assert(TopHalf && BottomHalf && 6684 "One half of the selector was all UNDEFs and the other was all the " 6685 "same value. This should have been addressed before this function."); 6686 return DAG.getNode( 6687 ISD::CONCAT_VECTORS, DL, VT, 6688 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 6689 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 6690 } 6691 6692 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 6693 if (Level >= AfterLegalizeTypes) 6694 return SDValue(); 6695 6696 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 6697 SDValue Mask = MSC->getMask(); 6698 SDValue Data = MSC->getValue(); 6699 SDLoc DL(N); 6700 6701 // If the MSCATTER data type requires splitting and the mask is provided by a 6702 // SETCC, then split both nodes and its operands before legalization. This 6703 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6704 // and enables future optimizations (e.g. min/max pattern matching on X86). 6705 if (Mask.getOpcode() != ISD::SETCC) 6706 return SDValue(); 6707 6708 // Check if any splitting is required. 6709 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 6710 TargetLowering::TypeSplitVector) 6711 return SDValue(); 6712 SDValue MaskLo, MaskHi, Lo, Hi; 6713 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6714 6715 EVT LoVT, HiVT; 6716 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 6717 6718 SDValue Chain = MSC->getChain(); 6719 6720 EVT MemoryVT = MSC->getMemoryVT(); 6721 unsigned Alignment = MSC->getOriginalAlignment(); 6722 6723 EVT LoMemVT, HiMemVT; 6724 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6725 6726 SDValue DataLo, DataHi; 6727 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6728 6729 SDValue BasePtr = MSC->getBasePtr(); 6730 SDValue IndexLo, IndexHi; 6731 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 6732 6733 MachineMemOperand *MMO = DAG.getMachineFunction(). 6734 getMachineMemOperand(MSC->getPointerInfo(), 6735 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6736 Alignment, MSC->getAAInfo(), MSC->getRanges()); 6737 6738 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 6739 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 6740 DL, OpsLo, MMO); 6741 6742 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 6743 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 6744 DL, OpsHi, MMO); 6745 6746 AddToWorklist(Lo.getNode()); 6747 AddToWorklist(Hi.getNode()); 6748 6749 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6750 } 6751 6752 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 6753 if (Level >= AfterLegalizeTypes) 6754 return SDValue(); 6755 6756 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 6757 SDValue Mask = MST->getMask(); 6758 SDValue Data = MST->getValue(); 6759 EVT VT = Data.getValueType(); 6760 SDLoc DL(N); 6761 6762 // If the MSTORE data type requires splitting and the mask is provided by a 6763 // SETCC, then split both nodes and its operands before legalization. This 6764 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6765 // and enables future optimizations (e.g. min/max pattern matching on X86). 6766 if (Mask.getOpcode() == ISD::SETCC) { 6767 // Check if any splitting is required. 6768 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6769 TargetLowering::TypeSplitVector) 6770 return SDValue(); 6771 6772 SDValue MaskLo, MaskHi, Lo, Hi; 6773 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6774 6775 SDValue Chain = MST->getChain(); 6776 SDValue Ptr = MST->getBasePtr(); 6777 6778 EVT MemoryVT = MST->getMemoryVT(); 6779 unsigned Alignment = MST->getOriginalAlignment(); 6780 6781 // if Alignment is equal to the vector size, 6782 // take the half of it for the second part 6783 unsigned SecondHalfAlignment = 6784 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment; 6785 6786 EVT LoMemVT, HiMemVT; 6787 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6788 6789 SDValue DataLo, DataHi; 6790 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6791 6792 MachineMemOperand *MMO = DAG.getMachineFunction(). 6793 getMachineMemOperand(MST->getPointerInfo(), 6794 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6795 Alignment, MST->getAAInfo(), MST->getRanges()); 6796 6797 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 6798 MST->isTruncatingStore(), 6799 MST->isCompressingStore()); 6800 6801 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6802 MST->isCompressingStore()); 6803 6804 MMO = DAG.getMachineFunction(). 6805 getMachineMemOperand(MST->getPointerInfo(), 6806 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 6807 SecondHalfAlignment, MST->getAAInfo(), 6808 MST->getRanges()); 6809 6810 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 6811 MST->isTruncatingStore(), 6812 MST->isCompressingStore()); 6813 6814 AddToWorklist(Lo.getNode()); 6815 AddToWorklist(Hi.getNode()); 6816 6817 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6818 } 6819 return SDValue(); 6820 } 6821 6822 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 6823 if (Level >= AfterLegalizeTypes) 6824 return SDValue(); 6825 6826 MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N); 6827 SDValue Mask = MGT->getMask(); 6828 SDLoc DL(N); 6829 6830 // If the MGATHER result requires splitting and the mask is provided by a 6831 // SETCC, then split both nodes and its operands before legalization. This 6832 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6833 // and enables future optimizations (e.g. min/max pattern matching on X86). 6834 6835 if (Mask.getOpcode() != ISD::SETCC) 6836 return SDValue(); 6837 6838 EVT VT = N->getValueType(0); 6839 6840 // Check if any splitting is required. 6841 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6842 TargetLowering::TypeSplitVector) 6843 return SDValue(); 6844 6845 SDValue MaskLo, MaskHi, Lo, Hi; 6846 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6847 6848 SDValue Src0 = MGT->getValue(); 6849 SDValue Src0Lo, Src0Hi; 6850 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6851 6852 EVT LoVT, HiVT; 6853 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 6854 6855 SDValue Chain = MGT->getChain(); 6856 EVT MemoryVT = MGT->getMemoryVT(); 6857 unsigned Alignment = MGT->getOriginalAlignment(); 6858 6859 EVT LoMemVT, HiMemVT; 6860 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6861 6862 SDValue BasePtr = MGT->getBasePtr(); 6863 SDValue Index = MGT->getIndex(); 6864 SDValue IndexLo, IndexHi; 6865 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 6866 6867 MachineMemOperand *MMO = DAG.getMachineFunction(). 6868 getMachineMemOperand(MGT->getPointerInfo(), 6869 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6870 Alignment, MGT->getAAInfo(), MGT->getRanges()); 6871 6872 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 6873 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 6874 MMO); 6875 6876 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 6877 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 6878 MMO); 6879 6880 AddToWorklist(Lo.getNode()); 6881 AddToWorklist(Hi.getNode()); 6882 6883 // Build a factor node to remember that this load is independent of the 6884 // other one. 6885 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6886 Hi.getValue(1)); 6887 6888 // Legalized the chain result - switch anything that used the old chain to 6889 // use the new one. 6890 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 6891 6892 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6893 6894 SDValue RetOps[] = { GatherRes, Chain }; 6895 return DAG.getMergeValues(RetOps, DL); 6896 } 6897 6898 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 6899 if (Level >= AfterLegalizeTypes) 6900 return SDValue(); 6901 6902 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 6903 SDValue Mask = MLD->getMask(); 6904 SDLoc DL(N); 6905 6906 // If the MLOAD result requires splitting and the mask is provided by a 6907 // SETCC, then split both nodes and its operands before legalization. This 6908 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6909 // and enables future optimizations (e.g. min/max pattern matching on X86). 6910 if (Mask.getOpcode() == ISD::SETCC) { 6911 EVT VT = N->getValueType(0); 6912 6913 // Check if any splitting is required. 6914 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6915 TargetLowering::TypeSplitVector) 6916 return SDValue(); 6917 6918 SDValue MaskLo, MaskHi, Lo, Hi; 6919 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6920 6921 SDValue Src0 = MLD->getSrc0(); 6922 SDValue Src0Lo, Src0Hi; 6923 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6924 6925 EVT LoVT, HiVT; 6926 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 6927 6928 SDValue Chain = MLD->getChain(); 6929 SDValue Ptr = MLD->getBasePtr(); 6930 EVT MemoryVT = MLD->getMemoryVT(); 6931 unsigned Alignment = MLD->getOriginalAlignment(); 6932 6933 // if Alignment is equal to the vector size, 6934 // take the half of it for the second part 6935 unsigned SecondHalfAlignment = 6936 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 6937 Alignment/2 : Alignment; 6938 6939 EVT LoMemVT, HiMemVT; 6940 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6941 6942 MachineMemOperand *MMO = DAG.getMachineFunction(). 6943 getMachineMemOperand(MLD->getPointerInfo(), 6944 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6945 Alignment, MLD->getAAInfo(), MLD->getRanges()); 6946 6947 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 6948 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6949 6950 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6951 MLD->isExpandingLoad()); 6952 6953 MMO = DAG.getMachineFunction(). 6954 getMachineMemOperand(MLD->getPointerInfo(), 6955 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 6956 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 6957 6958 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 6959 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6960 6961 AddToWorklist(Lo.getNode()); 6962 AddToWorklist(Hi.getNode()); 6963 6964 // Build a factor node to remember that this load is independent of the 6965 // other one. 6966 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6967 Hi.getValue(1)); 6968 6969 // Legalized the chain result - switch anything that used the old chain to 6970 // use the new one. 6971 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 6972 6973 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6974 6975 SDValue RetOps[] = { LoadRes, Chain }; 6976 return DAG.getMergeValues(RetOps, DL); 6977 } 6978 return SDValue(); 6979 } 6980 6981 /// A vector select of 2 constant vectors can be simplified to math/logic to 6982 /// avoid a variable select instruction and possibly avoid constant loads. 6983 SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) { 6984 SDValue Cond = N->getOperand(0); 6985 SDValue N1 = N->getOperand(1); 6986 SDValue N2 = N->getOperand(2); 6987 EVT VT = N->getValueType(0); 6988 if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 || 6989 !TLI.convertSelectOfConstantsToMath(VT) || 6990 !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) || 6991 !ISD::isBuildVectorOfConstantSDNodes(N2.getNode())) 6992 return SDValue(); 6993 6994 // Check if we can use the condition value to increment/decrement a single 6995 // constant value. This simplifies a select to an add and removes a constant 6996 // load/materialization from the general case. 6997 bool AllAddOne = true; 6998 bool AllSubOne = true; 6999 unsigned Elts = VT.getVectorNumElements(); 7000 for (unsigned i = 0; i != Elts; ++i) { 7001 SDValue N1Elt = N1.getOperand(i); 7002 SDValue N2Elt = N2.getOperand(i); 7003 if (N1Elt.isUndef() || N2Elt.isUndef()) 7004 continue; 7005 7006 const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue(); 7007 const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue(); 7008 if (C1 != C2 + 1) 7009 AllAddOne = false; 7010 if (C1 != C2 - 1) 7011 AllSubOne = false; 7012 } 7013 7014 // Further simplifications for the extra-special cases where the constants are 7015 // all 0 or all -1 should be implemented as folds of these patterns. 7016 SDLoc DL(N); 7017 if (AllAddOne || AllSubOne) { 7018 // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C 7019 // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C 7020 auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND; 7021 SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond); 7022 return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2); 7023 } 7024 7025 // The general case for select-of-constants: 7026 // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2 7027 // ...but that only makes sense if a vselect is slower than 2 logic ops, so 7028 // leave that to a machine-specific pass. 7029 return SDValue(); 7030 } 7031 7032 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 7033 SDValue N0 = N->getOperand(0); 7034 SDValue N1 = N->getOperand(1); 7035 SDValue N2 = N->getOperand(2); 7036 SDLoc DL(N); 7037 7038 // fold (vselect C, X, X) -> X 7039 if (N1 == N2) 7040 return N1; 7041 7042 // Canonicalize integer abs. 7043 // vselect (setg[te] X, 0), X, -X -> 7044 // vselect (setgt X, -1), X, -X -> 7045 // vselect (setl[te] X, 0), -X, X -> 7046 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 7047 if (N0.getOpcode() == ISD::SETCC) { 7048 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 7049 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 7050 bool isAbs = false; 7051 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 7052 7053 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 7054 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 7055 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 7056 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 7057 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 7058 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 7059 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 7060 7061 if (isAbs) { 7062 EVT VT = LHS.getValueType(); 7063 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) 7064 return DAG.getNode(ISD::ABS, DL, VT, LHS); 7065 7066 SDValue Shift = DAG.getNode( 7067 ISD::SRA, DL, VT, LHS, 7068 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT)); 7069 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 7070 AddToWorklist(Shift.getNode()); 7071 AddToWorklist(Add.getNode()); 7072 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 7073 } 7074 } 7075 7076 if (SimplifySelectOps(N, N1, N2)) 7077 return SDValue(N, 0); // Don't revisit N. 7078 7079 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 7080 if (ISD::isBuildVectorAllOnes(N0.getNode())) 7081 return N1; 7082 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 7083 if (ISD::isBuildVectorAllZeros(N0.getNode())) 7084 return N2; 7085 7086 // The ConvertSelectToConcatVector function is assuming both the above 7087 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 7088 // and addressed. 7089 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 7090 N2.getOpcode() == ISD::CONCAT_VECTORS && 7091 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 7092 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 7093 return CV; 7094 } 7095 7096 if (SDValue V = foldVSelectOfConstants(N)) 7097 return V; 7098 7099 return SDValue(); 7100 } 7101 7102 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 7103 SDValue N0 = N->getOperand(0); 7104 SDValue N1 = N->getOperand(1); 7105 SDValue N2 = N->getOperand(2); 7106 SDValue N3 = N->getOperand(3); 7107 SDValue N4 = N->getOperand(4); 7108 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 7109 7110 // fold select_cc lhs, rhs, x, x, cc -> x 7111 if (N2 == N3) 7112 return N2; 7113 7114 // Determine if the condition we're dealing with is constant 7115 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 7116 CC, SDLoc(N), false)) { 7117 AddToWorklist(SCC.getNode()); 7118 7119 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 7120 if (!SCCC->isNullValue()) 7121 return N2; // cond always true -> true val 7122 else 7123 return N3; // cond always false -> false val 7124 } else if (SCC->isUndef()) { 7125 // When the condition is UNDEF, just return the first operand. This is 7126 // coherent the DAG creation, no setcc node is created in this case 7127 return N2; 7128 } else if (SCC.getOpcode() == ISD::SETCC) { 7129 // Fold to a simpler select_cc 7130 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 7131 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 7132 SCC.getOperand(2)); 7133 } 7134 } 7135 7136 // If we can fold this based on the true/false value, do so. 7137 if (SimplifySelectOps(N, N2, N3)) 7138 return SDValue(N, 0); // Don't revisit N. 7139 7140 // fold select_cc into other things, such as min/max/abs 7141 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 7142 } 7143 7144 SDValue DAGCombiner::visitSETCC(SDNode *N) { 7145 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 7146 cast<CondCodeSDNode>(N->getOperand(2))->get(), 7147 SDLoc(N)); 7148 } 7149 7150 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 7151 SDValue LHS = N->getOperand(0); 7152 SDValue RHS = N->getOperand(1); 7153 SDValue Carry = N->getOperand(2); 7154 SDValue Cond = N->getOperand(3); 7155 7156 // If Carry is false, fold to a regular SETCC. 7157 if (Carry.getOpcode() == ISD::CARRY_FALSE) 7158 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 7159 7160 return SDValue(); 7161 } 7162 7163 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) { 7164 SDValue LHS = N->getOperand(0); 7165 SDValue RHS = N->getOperand(1); 7166 SDValue Carry = N->getOperand(2); 7167 SDValue Cond = N->getOperand(3); 7168 7169 // If Carry is false, fold to a regular SETCC. 7170 if (isNullConstant(Carry)) 7171 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 7172 7173 return SDValue(); 7174 } 7175 7176 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 7177 /// a build_vector of constants. 7178 /// This function is called by the DAGCombiner when visiting sext/zext/aext 7179 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 7180 /// Vector extends are not folded if operations are legal; this is to 7181 /// avoid introducing illegal build_vector dag nodes. 7182 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 7183 SelectionDAG &DAG, bool LegalTypes, 7184 bool LegalOperations) { 7185 unsigned Opcode = N->getOpcode(); 7186 SDValue N0 = N->getOperand(0); 7187 EVT VT = N->getValueType(0); 7188 7189 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 7190 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 7191 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 7192 && "Expected EXTEND dag node in input!"); 7193 7194 // fold (sext c1) -> c1 7195 // fold (zext c1) -> c1 7196 // fold (aext c1) -> c1 7197 if (isa<ConstantSDNode>(N0)) 7198 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 7199 7200 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 7201 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 7202 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 7203 EVT SVT = VT.getScalarType(); 7204 if (!(VT.isVector() && 7205 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 7206 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 7207 return nullptr; 7208 7209 // We can fold this node into a build_vector. 7210 unsigned VTBits = SVT.getSizeInBits(); 7211 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits(); 7212 SmallVector<SDValue, 8> Elts; 7213 unsigned NumElts = VT.getVectorNumElements(); 7214 SDLoc DL(N); 7215 7216 for (unsigned i=0; i != NumElts; ++i) { 7217 SDValue Op = N0->getOperand(i); 7218 if (Op->isUndef()) { 7219 Elts.push_back(DAG.getUNDEF(SVT)); 7220 continue; 7221 } 7222 7223 SDLoc DL(Op); 7224 // Get the constant value and if needed trunc it to the size of the type. 7225 // Nodes like build_vector might have constants wider than the scalar type. 7226 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 7227 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 7228 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 7229 else 7230 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 7231 } 7232 7233 return DAG.getBuildVector(VT, DL, Elts).getNode(); 7234 } 7235 7236 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 7237 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 7238 // transformation. Returns true if extension are possible and the above 7239 // mentioned transformation is profitable. 7240 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 7241 unsigned ExtOpc, 7242 SmallVectorImpl<SDNode *> &ExtendNodes, 7243 const TargetLowering &TLI) { 7244 bool HasCopyToRegUses = false; 7245 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 7246 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 7247 UE = N0.getNode()->use_end(); 7248 UI != UE; ++UI) { 7249 SDNode *User = *UI; 7250 if (User == N) 7251 continue; 7252 if (UI.getUse().getResNo() != N0.getResNo()) 7253 continue; 7254 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 7255 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 7256 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 7257 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 7258 // Sign bits will be lost after a zext. 7259 return false; 7260 bool Add = false; 7261 for (unsigned i = 0; i != 2; ++i) { 7262 SDValue UseOp = User->getOperand(i); 7263 if (UseOp == N0) 7264 continue; 7265 if (!isa<ConstantSDNode>(UseOp)) 7266 return false; 7267 Add = true; 7268 } 7269 if (Add) 7270 ExtendNodes.push_back(User); 7271 continue; 7272 } 7273 // If truncates aren't free and there are users we can't 7274 // extend, it isn't worthwhile. 7275 if (!isTruncFree) 7276 return false; 7277 // Remember if this value is live-out. 7278 if (User->getOpcode() == ISD::CopyToReg) 7279 HasCopyToRegUses = true; 7280 } 7281 7282 if (HasCopyToRegUses) { 7283 bool BothLiveOut = false; 7284 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 7285 UI != UE; ++UI) { 7286 SDUse &Use = UI.getUse(); 7287 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 7288 BothLiveOut = true; 7289 break; 7290 } 7291 } 7292 if (BothLiveOut) 7293 // Both unextended and extended values are live out. There had better be 7294 // a good reason for the transformation. 7295 return ExtendNodes.size(); 7296 } 7297 return true; 7298 } 7299 7300 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 7301 SDValue Trunc, SDValue ExtLoad, 7302 const SDLoc &DL, ISD::NodeType ExtType) { 7303 // Extend SetCC uses if necessary. 7304 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 7305 SDNode *SetCC = SetCCs[i]; 7306 SmallVector<SDValue, 4> Ops; 7307 7308 for (unsigned j = 0; j != 2; ++j) { 7309 SDValue SOp = SetCC->getOperand(j); 7310 if (SOp == Trunc) 7311 Ops.push_back(ExtLoad); 7312 else 7313 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 7314 } 7315 7316 Ops.push_back(SetCC->getOperand(2)); 7317 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 7318 } 7319 } 7320 7321 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 7322 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 7323 SDValue N0 = N->getOperand(0); 7324 EVT DstVT = N->getValueType(0); 7325 EVT SrcVT = N0.getValueType(); 7326 7327 assert((N->getOpcode() == ISD::SIGN_EXTEND || 7328 N->getOpcode() == ISD::ZERO_EXTEND) && 7329 "Unexpected node type (not an extend)!"); 7330 7331 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 7332 // For example, on a target with legal v4i32, but illegal v8i32, turn: 7333 // (v8i32 (sext (v8i16 (load x)))) 7334 // into: 7335 // (v8i32 (concat_vectors (v4i32 (sextload x)), 7336 // (v4i32 (sextload (x + 16))))) 7337 // Where uses of the original load, i.e.: 7338 // (v8i16 (load x)) 7339 // are replaced with: 7340 // (v8i16 (truncate 7341 // (v8i32 (concat_vectors (v4i32 (sextload x)), 7342 // (v4i32 (sextload (x + 16))))))) 7343 // 7344 // This combine is only applicable to illegal, but splittable, vectors. 7345 // All legal types, and illegal non-vector types, are handled elsewhere. 7346 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 7347 // 7348 if (N0->getOpcode() != ISD::LOAD) 7349 return SDValue(); 7350 7351 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7352 7353 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 7354 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 7355 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 7356 return SDValue(); 7357 7358 SmallVector<SDNode *, 4> SetCCs; 7359 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 7360 return SDValue(); 7361 7362 ISD::LoadExtType ExtType = 7363 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 7364 7365 // Try to split the vector types to get down to legal types. 7366 EVT SplitSrcVT = SrcVT; 7367 EVT SplitDstVT = DstVT; 7368 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 7369 SplitSrcVT.getVectorNumElements() > 1) { 7370 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 7371 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 7372 } 7373 7374 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 7375 return SDValue(); 7376 7377 SDLoc DL(N); 7378 const unsigned NumSplits = 7379 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 7380 const unsigned Stride = SplitSrcVT.getStoreSize(); 7381 SmallVector<SDValue, 4> Loads; 7382 SmallVector<SDValue, 4> Chains; 7383 7384 SDValue BasePtr = LN0->getBasePtr(); 7385 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 7386 const unsigned Offset = Idx * Stride; 7387 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 7388 7389 SDValue SplitLoad = DAG.getExtLoad( 7390 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 7391 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 7392 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 7393 7394 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 7395 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 7396 7397 Loads.push_back(SplitLoad.getValue(0)); 7398 Chains.push_back(SplitLoad.getValue(1)); 7399 } 7400 7401 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 7402 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 7403 7404 // Simplify TF. 7405 AddToWorklist(NewChain.getNode()); 7406 7407 CombineTo(N, NewValue); 7408 7409 // Replace uses of the original load (before extension) 7410 // with a truncate of the concatenated sextloaded vectors. 7411 SDValue Trunc = 7412 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 7413 CombineTo(N0.getNode(), Trunc, NewChain); 7414 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 7415 (ISD::NodeType)N->getOpcode()); 7416 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7417 } 7418 7419 /// If we're narrowing or widening the result of a vector select and the final 7420 /// size is the same size as a setcc (compare) feeding the select, then try to 7421 /// apply the cast operation to the select's operands because matching vector 7422 /// sizes for a select condition and other operands should be more efficient. 7423 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) { 7424 unsigned CastOpcode = Cast->getOpcode(); 7425 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || 7426 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || 7427 CastOpcode == ISD::FP_ROUND) && 7428 "Unexpected opcode for vector select narrowing/widening"); 7429 7430 // We only do this transform before legal ops because the pattern may be 7431 // obfuscated by target-specific operations after legalization. Do not create 7432 // an illegal select op, however, because that may be difficult to lower. 7433 EVT VT = Cast->getValueType(0); 7434 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT)) 7435 return SDValue(); 7436 7437 SDValue VSel = Cast->getOperand(0); 7438 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() || 7439 VSel.getOperand(0).getOpcode() != ISD::SETCC) 7440 return SDValue(); 7441 7442 // Does the setcc have the same vector size as the casted select? 7443 SDValue SetCC = VSel.getOperand(0); 7444 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType()); 7445 if (SetCCVT.getSizeInBits() != VT.getSizeInBits()) 7446 return SDValue(); 7447 7448 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B) 7449 SDValue A = VSel.getOperand(1); 7450 SDValue B = VSel.getOperand(2); 7451 SDValue CastA, CastB; 7452 SDLoc DL(Cast); 7453 if (CastOpcode == ISD::FP_ROUND) { 7454 // FP_ROUND (fptrunc) has an extra flag operand to pass along. 7455 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1)); 7456 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1)); 7457 } else { 7458 CastA = DAG.getNode(CastOpcode, DL, VT, A); 7459 CastB = DAG.getNode(CastOpcode, DL, VT, B); 7460 } 7461 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB); 7462 } 7463 7464 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 7465 SDValue N0 = N->getOperand(0); 7466 EVT VT = N->getValueType(0); 7467 SDLoc DL(N); 7468 7469 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7470 LegalOperations)) 7471 return SDValue(Res, 0); 7472 7473 // fold (sext (sext x)) -> (sext x) 7474 // fold (sext (aext x)) -> (sext x) 7475 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 7476 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0)); 7477 7478 if (N0.getOpcode() == ISD::TRUNCATE) { 7479 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 7480 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 7481 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7482 SDNode *oye = N0.getOperand(0).getNode(); 7483 if (NarrowLoad.getNode() != N0.getNode()) { 7484 CombineTo(N0.getNode(), NarrowLoad); 7485 // CombineTo deleted the truncate, if needed, but not what's under it. 7486 AddToWorklist(oye); 7487 } 7488 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7489 } 7490 7491 // See if the value being truncated is already sign extended. If so, just 7492 // eliminate the trunc/sext pair. 7493 SDValue Op = N0.getOperand(0); 7494 unsigned OpBits = Op.getScalarValueSizeInBits(); 7495 unsigned MidBits = N0.getScalarValueSizeInBits(); 7496 unsigned DestBits = VT.getScalarSizeInBits(); 7497 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 7498 7499 if (OpBits == DestBits) { 7500 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 7501 // bits, it is already ready. 7502 if (NumSignBits > DestBits-MidBits) 7503 return Op; 7504 } else if (OpBits < DestBits) { 7505 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 7506 // bits, just sext from i32. 7507 if (NumSignBits > OpBits-MidBits) 7508 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op); 7509 } else { 7510 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 7511 // bits, just truncate to i32. 7512 if (NumSignBits > OpBits-MidBits) 7513 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 7514 } 7515 7516 // fold (sext (truncate x)) -> (sextinreg x). 7517 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 7518 N0.getValueType())) { 7519 if (OpBits < DestBits) 7520 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 7521 else if (OpBits > DestBits) 7522 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 7523 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op, 7524 DAG.getValueType(N0.getValueType())); 7525 } 7526 } 7527 7528 // fold (sext (load x)) -> (sext (truncate (sextload x))) 7529 // Only generate vector extloads when 1) they're legal, and 2) they are 7530 // deemed desirable by the target. 7531 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7532 ((!LegalOperations && !VT.isVector() && 7533 !cast<LoadSDNode>(N0)->isVolatile()) || 7534 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 7535 bool DoXform = true; 7536 SmallVector<SDNode*, 4> SetCCs; 7537 if (!N0.hasOneUse()) 7538 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 7539 if (VT.isVector()) 7540 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 7541 if (DoXform) { 7542 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7543 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 7544 LN0->getBasePtr(), N0.getValueType(), 7545 LN0->getMemOperand()); 7546 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7547 N0.getValueType(), ExtLoad); 7548 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND); 7549 // If the load value is used only by N, replace it via CombineTo N. 7550 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 7551 CombineTo(N, ExtLoad); 7552 if (NoReplaceTrunc) 7553 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7554 else 7555 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 7556 return SDValue(N, 0); 7557 } 7558 } 7559 7560 // fold (sext (load x)) to multiple smaller sextloads. 7561 // Only on illegal but splittable vectors. 7562 if (SDValue ExtLoad = CombineExtLoad(N)) 7563 return ExtLoad; 7564 7565 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 7566 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 7567 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 7568 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 7569 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7570 EVT MemVT = LN0->getMemoryVT(); 7571 if ((!LegalOperations && !LN0->isVolatile()) || 7572 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 7573 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 7574 LN0->getBasePtr(), MemVT, 7575 LN0->getMemOperand()); 7576 CombineTo(N, ExtLoad); 7577 CombineTo(N0.getNode(), 7578 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7579 N0.getValueType(), ExtLoad), 7580 ExtLoad.getValue(1)); 7581 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7582 } 7583 } 7584 7585 // fold (sext (and/or/xor (load x), cst)) -> 7586 // (and/or/xor (sextload x), (sext cst)) 7587 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 7588 N0.getOpcode() == ISD::XOR) && 7589 isa<LoadSDNode>(N0.getOperand(0)) && 7590 N0.getOperand(1).getOpcode() == ISD::Constant && 7591 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 7592 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 7593 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 7594 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 7595 bool DoXform = true; 7596 SmallVector<SDNode*, 4> SetCCs; 7597 if (!N0.hasOneUse()) 7598 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 7599 SetCCs, TLI); 7600 if (DoXform) { 7601 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 7602 LN0->getChain(), LN0->getBasePtr(), 7603 LN0->getMemoryVT(), 7604 LN0->getMemOperand()); 7605 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7606 Mask = Mask.sext(VT.getSizeInBits()); 7607 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 7608 ExtLoad, DAG.getConstant(Mask, DL, VT)); 7609 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 7610 SDLoc(N0.getOperand(0)), 7611 N0.getOperand(0).getValueType(), ExtLoad); 7612 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND); 7613 bool NoReplaceTruncAnd = !N0.hasOneUse(); 7614 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 7615 CombineTo(N, And); 7616 // If N0 has multiple uses, change other uses as well. 7617 if (NoReplaceTruncAnd) { 7618 SDValue TruncAnd = 7619 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 7620 CombineTo(N0.getNode(), TruncAnd); 7621 } 7622 if (NoReplaceTrunc) 7623 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7624 else 7625 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 7626 return SDValue(N,0); // Return N so it doesn't get rechecked! 7627 } 7628 } 7629 } 7630 7631 if (N0.getOpcode() == ISD::SETCC) { 7632 SDValue N00 = N0.getOperand(0); 7633 SDValue N01 = N0.getOperand(1); 7634 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 7635 EVT N00VT = N0.getOperand(0).getValueType(); 7636 7637 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 7638 // Only do this before legalize for now. 7639 if (VT.isVector() && !LegalOperations && 7640 TLI.getBooleanContents(N00VT) == 7641 TargetLowering::ZeroOrNegativeOneBooleanContent) { 7642 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 7643 // of the same size as the compared operands. Only optimize sext(setcc()) 7644 // if this is the case. 7645 EVT SVT = getSetCCResultType(N00VT); 7646 7647 // We know that the # elements of the results is the same as the 7648 // # elements of the compare (and the # elements of the compare result 7649 // for that matter). Check to see that they are the same size. If so, 7650 // we know that the element size of the sext'd result matches the 7651 // element size of the compare operands. 7652 if (VT.getSizeInBits() == SVT.getSizeInBits()) 7653 return DAG.getSetCC(DL, VT, N00, N01, CC); 7654 7655 // If the desired elements are smaller or larger than the source 7656 // elements, we can use a matching integer vector type and then 7657 // truncate/sign extend. 7658 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger(); 7659 if (SVT == MatchingVecType) { 7660 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC); 7661 return DAG.getSExtOrTrunc(VsetCC, DL, VT); 7662 } 7663 } 7664 7665 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 7666 // Here, T can be 1 or -1, depending on the type of the setcc and 7667 // getBooleanContents(). 7668 unsigned SetCCWidth = N0.getScalarValueSizeInBits(); 7669 7670 // To determine the "true" side of the select, we need to know the high bit 7671 // of the value returned by the setcc if it evaluates to true. 7672 // If the type of the setcc is i1, then the true case of the select is just 7673 // sext(i1 1), that is, -1. 7674 // If the type of the setcc is larger (say, i8) then the value of the high 7675 // bit depends on getBooleanContents(), so ask TLI for a real "true" value 7676 // of the appropriate width. 7677 SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT) 7678 : TLI.getConstTrueVal(DAG, VT, DL); 7679 SDValue Zero = DAG.getConstant(0, DL, VT); 7680 if (SDValue SCC = 7681 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true)) 7682 return SCC; 7683 7684 if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) { 7685 EVT SetCCVT = getSetCCResultType(N00VT); 7686 // Don't do this transform for i1 because there's a select transform 7687 // that would reverse it. 7688 // TODO: We should not do this transform at all without a target hook 7689 // because a sext is likely cheaper than a select? 7690 if (SetCCVT.getScalarSizeInBits() != 1 && 7691 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) { 7692 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC); 7693 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero); 7694 } 7695 } 7696 } 7697 7698 // fold (sext x) -> (zext x) if the sign bit is known zero. 7699 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 7700 DAG.SignBitIsZero(N0)) 7701 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0); 7702 7703 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 7704 return NewVSel; 7705 7706 return SDValue(); 7707 } 7708 7709 // isTruncateOf - If N is a truncate of some other value, return true, record 7710 // the value being truncated in Op and which of Op's bits are zero/one in Known. 7711 // This function computes KnownBits to avoid a duplicated call to 7712 // computeKnownBits in the caller. 7713 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 7714 KnownBits &Known) { 7715 if (N->getOpcode() == ISD::TRUNCATE) { 7716 Op = N->getOperand(0); 7717 DAG.computeKnownBits(Op, Known); 7718 return true; 7719 } 7720 7721 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 7722 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 7723 return false; 7724 7725 SDValue Op0 = N->getOperand(0); 7726 SDValue Op1 = N->getOperand(1); 7727 assert(Op0.getValueType() == Op1.getValueType()); 7728 7729 if (isNullConstant(Op0)) 7730 Op = Op1; 7731 else if (isNullConstant(Op1)) 7732 Op = Op0; 7733 else 7734 return false; 7735 7736 DAG.computeKnownBits(Op, Known); 7737 7738 if (!(Known.Zero | 1).isAllOnesValue()) 7739 return false; 7740 7741 return true; 7742 } 7743 7744 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 7745 SDValue N0 = N->getOperand(0); 7746 EVT VT = N->getValueType(0); 7747 7748 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7749 LegalOperations)) 7750 return SDValue(Res, 0); 7751 7752 // fold (zext (zext x)) -> (zext x) 7753 // fold (zext (aext x)) -> (zext x) 7754 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 7755 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 7756 N0.getOperand(0)); 7757 7758 // fold (zext (truncate x)) -> (zext x) or 7759 // (zext (truncate x)) -> (truncate x) 7760 // This is valid when the truncated bits of x are already zero. 7761 // FIXME: We should extend this to work for vectors too. 7762 SDValue Op; 7763 KnownBits Known; 7764 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) { 7765 APInt TruncatedBits = 7766 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 7767 APInt(Op.getValueSizeInBits(), 0) : 7768 APInt::getBitsSet(Op.getValueSizeInBits(), 7769 N0.getValueSizeInBits(), 7770 std::min(Op.getValueSizeInBits(), 7771 VT.getSizeInBits())); 7772 if (TruncatedBits.isSubsetOf(Known.Zero)) 7773 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 7774 } 7775 7776 // fold (zext (truncate x)) -> (and x, mask) 7777 if (N0.getOpcode() == ISD::TRUNCATE) { 7778 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 7779 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 7780 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7781 SDNode *oye = N0.getOperand(0).getNode(); 7782 if (NarrowLoad.getNode() != N0.getNode()) { 7783 CombineTo(N0.getNode(), NarrowLoad); 7784 // CombineTo deleted the truncate, if needed, but not what's under it. 7785 AddToWorklist(oye); 7786 } 7787 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7788 } 7789 7790 EVT SrcVT = N0.getOperand(0).getValueType(); 7791 EVT MinVT = N0.getValueType(); 7792 7793 // Try to mask before the extension to avoid having to generate a larger mask, 7794 // possibly over several sub-vectors. 7795 if (SrcVT.bitsLT(VT)) { 7796 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 7797 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 7798 SDValue Op = N0.getOperand(0); 7799 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 7800 AddToWorklist(Op.getNode()); 7801 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 7802 } 7803 } 7804 7805 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 7806 SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 7807 AddToWorklist(Op.getNode()); 7808 SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 7809 // We may safely transfer the debug info describing the truncate node over 7810 // to the equivalent and operation. 7811 DAG.transferDbgValues(N0, And); 7812 return And; 7813 } 7814 } 7815 7816 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 7817 // if either of the casts is not free. 7818 if (N0.getOpcode() == ISD::AND && 7819 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 7820 N0.getOperand(1).getOpcode() == ISD::Constant && 7821 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 7822 N0.getValueType()) || 7823 !TLI.isZExtFree(N0.getValueType(), VT))) { 7824 SDValue X = N0.getOperand(0).getOperand(0); 7825 X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT); 7826 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7827 Mask = Mask.zext(VT.getSizeInBits()); 7828 SDLoc DL(N); 7829 return DAG.getNode(ISD::AND, DL, VT, 7830 X, DAG.getConstant(Mask, DL, VT)); 7831 } 7832 7833 // fold (zext (load x)) -> (zext (truncate (zextload x))) 7834 // Only generate vector extloads when 1) they're legal, and 2) they are 7835 // deemed desirable by the target. 7836 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7837 ((!LegalOperations && !VT.isVector() && 7838 !cast<LoadSDNode>(N0)->isVolatile()) || 7839 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 7840 bool DoXform = true; 7841 SmallVector<SDNode*, 4> SetCCs; 7842 if (!N0.hasOneUse()) 7843 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 7844 if (VT.isVector()) 7845 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 7846 if (DoXform) { 7847 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7848 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 7849 LN0->getChain(), 7850 LN0->getBasePtr(), N0.getValueType(), 7851 LN0->getMemOperand()); 7852 7853 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7854 N0.getValueType(), ExtLoad); 7855 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), ISD::ZERO_EXTEND); 7856 // If the load value is used only by N, replace it via CombineTo N. 7857 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 7858 CombineTo(N, ExtLoad); 7859 if (NoReplaceTrunc) 7860 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7861 else 7862 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 7863 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7864 } 7865 } 7866 7867 // fold (zext (load x)) to multiple smaller zextloads. 7868 // Only on illegal but splittable vectors. 7869 if (SDValue ExtLoad = CombineExtLoad(N)) 7870 return ExtLoad; 7871 7872 // fold (zext (and/or/xor (load x), cst)) -> 7873 // (and/or/xor (zextload x), (zext cst)) 7874 // Unless (and (load x) cst) will match as a zextload already and has 7875 // additional users. 7876 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 7877 N0.getOpcode() == ISD::XOR) && 7878 isa<LoadSDNode>(N0.getOperand(0)) && 7879 N0.getOperand(1).getOpcode() == ISD::Constant && 7880 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 7881 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 7882 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 7883 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 7884 bool DoXform = true; 7885 SmallVector<SDNode*, 4> SetCCs; 7886 if (!N0.hasOneUse()) { 7887 if (N0.getOpcode() == ISD::AND) { 7888 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 7889 EVT LoadResultTy = AndC->getValueType(0); 7890 EVT ExtVT; 7891 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT)) 7892 DoXform = false; 7893 } 7894 if (DoXform) 7895 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 7896 ISD::ZERO_EXTEND, SetCCs, TLI); 7897 } 7898 if (DoXform) { 7899 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 7900 LN0->getChain(), LN0->getBasePtr(), 7901 LN0->getMemoryVT(), 7902 LN0->getMemOperand()); 7903 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7904 Mask = Mask.zext(VT.getSizeInBits()); 7905 SDLoc DL(N); 7906 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 7907 ExtLoad, DAG.getConstant(Mask, DL, VT)); 7908 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 7909 SDLoc(N0.getOperand(0)), 7910 N0.getOperand(0).getValueType(), ExtLoad); 7911 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::ZERO_EXTEND); 7912 bool NoReplaceTruncAnd = !N0.hasOneUse(); 7913 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 7914 CombineTo(N, And); 7915 // If N0 has multiple uses, change other uses as well. 7916 if (NoReplaceTruncAnd) { 7917 SDValue TruncAnd = 7918 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 7919 CombineTo(N0.getNode(), TruncAnd); 7920 } 7921 if (NoReplaceTrunc) 7922 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7923 else 7924 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 7925 return SDValue(N,0); // Return N so it doesn't get rechecked! 7926 } 7927 } 7928 } 7929 7930 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 7931 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 7932 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 7933 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 7934 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7935 EVT MemVT = LN0->getMemoryVT(); 7936 if ((!LegalOperations && !LN0->isVolatile()) || 7937 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 7938 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 7939 LN0->getChain(), 7940 LN0->getBasePtr(), MemVT, 7941 LN0->getMemOperand()); 7942 CombineTo(N, ExtLoad); 7943 CombineTo(N0.getNode(), 7944 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 7945 ExtLoad), 7946 ExtLoad.getValue(1)); 7947 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7948 } 7949 } 7950 7951 if (N0.getOpcode() == ISD::SETCC) { 7952 // Only do this before legalize for now. 7953 if (!LegalOperations && VT.isVector() && 7954 N0.getValueType().getVectorElementType() == MVT::i1) { 7955 EVT N00VT = N0.getOperand(0).getValueType(); 7956 if (getSetCCResultType(N00VT) == N0.getValueType()) 7957 return SDValue(); 7958 7959 // We know that the # elements of the results is the same as the # 7960 // elements of the compare (and the # elements of the compare result for 7961 // that matter). Check to see that they are the same size. If so, we know 7962 // that the element size of the sext'd result matches the element size of 7963 // the compare operands. 7964 SDLoc DL(N); 7965 SDValue VecOnes = DAG.getConstant(1, DL, VT); 7966 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 7967 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 7968 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 7969 N0.getOperand(1), N0.getOperand(2)); 7970 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes); 7971 } 7972 7973 // If the desired elements are smaller or larger than the source 7974 // elements we can use a matching integer vector type and then 7975 // truncate/sign extend. 7976 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); 7977 SDValue VsetCC = 7978 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 7979 N0.getOperand(1), N0.getOperand(2)); 7980 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT), 7981 VecOnes); 7982 } 7983 7984 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 7985 SDLoc DL(N); 7986 if (SDValue SCC = SimplifySelectCC( 7987 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 7988 DAG.getConstant(0, DL, VT), 7989 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 7990 return SCC; 7991 } 7992 7993 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 7994 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 7995 isa<ConstantSDNode>(N0.getOperand(1)) && 7996 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 7997 N0.hasOneUse()) { 7998 SDValue ShAmt = N0.getOperand(1); 7999 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 8000 if (N0.getOpcode() == ISD::SHL) { 8001 SDValue InnerZExt = N0.getOperand(0); 8002 // If the original shl may be shifting out bits, do not perform this 8003 // transformation. 8004 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() - 8005 InnerZExt.getOperand(0).getValueSizeInBits(); 8006 if (ShAmtVal > KnownZeroBits) 8007 return SDValue(); 8008 } 8009 8010 SDLoc DL(N); 8011 8012 // Ensure that the shift amount is wide enough for the shifted value. 8013 if (VT.getSizeInBits() >= 256) 8014 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 8015 8016 return DAG.getNode(N0.getOpcode(), DL, VT, 8017 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 8018 ShAmt); 8019 } 8020 8021 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 8022 return NewVSel; 8023 8024 return SDValue(); 8025 } 8026 8027 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 8028 SDValue N0 = N->getOperand(0); 8029 EVT VT = N->getValueType(0); 8030 8031 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8032 LegalOperations)) 8033 return SDValue(Res, 0); 8034 8035 // fold (aext (aext x)) -> (aext x) 8036 // fold (aext (zext x)) -> (zext x) 8037 // fold (aext (sext x)) -> (sext x) 8038 if (N0.getOpcode() == ISD::ANY_EXTEND || 8039 N0.getOpcode() == ISD::ZERO_EXTEND || 8040 N0.getOpcode() == ISD::SIGN_EXTEND) 8041 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 8042 8043 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 8044 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 8045 if (N0.getOpcode() == ISD::TRUNCATE) { 8046 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 8047 SDNode *oye = N0.getOperand(0).getNode(); 8048 if (NarrowLoad.getNode() != N0.getNode()) { 8049 CombineTo(N0.getNode(), NarrowLoad); 8050 // CombineTo deleted the truncate, if needed, but not what's under it. 8051 AddToWorklist(oye); 8052 } 8053 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8054 } 8055 } 8056 8057 // fold (aext (truncate x)) 8058 if (N0.getOpcode() == ISD::TRUNCATE) 8059 return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 8060 8061 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 8062 // if the trunc is not free. 8063 if (N0.getOpcode() == ISD::AND && 8064 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 8065 N0.getOperand(1).getOpcode() == ISD::Constant && 8066 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 8067 N0.getValueType())) { 8068 SDLoc DL(N); 8069 SDValue X = N0.getOperand(0).getOperand(0); 8070 X = DAG.getAnyExtOrTrunc(X, DL, VT); 8071 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 8072 Mask = Mask.zext(VT.getSizeInBits()); 8073 return DAG.getNode(ISD::AND, DL, VT, 8074 X, DAG.getConstant(Mask, DL, VT)); 8075 } 8076 8077 // fold (aext (load x)) -> (aext (truncate (extload x))) 8078 // None of the supported targets knows how to perform load and any_ext 8079 // on vectors in one instruction. We only perform this transformation on 8080 // scalars. 8081 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 8082 ISD::isUNINDEXEDLoad(N0.getNode()) && 8083 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 8084 bool DoXform = true; 8085 SmallVector<SDNode*, 4> SetCCs; 8086 if (!N0.hasOneUse()) 8087 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 8088 if (DoXform) { 8089 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8090 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 8091 LN0->getChain(), 8092 LN0->getBasePtr(), N0.getValueType(), 8093 LN0->getMemOperand()); 8094 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 8095 N0.getValueType(), ExtLoad); 8096 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 8097 ISD::ANY_EXTEND); 8098 // If the load value is used only by N, replace it via CombineTo N. 8099 bool NoReplaceTrunc = N0.hasOneUse(); 8100 CombineTo(N, ExtLoad); 8101 if (NoReplaceTrunc) 8102 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 8103 else 8104 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 8105 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8106 } 8107 } 8108 8109 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 8110 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 8111 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 8112 if (N0.getOpcode() == ISD::LOAD && 8113 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 8114 N0.hasOneUse()) { 8115 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8116 ISD::LoadExtType ExtType = LN0->getExtensionType(); 8117 EVT MemVT = LN0->getMemoryVT(); 8118 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 8119 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 8120 VT, LN0->getChain(), LN0->getBasePtr(), 8121 MemVT, LN0->getMemOperand()); 8122 CombineTo(N, ExtLoad); 8123 CombineTo(N0.getNode(), 8124 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 8125 N0.getValueType(), ExtLoad), 8126 ExtLoad.getValue(1)); 8127 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8128 } 8129 } 8130 8131 if (N0.getOpcode() == ISD::SETCC) { 8132 // For vectors: 8133 // aext(setcc) -> vsetcc 8134 // aext(setcc) -> truncate(vsetcc) 8135 // aext(setcc) -> aext(vsetcc) 8136 // Only do this before legalize for now. 8137 if (VT.isVector() && !LegalOperations) { 8138 EVT N00VT = N0.getOperand(0).getValueType(); 8139 if (getSetCCResultType(N00VT) == N0.getValueType()) 8140 return SDValue(); 8141 8142 // We know that the # elements of the results is the same as the 8143 // # elements of the compare (and the # elements of the compare result 8144 // for that matter). Check to see that they are the same size. If so, 8145 // we know that the element size of the sext'd result matches the 8146 // element size of the compare operands. 8147 if (VT.getSizeInBits() == N00VT.getSizeInBits()) 8148 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 8149 N0.getOperand(1), 8150 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 8151 // If the desired elements are smaller or larger than the source 8152 // elements we can use a matching integer vector type and then 8153 // truncate/any extend 8154 else { 8155 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); 8156 SDValue VsetCC = 8157 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 8158 N0.getOperand(1), 8159 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 8160 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 8161 } 8162 } 8163 8164 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 8165 SDLoc DL(N); 8166 if (SDValue SCC = SimplifySelectCC( 8167 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 8168 DAG.getConstant(0, DL, VT), 8169 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 8170 return SCC; 8171 } 8172 8173 return SDValue(); 8174 } 8175 8176 SDValue DAGCombiner::visitAssertExt(SDNode *N) { 8177 unsigned Opcode = N->getOpcode(); 8178 SDValue N0 = N->getOperand(0); 8179 SDValue N1 = N->getOperand(1); 8180 EVT AssertVT = cast<VTSDNode>(N1)->getVT(); 8181 8182 // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt) 8183 if (N0.getOpcode() == Opcode && 8184 AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT()) 8185 return N0; 8186 8187 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && 8188 N0.getOperand(0).getOpcode() == Opcode) { 8189 // We have an assert, truncate, assert sandwich. Make one stronger assert 8190 // by asserting on the smallest asserted type to the larger source type. 8191 // This eliminates the later assert: 8192 // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN 8193 // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN 8194 SDValue BigA = N0.getOperand(0); 8195 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT(); 8196 assert(BigA_AssertVT.bitsLE(N0.getValueType()) && 8197 "Asserting zero/sign-extended bits to a type larger than the " 8198 "truncated destination does not provide information"); 8199 8200 SDLoc DL(N); 8201 EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT; 8202 SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT); 8203 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(), 8204 BigA.getOperand(0), MinAssertVTVal); 8205 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert); 8206 } 8207 8208 return SDValue(); 8209 } 8210 8211 /// If the result of a wider load is shifted to right of N bits and then 8212 /// truncated to a narrower type and where N is a multiple of number of bits of 8213 /// the narrower type, transform it to a narrower load from address + N / num of 8214 /// bits of new type. Also narrow the load if the result is masked with an AND 8215 /// to effectively produce a smaller type. If the result is to be extended, also 8216 /// fold the extension to form a extending load. 8217 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 8218 unsigned Opc = N->getOpcode(); 8219 8220 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 8221 SDValue N0 = N->getOperand(0); 8222 EVT VT = N->getValueType(0); 8223 EVT ExtVT = VT; 8224 8225 // This transformation isn't valid for vector loads. 8226 if (VT.isVector()) 8227 return SDValue(); 8228 8229 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 8230 // extended to VT. 8231 if (Opc == ISD::SIGN_EXTEND_INREG) { 8232 ExtType = ISD::SEXTLOAD; 8233 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8234 } else if (Opc == ISD::SRL) { 8235 // Another special-case: SRL is basically zero-extending a narrower value, 8236 // or it maybe shifting a higher subword, half or byte into the lowest 8237 // bits. 8238 ExtType = ISD::ZEXTLOAD; 8239 N0 = SDValue(N, 0); 8240 8241 auto *LN0 = dyn_cast<LoadSDNode>(N0.getOperand(0)); 8242 auto *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8243 if (!N01 || !LN0) 8244 return SDValue(); 8245 8246 uint64_t ShiftAmt = N01->getZExtValue(); 8247 uint64_t MemoryWidth = LN0->getMemoryVT().getSizeInBits(); 8248 if (LN0->getExtensionType() != ISD::SEXTLOAD && MemoryWidth > ShiftAmt) 8249 ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShiftAmt); 8250 else 8251 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 8252 VT.getSizeInBits() - ShiftAmt); 8253 } else if (Opc == ISD::AND) { 8254 // An AND with a constant mask is the same as a truncate + zero-extend. 8255 auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8256 if (!AndC || !AndC->getAPIntValue().isMask()) 8257 return SDValue(); 8258 8259 unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes(); 8260 ExtType = ISD::ZEXTLOAD; 8261 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 8262 } 8263 8264 unsigned ShAmt = 0; 8265 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 8266 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 8267 ShAmt = N01->getZExtValue(); 8268 unsigned EVTBits = ExtVT.getSizeInBits(); 8269 // Is the shift amount a multiple of size of VT? 8270 if ((ShAmt & (EVTBits-1)) == 0) { 8271 N0 = N0.getOperand(0); 8272 // Is the load width a multiple of size of VT? 8273 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0) 8274 return SDValue(); 8275 } 8276 8277 // At this point, we must have a load or else we can't do the transform. 8278 if (!isa<LoadSDNode>(N0)) return SDValue(); 8279 8280 // Because a SRL must be assumed to *need* to zero-extend the high bits 8281 // (as opposed to anyext the high bits), we can't combine the zextload 8282 // lowering of SRL and an sextload. 8283 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 8284 return SDValue(); 8285 8286 // If the shift amount is larger than the input type then we're not 8287 // accessing any of the loaded bytes. If the load was a zextload/extload 8288 // then the result of the shift+trunc is zero/undef (handled elsewhere). 8289 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 8290 return SDValue(); 8291 } 8292 } 8293 8294 // If the load is shifted left (and the result isn't shifted back right), 8295 // we can fold the truncate through the shift. 8296 unsigned ShLeftAmt = 0; 8297 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 8298 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 8299 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 8300 ShLeftAmt = N01->getZExtValue(); 8301 N0 = N0.getOperand(0); 8302 } 8303 } 8304 8305 // If we haven't found a load, we can't narrow it. 8306 if (!isa<LoadSDNode>(N0)) 8307 return SDValue(); 8308 8309 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8310 if (!isLegalNarrowLoad(LN0, ExtType, ExtVT, ShAmt)) 8311 return SDValue(); 8312 8313 // For big endian targets, we need to adjust the offset to the pointer to 8314 // load the correct bytes. 8315 if (DAG.getDataLayout().isBigEndian()) { 8316 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 8317 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 8318 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 8319 } 8320 8321 EVT PtrType = N0.getOperand(1).getValueType(); 8322 uint64_t PtrOff = ShAmt / 8; 8323 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 8324 SDLoc DL(LN0); 8325 // The original load itself didn't wrap, so an offset within it doesn't. 8326 SDNodeFlags Flags; 8327 Flags.setNoUnsignedWrap(true); 8328 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 8329 PtrType, LN0->getBasePtr(), 8330 DAG.getConstant(PtrOff, DL, PtrType), 8331 Flags); 8332 AddToWorklist(NewPtr.getNode()); 8333 8334 SDValue Load; 8335 if (ExtType == ISD::NON_EXTLOAD) 8336 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 8337 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 8338 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8339 else 8340 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr, 8341 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 8342 NewAlign, LN0->getMemOperand()->getFlags(), 8343 LN0->getAAInfo()); 8344 8345 // Replace the old load's chain with the new load's chain. 8346 WorklistRemover DeadNodes(*this); 8347 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 8348 8349 // Shift the result left, if we've swallowed a left shift. 8350 SDValue Result = Load; 8351 if (ShLeftAmt != 0) { 8352 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 8353 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 8354 ShImmTy = VT; 8355 // If the shift amount is as large as the result size (but, presumably, 8356 // no larger than the source) then the useful bits of the result are 8357 // zero; we can't simply return the shortened shift, because the result 8358 // of that operation is undefined. 8359 SDLoc DL(N0); 8360 if (ShLeftAmt >= VT.getSizeInBits()) 8361 Result = DAG.getConstant(0, DL, VT); 8362 else 8363 Result = DAG.getNode(ISD::SHL, DL, VT, 8364 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 8365 } 8366 8367 // Return the new loaded value. 8368 return Result; 8369 } 8370 8371 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 8372 SDValue N0 = N->getOperand(0); 8373 SDValue N1 = N->getOperand(1); 8374 EVT VT = N->getValueType(0); 8375 EVT EVT = cast<VTSDNode>(N1)->getVT(); 8376 unsigned VTBits = VT.getScalarSizeInBits(); 8377 unsigned EVTBits = EVT.getScalarSizeInBits(); 8378 8379 if (N0.isUndef()) 8380 return DAG.getUNDEF(VT); 8381 8382 // fold (sext_in_reg c1) -> c1 8383 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 8384 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 8385 8386 // If the input is already sign extended, just drop the extension. 8387 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 8388 return N0; 8389 8390 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 8391 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 8392 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 8393 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 8394 N0.getOperand(0), N1); 8395 8396 // fold (sext_in_reg (sext x)) -> (sext x) 8397 // fold (sext_in_reg (aext x)) -> (sext x) 8398 // if x is small enough. 8399 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 8400 SDValue N00 = N0.getOperand(0); 8401 if (N00.getScalarValueSizeInBits() <= EVTBits && 8402 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 8403 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 8404 } 8405 8406 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x) 8407 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG || 8408 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG || 8409 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) && 8410 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) { 8411 if (!LegalOperations || 8412 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT)) 8413 return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT); 8414 } 8415 8416 // fold (sext_in_reg (zext x)) -> (sext x) 8417 // iff we are extending the source sign bit. 8418 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 8419 SDValue N00 = N0.getOperand(0); 8420 if (N00.getScalarValueSizeInBits() == EVTBits && 8421 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 8422 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 8423 } 8424 8425 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 8426 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1))) 8427 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType()); 8428 8429 // fold operands of sext_in_reg based on knowledge that the top bits are not 8430 // demanded. 8431 if (SimplifyDemandedBits(SDValue(N, 0))) 8432 return SDValue(N, 0); 8433 8434 // fold (sext_in_reg (load x)) -> (smaller sextload x) 8435 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 8436 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 8437 return NarrowLoad; 8438 8439 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 8440 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 8441 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 8442 if (N0.getOpcode() == ISD::SRL) { 8443 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 8444 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 8445 // We can turn this into an SRA iff the input to the SRL is already sign 8446 // extended enough. 8447 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 8448 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 8449 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 8450 N0.getOperand(0), N0.getOperand(1)); 8451 } 8452 } 8453 8454 // fold (sext_inreg (extload x)) -> (sextload x) 8455 // If sextload is not supported by target, we can only do the combine when 8456 // load has one use. Doing otherwise can block folding the extload with other 8457 // extends that the target does support. 8458 if (ISD::isEXTLoad(N0.getNode()) && 8459 ISD::isUNINDEXEDLoad(N0.getNode()) && 8460 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 8461 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile() && 8462 N0.hasOneUse()) || 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 AddToWorklist(ExtLoad.getNode()); 8472 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8473 } 8474 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 8475 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 8476 N0.hasOneUse() && 8477 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 8478 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 8479 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 8480 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8481 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 8482 LN0->getChain(), 8483 LN0->getBasePtr(), EVT, 8484 LN0->getMemOperand()); 8485 CombineTo(N, ExtLoad); 8486 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 8487 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8488 } 8489 8490 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 8491 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 8492 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 8493 N0.getOperand(1), false)) 8494 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 8495 BSwap, N1); 8496 } 8497 8498 return SDValue(); 8499 } 8500 8501 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 8502 SDValue N0 = N->getOperand(0); 8503 EVT VT = N->getValueType(0); 8504 8505 if (N0.isUndef()) 8506 return DAG.getUNDEF(VT); 8507 8508 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8509 LegalOperations)) 8510 return SDValue(Res, 0); 8511 8512 return SDValue(); 8513 } 8514 8515 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 8516 SDValue N0 = N->getOperand(0); 8517 EVT VT = N->getValueType(0); 8518 8519 if (N0.isUndef()) 8520 return DAG.getUNDEF(VT); 8521 8522 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8523 LegalOperations)) 8524 return SDValue(Res, 0); 8525 8526 return SDValue(); 8527 } 8528 8529 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 8530 SDValue N0 = N->getOperand(0); 8531 EVT VT = N->getValueType(0); 8532 bool isLE = DAG.getDataLayout().isLittleEndian(); 8533 8534 // noop truncate 8535 if (N0.getValueType() == N->getValueType(0)) 8536 return N0; 8537 8538 // fold (truncate (truncate x)) -> (truncate x) 8539 if (N0.getOpcode() == ISD::TRUNCATE) 8540 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 8541 8542 // fold (truncate c1) -> c1 8543 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 8544 SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 8545 if (C.getNode() != N) 8546 return C; 8547 } 8548 8549 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 8550 if (N0.getOpcode() == ISD::ZERO_EXTEND || 8551 N0.getOpcode() == ISD::SIGN_EXTEND || 8552 N0.getOpcode() == ISD::ANY_EXTEND) { 8553 // if the source is smaller than the dest, we still need an extend. 8554 if (N0.getOperand(0).getValueType().bitsLT(VT)) 8555 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 8556 // if the source is larger than the dest, than we just need the truncate. 8557 if (N0.getOperand(0).getValueType().bitsGT(VT)) 8558 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 8559 // if the source and dest are the same type, we can drop both the extend 8560 // and the truncate. 8561 return N0.getOperand(0); 8562 } 8563 8564 // If this is anyext(trunc), don't fold it, allow ourselves to be folded. 8565 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND)) 8566 return SDValue(); 8567 8568 // Fold extract-and-trunc into a narrow extract. For example: 8569 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 8570 // i32 y = TRUNCATE(i64 x) 8571 // -- becomes -- 8572 // v16i8 b = BITCAST (v2i64 val) 8573 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 8574 // 8575 // Note: We only run this optimization after type legalization (which often 8576 // creates this pattern) and before operation legalization after which 8577 // we need to be more careful about the vector instructions that we generate. 8578 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 8579 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 8580 EVT VecTy = N0.getOperand(0).getValueType(); 8581 EVT ExTy = N0.getValueType(); 8582 EVT TrTy = N->getValueType(0); 8583 8584 unsigned NumElem = VecTy.getVectorNumElements(); 8585 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 8586 8587 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 8588 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 8589 8590 SDValue EltNo = N0->getOperand(1); 8591 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 8592 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 8593 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 8594 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 8595 8596 SDLoc DL(N); 8597 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 8598 DAG.getBitcast(NVT, N0.getOperand(0)), 8599 DAG.getConstant(Index, DL, IndexTy)); 8600 } 8601 } 8602 8603 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 8604 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) { 8605 EVT SrcVT = N0.getValueType(); 8606 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 8607 TLI.isTruncateFree(SrcVT, VT)) { 8608 SDLoc SL(N0); 8609 SDValue Cond = N0.getOperand(0); 8610 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 8611 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 8612 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 8613 } 8614 } 8615 8616 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits() 8617 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 8618 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 8619 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 8620 SDValue Amt = N0.getOperand(1); 8621 KnownBits Known; 8622 DAG.computeKnownBits(Amt, Known); 8623 unsigned Size = VT.getScalarSizeInBits(); 8624 if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) { 8625 SDLoc SL(N); 8626 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 8627 8628 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 8629 if (AmtVT != Amt.getValueType()) { 8630 Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT); 8631 AddToWorklist(Amt.getNode()); 8632 } 8633 return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt); 8634 } 8635 } 8636 8637 // Fold a series of buildvector, bitcast, and truncate if possible. 8638 // For example fold 8639 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 8640 // (2xi32 (buildvector x, y)). 8641 if (Level == AfterLegalizeVectorOps && VT.isVector() && 8642 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 8643 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 8644 N0.getOperand(0).hasOneUse()) { 8645 SDValue BuildVect = N0.getOperand(0); 8646 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 8647 EVT TruncVecEltTy = VT.getVectorElementType(); 8648 8649 // Check that the element types match. 8650 if (BuildVectEltTy == TruncVecEltTy) { 8651 // Now we only need to compute the offset of the truncated elements. 8652 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 8653 unsigned TruncVecNumElts = VT.getVectorNumElements(); 8654 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 8655 8656 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 8657 "Invalid number of elements"); 8658 8659 SmallVector<SDValue, 8> Opnds; 8660 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 8661 Opnds.push_back(BuildVect.getOperand(i)); 8662 8663 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 8664 } 8665 } 8666 8667 // See if we can simplify the input to this truncate through knowledge that 8668 // only the low bits are being used. 8669 // For example "trunc (or (shl x, 8), y)" // -> trunc y 8670 // Currently we only perform this optimization on scalars because vectors 8671 // may have different active low bits. 8672 if (!VT.isVector()) { 8673 APInt Mask = 8674 APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits()); 8675 if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask)) 8676 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 8677 } 8678 8679 // fold (truncate (load x)) -> (smaller load x) 8680 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 8681 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 8682 if (SDValue Reduced = ReduceLoadWidth(N)) 8683 return Reduced; 8684 8685 // Handle the case where the load remains an extending load even 8686 // after truncation. 8687 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 8688 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8689 if (!LN0->isVolatile() && 8690 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 8691 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 8692 VT, LN0->getChain(), LN0->getBasePtr(), 8693 LN0->getMemoryVT(), 8694 LN0->getMemOperand()); 8695 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 8696 return NewLoad; 8697 } 8698 } 8699 } 8700 8701 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 8702 // where ... are all 'undef'. 8703 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 8704 SmallVector<EVT, 8> VTs; 8705 SDValue V; 8706 unsigned Idx = 0; 8707 unsigned NumDefs = 0; 8708 8709 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 8710 SDValue X = N0.getOperand(i); 8711 if (!X.isUndef()) { 8712 V = X; 8713 Idx = i; 8714 NumDefs++; 8715 } 8716 // Stop if more than one members are non-undef. 8717 if (NumDefs > 1) 8718 break; 8719 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 8720 VT.getVectorElementType(), 8721 X.getValueType().getVectorNumElements())); 8722 } 8723 8724 if (NumDefs == 0) 8725 return DAG.getUNDEF(VT); 8726 8727 if (NumDefs == 1) { 8728 assert(V.getNode() && "The single defined operand is empty!"); 8729 SmallVector<SDValue, 8> Opnds; 8730 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 8731 if (i != Idx) { 8732 Opnds.push_back(DAG.getUNDEF(VTs[i])); 8733 continue; 8734 } 8735 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 8736 AddToWorklist(NV.getNode()); 8737 Opnds.push_back(NV); 8738 } 8739 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 8740 } 8741 } 8742 8743 // Fold truncate of a bitcast of a vector to an extract of the low vector 8744 // element. 8745 // 8746 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx 8747 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 8748 SDValue VecSrc = N0.getOperand(0); 8749 EVT SrcVT = VecSrc.getValueType(); 8750 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 8751 (!LegalOperations || 8752 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 8753 SDLoc SL(N); 8754 8755 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 8756 unsigned Idx = isLE ? 0 : SrcVT.getVectorNumElements() - 1; 8757 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 8758 VecSrc, DAG.getConstant(Idx, SL, IdxVT)); 8759 } 8760 } 8761 8762 // Simplify the operands using demanded-bits information. 8763 if (!VT.isVector() && 8764 SimplifyDemandedBits(SDValue(N, 0))) 8765 return SDValue(N, 0); 8766 8767 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry) 8768 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry) 8769 // When the adde's carry is not used. 8770 if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) && 8771 N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) && 8772 (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) { 8773 SDLoc SL(N); 8774 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 8775 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 8776 auto VTs = DAG.getVTList(VT, N0->getValueType(1)); 8777 return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2)); 8778 } 8779 8780 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 8781 return NewVSel; 8782 8783 return SDValue(); 8784 } 8785 8786 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 8787 SDValue Elt = N->getOperand(i); 8788 if (Elt.getOpcode() != ISD::MERGE_VALUES) 8789 return Elt.getNode(); 8790 return Elt.getOperand(Elt.getResNo()).getNode(); 8791 } 8792 8793 /// build_pair (load, load) -> load 8794 /// if load locations are consecutive. 8795 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 8796 assert(N->getOpcode() == ISD::BUILD_PAIR); 8797 8798 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 8799 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 8800 8801 // A BUILD_PAIR is always having the least significant part in elt 0 and the 8802 // most significant part in elt 1. So when combining into one large load, we 8803 // need to consider the endianness. 8804 if (DAG.getDataLayout().isBigEndian()) 8805 std::swap(LD1, LD2); 8806 8807 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 8808 LD1->getAddressSpace() != LD2->getAddressSpace()) 8809 return SDValue(); 8810 EVT LD1VT = LD1->getValueType(0); 8811 unsigned LD1Bytes = LD1VT.getStoreSize(); 8812 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 8813 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 8814 unsigned Align = LD1->getAlignment(); 8815 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 8816 VT.getTypeForEVT(*DAG.getContext())); 8817 8818 if (NewAlign <= Align && 8819 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 8820 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 8821 LD1->getPointerInfo(), Align); 8822 } 8823 8824 return SDValue(); 8825 } 8826 8827 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 8828 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 8829 // and Lo parts; on big-endian machines it doesn't. 8830 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 8831 } 8832 8833 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 8834 const TargetLowering &TLI) { 8835 // If this is not a bitcast to an FP type or if the target doesn't have 8836 // IEEE754-compliant FP logic, we're done. 8837 EVT VT = N->getValueType(0); 8838 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 8839 return SDValue(); 8840 8841 // TODO: Use splat values for the constant-checking below and remove this 8842 // restriction. 8843 SDValue N0 = N->getOperand(0); 8844 EVT SourceVT = N0.getValueType(); 8845 if (SourceVT.isVector()) 8846 return SDValue(); 8847 8848 unsigned FPOpcode; 8849 APInt SignMask; 8850 switch (N0.getOpcode()) { 8851 case ISD::AND: 8852 FPOpcode = ISD::FABS; 8853 SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits()); 8854 break; 8855 case ISD::XOR: 8856 FPOpcode = ISD::FNEG; 8857 SignMask = APInt::getSignMask(SourceVT.getSizeInBits()); 8858 break; 8859 // TODO: ISD::OR --> ISD::FNABS? 8860 default: 8861 return SDValue(); 8862 } 8863 8864 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 8865 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 8866 SDValue LogicOp0 = N0.getOperand(0); 8867 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8868 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 8869 LogicOp0.getOpcode() == ISD::BITCAST && 8870 LogicOp0->getOperand(0).getValueType() == VT) 8871 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0)); 8872 8873 return SDValue(); 8874 } 8875 8876 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 8877 SDValue N0 = N->getOperand(0); 8878 EVT VT = N->getValueType(0); 8879 8880 if (N0.isUndef()) 8881 return DAG.getUNDEF(VT); 8882 8883 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 8884 // Only do this before legalize, since afterward the target may be depending 8885 // on the bitconvert. 8886 // First check to see if this is all constant. 8887 if (!LegalTypes && 8888 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 8889 VT.isVector()) { 8890 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 8891 8892 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 8893 assert(!DestEltVT.isVector() && 8894 "Element type of vector ValueType must not be vector!"); 8895 if (isSimple) 8896 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 8897 } 8898 8899 // If the input is a constant, let getNode fold it. 8900 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 8901 // If we can't allow illegal operations, we need to check that this is just 8902 // a fp -> int or int -> conversion and that the resulting operation will 8903 // be legal. 8904 if (!LegalOperations || 8905 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 8906 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 8907 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 8908 TLI.isOperationLegal(ISD::Constant, VT))) 8909 return DAG.getBitcast(VT, N0); 8910 } 8911 8912 // (conv (conv x, t1), t2) -> (conv x, t2) 8913 if (N0.getOpcode() == ISD::BITCAST) 8914 return DAG.getBitcast(VT, N0.getOperand(0)); 8915 8916 // fold (conv (load x)) -> (load (conv*)x) 8917 // If the resultant load doesn't need a higher alignment than the original! 8918 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8919 // Do not change the width of a volatile load. 8920 !cast<LoadSDNode>(N0)->isVolatile() && 8921 // Do not remove the cast if the types differ in endian layout. 8922 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 8923 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 8924 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 8925 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 8926 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8927 unsigned OrigAlign = LN0->getAlignment(); 8928 8929 bool Fast = false; 8930 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 8931 LN0->getAddressSpace(), OrigAlign, &Fast) && 8932 Fast) { 8933 SDValue Load = 8934 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 8935 LN0->getPointerInfo(), OrigAlign, 8936 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8937 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 8938 return Load; 8939 } 8940 } 8941 8942 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 8943 return V; 8944 8945 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8946 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8947 // 8948 // For ppc_fp128: 8949 // fold (bitcast (fneg x)) -> 8950 // flipbit = signbit 8951 // (xor (bitcast x) (build_pair flipbit, flipbit)) 8952 // 8953 // fold (bitcast (fabs x)) -> 8954 // flipbit = (and (extract_element (bitcast x), 0), signbit) 8955 // (xor (bitcast x) (build_pair flipbit, flipbit)) 8956 // This often reduces constant pool loads. 8957 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 8958 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 8959 N0.getNode()->hasOneUse() && VT.isInteger() && 8960 !VT.isVector() && !N0.getValueType().isVector()) { 8961 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 8962 AddToWorklist(NewConv.getNode()); 8963 8964 SDLoc DL(N); 8965 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 8966 assert(VT.getSizeInBits() == 128); 8967 SDValue SignBit = DAG.getConstant( 8968 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 8969 SDValue FlipBit; 8970 if (N0.getOpcode() == ISD::FNEG) { 8971 FlipBit = SignBit; 8972 AddToWorklist(FlipBit.getNode()); 8973 } else { 8974 assert(N0.getOpcode() == ISD::FABS); 8975 SDValue Hi = 8976 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 8977 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 8978 SDLoc(NewConv))); 8979 AddToWorklist(Hi.getNode()); 8980 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 8981 AddToWorklist(FlipBit.getNode()); 8982 } 8983 SDValue FlipBits = 8984 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 8985 AddToWorklist(FlipBits.getNode()); 8986 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 8987 } 8988 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 8989 if (N0.getOpcode() == ISD::FNEG) 8990 return DAG.getNode(ISD::XOR, DL, VT, 8991 NewConv, DAG.getConstant(SignBit, DL, VT)); 8992 assert(N0.getOpcode() == ISD::FABS); 8993 return DAG.getNode(ISD::AND, DL, VT, 8994 NewConv, DAG.getConstant(~SignBit, DL, VT)); 8995 } 8996 8997 // fold (bitconvert (fcopysign cst, x)) -> 8998 // (or (and (bitconvert x), sign), (and cst, (not sign))) 8999 // Note that we don't handle (copysign x, cst) because this can always be 9000 // folded to an fneg or fabs. 9001 // 9002 // For ppc_fp128: 9003 // fold (bitcast (fcopysign cst, x)) -> 9004 // flipbit = (and (extract_element 9005 // (xor (bitcast cst), (bitcast x)), 0), 9006 // signbit) 9007 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 9008 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 9009 isa<ConstantFPSDNode>(N0.getOperand(0)) && 9010 VT.isInteger() && !VT.isVector()) { 9011 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits(); 9012 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 9013 if (isTypeLegal(IntXVT)) { 9014 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 9015 AddToWorklist(X.getNode()); 9016 9017 // If X has a different width than the result/lhs, sext it or truncate it. 9018 unsigned VTWidth = VT.getSizeInBits(); 9019 if (OrigXWidth < VTWidth) { 9020 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 9021 AddToWorklist(X.getNode()); 9022 } else if (OrigXWidth > VTWidth) { 9023 // To get the sign bit in the right place, we have to shift it right 9024 // before truncating. 9025 SDLoc DL(X); 9026 X = DAG.getNode(ISD::SRL, DL, 9027 X.getValueType(), X, 9028 DAG.getConstant(OrigXWidth-VTWidth, DL, 9029 X.getValueType())); 9030 AddToWorklist(X.getNode()); 9031 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 9032 AddToWorklist(X.getNode()); 9033 } 9034 9035 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 9036 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2); 9037 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 9038 AddToWorklist(Cst.getNode()); 9039 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 9040 AddToWorklist(X.getNode()); 9041 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 9042 AddToWorklist(XorResult.getNode()); 9043 SDValue XorResult64 = DAG.getNode( 9044 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 9045 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 9046 SDLoc(XorResult))); 9047 AddToWorklist(XorResult64.getNode()); 9048 SDValue FlipBit = 9049 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 9050 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 9051 AddToWorklist(FlipBit.getNode()); 9052 SDValue FlipBits = 9053 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 9054 AddToWorklist(FlipBits.getNode()); 9055 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 9056 } 9057 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 9058 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 9059 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 9060 AddToWorklist(X.getNode()); 9061 9062 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 9063 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 9064 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 9065 AddToWorklist(Cst.getNode()); 9066 9067 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 9068 } 9069 } 9070 9071 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 9072 if (N0.getOpcode() == ISD::BUILD_PAIR) 9073 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 9074 return CombineLD; 9075 9076 // Remove double bitcasts from shuffles - this is often a legacy of 9077 // XformToShuffleWithZero being used to combine bitmaskings (of 9078 // float vectors bitcast to integer vectors) into shuffles. 9079 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 9080 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 9081 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 9082 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 9083 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 9084 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 9085 9086 // If operands are a bitcast, peek through if it casts the original VT. 9087 // If operands are a constant, just bitcast back to original VT. 9088 auto PeekThroughBitcast = [&](SDValue Op) { 9089 if (Op.getOpcode() == ISD::BITCAST && 9090 Op.getOperand(0).getValueType() == VT) 9091 return SDValue(Op.getOperand(0)); 9092 if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 9093 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 9094 return DAG.getBitcast(VT, Op); 9095 return SDValue(); 9096 }; 9097 9098 // FIXME: If either input vector is bitcast, try to convert the shuffle to 9099 // the result type of this bitcast. This would eliminate at least one 9100 // bitcast. See the transform in InstCombine. 9101 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 9102 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 9103 if (!(SV0 && SV1)) 9104 return SDValue(); 9105 9106 int MaskScale = 9107 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 9108 SmallVector<int, 8> NewMask; 9109 for (int M : SVN->getMask()) 9110 for (int i = 0; i != MaskScale; ++i) 9111 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 9112 9113 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 9114 if (!LegalMask) { 9115 std::swap(SV0, SV1); 9116 ShuffleVectorSDNode::commuteMask(NewMask); 9117 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 9118 } 9119 9120 if (LegalMask) 9121 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 9122 } 9123 9124 return SDValue(); 9125 } 9126 9127 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 9128 EVT VT = N->getValueType(0); 9129 return CombineConsecutiveLoads(N, VT); 9130 } 9131 9132 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 9133 /// operands. DstEltVT indicates the destination element value type. 9134 SDValue DAGCombiner:: 9135 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 9136 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 9137 9138 // If this is already the right type, we're done. 9139 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 9140 9141 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 9142 unsigned DstBitSize = DstEltVT.getSizeInBits(); 9143 9144 // If this is a conversion of N elements of one type to N elements of another 9145 // type, convert each element. This handles FP<->INT cases. 9146 if (SrcBitSize == DstBitSize) { 9147 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 9148 BV->getValueType(0).getVectorNumElements()); 9149 9150 // Due to the FP element handling below calling this routine recursively, 9151 // we can end up with a scalar-to-vector node here. 9152 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 9153 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 9154 DAG.getBitcast(DstEltVT, BV->getOperand(0))); 9155 9156 SmallVector<SDValue, 8> Ops; 9157 for (SDValue Op : BV->op_values()) { 9158 // If the vector element type is not legal, the BUILD_VECTOR operands 9159 // are promoted and implicitly truncated. Make that explicit here. 9160 if (Op.getValueType() != SrcEltVT) 9161 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 9162 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 9163 AddToWorklist(Ops.back().getNode()); 9164 } 9165 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 9166 } 9167 9168 // Otherwise, we're growing or shrinking the elements. To avoid having to 9169 // handle annoying details of growing/shrinking FP values, we convert them to 9170 // int first. 9171 if (SrcEltVT.isFloatingPoint()) { 9172 // Convert the input float vector to a int vector where the elements are the 9173 // same sizes. 9174 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 9175 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 9176 SrcEltVT = IntVT; 9177 } 9178 9179 // Now we know the input is an integer vector. If the output is a FP type, 9180 // convert to integer first, then to FP of the right size. 9181 if (DstEltVT.isFloatingPoint()) { 9182 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 9183 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 9184 9185 // Next, convert to FP elements of the same size. 9186 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 9187 } 9188 9189 SDLoc DL(BV); 9190 9191 // Okay, we know the src/dst types are both integers of differing types. 9192 // Handling growing first. 9193 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 9194 if (SrcBitSize < DstBitSize) { 9195 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 9196 9197 SmallVector<SDValue, 8> Ops; 9198 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 9199 i += NumInputsPerOutput) { 9200 bool isLE = DAG.getDataLayout().isLittleEndian(); 9201 APInt NewBits = APInt(DstBitSize, 0); 9202 bool EltIsUndef = true; 9203 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 9204 // Shift the previously computed bits over. 9205 NewBits <<= SrcBitSize; 9206 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 9207 if (Op.isUndef()) continue; 9208 EltIsUndef = false; 9209 9210 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 9211 zextOrTrunc(SrcBitSize).zext(DstBitSize); 9212 } 9213 9214 if (EltIsUndef) 9215 Ops.push_back(DAG.getUNDEF(DstEltVT)); 9216 else 9217 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 9218 } 9219 9220 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 9221 return DAG.getBuildVector(VT, DL, Ops); 9222 } 9223 9224 // Finally, this must be the case where we are shrinking elements: each input 9225 // turns into multiple outputs. 9226 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 9227 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 9228 NumOutputsPerInput*BV->getNumOperands()); 9229 SmallVector<SDValue, 8> Ops; 9230 9231 for (const SDValue &Op : BV->op_values()) { 9232 if (Op.isUndef()) { 9233 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 9234 continue; 9235 } 9236 9237 APInt OpVal = cast<ConstantSDNode>(Op)-> 9238 getAPIntValue().zextOrTrunc(SrcBitSize); 9239 9240 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 9241 APInt ThisVal = OpVal.trunc(DstBitSize); 9242 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 9243 OpVal.lshrInPlace(DstBitSize); 9244 } 9245 9246 // For big endian targets, swap the order of the pieces of each element. 9247 if (DAG.getDataLayout().isBigEndian()) 9248 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 9249 } 9250 9251 return DAG.getBuildVector(VT, DL, Ops); 9252 } 9253 9254 static bool isContractable(SDNode *N) { 9255 SDNodeFlags F = N->getFlags(); 9256 return F.hasAllowContract() || F.hasUnsafeAlgebra(); 9257 } 9258 9259 /// Try to perform FMA combining on a given FADD node. 9260 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 9261 SDValue N0 = N->getOperand(0); 9262 SDValue N1 = N->getOperand(1); 9263 EVT VT = N->getValueType(0); 9264 SDLoc SL(N); 9265 9266 const TargetOptions &Options = DAG.getTarget().Options; 9267 9268 // Floating-point multiply-add with intermediate rounding. 9269 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9270 9271 // Floating-point multiply-add without intermediate rounding. 9272 bool HasFMA = 9273 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9274 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9275 9276 // No valid opcode, do not combine. 9277 if (!HasFMAD && !HasFMA) 9278 return SDValue(); 9279 9280 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 9281 Options.UnsafeFPMath || HasFMAD); 9282 // If the addition is not contractable, do not combine. 9283 if (!AllowFusionGlobally && !isContractable(N)) 9284 return SDValue(); 9285 9286 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 9287 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 9288 return SDValue(); 9289 9290 // Always prefer FMAD to FMA for precision. 9291 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9292 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9293 9294 // Is the node an FMUL and contractable either due to global flags or 9295 // SDNodeFlags. 9296 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 9297 if (N.getOpcode() != ISD::FMUL) 9298 return false; 9299 return AllowFusionGlobally || isContractable(N.getNode()); 9300 }; 9301 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 9302 // prefer to fold the multiply with fewer uses. 9303 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) { 9304 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 9305 std::swap(N0, N1); 9306 } 9307 9308 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 9309 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 9310 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9311 N0.getOperand(0), N0.getOperand(1), N1); 9312 } 9313 9314 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 9315 // Note: Commutes FADD operands. 9316 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) { 9317 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9318 N1.getOperand(0), N1.getOperand(1), N0); 9319 } 9320 9321 // Look through FP_EXTEND nodes to do more combining. 9322 9323 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 9324 if (N0.getOpcode() == ISD::FP_EXTEND) { 9325 SDValue N00 = N0.getOperand(0); 9326 if (isContractableFMUL(N00) && 9327 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 9328 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9329 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9330 N00.getOperand(0)), 9331 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9332 N00.getOperand(1)), N1); 9333 } 9334 } 9335 9336 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 9337 // Note: Commutes FADD operands. 9338 if (N1.getOpcode() == ISD::FP_EXTEND) { 9339 SDValue N10 = N1.getOperand(0); 9340 if (isContractableFMUL(N10) && 9341 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 9342 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9343 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9344 N10.getOperand(0)), 9345 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9346 N10.getOperand(1)), N0); 9347 } 9348 } 9349 9350 // More folding opportunities when target permits. 9351 if (Aggressive) { 9352 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 9353 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9354 // are currently only supported on binary nodes. 9355 if (Options.UnsafeFPMath && 9356 N0.getOpcode() == PreferredFusedOpcode && 9357 N0.getOperand(2).getOpcode() == ISD::FMUL && 9358 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) { 9359 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9360 N0.getOperand(0), N0.getOperand(1), 9361 DAG.getNode(PreferredFusedOpcode, SL, VT, 9362 N0.getOperand(2).getOperand(0), 9363 N0.getOperand(2).getOperand(1), 9364 N1)); 9365 } 9366 9367 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 9368 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9369 // are currently only supported on binary nodes. 9370 if (Options.UnsafeFPMath && 9371 N1->getOpcode() == PreferredFusedOpcode && 9372 N1.getOperand(2).getOpcode() == ISD::FMUL && 9373 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) { 9374 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9375 N1.getOperand(0), N1.getOperand(1), 9376 DAG.getNode(PreferredFusedOpcode, SL, VT, 9377 N1.getOperand(2).getOperand(0), 9378 N1.getOperand(2).getOperand(1), 9379 N0)); 9380 } 9381 9382 9383 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 9384 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 9385 auto FoldFAddFMAFPExtFMul = [&] ( 9386 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 9387 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 9388 DAG.getNode(PreferredFusedOpcode, SL, VT, 9389 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 9390 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 9391 Z)); 9392 }; 9393 if (N0.getOpcode() == PreferredFusedOpcode) { 9394 SDValue N02 = N0.getOperand(2); 9395 if (N02.getOpcode() == ISD::FP_EXTEND) { 9396 SDValue N020 = N02.getOperand(0); 9397 if (isContractableFMUL(N020) && 9398 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) { 9399 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 9400 N020.getOperand(0), N020.getOperand(1), 9401 N1); 9402 } 9403 } 9404 } 9405 9406 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 9407 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 9408 // FIXME: This turns two single-precision and one double-precision 9409 // operation into two double-precision operations, which might not be 9410 // interesting for all targets, especially GPUs. 9411 auto FoldFAddFPExtFMAFMul = [&] ( 9412 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 9413 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9414 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 9415 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 9416 DAG.getNode(PreferredFusedOpcode, SL, VT, 9417 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 9418 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 9419 Z)); 9420 }; 9421 if (N0.getOpcode() == ISD::FP_EXTEND) { 9422 SDValue N00 = N0.getOperand(0); 9423 if (N00.getOpcode() == PreferredFusedOpcode) { 9424 SDValue N002 = N00.getOperand(2); 9425 if (isContractableFMUL(N002) && 9426 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 9427 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 9428 N002.getOperand(0), N002.getOperand(1), 9429 N1); 9430 } 9431 } 9432 } 9433 9434 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 9435 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 9436 if (N1.getOpcode() == PreferredFusedOpcode) { 9437 SDValue N12 = N1.getOperand(2); 9438 if (N12.getOpcode() == ISD::FP_EXTEND) { 9439 SDValue N120 = N12.getOperand(0); 9440 if (isContractableFMUL(N120) && 9441 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) { 9442 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 9443 N120.getOperand(0), N120.getOperand(1), 9444 N0); 9445 } 9446 } 9447 } 9448 9449 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 9450 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 9451 // FIXME: This turns two single-precision and one double-precision 9452 // operation into two double-precision operations, which might not be 9453 // interesting for all targets, especially GPUs. 9454 if (N1.getOpcode() == ISD::FP_EXTEND) { 9455 SDValue N10 = N1.getOperand(0); 9456 if (N10.getOpcode() == PreferredFusedOpcode) { 9457 SDValue N102 = N10.getOperand(2); 9458 if (isContractableFMUL(N102) && 9459 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 9460 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 9461 N102.getOperand(0), N102.getOperand(1), 9462 N0); 9463 } 9464 } 9465 } 9466 } 9467 9468 return SDValue(); 9469 } 9470 9471 /// Try to perform FMA combining on a given FSUB node. 9472 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 9473 SDValue N0 = N->getOperand(0); 9474 SDValue N1 = N->getOperand(1); 9475 EVT VT = N->getValueType(0); 9476 SDLoc SL(N); 9477 9478 const TargetOptions &Options = DAG.getTarget().Options; 9479 // Floating-point multiply-add with intermediate rounding. 9480 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9481 9482 // Floating-point multiply-add without intermediate rounding. 9483 bool HasFMA = 9484 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9485 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9486 9487 // No valid opcode, do not combine. 9488 if (!HasFMAD && !HasFMA) 9489 return SDValue(); 9490 9491 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 9492 Options.UnsafeFPMath || HasFMAD); 9493 // If the subtraction is not contractable, do not combine. 9494 if (!AllowFusionGlobally && !isContractable(N)) 9495 return SDValue(); 9496 9497 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 9498 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 9499 return SDValue(); 9500 9501 // Always prefer FMAD to FMA for precision. 9502 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9503 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9504 9505 // Is the node an FMUL and contractable either due to global flags or 9506 // SDNodeFlags. 9507 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 9508 if (N.getOpcode() != ISD::FMUL) 9509 return false; 9510 return AllowFusionGlobally || isContractable(N.getNode()); 9511 }; 9512 9513 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 9514 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 9515 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9516 N0.getOperand(0), N0.getOperand(1), 9517 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9518 } 9519 9520 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 9521 // Note: Commutes FSUB operands. 9522 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) 9523 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9524 DAG.getNode(ISD::FNEG, SL, VT, 9525 N1.getOperand(0)), 9526 N1.getOperand(1), N0); 9527 9528 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 9529 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) && 9530 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 9531 SDValue N00 = N0.getOperand(0).getOperand(0); 9532 SDValue N01 = N0.getOperand(0).getOperand(1); 9533 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9534 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 9535 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9536 } 9537 9538 // Look through FP_EXTEND nodes to do more combining. 9539 9540 // fold (fsub (fpext (fmul x, y)), z) 9541 // -> (fma (fpext x), (fpext y), (fneg z)) 9542 if (N0.getOpcode() == ISD::FP_EXTEND) { 9543 SDValue N00 = N0.getOperand(0); 9544 if (isContractableFMUL(N00) && 9545 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 9546 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9547 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9548 N00.getOperand(0)), 9549 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9550 N00.getOperand(1)), 9551 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9552 } 9553 } 9554 9555 // fold (fsub x, (fpext (fmul y, z))) 9556 // -> (fma (fneg (fpext y)), (fpext z), x) 9557 // Note: Commutes FSUB operands. 9558 if (N1.getOpcode() == ISD::FP_EXTEND) { 9559 SDValue N10 = N1.getOperand(0); 9560 if (isContractableFMUL(N10) && 9561 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 9562 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9563 DAG.getNode(ISD::FNEG, SL, VT, 9564 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9565 N10.getOperand(0))), 9566 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9567 N10.getOperand(1)), 9568 N0); 9569 } 9570 } 9571 9572 // fold (fsub (fpext (fneg (fmul, x, y))), z) 9573 // -> (fneg (fma (fpext x), (fpext y), z)) 9574 // Note: This could be removed with appropriate canonicalization of the 9575 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 9576 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 9577 // from implementing the canonicalization in visitFSUB. 9578 if (N0.getOpcode() == ISD::FP_EXTEND) { 9579 SDValue N00 = N0.getOperand(0); 9580 if (N00.getOpcode() == ISD::FNEG) { 9581 SDValue N000 = N00.getOperand(0); 9582 if (isContractableFMUL(N000) && 9583 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 9584 return DAG.getNode(ISD::FNEG, SL, VT, 9585 DAG.getNode(PreferredFusedOpcode, SL, VT, 9586 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9587 N000.getOperand(0)), 9588 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9589 N000.getOperand(1)), 9590 N1)); 9591 } 9592 } 9593 } 9594 9595 // fold (fsub (fneg (fpext (fmul, x, y))), z) 9596 // -> (fneg (fma (fpext x)), (fpext y), z) 9597 // Note: This could be removed with appropriate canonicalization of the 9598 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 9599 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 9600 // from implementing the canonicalization in visitFSUB. 9601 if (N0.getOpcode() == ISD::FNEG) { 9602 SDValue N00 = N0.getOperand(0); 9603 if (N00.getOpcode() == ISD::FP_EXTEND) { 9604 SDValue N000 = N00.getOperand(0); 9605 if (isContractableFMUL(N000) && 9606 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N000.getValueType())) { 9607 return DAG.getNode(ISD::FNEG, SL, VT, 9608 DAG.getNode(PreferredFusedOpcode, SL, VT, 9609 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9610 N000.getOperand(0)), 9611 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9612 N000.getOperand(1)), 9613 N1)); 9614 } 9615 } 9616 } 9617 9618 // More folding opportunities when target permits. 9619 if (Aggressive) { 9620 // fold (fsub (fma x, y, (fmul u, v)), z) 9621 // -> (fma x, y (fma u, v, (fneg z))) 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 && N0.getOpcode() == PreferredFusedOpcode && 9625 isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() && 9626 N0.getOperand(2)->hasOneUse()) { 9627 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9628 N0.getOperand(0), N0.getOperand(1), 9629 DAG.getNode(PreferredFusedOpcode, SL, VT, 9630 N0.getOperand(2).getOperand(0), 9631 N0.getOperand(2).getOperand(1), 9632 DAG.getNode(ISD::FNEG, SL, VT, 9633 N1))); 9634 } 9635 9636 // fold (fsub x, (fma y, z, (fmul u, v))) 9637 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 9638 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9639 // are currently only supported on binary nodes. 9640 if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode && 9641 isContractableFMUL(N1.getOperand(2))) { 9642 SDValue N20 = N1.getOperand(2).getOperand(0); 9643 SDValue N21 = N1.getOperand(2).getOperand(1); 9644 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9645 DAG.getNode(ISD::FNEG, SL, VT, 9646 N1.getOperand(0)), 9647 N1.getOperand(1), 9648 DAG.getNode(PreferredFusedOpcode, SL, VT, 9649 DAG.getNode(ISD::FNEG, SL, VT, N20), 9650 9651 N21, N0)); 9652 } 9653 9654 9655 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 9656 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 9657 if (N0.getOpcode() == PreferredFusedOpcode) { 9658 SDValue N02 = N0.getOperand(2); 9659 if (N02.getOpcode() == ISD::FP_EXTEND) { 9660 SDValue N020 = N02.getOperand(0); 9661 if (isContractableFMUL(N020) && 9662 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) { 9663 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9664 N0.getOperand(0), N0.getOperand(1), 9665 DAG.getNode(PreferredFusedOpcode, SL, VT, 9666 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9667 N020.getOperand(0)), 9668 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9669 N020.getOperand(1)), 9670 DAG.getNode(ISD::FNEG, SL, VT, 9671 N1))); 9672 } 9673 } 9674 } 9675 9676 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 9677 // -> (fma (fpext x), (fpext y), 9678 // (fma (fpext u), (fpext v), (fneg z))) 9679 // FIXME: This turns two single-precision and one double-precision 9680 // operation into two double-precision operations, which might not be 9681 // interesting for all targets, especially GPUs. 9682 if (N0.getOpcode() == ISD::FP_EXTEND) { 9683 SDValue N00 = N0.getOperand(0); 9684 if (N00.getOpcode() == PreferredFusedOpcode) { 9685 SDValue N002 = N00.getOperand(2); 9686 if (isContractableFMUL(N002) && 9687 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 9688 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9689 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9690 N00.getOperand(0)), 9691 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9692 N00.getOperand(1)), 9693 DAG.getNode(PreferredFusedOpcode, SL, VT, 9694 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9695 N002.getOperand(0)), 9696 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9697 N002.getOperand(1)), 9698 DAG.getNode(ISD::FNEG, SL, VT, 9699 N1))); 9700 } 9701 } 9702 } 9703 9704 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 9705 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 9706 if (N1.getOpcode() == PreferredFusedOpcode && 9707 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 9708 SDValue N120 = N1.getOperand(2).getOperand(0); 9709 if (isContractableFMUL(N120) && 9710 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) { 9711 SDValue N1200 = N120.getOperand(0); 9712 SDValue N1201 = N120.getOperand(1); 9713 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9714 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 9715 N1.getOperand(1), 9716 DAG.getNode(PreferredFusedOpcode, SL, VT, 9717 DAG.getNode(ISD::FNEG, SL, VT, 9718 DAG.getNode(ISD::FP_EXTEND, SL, 9719 VT, N1200)), 9720 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9721 N1201), 9722 N0)); 9723 } 9724 } 9725 9726 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 9727 // -> (fma (fneg (fpext y)), (fpext z), 9728 // (fma (fneg (fpext u)), (fpext v), x)) 9729 // FIXME: This turns two single-precision and one double-precision 9730 // operation into two double-precision operations, which might not be 9731 // interesting for all targets, especially GPUs. 9732 if (N1.getOpcode() == ISD::FP_EXTEND && 9733 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 9734 SDValue CvtSrc = N1.getOperand(0); 9735 SDValue N100 = CvtSrc.getOperand(0); 9736 SDValue N101 = CvtSrc.getOperand(1); 9737 SDValue N102 = CvtSrc.getOperand(2); 9738 if (isContractableFMUL(N102) && 9739 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, CvtSrc.getValueType())) { 9740 SDValue N1020 = N102.getOperand(0); 9741 SDValue N1021 = N102.getOperand(1); 9742 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9743 DAG.getNode(ISD::FNEG, SL, VT, 9744 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9745 N100)), 9746 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 9747 DAG.getNode(PreferredFusedOpcode, SL, VT, 9748 DAG.getNode(ISD::FNEG, SL, VT, 9749 DAG.getNode(ISD::FP_EXTEND, SL, 9750 VT, N1020)), 9751 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9752 N1021), 9753 N0)); 9754 } 9755 } 9756 } 9757 9758 return SDValue(); 9759 } 9760 9761 /// Try to perform FMA combining on a given FMUL node based on the distributive 9762 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions, 9763 /// subtraction instead of addition). 9764 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) { 9765 SDValue N0 = N->getOperand(0); 9766 SDValue N1 = N->getOperand(1); 9767 EVT VT = N->getValueType(0); 9768 SDLoc SL(N); 9769 9770 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 9771 9772 const TargetOptions &Options = DAG.getTarget().Options; 9773 9774 // The transforms below are incorrect when x == 0 and y == inf, because the 9775 // intermediate multiplication produces a nan. 9776 if (!Options.NoInfsFPMath) 9777 return SDValue(); 9778 9779 // Floating-point multiply-add without intermediate rounding. 9780 bool HasFMA = 9781 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 9782 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9783 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9784 9785 // Floating-point multiply-add with intermediate rounding. This can result 9786 // in a less precise result due to the changed rounding order. 9787 bool HasFMAD = Options.UnsafeFPMath && 9788 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9789 9790 // No valid opcode, do not combine. 9791 if (!HasFMAD && !HasFMA) 9792 return SDValue(); 9793 9794 // Always prefer FMAD to FMA for precision. 9795 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9796 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9797 9798 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 9799 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 9800 auto FuseFADD = [&](SDValue X, SDValue Y) { 9801 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 9802 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 9803 if (XC1 && XC1->isExactlyValue(+1.0)) 9804 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 9805 if (XC1 && XC1->isExactlyValue(-1.0)) 9806 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 9807 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9808 } 9809 return SDValue(); 9810 }; 9811 9812 if (SDValue FMA = FuseFADD(N0, N1)) 9813 return FMA; 9814 if (SDValue FMA = FuseFADD(N1, N0)) 9815 return FMA; 9816 9817 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 9818 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 9819 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 9820 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 9821 auto FuseFSUB = [&](SDValue X, SDValue Y) { 9822 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 9823 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 9824 if (XC0 && XC0->isExactlyValue(+1.0)) 9825 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9826 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 9827 Y); 9828 if (XC0 && XC0->isExactlyValue(-1.0)) 9829 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9830 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 9831 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9832 9833 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 9834 if (XC1 && XC1->isExactlyValue(+1.0)) 9835 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 9836 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9837 if (XC1 && XC1->isExactlyValue(-1.0)) 9838 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 9839 } 9840 return SDValue(); 9841 }; 9842 9843 if (SDValue FMA = FuseFSUB(N0, N1)) 9844 return FMA; 9845 if (SDValue FMA = FuseFSUB(N1, N0)) 9846 return FMA; 9847 9848 return SDValue(); 9849 } 9850 9851 static bool isFMulNegTwo(SDValue &N) { 9852 if (N.getOpcode() != ISD::FMUL) 9853 return false; 9854 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1))) 9855 return CFP->isExactlyValue(-2.0); 9856 return false; 9857 } 9858 9859 SDValue DAGCombiner::visitFADD(SDNode *N) { 9860 SDValue N0 = N->getOperand(0); 9861 SDValue N1 = N->getOperand(1); 9862 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 9863 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 9864 EVT VT = N->getValueType(0); 9865 SDLoc DL(N); 9866 const TargetOptions &Options = DAG.getTarget().Options; 9867 const SDNodeFlags Flags = N->getFlags(); 9868 9869 // fold vector ops 9870 if (VT.isVector()) 9871 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9872 return FoldedVOp; 9873 9874 // fold (fadd c1, c2) -> c1 + c2 9875 if (N0CFP && N1CFP) 9876 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 9877 9878 // canonicalize constant to RHS 9879 if (N0CFP && !N1CFP) 9880 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 9881 9882 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9883 return NewSel; 9884 9885 // fold (fadd A, (fneg B)) -> (fsub A, B) 9886 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 9887 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 9888 return DAG.getNode(ISD::FSUB, DL, VT, N0, 9889 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 9890 9891 // fold (fadd (fneg A), B) -> (fsub B, A) 9892 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 9893 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 9894 return DAG.getNode(ISD::FSUB, DL, VT, N1, 9895 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 9896 9897 // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B)) 9898 // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B)) 9899 if ((isFMulNegTwo(N0) && N0.hasOneUse()) || 9900 (isFMulNegTwo(N1) && N1.hasOneUse())) { 9901 bool N1IsFMul = isFMulNegTwo(N1); 9902 SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0); 9903 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags); 9904 return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags); 9905 } 9906 9907 // FIXME: Auto-upgrade the target/function-level option. 9908 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) { 9909 // fold (fadd A, 0) -> A 9910 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 9911 if (N1C->isZero()) 9912 return N0; 9913 } 9914 9915 // If 'unsafe math' is enabled, fold lots of things. 9916 if (Options.UnsafeFPMath) { 9917 // No FP constant should be created after legalization as Instruction 9918 // Selection pass has a hard time dealing with FP constants. 9919 bool AllowNewConst = (Level < AfterLegalizeDAG); 9920 9921 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 9922 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 9923 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 9924 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 9925 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 9926 Flags), 9927 Flags); 9928 9929 // If allowed, fold (fadd (fneg x), x) -> 0.0 9930 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 9931 return DAG.getConstantFP(0.0, DL, VT); 9932 9933 // If allowed, fold (fadd x, (fneg x)) -> 0.0 9934 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 9935 return DAG.getConstantFP(0.0, DL, VT); 9936 9937 // We can fold chains of FADD's of the same value into multiplications. 9938 // This transform is not safe in general because we are reducing the number 9939 // of rounding steps. 9940 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 9941 if (N0.getOpcode() == ISD::FMUL) { 9942 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 9943 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 9944 9945 // (fadd (fmul x, c), x) -> (fmul x, c+1) 9946 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 9947 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 9948 DAG.getConstantFP(1.0, DL, VT), Flags); 9949 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 9950 } 9951 9952 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 9953 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 9954 N1.getOperand(0) == N1.getOperand(1) && 9955 N0.getOperand(0) == N1.getOperand(0)) { 9956 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 9957 DAG.getConstantFP(2.0, DL, VT), Flags); 9958 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 9959 } 9960 } 9961 9962 if (N1.getOpcode() == ISD::FMUL) { 9963 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 9964 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 9965 9966 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 9967 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 9968 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 9969 DAG.getConstantFP(1.0, DL, VT), Flags); 9970 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 9971 } 9972 9973 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 9974 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 9975 N0.getOperand(0) == N0.getOperand(1) && 9976 N1.getOperand(0) == N0.getOperand(0)) { 9977 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 9978 DAG.getConstantFP(2.0, DL, VT), Flags); 9979 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 9980 } 9981 } 9982 9983 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 9984 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 9985 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 9986 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 9987 (N0.getOperand(0) == N1)) { 9988 return DAG.getNode(ISD::FMUL, DL, VT, 9989 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 9990 } 9991 } 9992 9993 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 9994 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 9995 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 9996 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 9997 N1.getOperand(0) == N0) { 9998 return DAG.getNode(ISD::FMUL, DL, VT, 9999 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 10000 } 10001 } 10002 10003 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 10004 if (AllowNewConst && 10005 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 10006 N0.getOperand(0) == N0.getOperand(1) && 10007 N1.getOperand(0) == N1.getOperand(1) && 10008 N0.getOperand(0) == N1.getOperand(0)) { 10009 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 10010 DAG.getConstantFP(4.0, DL, VT), Flags); 10011 } 10012 } 10013 } // enable-unsafe-fp-math 10014 10015 // FADD -> FMA combines: 10016 if (SDValue Fused = visitFADDForFMACombine(N)) { 10017 AddToWorklist(Fused.getNode()); 10018 return Fused; 10019 } 10020 return SDValue(); 10021 } 10022 10023 SDValue DAGCombiner::visitFSUB(SDNode *N) { 10024 SDValue N0 = N->getOperand(0); 10025 SDValue N1 = N->getOperand(1); 10026 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10027 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10028 EVT VT = N->getValueType(0); 10029 SDLoc DL(N); 10030 const TargetOptions &Options = DAG.getTarget().Options; 10031 const SDNodeFlags Flags = N->getFlags(); 10032 10033 // fold vector ops 10034 if (VT.isVector()) 10035 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 10036 return FoldedVOp; 10037 10038 // fold (fsub c1, c2) -> c1-c2 10039 if (N0CFP && N1CFP) 10040 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags); 10041 10042 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10043 return NewSel; 10044 10045 // fold (fsub A, (fneg B)) -> (fadd A, B) 10046 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 10047 return DAG.getNode(ISD::FADD, DL, VT, N0, 10048 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 10049 10050 // FIXME: Auto-upgrade the target/function-level option. 10051 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) { 10052 // (fsub 0, B) -> -B 10053 if (N0CFP && N0CFP->isZero()) { 10054 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 10055 return GetNegatedExpression(N1, DAG, LegalOperations); 10056 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 10057 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags); 10058 } 10059 } 10060 10061 // If 'unsafe math' is enabled, fold lots of things. 10062 if (Options.UnsafeFPMath) { 10063 // (fsub A, 0) -> A 10064 if (N1CFP && N1CFP->isZero()) 10065 return N0; 10066 10067 // (fsub x, x) -> 0.0 10068 if (N0 == N1) 10069 return DAG.getConstantFP(0.0f, DL, VT); 10070 10071 // (fsub x, (fadd x, y)) -> (fneg y) 10072 // (fsub x, (fadd y, x)) -> (fneg y) 10073 if (N1.getOpcode() == ISD::FADD) { 10074 SDValue N10 = N1->getOperand(0); 10075 SDValue N11 = N1->getOperand(1); 10076 10077 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 10078 return GetNegatedExpression(N11, DAG, LegalOperations); 10079 10080 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 10081 return GetNegatedExpression(N10, DAG, LegalOperations); 10082 } 10083 } 10084 10085 // FSUB -> FMA combines: 10086 if (SDValue Fused = visitFSUBForFMACombine(N)) { 10087 AddToWorklist(Fused.getNode()); 10088 return Fused; 10089 } 10090 10091 return SDValue(); 10092 } 10093 10094 SDValue DAGCombiner::visitFMUL(SDNode *N) { 10095 SDValue N0 = N->getOperand(0); 10096 SDValue N1 = N->getOperand(1); 10097 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10098 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10099 EVT VT = N->getValueType(0); 10100 SDLoc DL(N); 10101 const TargetOptions &Options = DAG.getTarget().Options; 10102 const SDNodeFlags Flags = N->getFlags(); 10103 10104 // fold vector ops 10105 if (VT.isVector()) { 10106 // This just handles C1 * C2 for vectors. Other vector folds are below. 10107 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 10108 return FoldedVOp; 10109 } 10110 10111 // fold (fmul c1, c2) -> c1*c2 10112 if (N0CFP && N1CFP) 10113 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 10114 10115 // canonicalize constant to RHS 10116 if (isConstantFPBuildVectorOrConstantFP(N0) && 10117 !isConstantFPBuildVectorOrConstantFP(N1)) 10118 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 10119 10120 // fold (fmul A, 1.0) -> A 10121 if (N1CFP && N1CFP->isExactlyValue(1.0)) 10122 return N0; 10123 10124 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10125 return NewSel; 10126 10127 if (Options.UnsafeFPMath) { 10128 // fold (fmul A, 0) -> 0 10129 if (N1CFP && N1CFP->isZero()) 10130 return N1; 10131 10132 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 10133 if (N0.getOpcode() == ISD::FMUL) { 10134 // Fold scalars or any vector constants (not just splats). 10135 // This fold is done in general by InstCombine, but extra fmul insts 10136 // may have been generated during lowering. 10137 SDValue N00 = N0.getOperand(0); 10138 SDValue N01 = N0.getOperand(1); 10139 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 10140 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 10141 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 10142 10143 // Check 1: Make sure that the first operand of the inner multiply is NOT 10144 // a constant. Otherwise, we may induce infinite looping. 10145 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 10146 // Check 2: Make sure that the second operand of the inner multiply and 10147 // the second operand of the outer multiply are constants. 10148 if ((N1CFP && isConstOrConstSplatFP(N01)) || 10149 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 10150 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 10151 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 10152 } 10153 } 10154 } 10155 10156 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 10157 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 10158 // during an early run of DAGCombiner can prevent folding with fmuls 10159 // inserted during lowering. 10160 if (N0.getOpcode() == ISD::FADD && 10161 (N0.getOperand(0) == N0.getOperand(1)) && 10162 N0.hasOneUse()) { 10163 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 10164 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 10165 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 10166 } 10167 } 10168 10169 // fold (fmul X, 2.0) -> (fadd X, X) 10170 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 10171 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 10172 10173 // fold (fmul X, -1.0) -> (fneg X) 10174 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 10175 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 10176 return DAG.getNode(ISD::FNEG, DL, VT, N0); 10177 10178 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 10179 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 10180 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 10181 // Both can be negated for free, check to see if at least one is cheaper 10182 // negated. 10183 if (LHSNeg == 2 || RHSNeg == 2) 10184 return DAG.getNode(ISD::FMUL, DL, VT, 10185 GetNegatedExpression(N0, DAG, LegalOperations), 10186 GetNegatedExpression(N1, DAG, LegalOperations), 10187 Flags); 10188 } 10189 } 10190 10191 // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X)) 10192 // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X) 10193 if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() && 10194 (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) && 10195 TLI.isOperationLegal(ISD::FABS, VT)) { 10196 SDValue Select = N0, X = N1; 10197 if (Select.getOpcode() != ISD::SELECT) 10198 std::swap(Select, X); 10199 10200 SDValue Cond = Select.getOperand(0); 10201 auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1)); 10202 auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2)); 10203 10204 if (TrueOpnd && FalseOpnd && 10205 Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X && 10206 isa<ConstantFPSDNode>(Cond.getOperand(1)) && 10207 cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) { 10208 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 10209 switch (CC) { 10210 default: break; 10211 case ISD::SETOLT: 10212 case ISD::SETULT: 10213 case ISD::SETOLE: 10214 case ISD::SETULE: 10215 case ISD::SETLT: 10216 case ISD::SETLE: 10217 std::swap(TrueOpnd, FalseOpnd); 10218 LLVM_FALLTHROUGH; 10219 case ISD::SETOGT: 10220 case ISD::SETUGT: 10221 case ISD::SETOGE: 10222 case ISD::SETUGE: 10223 case ISD::SETGT: 10224 case ISD::SETGE: 10225 if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) && 10226 TLI.isOperationLegal(ISD::FNEG, VT)) 10227 return DAG.getNode(ISD::FNEG, DL, VT, 10228 DAG.getNode(ISD::FABS, DL, VT, X)); 10229 if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0)) 10230 return DAG.getNode(ISD::FABS, DL, VT, X); 10231 10232 break; 10233 } 10234 } 10235 } 10236 10237 // FMUL -> FMA combines: 10238 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) { 10239 AddToWorklist(Fused.getNode()); 10240 return Fused; 10241 } 10242 10243 return SDValue(); 10244 } 10245 10246 SDValue DAGCombiner::visitFMA(SDNode *N) { 10247 SDValue N0 = N->getOperand(0); 10248 SDValue N1 = N->getOperand(1); 10249 SDValue N2 = N->getOperand(2); 10250 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10251 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10252 EVT VT = N->getValueType(0); 10253 SDLoc DL(N); 10254 const TargetOptions &Options = DAG.getTarget().Options; 10255 10256 // Constant fold FMA. 10257 if (isa<ConstantFPSDNode>(N0) && 10258 isa<ConstantFPSDNode>(N1) && 10259 isa<ConstantFPSDNode>(N2)) { 10260 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2); 10261 } 10262 10263 if (Options.UnsafeFPMath) { 10264 if (N0CFP && N0CFP->isZero()) 10265 return N2; 10266 if (N1CFP && N1CFP->isZero()) 10267 return N2; 10268 } 10269 // TODO: The FMA node should have flags that propagate to these nodes. 10270 if (N0CFP && N0CFP->isExactlyValue(1.0)) 10271 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 10272 if (N1CFP && N1CFP->isExactlyValue(1.0)) 10273 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 10274 10275 // Canonicalize (fma c, x, y) -> (fma x, c, y) 10276 if (isConstantFPBuildVectorOrConstantFP(N0) && 10277 !isConstantFPBuildVectorOrConstantFP(N1)) 10278 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 10279 10280 // TODO: FMA nodes should have flags that propagate to the created nodes. 10281 // For now, create a Flags object for use with all unsafe math transforms. 10282 SDNodeFlags Flags; 10283 Flags.setUnsafeAlgebra(true); 10284 10285 if (Options.UnsafeFPMath) { 10286 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 10287 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 10288 isConstantFPBuildVectorOrConstantFP(N1) && 10289 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 10290 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10291 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1), 10292 Flags), Flags); 10293 } 10294 10295 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 10296 if (N0.getOpcode() == ISD::FMUL && 10297 isConstantFPBuildVectorOrConstantFP(N1) && 10298 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 10299 return DAG.getNode(ISD::FMA, DL, VT, 10300 N0.getOperand(0), 10301 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1), 10302 Flags), 10303 N2); 10304 } 10305 } 10306 10307 // (fma x, 1, y) -> (fadd x, y) 10308 // (fma x, -1, y) -> (fadd (fneg x), y) 10309 if (N1CFP) { 10310 if (N1CFP->isExactlyValue(1.0)) 10311 // TODO: The FMA node should have flags that propagate to this node. 10312 return DAG.getNode(ISD::FADD, DL, VT, N0, N2); 10313 10314 if (N1CFP->isExactlyValue(-1.0) && 10315 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 10316 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0); 10317 AddToWorklist(RHSNeg.getNode()); 10318 // TODO: The FMA node should have flags that propagate to this node. 10319 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg); 10320 } 10321 10322 // fma (fneg x), K, y -> fma x -K, y 10323 if (N0.getOpcode() == ISD::FNEG && 10324 (TLI.isOperationLegal(ISD::ConstantFP, VT) || 10325 (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT)))) { 10326 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0), 10327 DAG.getNode(ISD::FNEG, DL, VT, N1, Flags), N2); 10328 } 10329 } 10330 10331 if (Options.UnsafeFPMath) { 10332 // (fma x, c, x) -> (fmul x, (c+1)) 10333 if (N1CFP && N0 == N2) { 10334 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10335 DAG.getNode(ISD::FADD, DL, VT, N1, 10336 DAG.getConstantFP(1.0, DL, VT), Flags), 10337 Flags); 10338 } 10339 10340 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 10341 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 10342 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10343 DAG.getNode(ISD::FADD, DL, VT, N1, 10344 DAG.getConstantFP(-1.0, DL, VT), Flags), 10345 Flags); 10346 } 10347 } 10348 10349 return SDValue(); 10350 } 10351 10352 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10353 // reciprocal. 10354 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 10355 // Notice that this is not always beneficial. One reason is different targets 10356 // may have different costs for FDIV and FMUL, so sometimes the cost of two 10357 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 10358 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 10359 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 10360 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 10361 const SDNodeFlags Flags = N->getFlags(); 10362 if (!UnsafeMath && !Flags.hasAllowReciprocal()) 10363 return SDValue(); 10364 10365 // Skip if current node is a reciprocal. 10366 SDValue N0 = N->getOperand(0); 10367 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10368 if (N0CFP && N0CFP->isExactlyValue(1.0)) 10369 return SDValue(); 10370 10371 // Exit early if the target does not want this transform or if there can't 10372 // possibly be enough uses of the divisor to make the transform worthwhile. 10373 SDValue N1 = N->getOperand(1); 10374 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 10375 if (!MinUses || N1->use_size() < MinUses) 10376 return SDValue(); 10377 10378 // Find all FDIV users of the same divisor. 10379 // Use a set because duplicates may be present in the user list. 10380 SetVector<SDNode *> Users; 10381 for (auto *U : N1->uses()) { 10382 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 10383 // This division is eligible for optimization only if global unsafe math 10384 // is enabled or if this division allows reciprocal formation. 10385 if (UnsafeMath || U->getFlags().hasAllowReciprocal()) 10386 Users.insert(U); 10387 } 10388 } 10389 10390 // Now that we have the actual number of divisor uses, make sure it meets 10391 // the minimum threshold specified by the target. 10392 if (Users.size() < MinUses) 10393 return SDValue(); 10394 10395 EVT VT = N->getValueType(0); 10396 SDLoc DL(N); 10397 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 10398 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 10399 10400 // Dividend / Divisor -> Dividend * Reciprocal 10401 for (auto *U : Users) { 10402 SDValue Dividend = U->getOperand(0); 10403 if (Dividend != FPOne) { 10404 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 10405 Reciprocal, Flags); 10406 CombineTo(U, NewNode); 10407 } else if (U != Reciprocal.getNode()) { 10408 // In the absence of fast-math-flags, this user node is always the 10409 // same node as Reciprocal, but with FMF they may be different nodes. 10410 CombineTo(U, Reciprocal); 10411 } 10412 } 10413 return SDValue(N, 0); // N was replaced. 10414 } 10415 10416 SDValue DAGCombiner::visitFDIV(SDNode *N) { 10417 SDValue N0 = N->getOperand(0); 10418 SDValue N1 = N->getOperand(1); 10419 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10420 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10421 EVT VT = N->getValueType(0); 10422 SDLoc DL(N); 10423 const TargetOptions &Options = DAG.getTarget().Options; 10424 SDNodeFlags Flags = N->getFlags(); 10425 10426 // fold vector ops 10427 if (VT.isVector()) 10428 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 10429 return FoldedVOp; 10430 10431 // fold (fdiv c1, c2) -> c1/c2 10432 if (N0CFP && N1CFP) 10433 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 10434 10435 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10436 return NewSel; 10437 10438 if (Options.UnsafeFPMath) { 10439 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 10440 if (N1CFP) { 10441 // Compute the reciprocal 1.0 / c2. 10442 const APFloat &N1APF = N1CFP->getValueAPF(); 10443 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 10444 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 10445 // Only do the transform if the reciprocal is a legal fp immediate that 10446 // isn't too nasty (eg NaN, denormal, ...). 10447 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 10448 (!LegalOperations || 10449 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 10450 // backend)... we should handle this gracefully after Legalize. 10451 // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) || 10452 TLI.isOperationLegal(ISD::ConstantFP, VT) || 10453 TLI.isFPImmLegal(Recip, VT))) 10454 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10455 DAG.getConstantFP(Recip, DL, VT), Flags); 10456 } 10457 10458 // If this FDIV is part of a reciprocal square root, it may be folded 10459 // into a target-specific square root estimate instruction. 10460 if (N1.getOpcode() == ISD::FSQRT) { 10461 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) { 10462 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10463 } 10464 } else if (N1.getOpcode() == ISD::FP_EXTEND && 10465 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10466 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 10467 Flags)) { 10468 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 10469 AddToWorklist(RV.getNode()); 10470 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10471 } 10472 } else if (N1.getOpcode() == ISD::FP_ROUND && 10473 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10474 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 10475 Flags)) { 10476 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 10477 AddToWorklist(RV.getNode()); 10478 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10479 } 10480 } else if (N1.getOpcode() == ISD::FMUL) { 10481 // Look through an FMUL. Even though this won't remove the FDIV directly, 10482 // it's still worthwhile to get rid of the FSQRT if possible. 10483 SDValue SqrtOp; 10484 SDValue OtherOp; 10485 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10486 SqrtOp = N1.getOperand(0); 10487 OtherOp = N1.getOperand(1); 10488 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 10489 SqrtOp = N1.getOperand(1); 10490 OtherOp = N1.getOperand(0); 10491 } 10492 if (SqrtOp.getNode()) { 10493 // We found a FSQRT, so try to make this fold: 10494 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 10495 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 10496 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 10497 AddToWorklist(RV.getNode()); 10498 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10499 } 10500 } 10501 } 10502 10503 // Fold into a reciprocal estimate and multiply instead of a real divide. 10504 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 10505 AddToWorklist(RV.getNode()); 10506 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10507 } 10508 } 10509 10510 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 10511 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 10512 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 10513 // Both can be negated for free, check to see if at least one is cheaper 10514 // negated. 10515 if (LHSNeg == 2 || RHSNeg == 2) 10516 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 10517 GetNegatedExpression(N0, DAG, LegalOperations), 10518 GetNegatedExpression(N1, DAG, LegalOperations), 10519 Flags); 10520 } 10521 } 10522 10523 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 10524 return CombineRepeatedDivisors; 10525 10526 return SDValue(); 10527 } 10528 10529 SDValue DAGCombiner::visitFREM(SDNode *N) { 10530 SDValue N0 = N->getOperand(0); 10531 SDValue N1 = N->getOperand(1); 10532 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10533 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10534 EVT VT = N->getValueType(0); 10535 10536 // fold (frem c1, c2) -> fmod(c1,c2) 10537 if (N0CFP && N1CFP) 10538 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags()); 10539 10540 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10541 return NewSel; 10542 10543 return SDValue(); 10544 } 10545 10546 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 10547 if (!DAG.getTarget().Options.UnsafeFPMath) 10548 return SDValue(); 10549 10550 SDValue N0 = N->getOperand(0); 10551 if (TLI.isFsqrtCheap(N0, DAG)) 10552 return SDValue(); 10553 10554 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 10555 // For now, create a Flags object for use with all unsafe math transforms. 10556 SDNodeFlags Flags; 10557 Flags.setUnsafeAlgebra(true); 10558 return buildSqrtEstimate(N0, Flags); 10559 } 10560 10561 /// copysign(x, fp_extend(y)) -> copysign(x, y) 10562 /// copysign(x, fp_round(y)) -> copysign(x, y) 10563 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 10564 SDValue N1 = N->getOperand(1); 10565 if ((N1.getOpcode() == ISD::FP_EXTEND || 10566 N1.getOpcode() == ISD::FP_ROUND)) { 10567 // Do not optimize out type conversion of f128 type yet. 10568 // For some targets like x86_64, configuration is changed to keep one f128 10569 // value in one SSE register, but instruction selection cannot handle 10570 // FCOPYSIGN on SSE registers yet. 10571 EVT N1VT = N1->getValueType(0); 10572 EVT N1Op0VT = N1->getOperand(0).getValueType(); 10573 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 10574 } 10575 return false; 10576 } 10577 10578 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 10579 SDValue N0 = N->getOperand(0); 10580 SDValue N1 = N->getOperand(1); 10581 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10582 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10583 EVT VT = N->getValueType(0); 10584 10585 if (N0CFP && N1CFP) // Constant fold 10586 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 10587 10588 if (N1CFP) { 10589 const APFloat &V = N1CFP->getValueAPF(); 10590 // copysign(x, c1) -> fabs(x) iff ispos(c1) 10591 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 10592 if (!V.isNegative()) { 10593 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 10594 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10595 } else { 10596 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 10597 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 10598 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 10599 } 10600 } 10601 10602 // copysign(fabs(x), y) -> copysign(x, y) 10603 // copysign(fneg(x), y) -> copysign(x, y) 10604 // copysign(copysign(x,z), y) -> copysign(x, y) 10605 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 10606 N0.getOpcode() == ISD::FCOPYSIGN) 10607 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1); 10608 10609 // copysign(x, abs(y)) -> abs(x) 10610 if (N1.getOpcode() == ISD::FABS) 10611 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10612 10613 // copysign(x, copysign(y,z)) -> copysign(x, z) 10614 if (N1.getOpcode() == ISD::FCOPYSIGN) 10615 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1)); 10616 10617 // copysign(x, fp_extend(y)) -> copysign(x, y) 10618 // copysign(x, fp_round(y)) -> copysign(x, y) 10619 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 10620 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0)); 10621 10622 return SDValue(); 10623 } 10624 10625 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 10626 SDValue N0 = N->getOperand(0); 10627 EVT VT = N->getValueType(0); 10628 EVT OpVT = N0.getValueType(); 10629 10630 // fold (sint_to_fp c1) -> c1fp 10631 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 10632 // ...but only if the target supports immediate floating-point values 10633 (!LegalOperations || 10634 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) 10635 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 10636 10637 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 10638 // but UINT_TO_FP is legal on this target, try to convert. 10639 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 10640 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 10641 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 10642 if (DAG.SignBitIsZero(N0)) 10643 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 10644 } 10645 10646 // The next optimizations are desirable only if SELECT_CC can be lowered. 10647 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 10648 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 10649 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 10650 !VT.isVector() && 10651 (!LegalOperations || 10652 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 10653 SDLoc DL(N); 10654 SDValue Ops[] = 10655 { N0.getOperand(0), N0.getOperand(1), 10656 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10657 N0.getOperand(2) }; 10658 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10659 } 10660 10661 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 10662 // (select_cc x, y, 1.0, 0.0,, cc) 10663 if (N0.getOpcode() == ISD::ZERO_EXTEND && 10664 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 10665 (!LegalOperations || 10666 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 10667 SDLoc DL(N); 10668 SDValue Ops[] = 10669 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 10670 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10671 N0.getOperand(0).getOperand(2) }; 10672 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10673 } 10674 } 10675 10676 return SDValue(); 10677 } 10678 10679 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 10680 SDValue N0 = N->getOperand(0); 10681 EVT VT = N->getValueType(0); 10682 EVT OpVT = N0.getValueType(); 10683 10684 // fold (uint_to_fp c1) -> c1fp 10685 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 10686 // ...but only if the target supports immediate floating-point values 10687 (!LegalOperations || 10688 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) 10689 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 10690 10691 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 10692 // but SINT_TO_FP is legal on this target, try to convert. 10693 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 10694 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 10695 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 10696 if (DAG.SignBitIsZero(N0)) 10697 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 10698 } 10699 10700 // The next optimizations are desirable only if SELECT_CC can be lowered. 10701 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 10702 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 10703 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 10704 (!LegalOperations || 10705 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 10706 SDLoc DL(N); 10707 SDValue Ops[] = 10708 { N0.getOperand(0), N0.getOperand(1), 10709 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10710 N0.getOperand(2) }; 10711 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10712 } 10713 } 10714 10715 return SDValue(); 10716 } 10717 10718 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 10719 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 10720 SDValue N0 = N->getOperand(0); 10721 EVT VT = N->getValueType(0); 10722 10723 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 10724 return SDValue(); 10725 10726 SDValue Src = N0.getOperand(0); 10727 EVT SrcVT = Src.getValueType(); 10728 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 10729 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 10730 10731 // We can safely assume the conversion won't overflow the output range, 10732 // because (for example) (uint8_t)18293.f is undefined behavior. 10733 10734 // Since we can assume the conversion won't overflow, our decision as to 10735 // whether the input will fit in the float should depend on the minimum 10736 // of the input range and output range. 10737 10738 // This means this is also safe for a signed input and unsigned output, since 10739 // a negative input would lead to undefined behavior. 10740 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 10741 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 10742 unsigned ActualSize = std::min(InputSize, OutputSize); 10743 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 10744 10745 // We can only fold away the float conversion if the input range can be 10746 // represented exactly in the float range. 10747 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 10748 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 10749 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 10750 : ISD::ZERO_EXTEND; 10751 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 10752 } 10753 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 10754 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 10755 return DAG.getBitcast(VT, Src); 10756 } 10757 return SDValue(); 10758 } 10759 10760 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 10761 SDValue N0 = N->getOperand(0); 10762 EVT VT = N->getValueType(0); 10763 10764 // fold (fp_to_sint c1fp) -> c1 10765 if (isConstantFPBuildVectorOrConstantFP(N0)) 10766 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 10767 10768 return FoldIntToFPToInt(N, DAG); 10769 } 10770 10771 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 10772 SDValue N0 = N->getOperand(0); 10773 EVT VT = N->getValueType(0); 10774 10775 // fold (fp_to_uint c1fp) -> c1 10776 if (isConstantFPBuildVectorOrConstantFP(N0)) 10777 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 10778 10779 return FoldIntToFPToInt(N, DAG); 10780 } 10781 10782 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 10783 SDValue N0 = N->getOperand(0); 10784 SDValue N1 = N->getOperand(1); 10785 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10786 EVT VT = N->getValueType(0); 10787 10788 // fold (fp_round c1fp) -> c1fp 10789 if (N0CFP) 10790 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 10791 10792 // fold (fp_round (fp_extend x)) -> x 10793 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 10794 return N0.getOperand(0); 10795 10796 // fold (fp_round (fp_round x)) -> (fp_round x) 10797 if (N0.getOpcode() == ISD::FP_ROUND) { 10798 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 10799 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1; 10800 10801 // Skip this folding if it results in an fp_round from f80 to f16. 10802 // 10803 // f80 to f16 always generates an expensive (and as yet, unimplemented) 10804 // libcall to __truncxfhf2 instead of selecting native f16 conversion 10805 // instructions from f32 or f64. Moreover, the first (value-preserving) 10806 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 10807 // x86. 10808 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 10809 return SDValue(); 10810 10811 // If the first fp_round isn't a value preserving truncation, it might 10812 // introduce a tie in the second fp_round, that wouldn't occur in the 10813 // single-step fp_round we want to fold to. 10814 // In other words, double rounding isn't the same as rounding. 10815 // Also, this is a value preserving truncation iff both fp_round's are. 10816 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 10817 SDLoc DL(N); 10818 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 10819 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 10820 } 10821 } 10822 10823 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 10824 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 10825 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 10826 N0.getOperand(0), N1); 10827 AddToWorklist(Tmp.getNode()); 10828 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 10829 Tmp, N0.getOperand(1)); 10830 } 10831 10832 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 10833 return NewVSel; 10834 10835 return SDValue(); 10836 } 10837 10838 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 10839 SDValue N0 = N->getOperand(0); 10840 EVT VT = N->getValueType(0); 10841 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 10842 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10843 10844 // fold (fp_round_inreg c1fp) -> c1fp 10845 if (N0CFP && isTypeLegal(EVT)) { 10846 SDLoc DL(N); 10847 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 10848 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 10849 } 10850 10851 return SDValue(); 10852 } 10853 10854 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 10855 SDValue N0 = N->getOperand(0); 10856 EVT VT = N->getValueType(0); 10857 10858 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 10859 if (N->hasOneUse() && 10860 N->use_begin()->getOpcode() == ISD::FP_ROUND) 10861 return SDValue(); 10862 10863 // fold (fp_extend c1fp) -> c1fp 10864 if (isConstantFPBuildVectorOrConstantFP(N0)) 10865 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 10866 10867 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 10868 if (N0.getOpcode() == ISD::FP16_TO_FP && 10869 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 10870 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 10871 10872 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 10873 // value of X. 10874 if (N0.getOpcode() == ISD::FP_ROUND 10875 && N0.getConstantOperandVal(1) == 1) { 10876 SDValue In = N0.getOperand(0); 10877 if (In.getValueType() == VT) return In; 10878 if (VT.bitsLT(In.getValueType())) 10879 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 10880 In, N0.getOperand(1)); 10881 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 10882 } 10883 10884 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 10885 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10886 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 10887 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10888 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 10889 LN0->getChain(), 10890 LN0->getBasePtr(), N0.getValueType(), 10891 LN0->getMemOperand()); 10892 CombineTo(N, ExtLoad); 10893 CombineTo(N0.getNode(), 10894 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 10895 N0.getValueType(), ExtLoad, 10896 DAG.getIntPtrConstant(1, SDLoc(N0))), 10897 ExtLoad.getValue(1)); 10898 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10899 } 10900 10901 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 10902 return NewVSel; 10903 10904 return SDValue(); 10905 } 10906 10907 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 10908 SDValue N0 = N->getOperand(0); 10909 EVT VT = N->getValueType(0); 10910 10911 // fold (fceil c1) -> fceil(c1) 10912 if (isConstantFPBuildVectorOrConstantFP(N0)) 10913 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 10914 10915 return SDValue(); 10916 } 10917 10918 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 10919 SDValue N0 = N->getOperand(0); 10920 EVT VT = N->getValueType(0); 10921 10922 // fold (ftrunc c1) -> ftrunc(c1) 10923 if (isConstantFPBuildVectorOrConstantFP(N0)) 10924 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 10925 10926 // fold ftrunc (known rounded int x) -> x 10927 // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is 10928 // likely to be generated to extract integer from a rounded floating value. 10929 switch (N0.getOpcode()) { 10930 default: break; 10931 case ISD::FRINT: 10932 case ISD::FTRUNC: 10933 case ISD::FNEARBYINT: 10934 case ISD::FFLOOR: 10935 case ISD::FCEIL: 10936 return N0; 10937 } 10938 10939 return SDValue(); 10940 } 10941 10942 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 10943 SDValue N0 = N->getOperand(0); 10944 EVT VT = N->getValueType(0); 10945 10946 // fold (ffloor c1) -> ffloor(c1) 10947 if (isConstantFPBuildVectorOrConstantFP(N0)) 10948 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 10949 10950 return SDValue(); 10951 } 10952 10953 // FIXME: FNEG and FABS have a lot in common; refactor. 10954 SDValue DAGCombiner::visitFNEG(SDNode *N) { 10955 SDValue N0 = N->getOperand(0); 10956 EVT VT = N->getValueType(0); 10957 10958 // Constant fold FNEG. 10959 if (isConstantFPBuildVectorOrConstantFP(N0)) 10960 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 10961 10962 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 10963 &DAG.getTarget().Options)) 10964 return GetNegatedExpression(N0, DAG, LegalOperations); 10965 10966 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 10967 // constant pool values. 10968 if (!TLI.isFNegFree(VT) && 10969 N0.getOpcode() == ISD::BITCAST && 10970 N0.getNode()->hasOneUse()) { 10971 SDValue Int = N0.getOperand(0); 10972 EVT IntVT = Int.getValueType(); 10973 if (IntVT.isInteger() && !IntVT.isVector()) { 10974 APInt SignMask; 10975 if (N0.getValueType().isVector()) { 10976 // For a vector, get a mask such as 0x80... per scalar element 10977 // and splat it. 10978 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits()); 10979 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 10980 } else { 10981 // For a scalar, just generate 0x80... 10982 SignMask = APInt::getSignMask(IntVT.getSizeInBits()); 10983 } 10984 SDLoc DL0(N0); 10985 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 10986 DAG.getConstant(SignMask, DL0, IntVT)); 10987 AddToWorklist(Int.getNode()); 10988 return DAG.getBitcast(VT, Int); 10989 } 10990 } 10991 10992 // (fneg (fmul c, x)) -> (fmul -c, x) 10993 if (N0.getOpcode() == ISD::FMUL && 10994 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 10995 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10996 if (CFP1) { 10997 APFloat CVal = CFP1->getValueAPF(); 10998 CVal.changeSign(); 10999 if (Level >= AfterLegalizeDAG && 11000 (TLI.isFPImmLegal(CVal, VT) || 11001 TLI.isOperationLegal(ISD::ConstantFP, VT))) 11002 return DAG.getNode( 11003 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 11004 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)), 11005 N0->getFlags()); 11006 } 11007 } 11008 11009 return SDValue(); 11010 } 11011 11012 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 11013 SDValue N0 = N->getOperand(0); 11014 SDValue N1 = N->getOperand(1); 11015 EVT VT = N->getValueType(0); 11016 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 11017 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 11018 11019 if (N0CFP && N1CFP) { 11020 const APFloat &C0 = N0CFP->getValueAPF(); 11021 const APFloat &C1 = N1CFP->getValueAPF(); 11022 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 11023 } 11024 11025 // Canonicalize to constant on RHS. 11026 if (isConstantFPBuildVectorOrConstantFP(N0) && 11027 !isConstantFPBuildVectorOrConstantFP(N1)) 11028 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 11029 11030 return SDValue(); 11031 } 11032 11033 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 11034 SDValue N0 = N->getOperand(0); 11035 SDValue N1 = N->getOperand(1); 11036 EVT VT = N->getValueType(0); 11037 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 11038 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 11039 11040 if (N0CFP && N1CFP) { 11041 const APFloat &C0 = N0CFP->getValueAPF(); 11042 const APFloat &C1 = N1CFP->getValueAPF(); 11043 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 11044 } 11045 11046 // Canonicalize to constant on RHS. 11047 if (isConstantFPBuildVectorOrConstantFP(N0) && 11048 !isConstantFPBuildVectorOrConstantFP(N1)) 11049 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 11050 11051 return SDValue(); 11052 } 11053 11054 SDValue DAGCombiner::visitFABS(SDNode *N) { 11055 SDValue N0 = N->getOperand(0); 11056 EVT VT = N->getValueType(0); 11057 11058 // fold (fabs c1) -> fabs(c1) 11059 if (isConstantFPBuildVectorOrConstantFP(N0)) 11060 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 11061 11062 // fold (fabs (fabs x)) -> (fabs x) 11063 if (N0.getOpcode() == ISD::FABS) 11064 return N->getOperand(0); 11065 11066 // fold (fabs (fneg x)) -> (fabs x) 11067 // fold (fabs (fcopysign x, y)) -> (fabs x) 11068 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 11069 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 11070 11071 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 11072 // constant pool values. 11073 if (!TLI.isFAbsFree(VT) && 11074 N0.getOpcode() == ISD::BITCAST && 11075 N0.getNode()->hasOneUse()) { 11076 SDValue Int = N0.getOperand(0); 11077 EVT IntVT = Int.getValueType(); 11078 if (IntVT.isInteger() && !IntVT.isVector()) { 11079 APInt SignMask; 11080 if (N0.getValueType().isVector()) { 11081 // For a vector, get a mask such as 0x7f... per scalar element 11082 // and splat it. 11083 SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits()); 11084 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 11085 } else { 11086 // For a scalar, just generate 0x7f... 11087 SignMask = ~APInt::getSignMask(IntVT.getSizeInBits()); 11088 } 11089 SDLoc DL(N0); 11090 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 11091 DAG.getConstant(SignMask, DL, IntVT)); 11092 AddToWorklist(Int.getNode()); 11093 return DAG.getBitcast(N->getValueType(0), Int); 11094 } 11095 } 11096 11097 return SDValue(); 11098 } 11099 11100 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 11101 SDValue Chain = N->getOperand(0); 11102 SDValue N1 = N->getOperand(1); 11103 SDValue N2 = N->getOperand(2); 11104 11105 // If N is a constant we could fold this into a fallthrough or unconditional 11106 // branch. However that doesn't happen very often in normal code, because 11107 // Instcombine/SimplifyCFG should have handled the available opportunities. 11108 // If we did this folding here, it would be necessary to update the 11109 // MachineBasicBlock CFG, which is awkward. 11110 11111 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 11112 // on the target. 11113 if (N1.getOpcode() == ISD::SETCC && 11114 TLI.isOperationLegalOrCustom(ISD::BR_CC, 11115 N1.getOperand(0).getValueType())) { 11116 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 11117 Chain, N1.getOperand(2), 11118 N1.getOperand(0), N1.getOperand(1), N2); 11119 } 11120 11121 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 11122 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 11123 (N1.getOperand(0).hasOneUse() && 11124 N1.getOperand(0).getOpcode() == ISD::SRL))) { 11125 SDNode *Trunc = nullptr; 11126 if (N1.getOpcode() == ISD::TRUNCATE) { 11127 // Look pass the truncate. 11128 Trunc = N1.getNode(); 11129 N1 = N1.getOperand(0); 11130 } 11131 11132 // Match this pattern so that we can generate simpler code: 11133 // 11134 // %a = ... 11135 // %b = and i32 %a, 2 11136 // %c = srl i32 %b, 1 11137 // brcond i32 %c ... 11138 // 11139 // into 11140 // 11141 // %a = ... 11142 // %b = and i32 %a, 2 11143 // %c = setcc eq %b, 0 11144 // brcond %c ... 11145 // 11146 // This applies only when the AND constant value has one bit set and the 11147 // SRL constant is equal to the log2 of the AND constant. The back-end is 11148 // smart enough to convert the result into a TEST/JMP sequence. 11149 SDValue Op0 = N1.getOperand(0); 11150 SDValue Op1 = N1.getOperand(1); 11151 11152 if (Op0.getOpcode() == ISD::AND && 11153 Op1.getOpcode() == ISD::Constant) { 11154 SDValue AndOp1 = Op0.getOperand(1); 11155 11156 if (AndOp1.getOpcode() == ISD::Constant) { 11157 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 11158 11159 if (AndConst.isPowerOf2() && 11160 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 11161 SDLoc DL(N); 11162 SDValue SetCC = 11163 DAG.getSetCC(DL, 11164 getSetCCResultType(Op0.getValueType()), 11165 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 11166 ISD::SETNE); 11167 11168 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 11169 MVT::Other, Chain, SetCC, N2); 11170 // Don't add the new BRCond into the worklist or else SimplifySelectCC 11171 // will convert it back to (X & C1) >> C2. 11172 CombineTo(N, NewBRCond, false); 11173 // Truncate is dead. 11174 if (Trunc) 11175 deleteAndRecombine(Trunc); 11176 // Replace the uses of SRL with SETCC 11177 WorklistRemover DeadNodes(*this); 11178 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 11179 deleteAndRecombine(N1.getNode()); 11180 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11181 } 11182 } 11183 } 11184 11185 if (Trunc) 11186 // Restore N1 if the above transformation doesn't match. 11187 N1 = N->getOperand(1); 11188 } 11189 11190 // Transform br(xor(x, y)) -> br(x != y) 11191 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 11192 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 11193 SDNode *TheXor = N1.getNode(); 11194 SDValue Op0 = TheXor->getOperand(0); 11195 SDValue Op1 = TheXor->getOperand(1); 11196 if (Op0.getOpcode() == Op1.getOpcode()) { 11197 // Avoid missing important xor optimizations. 11198 if (SDValue Tmp = visitXOR(TheXor)) { 11199 if (Tmp.getNode() != TheXor) { 11200 DEBUG(dbgs() << "\nReplacing.8 "; 11201 TheXor->dump(&DAG); 11202 dbgs() << "\nWith: "; 11203 Tmp.getNode()->dump(&DAG); 11204 dbgs() << '\n'); 11205 WorklistRemover DeadNodes(*this); 11206 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 11207 deleteAndRecombine(TheXor); 11208 return DAG.getNode(ISD::BRCOND, SDLoc(N), 11209 MVT::Other, Chain, Tmp, N2); 11210 } 11211 11212 // visitXOR has changed XOR's operands or replaced the XOR completely, 11213 // bail out. 11214 return SDValue(N, 0); 11215 } 11216 } 11217 11218 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 11219 bool Equal = false; 11220 if (isOneConstant(Op0) && Op0.hasOneUse() && 11221 Op0.getOpcode() == ISD::XOR) { 11222 TheXor = Op0.getNode(); 11223 Equal = true; 11224 } 11225 11226 EVT SetCCVT = N1.getValueType(); 11227 if (LegalTypes) 11228 SetCCVT = getSetCCResultType(SetCCVT); 11229 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 11230 SetCCVT, 11231 Op0, Op1, 11232 Equal ? ISD::SETEQ : ISD::SETNE); 11233 // Replace the uses of XOR with SETCC 11234 WorklistRemover DeadNodes(*this); 11235 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 11236 deleteAndRecombine(N1.getNode()); 11237 return DAG.getNode(ISD::BRCOND, SDLoc(N), 11238 MVT::Other, Chain, SetCC, N2); 11239 } 11240 } 11241 11242 return SDValue(); 11243 } 11244 11245 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 11246 // 11247 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 11248 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 11249 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 11250 11251 // If N is a constant we could fold this into a fallthrough or unconditional 11252 // branch. However that doesn't happen very often in normal code, because 11253 // Instcombine/SimplifyCFG should have handled the available opportunities. 11254 // If we did this folding here, it would be necessary to update the 11255 // MachineBasicBlock CFG, which is awkward. 11256 11257 // Use SimplifySetCC to simplify SETCC's. 11258 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 11259 CondLHS, CondRHS, CC->get(), SDLoc(N), 11260 false); 11261 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 11262 11263 // fold to a simpler setcc 11264 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 11265 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 11266 N->getOperand(0), Simp.getOperand(2), 11267 Simp.getOperand(0), Simp.getOperand(1), 11268 N->getOperand(4)); 11269 11270 return SDValue(); 11271 } 11272 11273 /// Return true if 'Use' is a load or a store that uses N as its base pointer 11274 /// and that N may be folded in the load / store addressing mode. 11275 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 11276 SelectionDAG &DAG, 11277 const TargetLowering &TLI) { 11278 EVT VT; 11279 unsigned AS; 11280 11281 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 11282 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 11283 return false; 11284 VT = LD->getMemoryVT(); 11285 AS = LD->getAddressSpace(); 11286 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 11287 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 11288 return false; 11289 VT = ST->getMemoryVT(); 11290 AS = ST->getAddressSpace(); 11291 } else 11292 return false; 11293 11294 TargetLowering::AddrMode AM; 11295 if (N->getOpcode() == ISD::ADD) { 11296 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11297 if (Offset) 11298 // [reg +/- imm] 11299 AM.BaseOffs = Offset->getSExtValue(); 11300 else 11301 // [reg +/- reg] 11302 AM.Scale = 1; 11303 } else if (N->getOpcode() == ISD::SUB) { 11304 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11305 if (Offset) 11306 // [reg +/- imm] 11307 AM.BaseOffs = -Offset->getSExtValue(); 11308 else 11309 // [reg +/- reg] 11310 AM.Scale = 1; 11311 } else 11312 return false; 11313 11314 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 11315 VT.getTypeForEVT(*DAG.getContext()), AS); 11316 } 11317 11318 /// Try turning a load/store into a pre-indexed load/store when the base 11319 /// pointer is an add or subtract and it has other uses besides the load/store. 11320 /// After the transformation, the new indexed load/store has effectively folded 11321 /// the add/subtract in and all of its other uses are redirected to the 11322 /// new load/store. 11323 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 11324 if (Level < AfterLegalizeDAG) 11325 return false; 11326 11327 bool isLoad = true; 11328 SDValue Ptr; 11329 EVT VT; 11330 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11331 if (LD->isIndexed()) 11332 return false; 11333 VT = LD->getMemoryVT(); 11334 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 11335 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 11336 return false; 11337 Ptr = LD->getBasePtr(); 11338 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11339 if (ST->isIndexed()) 11340 return false; 11341 VT = ST->getMemoryVT(); 11342 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 11343 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 11344 return false; 11345 Ptr = ST->getBasePtr(); 11346 isLoad = false; 11347 } else { 11348 return false; 11349 } 11350 11351 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 11352 // out. There is no reason to make this a preinc/predec. 11353 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 11354 Ptr.getNode()->hasOneUse()) 11355 return false; 11356 11357 // Ask the target to do addressing mode selection. 11358 SDValue BasePtr; 11359 SDValue Offset; 11360 ISD::MemIndexedMode AM = ISD::UNINDEXED; 11361 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 11362 return false; 11363 11364 // Backends without true r+i pre-indexed forms may need to pass a 11365 // constant base with a variable offset so that constant coercion 11366 // will work with the patterns in canonical form. 11367 bool Swapped = false; 11368 if (isa<ConstantSDNode>(BasePtr)) { 11369 std::swap(BasePtr, Offset); 11370 Swapped = true; 11371 } 11372 11373 // Don't create a indexed load / store with zero offset. 11374 if (isNullConstant(Offset)) 11375 return false; 11376 11377 // Try turning it into a pre-indexed load / store except when: 11378 // 1) The new base ptr is a frame index. 11379 // 2) If N is a store and the new base ptr is either the same as or is a 11380 // predecessor of the value being stored. 11381 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 11382 // that would create a cycle. 11383 // 4) All uses are load / store ops that use it as old base ptr. 11384 11385 // Check #1. Preinc'ing a frame index would require copying the stack pointer 11386 // (plus the implicit offset) to a register to preinc anyway. 11387 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 11388 return false; 11389 11390 // Check #2. 11391 if (!isLoad) { 11392 SDValue Val = cast<StoreSDNode>(N)->getValue(); 11393 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 11394 return false; 11395 } 11396 11397 // Caches for hasPredecessorHelper. 11398 SmallPtrSet<const SDNode *, 32> Visited; 11399 SmallVector<const SDNode *, 16> Worklist; 11400 Worklist.push_back(N); 11401 11402 // If the offset is a constant, there may be other adds of constants that 11403 // can be folded with this one. We should do this to avoid having to keep 11404 // a copy of the original base pointer. 11405 SmallVector<SDNode *, 16> OtherUses; 11406 if (isa<ConstantSDNode>(Offset)) 11407 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 11408 UE = BasePtr.getNode()->use_end(); 11409 UI != UE; ++UI) { 11410 SDUse &Use = UI.getUse(); 11411 // Skip the use that is Ptr and uses of other results from BasePtr's 11412 // node (important for nodes that return multiple results). 11413 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 11414 continue; 11415 11416 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 11417 continue; 11418 11419 if (Use.getUser()->getOpcode() != ISD::ADD && 11420 Use.getUser()->getOpcode() != ISD::SUB) { 11421 OtherUses.clear(); 11422 break; 11423 } 11424 11425 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 11426 if (!isa<ConstantSDNode>(Op1)) { 11427 OtherUses.clear(); 11428 break; 11429 } 11430 11431 // FIXME: In some cases, we can be smarter about this. 11432 if (Op1.getValueType() != Offset.getValueType()) { 11433 OtherUses.clear(); 11434 break; 11435 } 11436 11437 OtherUses.push_back(Use.getUser()); 11438 } 11439 11440 if (Swapped) 11441 std::swap(BasePtr, Offset); 11442 11443 // Now check for #3 and #4. 11444 bool RealUse = false; 11445 11446 for (SDNode *Use : Ptr.getNode()->uses()) { 11447 if (Use == N) 11448 continue; 11449 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 11450 return false; 11451 11452 // If Ptr may be folded in addressing mode of other use, then it's 11453 // not profitable to do this transformation. 11454 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 11455 RealUse = true; 11456 } 11457 11458 if (!RealUse) 11459 return false; 11460 11461 SDValue Result; 11462 if (isLoad) 11463 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 11464 BasePtr, Offset, AM); 11465 else 11466 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 11467 BasePtr, Offset, AM); 11468 ++PreIndexedNodes; 11469 ++NodesCombined; 11470 DEBUG(dbgs() << "\nReplacing.4 "; 11471 N->dump(&DAG); 11472 dbgs() << "\nWith: "; 11473 Result.getNode()->dump(&DAG); 11474 dbgs() << '\n'); 11475 WorklistRemover DeadNodes(*this); 11476 if (isLoad) { 11477 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 11478 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 11479 } else { 11480 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 11481 } 11482 11483 // Finally, since the node is now dead, remove it from the graph. 11484 deleteAndRecombine(N); 11485 11486 if (Swapped) 11487 std::swap(BasePtr, Offset); 11488 11489 // Replace other uses of BasePtr that can be updated to use Ptr 11490 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 11491 unsigned OffsetIdx = 1; 11492 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 11493 OffsetIdx = 0; 11494 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 11495 BasePtr.getNode() && "Expected BasePtr operand"); 11496 11497 // We need to replace ptr0 in the following expression: 11498 // x0 * offset0 + y0 * ptr0 = t0 11499 // knowing that 11500 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 11501 // 11502 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 11503 // indexed load/store and the expression that needs to be re-written. 11504 // 11505 // Therefore, we have: 11506 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 11507 11508 ConstantSDNode *CN = 11509 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 11510 int X0, X1, Y0, Y1; 11511 const APInt &Offset0 = CN->getAPIntValue(); 11512 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 11513 11514 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 11515 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 11516 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 11517 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 11518 11519 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 11520 11521 APInt CNV = Offset0; 11522 if (X0 < 0) CNV = -CNV; 11523 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 11524 else CNV = CNV - Offset1; 11525 11526 SDLoc DL(OtherUses[i]); 11527 11528 // We can now generate the new expression. 11529 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 11530 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 11531 11532 SDValue NewUse = DAG.getNode(Opcode, 11533 DL, 11534 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 11535 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 11536 deleteAndRecombine(OtherUses[i]); 11537 } 11538 11539 // Replace the uses of Ptr with uses of the updated base value. 11540 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 11541 deleteAndRecombine(Ptr.getNode()); 11542 AddToWorklist(Result.getNode()); 11543 11544 return true; 11545 } 11546 11547 /// Try to combine a load/store with a add/sub of the base pointer node into a 11548 /// post-indexed load/store. The transformation folded the add/subtract into the 11549 /// new indexed load/store effectively and all of its uses are redirected to the 11550 /// new load/store. 11551 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 11552 if (Level < AfterLegalizeDAG) 11553 return false; 11554 11555 bool isLoad = true; 11556 SDValue Ptr; 11557 EVT VT; 11558 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11559 if (LD->isIndexed()) 11560 return false; 11561 VT = LD->getMemoryVT(); 11562 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 11563 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 11564 return false; 11565 Ptr = LD->getBasePtr(); 11566 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11567 if (ST->isIndexed()) 11568 return false; 11569 VT = ST->getMemoryVT(); 11570 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 11571 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 11572 return false; 11573 Ptr = ST->getBasePtr(); 11574 isLoad = false; 11575 } else { 11576 return false; 11577 } 11578 11579 if (Ptr.getNode()->hasOneUse()) 11580 return false; 11581 11582 for (SDNode *Op : Ptr.getNode()->uses()) { 11583 if (Op == N || 11584 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 11585 continue; 11586 11587 SDValue BasePtr; 11588 SDValue Offset; 11589 ISD::MemIndexedMode AM = ISD::UNINDEXED; 11590 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 11591 // Don't create a indexed load / store with zero offset. 11592 if (isNullConstant(Offset)) 11593 continue; 11594 11595 // Try turning it into a post-indexed load / store except when 11596 // 1) All uses are load / store ops that use it as base ptr (and 11597 // it may be folded as addressing mmode). 11598 // 2) Op must be independent of N, i.e. Op is neither a predecessor 11599 // nor a successor of N. Otherwise, if Op is folded that would 11600 // create a cycle. 11601 11602 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 11603 continue; 11604 11605 // Check for #1. 11606 bool TryNext = false; 11607 for (SDNode *Use : BasePtr.getNode()->uses()) { 11608 if (Use == Ptr.getNode()) 11609 continue; 11610 11611 // If all the uses are load / store addresses, then don't do the 11612 // transformation. 11613 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 11614 bool RealUse = false; 11615 for (SDNode *UseUse : Use->uses()) { 11616 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 11617 RealUse = true; 11618 } 11619 11620 if (!RealUse) { 11621 TryNext = true; 11622 break; 11623 } 11624 } 11625 } 11626 11627 if (TryNext) 11628 continue; 11629 11630 // Check for #2 11631 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 11632 SDValue Result = isLoad 11633 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 11634 BasePtr, Offset, AM) 11635 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 11636 BasePtr, Offset, AM); 11637 ++PostIndexedNodes; 11638 ++NodesCombined; 11639 DEBUG(dbgs() << "\nReplacing.5 "; 11640 N->dump(&DAG); 11641 dbgs() << "\nWith: "; 11642 Result.getNode()->dump(&DAG); 11643 dbgs() << '\n'); 11644 WorklistRemover DeadNodes(*this); 11645 if (isLoad) { 11646 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 11647 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 11648 } else { 11649 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 11650 } 11651 11652 // Finally, since the node is now dead, remove it from the graph. 11653 deleteAndRecombine(N); 11654 11655 // Replace the uses of Use with uses of the updated base value. 11656 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 11657 Result.getValue(isLoad ? 1 : 0)); 11658 deleteAndRecombine(Op); 11659 return true; 11660 } 11661 } 11662 } 11663 11664 return false; 11665 } 11666 11667 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 11668 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 11669 ISD::MemIndexedMode AM = LD->getAddressingMode(); 11670 assert(AM != ISD::UNINDEXED); 11671 SDValue BP = LD->getOperand(1); 11672 SDValue Inc = LD->getOperand(2); 11673 11674 // Some backends use TargetConstants for load offsets, but don't expect 11675 // TargetConstants in general ADD nodes. We can convert these constants into 11676 // regular Constants (if the constant is not opaque). 11677 assert((Inc.getOpcode() != ISD::TargetConstant || 11678 !cast<ConstantSDNode>(Inc)->isOpaque()) && 11679 "Cannot split out indexing using opaque target constants"); 11680 if (Inc.getOpcode() == ISD::TargetConstant) { 11681 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 11682 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 11683 ConstInc->getValueType(0)); 11684 } 11685 11686 unsigned Opc = 11687 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 11688 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 11689 } 11690 11691 SDValue DAGCombiner::visitLOAD(SDNode *N) { 11692 LoadSDNode *LD = cast<LoadSDNode>(N); 11693 SDValue Chain = LD->getChain(); 11694 SDValue Ptr = LD->getBasePtr(); 11695 11696 // If load is not volatile and there are no uses of the loaded value (and 11697 // the updated indexed value in case of indexed loads), change uses of the 11698 // chain value into uses of the chain input (i.e. delete the dead load). 11699 if (!LD->isVolatile()) { 11700 if (N->getValueType(1) == MVT::Other) { 11701 // Unindexed loads. 11702 if (!N->hasAnyUseOfValue(0)) { 11703 // It's not safe to use the two value CombineTo variant here. e.g. 11704 // v1, chain2 = load chain1, loc 11705 // v2, chain3 = load chain2, loc 11706 // v3 = add v2, c 11707 // Now we replace use of chain2 with chain1. This makes the second load 11708 // isomorphic to the one we are deleting, and thus makes this load live. 11709 DEBUG(dbgs() << "\nReplacing.6 "; 11710 N->dump(&DAG); 11711 dbgs() << "\nWith chain: "; 11712 Chain.getNode()->dump(&DAG); 11713 dbgs() << "\n"); 11714 WorklistRemover DeadNodes(*this); 11715 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 11716 AddUsersToWorklist(Chain.getNode()); 11717 if (N->use_empty()) 11718 deleteAndRecombine(N); 11719 11720 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11721 } 11722 } else { 11723 // Indexed loads. 11724 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 11725 11726 // If this load has an opaque TargetConstant offset, then we cannot split 11727 // the indexing into an add/sub directly (that TargetConstant may not be 11728 // valid for a different type of node, and we cannot convert an opaque 11729 // target constant into a regular constant). 11730 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 11731 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 11732 11733 if (!N->hasAnyUseOfValue(0) && 11734 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 11735 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 11736 SDValue Index; 11737 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 11738 Index = SplitIndexingFromLoad(LD); 11739 // Try to fold the base pointer arithmetic into subsequent loads and 11740 // stores. 11741 AddUsersToWorklist(N); 11742 } else 11743 Index = DAG.getUNDEF(N->getValueType(1)); 11744 DEBUG(dbgs() << "\nReplacing.7 "; 11745 N->dump(&DAG); 11746 dbgs() << "\nWith: "; 11747 Undef.getNode()->dump(&DAG); 11748 dbgs() << " and 2 other values\n"); 11749 WorklistRemover DeadNodes(*this); 11750 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 11751 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 11752 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 11753 deleteAndRecombine(N); 11754 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11755 } 11756 } 11757 } 11758 11759 // If this load is directly stored, replace the load value with the stored 11760 // value. 11761 // TODO: Handle store large -> read small portion. 11762 // TODO: Handle TRUNCSTORE/LOADEXT 11763 if (OptLevel != CodeGenOpt::None && 11764 ISD::isNormalLoad(N) && !LD->isVolatile()) { 11765 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 11766 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 11767 if (PrevST->getBasePtr() == Ptr && 11768 PrevST->getValue().getValueType() == N->getValueType(0)) 11769 return CombineTo(N, PrevST->getOperand(1), Chain); 11770 } 11771 } 11772 11773 // Try to infer better alignment information than the load already has. 11774 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 11775 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 11776 if (Align > LD->getMemOperand()->getBaseAlignment()) { 11777 SDValue NewLoad = DAG.getExtLoad( 11778 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 11779 LD->getPointerInfo(), LD->getMemoryVT(), Align, 11780 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 11781 if (NewLoad.getNode() != N) 11782 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 11783 } 11784 } 11785 } 11786 11787 if (LD->isUnindexed()) { 11788 // Walk up chain skipping non-aliasing memory nodes. 11789 SDValue BetterChain = FindBetterChain(N, Chain); 11790 11791 // If there is a better chain. 11792 if (Chain != BetterChain) { 11793 SDValue ReplLoad; 11794 11795 // Replace the chain to void dependency. 11796 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 11797 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 11798 BetterChain, Ptr, LD->getMemOperand()); 11799 } else { 11800 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 11801 LD->getValueType(0), 11802 BetterChain, Ptr, LD->getMemoryVT(), 11803 LD->getMemOperand()); 11804 } 11805 11806 // Create token factor to keep old chain connected. 11807 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 11808 MVT::Other, Chain, ReplLoad.getValue(1)); 11809 11810 // Replace uses with load result and token factor 11811 return CombineTo(N, ReplLoad.getValue(0), Token); 11812 } 11813 } 11814 11815 // Try transforming N to an indexed load. 11816 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 11817 return SDValue(N, 0); 11818 11819 // Try to slice up N to more direct loads if the slices are mapped to 11820 // different register banks or pairing can take place. 11821 if (SliceUpLoad(N)) 11822 return SDValue(N, 0); 11823 11824 return SDValue(); 11825 } 11826 11827 namespace { 11828 11829 /// \brief Helper structure used to slice a load in smaller loads. 11830 /// Basically a slice is obtained from the following sequence: 11831 /// Origin = load Ty1, Base 11832 /// Shift = srl Ty1 Origin, CstTy Amount 11833 /// Inst = trunc Shift to Ty2 11834 /// 11835 /// Then, it will be rewritten into: 11836 /// Slice = load SliceTy, Base + SliceOffset 11837 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 11838 /// 11839 /// SliceTy is deduced from the number of bits that are actually used to 11840 /// build Inst. 11841 struct LoadedSlice { 11842 /// \brief Helper structure used to compute the cost of a slice. 11843 struct Cost { 11844 /// Are we optimizing for code size. 11845 bool ForCodeSize; 11846 11847 /// Various cost. 11848 unsigned Loads = 0; 11849 unsigned Truncates = 0; 11850 unsigned CrossRegisterBanksCopies = 0; 11851 unsigned ZExts = 0; 11852 unsigned Shift = 0; 11853 11854 Cost(bool ForCodeSize = false) : ForCodeSize(ForCodeSize) {} 11855 11856 /// \brief Get the cost of one isolated slice. 11857 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 11858 : ForCodeSize(ForCodeSize), Loads(1) { 11859 EVT TruncType = LS.Inst->getValueType(0); 11860 EVT LoadedType = LS.getLoadedType(); 11861 if (TruncType != LoadedType && 11862 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 11863 ZExts = 1; 11864 } 11865 11866 /// \brief Account for slicing gain in the current cost. 11867 /// Slicing provide a few gains like removing a shift or a 11868 /// truncate. This method allows to grow the cost of the original 11869 /// load with the gain from this slice. 11870 void addSliceGain(const LoadedSlice &LS) { 11871 // Each slice saves a truncate. 11872 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 11873 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 11874 LS.Inst->getValueType(0))) 11875 ++Truncates; 11876 // If there is a shift amount, this slice gets rid of it. 11877 if (LS.Shift) 11878 ++Shift; 11879 // If this slice can merge a cross register bank copy, account for it. 11880 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 11881 ++CrossRegisterBanksCopies; 11882 } 11883 11884 Cost &operator+=(const Cost &RHS) { 11885 Loads += RHS.Loads; 11886 Truncates += RHS.Truncates; 11887 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 11888 ZExts += RHS.ZExts; 11889 Shift += RHS.Shift; 11890 return *this; 11891 } 11892 11893 bool operator==(const Cost &RHS) const { 11894 return Loads == RHS.Loads && Truncates == RHS.Truncates && 11895 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 11896 ZExts == RHS.ZExts && Shift == RHS.Shift; 11897 } 11898 11899 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 11900 11901 bool operator<(const Cost &RHS) const { 11902 // Assume cross register banks copies are as expensive as loads. 11903 // FIXME: Do we want some more target hooks? 11904 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 11905 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 11906 // Unless we are optimizing for code size, consider the 11907 // expensive operation first. 11908 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 11909 return ExpensiveOpsLHS < ExpensiveOpsRHS; 11910 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 11911 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 11912 } 11913 11914 bool operator>(const Cost &RHS) const { return RHS < *this; } 11915 11916 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 11917 11918 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 11919 }; 11920 11921 // The last instruction that represent the slice. This should be a 11922 // truncate instruction. 11923 SDNode *Inst; 11924 11925 // The original load instruction. 11926 LoadSDNode *Origin; 11927 11928 // The right shift amount in bits from the original load. 11929 unsigned Shift; 11930 11931 // The DAG from which Origin came from. 11932 // This is used to get some contextual information about legal types, etc. 11933 SelectionDAG *DAG; 11934 11935 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 11936 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 11937 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 11938 11939 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 11940 /// \return Result is \p BitWidth and has used bits set to 1 and 11941 /// not used bits set to 0. 11942 APInt getUsedBits() const { 11943 // Reproduce the trunc(lshr) sequence: 11944 // - Start from the truncated value. 11945 // - Zero extend to the desired bit width. 11946 // - Shift left. 11947 assert(Origin && "No original load to compare against."); 11948 unsigned BitWidth = Origin->getValueSizeInBits(0); 11949 assert(Inst && "This slice is not bound to an instruction"); 11950 assert(Inst->getValueSizeInBits(0) <= BitWidth && 11951 "Extracted slice is bigger than the whole type!"); 11952 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 11953 UsedBits.setAllBits(); 11954 UsedBits = UsedBits.zext(BitWidth); 11955 UsedBits <<= Shift; 11956 return UsedBits; 11957 } 11958 11959 /// \brief Get the size of the slice to be loaded in bytes. 11960 unsigned getLoadedSize() const { 11961 unsigned SliceSize = getUsedBits().countPopulation(); 11962 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 11963 return SliceSize / 8; 11964 } 11965 11966 /// \brief Get the type that will be loaded for this slice. 11967 /// Note: This may not be the final type for the slice. 11968 EVT getLoadedType() const { 11969 assert(DAG && "Missing context"); 11970 LLVMContext &Ctxt = *DAG->getContext(); 11971 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 11972 } 11973 11974 /// \brief Get the alignment of the load used for this slice. 11975 unsigned getAlignment() const { 11976 unsigned Alignment = Origin->getAlignment(); 11977 unsigned Offset = getOffsetFromBase(); 11978 if (Offset != 0) 11979 Alignment = MinAlign(Alignment, Alignment + Offset); 11980 return Alignment; 11981 } 11982 11983 /// \brief Check if this slice can be rewritten with legal operations. 11984 bool isLegal() const { 11985 // An invalid slice is not legal. 11986 if (!Origin || !Inst || !DAG) 11987 return false; 11988 11989 // Offsets are for indexed load only, we do not handle that. 11990 if (!Origin->getOffset().isUndef()) 11991 return false; 11992 11993 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 11994 11995 // Check that the type is legal. 11996 EVT SliceType = getLoadedType(); 11997 if (!TLI.isTypeLegal(SliceType)) 11998 return false; 11999 12000 // Check that the load is legal for this type. 12001 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 12002 return false; 12003 12004 // Check that the offset can be computed. 12005 // 1. Check its type. 12006 EVT PtrType = Origin->getBasePtr().getValueType(); 12007 if (PtrType == MVT::Untyped || PtrType.isExtended()) 12008 return false; 12009 12010 // 2. Check that it fits in the immediate. 12011 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 12012 return false; 12013 12014 // 3. Check that the computation is legal. 12015 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 12016 return false; 12017 12018 // Check that the zext is legal if it needs one. 12019 EVT TruncateType = Inst->getValueType(0); 12020 if (TruncateType != SliceType && 12021 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 12022 return false; 12023 12024 return true; 12025 } 12026 12027 /// \brief Get the offset in bytes of this slice in the original chunk of 12028 /// bits. 12029 /// \pre DAG != nullptr. 12030 uint64_t getOffsetFromBase() const { 12031 assert(DAG && "Missing context."); 12032 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 12033 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 12034 uint64_t Offset = Shift / 8; 12035 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 12036 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 12037 "The size of the original loaded type is not a multiple of a" 12038 " byte."); 12039 // If Offset is bigger than TySizeInBytes, it means we are loading all 12040 // zeros. This should have been optimized before in the process. 12041 assert(TySizeInBytes > Offset && 12042 "Invalid shift amount for given loaded size"); 12043 if (IsBigEndian) 12044 Offset = TySizeInBytes - Offset - getLoadedSize(); 12045 return Offset; 12046 } 12047 12048 /// \brief Generate the sequence of instructions to load the slice 12049 /// represented by this object and redirect the uses of this slice to 12050 /// this new sequence of instructions. 12051 /// \pre this->Inst && this->Origin are valid Instructions and this 12052 /// object passed the legal check: LoadedSlice::isLegal returned true. 12053 /// \return The last instruction of the sequence used to load the slice. 12054 SDValue loadSlice() const { 12055 assert(Inst && Origin && "Unable to replace a non-existing slice."); 12056 const SDValue &OldBaseAddr = Origin->getBasePtr(); 12057 SDValue BaseAddr = OldBaseAddr; 12058 // Get the offset in that chunk of bytes w.r.t. the endianness. 12059 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 12060 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 12061 if (Offset) { 12062 // BaseAddr = BaseAddr + Offset. 12063 EVT ArithType = BaseAddr.getValueType(); 12064 SDLoc DL(Origin); 12065 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 12066 DAG->getConstant(Offset, DL, ArithType)); 12067 } 12068 12069 // Create the type of the loaded slice according to its size. 12070 EVT SliceType = getLoadedType(); 12071 12072 // Create the load for the slice. 12073 SDValue LastInst = 12074 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 12075 Origin->getPointerInfo().getWithOffset(Offset), 12076 getAlignment(), Origin->getMemOperand()->getFlags()); 12077 // If the final type is not the same as the loaded type, this means that 12078 // we have to pad with zero. Create a zero extend for that. 12079 EVT FinalType = Inst->getValueType(0); 12080 if (SliceType != FinalType) 12081 LastInst = 12082 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 12083 return LastInst; 12084 } 12085 12086 /// \brief Check if this slice can be merged with an expensive cross register 12087 /// bank copy. E.g., 12088 /// i = load i32 12089 /// f = bitcast i32 i to float 12090 bool canMergeExpensiveCrossRegisterBankCopy() const { 12091 if (!Inst || !Inst->hasOneUse()) 12092 return false; 12093 SDNode *Use = *Inst->use_begin(); 12094 if (Use->getOpcode() != ISD::BITCAST) 12095 return false; 12096 assert(DAG && "Missing context"); 12097 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 12098 EVT ResVT = Use->getValueType(0); 12099 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 12100 const TargetRegisterClass *ArgRC = 12101 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 12102 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 12103 return false; 12104 12105 // At this point, we know that we perform a cross-register-bank copy. 12106 // Check if it is expensive. 12107 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 12108 // Assume bitcasts are cheap, unless both register classes do not 12109 // explicitly share a common sub class. 12110 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 12111 return false; 12112 12113 // Check if it will be merged with the load. 12114 // 1. Check the alignment constraint. 12115 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 12116 ResVT.getTypeForEVT(*DAG->getContext())); 12117 12118 if (RequiredAlignment > getAlignment()) 12119 return false; 12120 12121 // 2. Check that the load is a legal operation for that type. 12122 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 12123 return false; 12124 12125 // 3. Check that we do not have a zext in the way. 12126 if (Inst->getValueType(0) != getLoadedType()) 12127 return false; 12128 12129 return true; 12130 } 12131 }; 12132 12133 } // end anonymous namespace 12134 12135 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 12136 /// \p UsedBits looks like 0..0 1..1 0..0. 12137 static bool areUsedBitsDense(const APInt &UsedBits) { 12138 // If all the bits are one, this is dense! 12139 if (UsedBits.isAllOnesValue()) 12140 return true; 12141 12142 // Get rid of the unused bits on the right. 12143 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 12144 // Get rid of the unused bits on the left. 12145 if (NarrowedUsedBits.countLeadingZeros()) 12146 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 12147 // Check that the chunk of bits is completely used. 12148 return NarrowedUsedBits.isAllOnesValue(); 12149 } 12150 12151 /// \brief Check whether or not \p First and \p Second are next to each other 12152 /// in memory. This means that there is no hole between the bits loaded 12153 /// by \p First and the bits loaded by \p Second. 12154 static bool areSlicesNextToEachOther(const LoadedSlice &First, 12155 const LoadedSlice &Second) { 12156 assert(First.Origin == Second.Origin && First.Origin && 12157 "Unable to match different memory origins."); 12158 APInt UsedBits = First.getUsedBits(); 12159 assert((UsedBits & Second.getUsedBits()) == 0 && 12160 "Slices are not supposed to overlap."); 12161 UsedBits |= Second.getUsedBits(); 12162 return areUsedBitsDense(UsedBits); 12163 } 12164 12165 /// \brief Adjust the \p GlobalLSCost according to the target 12166 /// paring capabilities and the layout of the slices. 12167 /// \pre \p GlobalLSCost should account for at least as many loads as 12168 /// there is in the slices in \p LoadedSlices. 12169 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 12170 LoadedSlice::Cost &GlobalLSCost) { 12171 unsigned NumberOfSlices = LoadedSlices.size(); 12172 // If there is less than 2 elements, no pairing is possible. 12173 if (NumberOfSlices < 2) 12174 return; 12175 12176 // Sort the slices so that elements that are likely to be next to each 12177 // other in memory are next to each other in the list. 12178 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 12179 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 12180 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 12181 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 12182 }); 12183 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 12184 // First (resp. Second) is the first (resp. Second) potentially candidate 12185 // to be placed in a paired load. 12186 const LoadedSlice *First = nullptr; 12187 const LoadedSlice *Second = nullptr; 12188 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 12189 // Set the beginning of the pair. 12190 First = Second) { 12191 Second = &LoadedSlices[CurrSlice]; 12192 12193 // If First is NULL, it means we start a new pair. 12194 // Get to the next slice. 12195 if (!First) 12196 continue; 12197 12198 EVT LoadedType = First->getLoadedType(); 12199 12200 // If the types of the slices are different, we cannot pair them. 12201 if (LoadedType != Second->getLoadedType()) 12202 continue; 12203 12204 // Check if the target supplies paired loads for this type. 12205 unsigned RequiredAlignment = 0; 12206 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 12207 // move to the next pair, this type is hopeless. 12208 Second = nullptr; 12209 continue; 12210 } 12211 // Check if we meet the alignment requirement. 12212 if (RequiredAlignment > First->getAlignment()) 12213 continue; 12214 12215 // Check that both loads are next to each other in memory. 12216 if (!areSlicesNextToEachOther(*First, *Second)) 12217 continue; 12218 12219 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 12220 --GlobalLSCost.Loads; 12221 // Move to the next pair. 12222 Second = nullptr; 12223 } 12224 } 12225 12226 /// \brief Check the profitability of all involved LoadedSlice. 12227 /// Currently, it is considered profitable if there is exactly two 12228 /// involved slices (1) which are (2) next to each other in memory, and 12229 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 12230 /// 12231 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 12232 /// the elements themselves. 12233 /// 12234 /// FIXME: When the cost model will be mature enough, we can relax 12235 /// constraints (1) and (2). 12236 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 12237 const APInt &UsedBits, bool ForCodeSize) { 12238 unsigned NumberOfSlices = LoadedSlices.size(); 12239 if (StressLoadSlicing) 12240 return NumberOfSlices > 1; 12241 12242 // Check (1). 12243 if (NumberOfSlices != 2) 12244 return false; 12245 12246 // Check (2). 12247 if (!areUsedBitsDense(UsedBits)) 12248 return false; 12249 12250 // Check (3). 12251 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 12252 // The original code has one big load. 12253 OrigCost.Loads = 1; 12254 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 12255 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 12256 // Accumulate the cost of all the slices. 12257 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 12258 GlobalSlicingCost += SliceCost; 12259 12260 // Account as cost in the original configuration the gain obtained 12261 // with the current slices. 12262 OrigCost.addSliceGain(LS); 12263 } 12264 12265 // If the target supports paired load, adjust the cost accordingly. 12266 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 12267 return OrigCost > GlobalSlicingCost; 12268 } 12269 12270 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 12271 /// operations, split it in the various pieces being extracted. 12272 /// 12273 /// This sort of thing is introduced by SROA. 12274 /// This slicing takes care not to insert overlapping loads. 12275 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 12276 bool DAGCombiner::SliceUpLoad(SDNode *N) { 12277 if (Level < AfterLegalizeDAG) 12278 return false; 12279 12280 LoadSDNode *LD = cast<LoadSDNode>(N); 12281 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 12282 !LD->getValueType(0).isInteger()) 12283 return false; 12284 12285 // Keep track of already used bits to detect overlapping values. 12286 // In that case, we will just abort the transformation. 12287 APInt UsedBits(LD->getValueSizeInBits(0), 0); 12288 12289 SmallVector<LoadedSlice, 4> LoadedSlices; 12290 12291 // Check if this load is used as several smaller chunks of bits. 12292 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 12293 // of computation for each trunc. 12294 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 12295 UI != UIEnd; ++UI) { 12296 // Skip the uses of the chain. 12297 if (UI.getUse().getResNo() != 0) 12298 continue; 12299 12300 SDNode *User = *UI; 12301 unsigned Shift = 0; 12302 12303 // Check if this is a trunc(lshr). 12304 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 12305 isa<ConstantSDNode>(User->getOperand(1))) { 12306 Shift = User->getConstantOperandVal(1); 12307 User = *User->use_begin(); 12308 } 12309 12310 // At this point, User is a Truncate, iff we encountered, trunc or 12311 // trunc(lshr). 12312 if (User->getOpcode() != ISD::TRUNCATE) 12313 return false; 12314 12315 // The width of the type must be a power of 2 and greater than 8-bits. 12316 // Otherwise the load cannot be represented in LLVM IR. 12317 // Moreover, if we shifted with a non-8-bits multiple, the slice 12318 // will be across several bytes. We do not support that. 12319 unsigned Width = User->getValueSizeInBits(0); 12320 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 12321 return false; 12322 12323 // Build the slice for this chain of computations. 12324 LoadedSlice LS(User, LD, Shift, &DAG); 12325 APInt CurrentUsedBits = LS.getUsedBits(); 12326 12327 // Check if this slice overlaps with another. 12328 if ((CurrentUsedBits & UsedBits) != 0) 12329 return false; 12330 // Update the bits used globally. 12331 UsedBits |= CurrentUsedBits; 12332 12333 // Check if the new slice would be legal. 12334 if (!LS.isLegal()) 12335 return false; 12336 12337 // Record the slice. 12338 LoadedSlices.push_back(LS); 12339 } 12340 12341 // Abort slicing if it does not seem to be profitable. 12342 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 12343 return false; 12344 12345 ++SlicedLoads; 12346 12347 // Rewrite each chain to use an independent load. 12348 // By construction, each chain can be represented by a unique load. 12349 12350 // Prepare the argument for the new token factor for all the slices. 12351 SmallVector<SDValue, 8> ArgChains; 12352 for (SmallVectorImpl<LoadedSlice>::const_iterator 12353 LSIt = LoadedSlices.begin(), 12354 LSItEnd = LoadedSlices.end(); 12355 LSIt != LSItEnd; ++LSIt) { 12356 SDValue SliceInst = LSIt->loadSlice(); 12357 CombineTo(LSIt->Inst, SliceInst, true); 12358 if (SliceInst.getOpcode() != ISD::LOAD) 12359 SliceInst = SliceInst.getOperand(0); 12360 assert(SliceInst->getOpcode() == ISD::LOAD && 12361 "It takes more than a zext to get to the loaded slice!!"); 12362 ArgChains.push_back(SliceInst.getValue(1)); 12363 } 12364 12365 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 12366 ArgChains); 12367 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 12368 AddToWorklist(Chain.getNode()); 12369 return true; 12370 } 12371 12372 /// Check to see if V is (and load (ptr), imm), where the load is having 12373 /// specific bytes cleared out. If so, return the byte size being masked out 12374 /// and the shift amount. 12375 static std::pair<unsigned, unsigned> 12376 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 12377 std::pair<unsigned, unsigned> Result(0, 0); 12378 12379 // Check for the structure we're looking for. 12380 if (V->getOpcode() != ISD::AND || 12381 !isa<ConstantSDNode>(V->getOperand(1)) || 12382 !ISD::isNormalLoad(V->getOperand(0).getNode())) 12383 return Result; 12384 12385 // Check the chain and pointer. 12386 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 12387 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 12388 12389 // The store should be chained directly to the load or be an operand of a 12390 // tokenfactor. 12391 if (LD == Chain.getNode()) 12392 ; // ok. 12393 else if (Chain->getOpcode() != ISD::TokenFactor) 12394 return Result; // Fail. 12395 else { 12396 bool isOk = false; 12397 for (const SDValue &ChainOp : Chain->op_values()) 12398 if (ChainOp.getNode() == LD) { 12399 isOk = true; 12400 break; 12401 } 12402 if (!isOk) return Result; 12403 } 12404 12405 // This only handles simple types. 12406 if (V.getValueType() != MVT::i16 && 12407 V.getValueType() != MVT::i32 && 12408 V.getValueType() != MVT::i64) 12409 return Result; 12410 12411 // Check the constant mask. Invert it so that the bits being masked out are 12412 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 12413 // follow the sign bit for uniformity. 12414 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 12415 unsigned NotMaskLZ = countLeadingZeros(NotMask); 12416 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 12417 unsigned NotMaskTZ = countTrailingZeros(NotMask); 12418 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 12419 if (NotMaskLZ == 64) return Result; // All zero mask. 12420 12421 // See if we have a continuous run of bits. If so, we have 0*1+0* 12422 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 12423 return Result; 12424 12425 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 12426 if (V.getValueType() != MVT::i64 && NotMaskLZ) 12427 NotMaskLZ -= 64-V.getValueSizeInBits(); 12428 12429 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 12430 switch (MaskedBytes) { 12431 case 1: 12432 case 2: 12433 case 4: break; 12434 default: return Result; // All one mask, or 5-byte mask. 12435 } 12436 12437 // Verify that the first bit starts at a multiple of mask so that the access 12438 // is aligned the same as the access width. 12439 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 12440 12441 Result.first = MaskedBytes; 12442 Result.second = NotMaskTZ/8; 12443 return Result; 12444 } 12445 12446 /// Check to see if IVal is something that provides a value as specified by 12447 /// MaskInfo. If so, replace the specified store with a narrower store of 12448 /// truncated IVal. 12449 static SDNode * 12450 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 12451 SDValue IVal, StoreSDNode *St, 12452 DAGCombiner *DC) { 12453 unsigned NumBytes = MaskInfo.first; 12454 unsigned ByteShift = MaskInfo.second; 12455 SelectionDAG &DAG = DC->getDAG(); 12456 12457 // Check to see if IVal is all zeros in the part being masked in by the 'or' 12458 // that uses this. If not, this is not a replacement. 12459 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 12460 ByteShift*8, (ByteShift+NumBytes)*8); 12461 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 12462 12463 // Check that it is legal on the target to do this. It is legal if the new 12464 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 12465 // legalization. 12466 MVT VT = MVT::getIntegerVT(NumBytes*8); 12467 if (!DC->isTypeLegal(VT)) 12468 return nullptr; 12469 12470 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 12471 // shifted by ByteShift and truncated down to NumBytes. 12472 if (ByteShift) { 12473 SDLoc DL(IVal); 12474 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 12475 DAG.getConstant(ByteShift*8, DL, 12476 DC->getShiftAmountTy(IVal.getValueType()))); 12477 } 12478 12479 // Figure out the offset for the store and the alignment of the access. 12480 unsigned StOffset; 12481 unsigned NewAlign = St->getAlignment(); 12482 12483 if (DAG.getDataLayout().isLittleEndian()) 12484 StOffset = ByteShift; 12485 else 12486 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 12487 12488 SDValue Ptr = St->getBasePtr(); 12489 if (StOffset) { 12490 SDLoc DL(IVal); 12491 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 12492 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 12493 NewAlign = MinAlign(NewAlign, StOffset); 12494 } 12495 12496 // Truncate down to the new size. 12497 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 12498 12499 ++OpsNarrowed; 12500 return DAG 12501 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 12502 St->getPointerInfo().getWithOffset(StOffset), NewAlign) 12503 .getNode(); 12504 } 12505 12506 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 12507 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 12508 /// narrowing the load and store if it would end up being a win for performance 12509 /// or code size. 12510 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 12511 StoreSDNode *ST = cast<StoreSDNode>(N); 12512 if (ST->isVolatile()) 12513 return SDValue(); 12514 12515 SDValue Chain = ST->getChain(); 12516 SDValue Value = ST->getValue(); 12517 SDValue Ptr = ST->getBasePtr(); 12518 EVT VT = Value.getValueType(); 12519 12520 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 12521 return SDValue(); 12522 12523 unsigned Opc = Value.getOpcode(); 12524 12525 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 12526 // is a byte mask indicating a consecutive number of bytes, check to see if 12527 // Y is known to provide just those bytes. If so, we try to replace the 12528 // load + replace + store sequence with a single (narrower) store, which makes 12529 // the load dead. 12530 if (Opc == ISD::OR) { 12531 std::pair<unsigned, unsigned> MaskedLoad; 12532 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 12533 if (MaskedLoad.first) 12534 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 12535 Value.getOperand(1), ST,this)) 12536 return SDValue(NewST, 0); 12537 12538 // Or is commutative, so try swapping X and Y. 12539 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 12540 if (MaskedLoad.first) 12541 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 12542 Value.getOperand(0), ST,this)) 12543 return SDValue(NewST, 0); 12544 } 12545 12546 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 12547 Value.getOperand(1).getOpcode() != ISD::Constant) 12548 return SDValue(); 12549 12550 SDValue N0 = Value.getOperand(0); 12551 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 12552 Chain == SDValue(N0.getNode(), 1)) { 12553 LoadSDNode *LD = cast<LoadSDNode>(N0); 12554 if (LD->getBasePtr() != Ptr || 12555 LD->getPointerInfo().getAddrSpace() != 12556 ST->getPointerInfo().getAddrSpace()) 12557 return SDValue(); 12558 12559 // Find the type to narrow it the load / op / store to. 12560 SDValue N1 = Value.getOperand(1); 12561 unsigned BitWidth = N1.getValueSizeInBits(); 12562 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 12563 if (Opc == ISD::AND) 12564 Imm ^= APInt::getAllOnesValue(BitWidth); 12565 if (Imm == 0 || Imm.isAllOnesValue()) 12566 return SDValue(); 12567 unsigned ShAmt = Imm.countTrailingZeros(); 12568 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 12569 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 12570 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 12571 // The narrowing should be profitable, the load/store operation should be 12572 // legal (or custom) and the store size should be equal to the NewVT width. 12573 while (NewBW < BitWidth && 12574 (NewVT.getStoreSizeInBits() != NewBW || 12575 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 12576 !TLI.isNarrowingProfitable(VT, NewVT))) { 12577 NewBW = NextPowerOf2(NewBW); 12578 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 12579 } 12580 if (NewBW >= BitWidth) 12581 return SDValue(); 12582 12583 // If the lsb changed does not start at the type bitwidth boundary, 12584 // start at the previous one. 12585 if (ShAmt % NewBW) 12586 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 12587 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 12588 std::min(BitWidth, ShAmt + NewBW)); 12589 if ((Imm & Mask) == Imm) { 12590 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 12591 if (Opc == ISD::AND) 12592 NewImm ^= APInt::getAllOnesValue(NewBW); 12593 uint64_t PtrOff = ShAmt / 8; 12594 // For big endian targets, we need to adjust the offset to the pointer to 12595 // load the correct bytes. 12596 if (DAG.getDataLayout().isBigEndian()) 12597 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 12598 12599 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 12600 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 12601 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 12602 return SDValue(); 12603 12604 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 12605 Ptr.getValueType(), Ptr, 12606 DAG.getConstant(PtrOff, SDLoc(LD), 12607 Ptr.getValueType())); 12608 SDValue NewLD = 12609 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 12610 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 12611 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 12612 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 12613 DAG.getConstant(NewImm, SDLoc(Value), 12614 NewVT)); 12615 SDValue NewST = 12616 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 12617 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 12618 12619 AddToWorklist(NewPtr.getNode()); 12620 AddToWorklist(NewLD.getNode()); 12621 AddToWorklist(NewVal.getNode()); 12622 WorklistRemover DeadNodes(*this); 12623 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 12624 ++OpsNarrowed; 12625 return NewST; 12626 } 12627 } 12628 12629 return SDValue(); 12630 } 12631 12632 /// For a given floating point load / store pair, if the load value isn't used 12633 /// by any other operations, then consider transforming the pair to integer 12634 /// load / store operations if the target deems the transformation profitable. 12635 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 12636 StoreSDNode *ST = cast<StoreSDNode>(N); 12637 SDValue Chain = ST->getChain(); 12638 SDValue Value = ST->getValue(); 12639 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 12640 Value.hasOneUse() && 12641 Chain == SDValue(Value.getNode(), 1)) { 12642 LoadSDNode *LD = cast<LoadSDNode>(Value); 12643 EVT VT = LD->getMemoryVT(); 12644 if (!VT.isFloatingPoint() || 12645 VT != ST->getMemoryVT() || 12646 LD->isNonTemporal() || 12647 ST->isNonTemporal() || 12648 LD->getPointerInfo().getAddrSpace() != 0 || 12649 ST->getPointerInfo().getAddrSpace() != 0) 12650 return SDValue(); 12651 12652 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 12653 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 12654 !TLI.isOperationLegal(ISD::STORE, IntVT) || 12655 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 12656 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 12657 return SDValue(); 12658 12659 unsigned LDAlign = LD->getAlignment(); 12660 unsigned STAlign = ST->getAlignment(); 12661 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 12662 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 12663 if (LDAlign < ABIAlign || STAlign < ABIAlign) 12664 return SDValue(); 12665 12666 SDValue NewLD = 12667 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 12668 LD->getPointerInfo(), LDAlign); 12669 12670 SDValue NewST = 12671 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(), 12672 ST->getPointerInfo(), STAlign); 12673 12674 AddToWorklist(NewLD.getNode()); 12675 AddToWorklist(NewST.getNode()); 12676 WorklistRemover DeadNodes(*this); 12677 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 12678 ++LdStFP2Int; 12679 return NewST; 12680 } 12681 12682 return SDValue(); 12683 } 12684 12685 // This is a helper function for visitMUL to check the profitability 12686 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 12687 // MulNode is the original multiply, AddNode is (add x, c1), 12688 // and ConstNode is c2. 12689 // 12690 // If the (add x, c1) has multiple uses, we could increase 12691 // the number of adds if we make this transformation. 12692 // It would only be worth doing this if we can remove a 12693 // multiply in the process. Check for that here. 12694 // To illustrate: 12695 // (A + c1) * c3 12696 // (A + c2) * c3 12697 // We're checking for cases where we have common "c3 * A" expressions. 12698 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 12699 SDValue &AddNode, 12700 SDValue &ConstNode) { 12701 APInt Val; 12702 12703 // If the add only has one use, this would be OK to do. 12704 if (AddNode.getNode()->hasOneUse()) 12705 return true; 12706 12707 // Walk all the users of the constant with which we're multiplying. 12708 for (SDNode *Use : ConstNode->uses()) { 12709 if (Use == MulNode) // This use is the one we're on right now. Skip it. 12710 continue; 12711 12712 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 12713 SDNode *OtherOp; 12714 SDNode *MulVar = AddNode.getOperand(0).getNode(); 12715 12716 // OtherOp is what we're multiplying against the constant. 12717 if (Use->getOperand(0) == ConstNode) 12718 OtherOp = Use->getOperand(1).getNode(); 12719 else 12720 OtherOp = Use->getOperand(0).getNode(); 12721 12722 // Check to see if multiply is with the same operand of our "add". 12723 // 12724 // ConstNode = CONST 12725 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 12726 // ... 12727 // AddNode = (A + c1) <-- MulVar is A. 12728 // = AddNode * ConstNode <-- current visiting instruction. 12729 // 12730 // If we make this transformation, we will have a common 12731 // multiply (ConstNode * A) that we can save. 12732 if (OtherOp == MulVar) 12733 return true; 12734 12735 // Now check to see if a future expansion will give us a common 12736 // multiply. 12737 // 12738 // ConstNode = CONST 12739 // AddNode = (A + c1) 12740 // ... = AddNode * ConstNode <-- current visiting instruction. 12741 // ... 12742 // OtherOp = (A + c2) 12743 // Use = OtherOp * ConstNode <-- visiting Use. 12744 // 12745 // If we make this transformation, we will have a common 12746 // multiply (CONST * A) after we also do the same transformation 12747 // to the "t2" instruction. 12748 if (OtherOp->getOpcode() == ISD::ADD && 12749 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 12750 OtherOp->getOperand(0).getNode() == MulVar) 12751 return true; 12752 } 12753 } 12754 12755 // Didn't find a case where this would be profitable. 12756 return false; 12757 } 12758 12759 static SDValue peekThroughBitcast(SDValue V) { 12760 while (V.getOpcode() == ISD::BITCAST) 12761 V = V.getOperand(0); 12762 return V; 12763 } 12764 12765 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 12766 unsigned NumStores) { 12767 SmallVector<SDValue, 8> Chains; 12768 SmallPtrSet<const SDNode *, 8> Visited; 12769 SDLoc StoreDL(StoreNodes[0].MemNode); 12770 12771 for (unsigned i = 0; i < NumStores; ++i) { 12772 Visited.insert(StoreNodes[i].MemNode); 12773 } 12774 12775 // don't include nodes that are children 12776 for (unsigned i = 0; i < NumStores; ++i) { 12777 if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0) 12778 Chains.push_back(StoreNodes[i].MemNode->getChain()); 12779 } 12780 12781 assert(Chains.size() > 0 && "Chain should have generated a chain"); 12782 return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains); 12783 } 12784 12785 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 12786 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores, 12787 bool IsConstantSrc, bool UseVector, bool UseTrunc) { 12788 // Make sure we have something to merge. 12789 if (NumStores < 2) 12790 return false; 12791 12792 // The latest Node in the DAG. 12793 SDLoc DL(StoreNodes[0].MemNode); 12794 12795 int64_t ElementSizeBits = MemVT.getStoreSizeInBits(); 12796 unsigned SizeInBits = NumStores * ElementSizeBits; 12797 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 12798 12799 EVT StoreTy; 12800 if (UseVector) { 12801 unsigned Elts = NumStores * NumMemElts; 12802 // Get the type for the merged vector store. 12803 StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 12804 } else 12805 StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 12806 12807 SDValue StoredVal; 12808 if (UseVector) { 12809 if (IsConstantSrc) { 12810 SmallVector<SDValue, 8> BuildVector; 12811 for (unsigned I = 0; I != NumStores; ++I) { 12812 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode); 12813 SDValue Val = St->getValue(); 12814 // If constant is of the wrong type, convert it now. 12815 if (MemVT != Val.getValueType()) { 12816 Val = peekThroughBitcast(Val); 12817 // Deal with constants of wrong size. 12818 if (ElementSizeBits != Val.getValueSizeInBits()) { 12819 EVT IntMemVT = 12820 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 12821 if (isa<ConstantFPSDNode>(Val)) { 12822 // Not clear how to truncate FP values. 12823 return false; 12824 } else if (auto *C = dyn_cast<ConstantSDNode>(Val)) 12825 Val = DAG.getConstant(C->getAPIntValue() 12826 .zextOrTrunc(Val.getValueSizeInBits()) 12827 .zextOrTrunc(ElementSizeBits), 12828 SDLoc(C), IntMemVT); 12829 } 12830 // Make sure correctly size type is the correct type. 12831 Val = DAG.getBitcast(MemVT, Val); 12832 } 12833 BuildVector.push_back(Val); 12834 } 12835 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS 12836 : ISD::BUILD_VECTOR, 12837 DL, StoreTy, BuildVector); 12838 } else { 12839 SmallVector<SDValue, 8> Ops; 12840 for (unsigned i = 0; i < NumStores; ++i) { 12841 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12842 SDValue Val = peekThroughBitcast(St->getValue()); 12843 // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of 12844 // type MemVT. If the underlying value is not the correct 12845 // type, but it is an extraction of an appropriate vector we 12846 // can recast Val to be of the correct type. This may require 12847 // converting between EXTRACT_VECTOR_ELT and 12848 // EXTRACT_SUBVECTOR. 12849 if ((MemVT != Val.getValueType()) && 12850 (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12851 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) { 12852 SDValue Vec = Val.getOperand(0); 12853 EVT MemVTScalarTy = MemVT.getScalarType(); 12854 // We may need to add a bitcast here to get types to line up. 12855 if (MemVTScalarTy != Vec.getValueType()) { 12856 unsigned Elts = Vec.getValueType().getSizeInBits() / 12857 MemVTScalarTy.getSizeInBits(); 12858 EVT NewVecTy = 12859 EVT::getVectorVT(*DAG.getContext(), MemVTScalarTy, Elts); 12860 Vec = DAG.getBitcast(NewVecTy, Vec); 12861 } 12862 auto OpC = (MemVT.isVector()) ? ISD::EXTRACT_SUBVECTOR 12863 : ISD::EXTRACT_VECTOR_ELT; 12864 Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Val.getOperand(1)); 12865 } 12866 Ops.push_back(Val); 12867 } 12868 12869 // Build the extracted vector elements back into a vector. 12870 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS 12871 : ISD::BUILD_VECTOR, 12872 DL, StoreTy, Ops); 12873 } 12874 } else { 12875 // We should always use a vector store when merging extracted vector 12876 // elements, so this path implies a store of constants. 12877 assert(IsConstantSrc && "Merged vector elements should use vector store"); 12878 12879 APInt StoreInt(SizeInBits, 0); 12880 12881 // Construct a single integer constant which is made of the smaller 12882 // constant inputs. 12883 bool IsLE = DAG.getDataLayout().isLittleEndian(); 12884 for (unsigned i = 0; i < NumStores; ++i) { 12885 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 12886 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 12887 12888 SDValue Val = St->getValue(); 12889 StoreInt <<= ElementSizeBits; 12890 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 12891 StoreInt |= C->getAPIntValue() 12892 .zextOrTrunc(ElementSizeBits) 12893 .zextOrTrunc(SizeInBits); 12894 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 12895 StoreInt |= C->getValueAPF() 12896 .bitcastToAPInt() 12897 .zextOrTrunc(ElementSizeBits) 12898 .zextOrTrunc(SizeInBits); 12899 // If fp truncation is necessary give up for now. 12900 if (MemVT.getSizeInBits() != ElementSizeBits) 12901 return false; 12902 } else { 12903 llvm_unreachable("Invalid constant element type"); 12904 } 12905 } 12906 12907 // Create the new Load and Store operations. 12908 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 12909 } 12910 12911 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12912 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores); 12913 12914 // make sure we use trunc store if it's necessary to be legal. 12915 SDValue NewStore; 12916 if (!UseTrunc) { 12917 NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(), 12918 FirstInChain->getPointerInfo(), 12919 FirstInChain->getAlignment()); 12920 } else { // Must be realized as a trunc store 12921 EVT LegalizedStoredValueTy = 12922 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 12923 unsigned LegalizedStoreSize = LegalizedStoredValueTy.getSizeInBits(); 12924 ConstantSDNode *C = cast<ConstantSDNode>(StoredVal); 12925 SDValue ExtendedStoreVal = 12926 DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL, 12927 LegalizedStoredValueTy); 12928 NewStore = DAG.getTruncStore( 12929 NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(), 12930 FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/, 12931 FirstInChain->getAlignment(), 12932 FirstInChain->getMemOperand()->getFlags()); 12933 } 12934 12935 // Replace all merged stores with the new store. 12936 for (unsigned i = 0; i < NumStores; ++i) 12937 CombineTo(StoreNodes[i].MemNode, NewStore); 12938 12939 AddToWorklist(NewChain.getNode()); 12940 return true; 12941 } 12942 12943 void DAGCombiner::getStoreMergeCandidates( 12944 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) { 12945 // This holds the base pointer, index, and the offset in bytes from the base 12946 // pointer. 12947 BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); 12948 EVT MemVT = St->getMemoryVT(); 12949 12950 SDValue Val = peekThroughBitcast(St->getValue()); 12951 // We must have a base and an offset. 12952 if (!BasePtr.getBase().getNode()) 12953 return; 12954 12955 // Do not handle stores to undef base pointers. 12956 if (BasePtr.getBase().isUndef()) 12957 return; 12958 12959 bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val); 12960 bool IsExtractVecSrc = (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12961 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR); 12962 bool IsLoadSrc = isa<LoadSDNode>(Val); 12963 BaseIndexOffset LBasePtr; 12964 // Match on loadbaseptr if relevant. 12965 EVT LoadVT; 12966 if (IsLoadSrc) { 12967 auto *Ld = cast<LoadSDNode>(Val); 12968 LBasePtr = BaseIndexOffset::match(Ld, DAG); 12969 LoadVT = Ld->getMemoryVT(); 12970 // Load and store should be the same type. 12971 if (MemVT != LoadVT) 12972 return; 12973 } 12974 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr, 12975 int64_t &Offset) -> bool { 12976 if (Other->isVolatile() || Other->isIndexed()) 12977 return false; 12978 SDValue Val = peekThroughBitcast(Other->getValue()); 12979 // Allow merging constants of different types as integers. 12980 bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT()) 12981 : Other->getMemoryVT() != MemVT; 12982 if (IsLoadSrc) { 12983 if (NoTypeMatch) 12984 return false; 12985 // The Load's Base Ptr must also match 12986 if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Val)) { 12987 auto LPtr = BaseIndexOffset::match(OtherLd, DAG); 12988 if (LoadVT != OtherLd->getMemoryVT()) 12989 return false; 12990 if (!(LBasePtr.equalBaseIndex(LPtr, DAG))) 12991 return false; 12992 } else 12993 return false; 12994 } 12995 if (IsConstantSrc) { 12996 if (NoTypeMatch) 12997 return false; 12998 if (!(isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val))) 12999 return false; 13000 } 13001 if (IsExtractVecSrc) { 13002 // Do not merge truncated stores here. 13003 if (Other->isTruncatingStore()) 13004 return false; 13005 if (!MemVT.bitsEq(Val.getValueType())) 13006 return false; 13007 if (Val.getOpcode() != ISD::EXTRACT_VECTOR_ELT && 13008 Val.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13009 return false; 13010 } 13011 Ptr = BaseIndexOffset::match(Other, DAG); 13012 return (BasePtr.equalBaseIndex(Ptr, DAG, Offset)); 13013 }; 13014 13015 // We looking for a root node which is an ancestor to all mergable 13016 // stores. We search up through a load, to our root and then down 13017 // through all children. For instance we will find Store{1,2,3} if 13018 // St is Store1, Store2. or Store3 where the root is not a load 13019 // which always true for nonvolatile ops. TODO: Expand 13020 // the search to find all valid candidates through multiple layers of loads. 13021 // 13022 // Root 13023 // |-------|-------| 13024 // Load Load Store3 13025 // | | 13026 // Store1 Store2 13027 // 13028 // FIXME: We should be able to climb and 13029 // descend TokenFactors to find candidates as well. 13030 13031 SDNode *RootNode = (St->getChain()).getNode(); 13032 13033 if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) { 13034 RootNode = Ldn->getChain().getNode(); 13035 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 13036 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain 13037 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2) 13038 if (I2.getOperandNo() == 0) 13039 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) { 13040 BaseIndexOffset Ptr; 13041 int64_t PtrDiff; 13042 if (CandidateMatch(OtherST, Ptr, PtrDiff)) 13043 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff)); 13044 } 13045 } else 13046 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 13047 if (I.getOperandNo() == 0) 13048 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 13049 BaseIndexOffset Ptr; 13050 int64_t PtrDiff; 13051 if (CandidateMatch(OtherST, Ptr, PtrDiff)) 13052 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff)); 13053 } 13054 } 13055 13056 // We need to check that merging these stores does not cause a loop in 13057 // the DAG. Any store candidate may depend on another candidate 13058 // indirectly through its operand (we already consider dependencies 13059 // through the chain). Check in parallel by searching up from 13060 // non-chain operands of candidates. 13061 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 13062 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) { 13063 // FIXME: We should be able to truncate a full search of 13064 // predecessors by doing a BFS and keeping tabs the originating 13065 // stores from which worklist nodes come from in a similar way to 13066 // TokenFactor simplfication. 13067 13068 SmallPtrSet<const SDNode *, 16> Visited; 13069 SmallVector<const SDNode *, 8> Worklist; 13070 unsigned int Max = 8192; 13071 // Search Ops of store candidates. 13072 for (unsigned i = 0; i < NumStores; ++i) { 13073 SDNode *n = StoreNodes[i].MemNode; 13074 // Potential loops may happen only through non-chain operands 13075 for (unsigned j = 1; j < n->getNumOperands(); ++j) 13076 Worklist.push_back(n->getOperand(j).getNode()); 13077 } 13078 // Search through DAG. We can stop early if we find a store node. 13079 for (unsigned i = 0; i < NumStores; ++i) { 13080 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist, 13081 Max)) 13082 return false; 13083 // Check if we ended early, failing conservatively if so. 13084 if (Visited.size() >= Max) 13085 return false; 13086 } 13087 return true; 13088 } 13089 13090 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) { 13091 if (OptLevel == CodeGenOpt::None) 13092 return false; 13093 13094 EVT MemVT = St->getMemoryVT(); 13095 int64_t ElementSizeBytes = MemVT.getStoreSize(); 13096 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 13097 13098 if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits) 13099 return false; 13100 13101 bool NoVectors = DAG.getMachineFunction().getFunction().hasFnAttribute( 13102 Attribute::NoImplicitFloat); 13103 13104 // This function cannot currently deal with non-byte-sized memory sizes. 13105 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 13106 return false; 13107 13108 if (!MemVT.isSimple()) 13109 return false; 13110 13111 // Perform an early exit check. Do not bother looking at stored values that 13112 // are not constants, loads, or extracted vector elements. 13113 SDValue StoredVal = peekThroughBitcast(St->getValue()); 13114 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 13115 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 13116 isa<ConstantFPSDNode>(StoredVal); 13117 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 13118 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 13119 13120 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 13121 return false; 13122 13123 SmallVector<MemOpLink, 8> StoreNodes; 13124 // Find potential store merge candidates by searching through chain sub-DAG 13125 getStoreMergeCandidates(St, StoreNodes); 13126 13127 // Check if there is anything to merge. 13128 if (StoreNodes.size() < 2) 13129 return false; 13130 13131 // Sort the memory operands according to their distance from the 13132 // base pointer. 13133 std::sort(StoreNodes.begin(), StoreNodes.end(), 13134 [](MemOpLink LHS, MemOpLink RHS) { 13135 return LHS.OffsetFromBase < RHS.OffsetFromBase; 13136 }); 13137 13138 // Store Merge attempts to merge the lowest stores. This generally 13139 // works out as if successful, as the remaining stores are checked 13140 // after the first collection of stores is merged. However, in the 13141 // case that a non-mergeable store is found first, e.g., {p[-2], 13142 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent 13143 // mergeable cases. To prevent this, we prune such stores from the 13144 // front of StoreNodes here. 13145 13146 bool RV = false; 13147 while (StoreNodes.size() > 1) { 13148 unsigned StartIdx = 0; 13149 while ((StartIdx + 1 < StoreNodes.size()) && 13150 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes != 13151 StoreNodes[StartIdx + 1].OffsetFromBase) 13152 ++StartIdx; 13153 13154 // Bail if we don't have enough candidates to merge. 13155 if (StartIdx + 1 >= StoreNodes.size()) 13156 return RV; 13157 13158 if (StartIdx) 13159 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx); 13160 13161 // Scan the memory operations on the chain and find the first 13162 // non-consecutive store memory address. 13163 unsigned NumConsecutiveStores = 1; 13164 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 13165 // Check that the addresses are consecutive starting from the second 13166 // element in the list of stores. 13167 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) { 13168 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 13169 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 13170 break; 13171 NumConsecutiveStores = i + 1; 13172 } 13173 13174 if (NumConsecutiveStores < 2) { 13175 StoreNodes.erase(StoreNodes.begin(), 13176 StoreNodes.begin() + NumConsecutiveStores); 13177 continue; 13178 } 13179 13180 // Check that we can merge these candidates without causing a cycle 13181 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, 13182 NumConsecutiveStores)) { 13183 StoreNodes.erase(StoreNodes.begin(), 13184 StoreNodes.begin() + NumConsecutiveStores); 13185 continue; 13186 } 13187 13188 // The node with the lowest store address. 13189 LLVMContext &Context = *DAG.getContext(); 13190 const DataLayout &DL = DAG.getDataLayout(); 13191 13192 // Store the constants into memory as one consecutive store. 13193 if (IsConstantSrc) { 13194 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 13195 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 13196 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 13197 unsigned LastLegalType = 1; 13198 unsigned LastLegalVectorType = 1; 13199 bool LastIntegerTrunc = false; 13200 bool NonZero = false; 13201 unsigned FirstZeroAfterNonZero = NumConsecutiveStores; 13202 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 13203 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode); 13204 SDValue StoredVal = ST->getValue(); 13205 bool IsElementZero = false; 13206 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) 13207 IsElementZero = C->isNullValue(); 13208 else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) 13209 IsElementZero = C->getConstantFPValue()->isNullValue(); 13210 if (IsElementZero) { 13211 if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores) 13212 FirstZeroAfterNonZero = i; 13213 } 13214 NonZero |= !IsElementZero; 13215 13216 // Find a legal type for the constant store. 13217 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 13218 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 13219 bool IsFast = false; 13220 if (TLI.isTypeLegal(StoreTy) && 13221 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 13222 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13223 FirstStoreAlign, &IsFast) && 13224 IsFast) { 13225 LastIntegerTrunc = false; 13226 LastLegalType = i + 1; 13227 // Or check whether a truncstore is legal. 13228 } else if (TLI.getTypeAction(Context, StoreTy) == 13229 TargetLowering::TypePromoteInteger) { 13230 EVT LegalizedStoredValueTy = 13231 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 13232 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 13233 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) && 13234 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13235 FirstStoreAlign, &IsFast) && 13236 IsFast) { 13237 LastIntegerTrunc = true; 13238 LastLegalType = i + 1; 13239 } 13240 } 13241 13242 // We only use vectors if the constant is known to be zero or the target 13243 // allows it and the function is not marked with the noimplicitfloat 13244 // attribute. 13245 if ((!NonZero || 13246 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) && 13247 !NoVectors) { 13248 // Find a legal type for the vector store. 13249 unsigned Elts = (i + 1) * NumMemElts; 13250 EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 13251 if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) && 13252 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && 13253 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 13254 FirstStoreAlign, &IsFast) && 13255 IsFast) 13256 LastLegalVectorType = i + 1; 13257 } 13258 } 13259 13260 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 13261 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType; 13262 13263 // Check if we found a legal integer type that creates a meaningful merge. 13264 if (NumElem < 2) { 13265 // We know that candidate stores are in order and of correct 13266 // shape. While there is no mergeable sequence from the 13267 // beginning one may start later in the sequence. The only 13268 // reason a merge of size N could have failed where another of 13269 // the same size would not have, is if the alignment has 13270 // improved or we've dropped a non-zero value. Drop as many 13271 // candidates as we can here. 13272 unsigned NumSkip = 1; 13273 while ( 13274 (NumSkip < NumConsecutiveStores) && 13275 (NumSkip < FirstZeroAfterNonZero) && 13276 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) { 13277 NumSkip++; 13278 } 13279 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 13280 continue; 13281 } 13282 13283 bool Merged = MergeStoresOfConstantsOrVecElts( 13284 StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc); 13285 RV |= Merged; 13286 13287 // Remove merged stores for next iteration. 13288 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 13289 continue; 13290 } 13291 13292 // When extracting multiple vector elements, try to store them 13293 // in one vector store rather than a sequence of scalar stores. 13294 if (IsExtractVecSrc) { 13295 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 13296 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 13297 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 13298 unsigned NumStoresToMerge = 1; 13299 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 13300 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 13301 SDValue StVal = peekThroughBitcast(St->getValue()); 13302 // This restriction could be loosened. 13303 // Bail out if any stored values are not elements extracted from a 13304 // vector. It should be possible to handle mixed sources, but load 13305 // sources need more careful handling (see the block of code below that 13306 // handles consecutive loads). 13307 if (StVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT && 13308 StVal.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13309 return RV; 13310 13311 // Find a legal type for the vector store. 13312 unsigned Elts = (i + 1) * NumMemElts; 13313 EVT Ty = 13314 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 13315 bool IsFast; 13316 if (TLI.isTypeLegal(Ty) && 13317 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && 13318 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 13319 FirstStoreAlign, &IsFast) && 13320 IsFast) 13321 NumStoresToMerge = i + 1; 13322 } 13323 13324 // Check if we found a legal integer type that creates a meaningful merge. 13325 if (NumStoresToMerge < 2) { 13326 // We know that candidate stores are in order and of correct 13327 // shape. While there is no mergeable sequence from the 13328 // beginning one may start later in the sequence. The only 13329 // reason a merge of size N could have failed where another of 13330 // the same size would not have, is if the alignment has 13331 // improved. Drop as many candidates as we can here. 13332 unsigned NumSkip = 1; 13333 while ((NumSkip < NumConsecutiveStores) && 13334 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 13335 NumSkip++; 13336 13337 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 13338 continue; 13339 } 13340 13341 bool Merged = MergeStoresOfConstantsOrVecElts( 13342 StoreNodes, MemVT, NumStoresToMerge, false, true, false); 13343 if (!Merged) { 13344 StoreNodes.erase(StoreNodes.begin(), 13345 StoreNodes.begin() + NumStoresToMerge); 13346 continue; 13347 } 13348 // Remove merged stores for next iteration. 13349 StoreNodes.erase(StoreNodes.begin(), 13350 StoreNodes.begin() + NumStoresToMerge); 13351 RV = true; 13352 continue; 13353 } 13354 13355 // Below we handle the case of multiple consecutive stores that 13356 // come from multiple consecutive loads. We merge them into a single 13357 // wide load and a single wide store. 13358 13359 // Look for load nodes which are used by the stored values. 13360 SmallVector<MemOpLink, 8> LoadNodes; 13361 13362 // Find acceptable loads. Loads need to have the same chain (token factor), 13363 // must not be zext, volatile, indexed, and they must be consecutive. 13364 BaseIndexOffset LdBasePtr; 13365 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 13366 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 13367 SDValue Val = peekThroughBitcast(St->getValue()); 13368 LoadSDNode *Ld = dyn_cast<LoadSDNode>(Val); 13369 if (!Ld) 13370 break; 13371 13372 // Loads must only have one use. 13373 if (!Ld->hasNUsesOfValue(1, 0)) 13374 break; 13375 13376 // The memory operands must not be volatile. 13377 if (Ld->isVolatile() || Ld->isIndexed()) 13378 break; 13379 13380 // The stored memory type must be the same. 13381 if (Ld->getMemoryVT() != MemVT) 13382 break; 13383 13384 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld, DAG); 13385 // If this is not the first ptr that we check. 13386 int64_t LdOffset = 0; 13387 if (LdBasePtr.getBase().getNode()) { 13388 // The base ptr must be the same. 13389 if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset)) 13390 break; 13391 } else { 13392 // Check that all other base pointers are the same as this one. 13393 LdBasePtr = LdPtr; 13394 } 13395 13396 // We found a potential memory operand to merge. 13397 LoadNodes.push_back(MemOpLink(Ld, LdOffset)); 13398 } 13399 13400 if (LoadNodes.size() < 2) { 13401 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1); 13402 continue; 13403 } 13404 13405 // If we have load/store pair instructions and we only have two values, 13406 // don't bother merging. 13407 unsigned RequiredAlignment; 13408 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 13409 StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) { 13410 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2); 13411 continue; 13412 } 13413 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 13414 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 13415 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 13416 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 13417 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 13418 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 13419 13420 // Scan the memory operations on the chain and find the first 13421 // non-consecutive load memory address. These variables hold the index in 13422 // the store node array. 13423 unsigned LastConsecutiveLoad = 1; 13424 // This variable refers to the size and not index in the array. 13425 unsigned LastLegalVectorType = 1; 13426 unsigned LastLegalIntegerType = 1; 13427 bool isDereferenceable = true; 13428 bool DoIntegerTruncate = false; 13429 StartAddress = LoadNodes[0].OffsetFromBase; 13430 SDValue FirstChain = FirstLoad->getChain(); 13431 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 13432 // All loads must share the same chain. 13433 if (LoadNodes[i].MemNode->getChain() != FirstChain) 13434 break; 13435 13436 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 13437 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 13438 break; 13439 LastConsecutiveLoad = i; 13440 13441 if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable()) 13442 isDereferenceable = false; 13443 13444 // Find a legal type for the vector store. 13445 unsigned Elts = (i + 1) * NumMemElts; 13446 EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 13447 13448 bool IsFastSt, IsFastLd; 13449 if (TLI.isTypeLegal(StoreTy) && 13450 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 13451 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13452 FirstStoreAlign, &IsFastSt) && 13453 IsFastSt && 13454 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 13455 FirstLoadAlign, &IsFastLd) && 13456 IsFastLd) { 13457 LastLegalVectorType = i + 1; 13458 } 13459 13460 // Find a legal type for the integer store. 13461 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 13462 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 13463 if (TLI.isTypeLegal(StoreTy) && 13464 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 13465 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13466 FirstStoreAlign, &IsFastSt) && 13467 IsFastSt && 13468 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 13469 FirstLoadAlign, &IsFastLd) && 13470 IsFastLd) { 13471 LastLegalIntegerType = i + 1; 13472 DoIntegerTruncate = false; 13473 // Or check whether a truncstore and extload is legal. 13474 } else if (TLI.getTypeAction(Context, StoreTy) == 13475 TargetLowering::TypePromoteInteger) { 13476 EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy); 13477 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 13478 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) && 13479 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, 13480 StoreTy) && 13481 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, 13482 StoreTy) && 13483 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 13484 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13485 FirstStoreAlign, &IsFastSt) && 13486 IsFastSt && 13487 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 13488 FirstLoadAlign, &IsFastLd) && 13489 IsFastLd) { 13490 LastLegalIntegerType = i + 1; 13491 DoIntegerTruncate = true; 13492 } 13493 } 13494 } 13495 13496 // Only use vector types if the vector type is larger than the integer type. 13497 // If they are the same, use integers. 13498 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 13499 unsigned LastLegalType = 13500 std::max(LastLegalVectorType, LastLegalIntegerType); 13501 13502 // We add +1 here because the LastXXX variables refer to location while 13503 // the NumElem refers to array/index size. 13504 unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1); 13505 NumElem = std::min(LastLegalType, NumElem); 13506 13507 if (NumElem < 2) { 13508 // We know that candidate stores are in order and of correct 13509 // shape. While there is no mergeable sequence from the 13510 // beginning one may start later in the sequence. The only 13511 // reason a merge of size N could have failed where another of 13512 // the same size would not have is if the alignment or either 13513 // the load or store has improved. Drop as many candidates as we 13514 // can here. 13515 unsigned NumSkip = 1; 13516 while ((NumSkip < LoadNodes.size()) && 13517 (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) && 13518 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 13519 NumSkip++; 13520 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 13521 continue; 13522 } 13523 13524 // Find if it is better to use vectors or integers to load and store 13525 // to memory. 13526 EVT JointMemOpVT; 13527 if (UseVectorTy) { 13528 // Find a legal type for the vector store. 13529 unsigned Elts = NumElem * NumMemElts; 13530 JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 13531 } else { 13532 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 13533 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 13534 } 13535 13536 SDLoc LoadDL(LoadNodes[0].MemNode); 13537 SDLoc StoreDL(StoreNodes[0].MemNode); 13538 13539 // The merged loads are required to have the same incoming chain, so 13540 // using the first's chain is acceptable. 13541 13542 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem); 13543 AddToWorklist(NewStoreChain.getNode()); 13544 13545 MachineMemOperand::Flags MMOFlags = isDereferenceable ? 13546 MachineMemOperand::MODereferenceable: 13547 MachineMemOperand::MONone; 13548 13549 SDValue NewLoad, NewStore; 13550 if (UseVectorTy || !DoIntegerTruncate) { 13551 NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(), 13552 FirstLoad->getBasePtr(), 13553 FirstLoad->getPointerInfo(), FirstLoadAlign, 13554 MMOFlags); 13555 NewStore = DAG.getStore(NewStoreChain, StoreDL, NewLoad, 13556 FirstInChain->getBasePtr(), 13557 FirstInChain->getPointerInfo(), FirstStoreAlign); 13558 } else { // This must be the truncstore/extload case 13559 EVT ExtendedTy = 13560 TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT); 13561 NewLoad = 13562 DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, FirstLoad->getChain(), 13563 FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(), 13564 JointMemOpVT, FirstLoadAlign, MMOFlags); 13565 NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad, 13566 FirstInChain->getBasePtr(), 13567 FirstInChain->getPointerInfo(), JointMemOpVT, 13568 FirstInChain->getAlignment(), 13569 FirstInChain->getMemOperand()->getFlags()); 13570 } 13571 13572 // Transfer chain users from old loads to the new load. 13573 for (unsigned i = 0; i < NumElem; ++i) { 13574 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 13575 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 13576 SDValue(NewLoad.getNode(), 1)); 13577 } 13578 13579 // Replace the all stores with the new store. Recursively remove 13580 // corresponding value if its no longer used. 13581 for (unsigned i = 0; i < NumElem; ++i) { 13582 SDValue Val = StoreNodes[i].MemNode->getOperand(1); 13583 CombineTo(StoreNodes[i].MemNode, NewStore); 13584 if (Val.getNode()->use_empty()) 13585 recursivelyDeleteUnusedNodes(Val.getNode()); 13586 } 13587 13588 RV = true; 13589 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 13590 } 13591 return RV; 13592 } 13593 13594 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 13595 SDLoc SL(ST); 13596 SDValue ReplStore; 13597 13598 // Replace the chain to avoid dependency. 13599 if (ST->isTruncatingStore()) { 13600 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 13601 ST->getBasePtr(), ST->getMemoryVT(), 13602 ST->getMemOperand()); 13603 } else { 13604 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 13605 ST->getMemOperand()); 13606 } 13607 13608 // Create token to keep both nodes around. 13609 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 13610 MVT::Other, ST->getChain(), ReplStore); 13611 13612 // Make sure the new and old chains are cleaned up. 13613 AddToWorklist(Token.getNode()); 13614 13615 // Don't add users to work list. 13616 return CombineTo(ST, Token, false); 13617 } 13618 13619 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 13620 SDValue Value = ST->getValue(); 13621 if (Value.getOpcode() == ISD::TargetConstantFP) 13622 return SDValue(); 13623 13624 SDLoc DL(ST); 13625 13626 SDValue Chain = ST->getChain(); 13627 SDValue Ptr = ST->getBasePtr(); 13628 13629 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 13630 13631 // NOTE: If the original store is volatile, this transform must not increase 13632 // the number of stores. For example, on x86-32 an f64 can be stored in one 13633 // processor operation but an i64 (which is not legal) requires two. So the 13634 // transform should not be done in this case. 13635 13636 SDValue Tmp; 13637 switch (CFP->getSimpleValueType(0).SimpleTy) { 13638 default: 13639 llvm_unreachable("Unknown FP type"); 13640 case MVT::f16: // We don't do this for these yet. 13641 case MVT::f80: 13642 case MVT::f128: 13643 case MVT::ppcf128: 13644 return SDValue(); 13645 case MVT::f32: 13646 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 13647 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 13648 ; 13649 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 13650 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 13651 MVT::i32); 13652 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 13653 } 13654 13655 return SDValue(); 13656 case MVT::f64: 13657 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 13658 !ST->isVolatile()) || 13659 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 13660 ; 13661 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 13662 getZExtValue(), SDLoc(CFP), MVT::i64); 13663 return DAG.getStore(Chain, DL, Tmp, 13664 Ptr, ST->getMemOperand()); 13665 } 13666 13667 if (!ST->isVolatile() && 13668 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 13669 // Many FP stores are not made apparent until after legalize, e.g. for 13670 // argument passing. Since this is so common, custom legalize the 13671 // 64-bit integer store into two 32-bit stores. 13672 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 13673 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 13674 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 13675 if (DAG.getDataLayout().isBigEndian()) 13676 std::swap(Lo, Hi); 13677 13678 unsigned Alignment = ST->getAlignment(); 13679 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 13680 AAMDNodes AAInfo = ST->getAAInfo(); 13681 13682 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 13683 ST->getAlignment(), MMOFlags, AAInfo); 13684 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 13685 DAG.getConstant(4, DL, Ptr.getValueType())); 13686 Alignment = MinAlign(Alignment, 4U); 13687 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 13688 ST->getPointerInfo().getWithOffset(4), 13689 Alignment, MMOFlags, AAInfo); 13690 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 13691 St0, St1); 13692 } 13693 13694 return SDValue(); 13695 } 13696 } 13697 13698 SDValue DAGCombiner::visitSTORE(SDNode *N) { 13699 StoreSDNode *ST = cast<StoreSDNode>(N); 13700 SDValue Chain = ST->getChain(); 13701 SDValue Value = ST->getValue(); 13702 SDValue Ptr = ST->getBasePtr(); 13703 13704 // If this is a store of a bit convert, store the input value if the 13705 // resultant store does not need a higher alignment than the original. 13706 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 13707 ST->isUnindexed()) { 13708 EVT SVT = Value.getOperand(0).getValueType(); 13709 if (((!LegalOperations && !ST->isVolatile()) || 13710 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) && 13711 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 13712 unsigned OrigAlign = ST->getAlignment(); 13713 bool Fast = false; 13714 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 13715 ST->getAddressSpace(), OrigAlign, &Fast) && 13716 Fast) { 13717 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 13718 ST->getPointerInfo(), OrigAlign, 13719 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 13720 } 13721 } 13722 } 13723 13724 // Turn 'store undef, Ptr' -> nothing. 13725 if (Value.isUndef() && ST->isUnindexed()) 13726 return Chain; 13727 13728 // Try to infer better alignment information than the store already has. 13729 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 13730 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 13731 if (Align > ST->getAlignment()) { 13732 SDValue NewStore = 13733 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 13734 ST->getMemoryVT(), Align, 13735 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 13736 if (NewStore.getNode() != N) 13737 return CombineTo(ST, NewStore, true); 13738 } 13739 } 13740 } 13741 13742 // Try transforming a pair floating point load / store ops to integer 13743 // load / store ops. 13744 if (SDValue NewST = TransformFPLoadStorePair(N)) 13745 return NewST; 13746 13747 if (ST->isUnindexed()) { 13748 // Walk up chain skipping non-aliasing memory nodes, on this store and any 13749 // adjacent stores. 13750 if (findBetterNeighborChains(ST)) { 13751 // replaceStoreChain uses CombineTo, which handled all of the worklist 13752 // manipulation. Return the original node to not do anything else. 13753 return SDValue(ST, 0); 13754 } 13755 Chain = ST->getChain(); 13756 } 13757 13758 // FIXME: is there such a thing as a truncating indexed store? 13759 if (ST->isTruncatingStore() && ST->isUnindexed() && 13760 Value.getValueType().isInteger()) { 13761 // See if we can simplify the input to this truncstore with knowledge that 13762 // only the low bits are being used. For example: 13763 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 13764 SDValue Shorter = DAG.GetDemandedBits( 13765 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 13766 ST->getMemoryVT().getScalarSizeInBits())); 13767 AddToWorklist(Value.getNode()); 13768 if (Shorter.getNode()) 13769 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 13770 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 13771 13772 // Otherwise, see if we can simplify the operation with 13773 // SimplifyDemandedBits, which only works if the value has a single use. 13774 if (SimplifyDemandedBits( 13775 Value, 13776 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 13777 ST->getMemoryVT().getScalarSizeInBits()))) { 13778 // Re-visit the store if anything changed and the store hasn't been merged 13779 // with another node (N is deleted) SimplifyDemandedBits will add Value's 13780 // node back to the worklist if necessary, but we also need to re-visit 13781 // the Store node itself. 13782 if (N->getOpcode() != ISD::DELETED_NODE) 13783 AddToWorklist(N); 13784 return SDValue(N, 0); 13785 } 13786 } 13787 13788 // If this is a load followed by a store to the same location, then the store 13789 // is dead/noop. 13790 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 13791 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 13792 ST->isUnindexed() && !ST->isVolatile() && 13793 // There can't be any side effects between the load and store, such as 13794 // a call or store. 13795 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 13796 // The store is dead, remove it. 13797 return Chain; 13798 } 13799 } 13800 13801 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 13802 if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() && 13803 !ST1->isVolatile() && ST1->getBasePtr() == Ptr && 13804 ST->getMemoryVT() == ST1->getMemoryVT()) { 13805 // If this is a store followed by a store with the same value to the same 13806 // location, then the store is dead/noop. 13807 if (ST1->getValue() == Value) { 13808 // The store is dead, remove it. 13809 return Chain; 13810 } 13811 13812 // If this is a store who's preceeding store to the same location 13813 // and no one other node is chained to that store we can effectively 13814 // drop the store. Do not remove stores to undef as they may be used as 13815 // data sinks. 13816 if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() && 13817 !ST1->getBasePtr().isUndef()) { 13818 // ST1 is fully overwritten and can be elided. Combine with it's chain 13819 // value. 13820 CombineTo(ST1, ST1->getChain()); 13821 return SDValue(); 13822 } 13823 } 13824 } 13825 13826 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 13827 // truncating store. We can do this even if this is already a truncstore. 13828 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 13829 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 13830 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 13831 ST->getMemoryVT())) { 13832 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 13833 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 13834 } 13835 13836 // Always perform this optimization before types are legal. If the target 13837 // prefers, also try this after legalization to catch stores that were created 13838 // by intrinsics or other nodes. 13839 if (!LegalTypes || (TLI.mergeStoresAfterLegalization())) { 13840 while (true) { 13841 // There can be multiple store sequences on the same chain. 13842 // Keep trying to merge store sequences until we are unable to do so 13843 // or until we merge the last store on the chain. 13844 bool Changed = MergeConsecutiveStores(ST); 13845 if (!Changed) break; 13846 // Return N as merge only uses CombineTo and no worklist clean 13847 // up is necessary. 13848 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N)) 13849 return SDValue(N, 0); 13850 } 13851 } 13852 13853 // Try transforming N to an indexed store. 13854 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 13855 return SDValue(N, 0); 13856 13857 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 13858 // 13859 // Make sure to do this only after attempting to merge stores in order to 13860 // avoid changing the types of some subset of stores due to visit order, 13861 // preventing their merging. 13862 if (isa<ConstantFPSDNode>(ST->getValue())) { 13863 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 13864 return NewSt; 13865 } 13866 13867 if (SDValue NewSt = splitMergedValStore(ST)) 13868 return NewSt; 13869 13870 return ReduceLoadOpStoreWidth(N); 13871 } 13872 13873 /// For the instruction sequence of store below, F and I values 13874 /// are bundled together as an i64 value before being stored into memory. 13875 /// Sometimes it is more efficent to generate separate stores for F and I, 13876 /// which can remove the bitwise instructions or sink them to colder places. 13877 /// 13878 /// (store (or (zext (bitcast F to i32) to i64), 13879 /// (shl (zext I to i64), 32)), addr) --> 13880 /// (store F, addr) and (store I, addr+4) 13881 /// 13882 /// Similarly, splitting for other merged store can also be beneficial, like: 13883 /// For pair of {i32, i32}, i64 store --> two i32 stores. 13884 /// For pair of {i32, i16}, i64 store --> two i32 stores. 13885 /// For pair of {i16, i16}, i32 store --> two i16 stores. 13886 /// For pair of {i16, i8}, i32 store --> two i16 stores. 13887 /// For pair of {i8, i8}, i16 store --> two i8 stores. 13888 /// 13889 /// We allow each target to determine specifically which kind of splitting is 13890 /// supported. 13891 /// 13892 /// The store patterns are commonly seen from the simple code snippet below 13893 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 13894 /// void goo(const std::pair<int, float> &); 13895 /// hoo() { 13896 /// ... 13897 /// goo(std::make_pair(tmp, ftmp)); 13898 /// ... 13899 /// } 13900 /// 13901 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) { 13902 if (OptLevel == CodeGenOpt::None) 13903 return SDValue(); 13904 13905 SDValue Val = ST->getValue(); 13906 SDLoc DL(ST); 13907 13908 // Match OR operand. 13909 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR) 13910 return SDValue(); 13911 13912 // Match SHL operand and get Lower and Higher parts of Val. 13913 SDValue Op1 = Val.getOperand(0); 13914 SDValue Op2 = Val.getOperand(1); 13915 SDValue Lo, Hi; 13916 if (Op1.getOpcode() != ISD::SHL) { 13917 std::swap(Op1, Op2); 13918 if (Op1.getOpcode() != ISD::SHL) 13919 return SDValue(); 13920 } 13921 Lo = Op2; 13922 Hi = Op1.getOperand(0); 13923 if (!Op1.hasOneUse()) 13924 return SDValue(); 13925 13926 // Match shift amount to HalfValBitSize. 13927 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2; 13928 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1)); 13929 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize) 13930 return SDValue(); 13931 13932 // Lo and Hi are zero-extended from int with size less equal than 32 13933 // to i64. 13934 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() || 13935 !Lo.getOperand(0).getValueType().isScalarInteger() || 13936 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize || 13937 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() || 13938 !Hi.getOperand(0).getValueType().isScalarInteger() || 13939 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize) 13940 return SDValue(); 13941 13942 // Use the EVT of low and high parts before bitcast as the input 13943 // of target query. 13944 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST) 13945 ? Lo.getOperand(0).getValueType() 13946 : Lo.getValueType(); 13947 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST) 13948 ? Hi.getOperand(0).getValueType() 13949 : Hi.getValueType(); 13950 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) 13951 return SDValue(); 13952 13953 // Start to split store. 13954 unsigned Alignment = ST->getAlignment(); 13955 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 13956 AAMDNodes AAInfo = ST->getAAInfo(); 13957 13958 // Change the sizes of Lo and Hi's value types to HalfValBitSize. 13959 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize); 13960 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0)); 13961 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0)); 13962 13963 SDValue Chain = ST->getChain(); 13964 SDValue Ptr = ST->getBasePtr(); 13965 // Lower value store. 13966 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 13967 ST->getAlignment(), MMOFlags, AAInfo); 13968 Ptr = 13969 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 13970 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType())); 13971 // Higher value store. 13972 SDValue St1 = 13973 DAG.getStore(St0, DL, Hi, Ptr, 13974 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8), 13975 Alignment / 2, MMOFlags, AAInfo); 13976 return St1; 13977 } 13978 13979 /// Convert a disguised subvector insertion into a shuffle: 13980 /// insert_vector_elt V, (bitcast X from vector type), IdxC --> 13981 /// bitcast(shuffle (bitcast V), (extended X), Mask) 13982 /// Note: We do not use an insert_subvector node because that requires a legal 13983 /// subvector type. 13984 SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) { 13985 SDValue InsertVal = N->getOperand(1); 13986 if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() || 13987 !InsertVal.getOperand(0).getValueType().isVector()) 13988 return SDValue(); 13989 13990 SDValue SubVec = InsertVal.getOperand(0); 13991 SDValue DestVec = N->getOperand(0); 13992 EVT SubVecVT = SubVec.getValueType(); 13993 EVT VT = DestVec.getValueType(); 13994 unsigned NumSrcElts = SubVecVT.getVectorNumElements(); 13995 unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits(); 13996 unsigned NumMaskVals = ExtendRatio * NumSrcElts; 13997 13998 // Step 1: Create a shuffle mask that implements this insert operation. The 13999 // vector that we are inserting into will be operand 0 of the shuffle, so 14000 // those elements are just 'i'. The inserted subvector is in the first 14001 // positions of operand 1 of the shuffle. Example: 14002 // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7} 14003 SmallVector<int, 16> Mask(NumMaskVals); 14004 for (unsigned i = 0; i != NumMaskVals; ++i) { 14005 if (i / NumSrcElts == InsIndex) 14006 Mask[i] = (i % NumSrcElts) + NumMaskVals; 14007 else 14008 Mask[i] = i; 14009 } 14010 14011 // Bail out if the target can not handle the shuffle we want to create. 14012 EVT SubVecEltVT = SubVecVT.getVectorElementType(); 14013 EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals); 14014 if (!TLI.isShuffleMaskLegal(Mask, ShufVT)) 14015 return SDValue(); 14016 14017 // Step 2: Create a wide vector from the inserted source vector by appending 14018 // undefined elements. This is the same size as our destination vector. 14019 SDLoc DL(N); 14020 SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT)); 14021 ConcatOps[0] = SubVec; 14022 SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps); 14023 14024 // Step 3: Shuffle in the padded subvector. 14025 SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec); 14026 SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask); 14027 AddToWorklist(PaddedSubV.getNode()); 14028 AddToWorklist(DestVecBC.getNode()); 14029 AddToWorklist(Shuf.getNode()); 14030 return DAG.getBitcast(VT, Shuf); 14031 } 14032 14033 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 14034 SDValue InVec = N->getOperand(0); 14035 SDValue InVal = N->getOperand(1); 14036 SDValue EltNo = N->getOperand(2); 14037 SDLoc DL(N); 14038 14039 // If the inserted element is an UNDEF, just use the input vector. 14040 if (InVal.isUndef()) 14041 return InVec; 14042 14043 EVT VT = InVec.getValueType(); 14044 14045 // Remove redundant insertions: 14046 // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x 14047 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 14048 InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1)) 14049 return InVec; 14050 14051 // We must know which element is being inserted for folds below here. 14052 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo); 14053 if (!IndexC) 14054 return SDValue(); 14055 unsigned Elt = IndexC->getZExtValue(); 14056 14057 if (SDValue Shuf = combineInsertEltToShuffle(N, Elt)) 14058 return Shuf; 14059 14060 // Canonicalize insert_vector_elt dag nodes. 14061 // Example: 14062 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 14063 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 14064 // 14065 // Do this only if the child insert_vector node has one use; also 14066 // do this only if indices are both constants and Idx1 < Idx0. 14067 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 14068 && isa<ConstantSDNode>(InVec.getOperand(2))) { 14069 unsigned OtherElt = InVec.getConstantOperandVal(2); 14070 if (Elt < OtherElt) { 14071 // Swap nodes. 14072 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, 14073 InVec.getOperand(0), InVal, EltNo); 14074 AddToWorklist(NewOp.getNode()); 14075 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 14076 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 14077 } 14078 } 14079 14080 // If we can't generate a legal BUILD_VECTOR, exit 14081 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 14082 return SDValue(); 14083 14084 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 14085 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 14086 // vector elements. 14087 SmallVector<SDValue, 8> Ops; 14088 // Do not combine these two vectors if the output vector will not replace 14089 // the input vector. 14090 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 14091 Ops.append(InVec.getNode()->op_begin(), 14092 InVec.getNode()->op_end()); 14093 } else if (InVec.isUndef()) { 14094 unsigned NElts = VT.getVectorNumElements(); 14095 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 14096 } else { 14097 return SDValue(); 14098 } 14099 14100 // Insert the element 14101 if (Elt < Ops.size()) { 14102 // All the operands of BUILD_VECTOR must have the same type; 14103 // we enforce that here. 14104 EVT OpVT = Ops[0].getValueType(); 14105 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal; 14106 } 14107 14108 // Return the new vector 14109 return DAG.getBuildVector(VT, DL, Ops); 14110 } 14111 14112 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 14113 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 14114 assert(!OriginalLoad->isVolatile()); 14115 14116 EVT ResultVT = EVE->getValueType(0); 14117 EVT VecEltVT = InVecVT.getVectorElementType(); 14118 unsigned Align = OriginalLoad->getAlignment(); 14119 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 14120 VecEltVT.getTypeForEVT(*DAG.getContext())); 14121 14122 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 14123 return SDValue(); 14124 14125 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ? 14126 ISD::NON_EXTLOAD : ISD::EXTLOAD; 14127 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT)) 14128 return SDValue(); 14129 14130 Align = NewAlign; 14131 14132 SDValue NewPtr = OriginalLoad->getBasePtr(); 14133 SDValue Offset; 14134 EVT PtrType = NewPtr.getValueType(); 14135 MachinePointerInfo MPI; 14136 SDLoc DL(EVE); 14137 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 14138 int Elt = ConstEltNo->getZExtValue(); 14139 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 14140 Offset = DAG.getConstant(PtrOff, DL, PtrType); 14141 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 14142 } else { 14143 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 14144 Offset = DAG.getNode( 14145 ISD::MUL, DL, PtrType, Offset, 14146 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 14147 MPI = OriginalLoad->getPointerInfo(); 14148 } 14149 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 14150 14151 // The replacement we need to do here is a little tricky: we need to 14152 // replace an extractelement of a load with a load. 14153 // Use ReplaceAllUsesOfValuesWith to do the replacement. 14154 // Note that this replacement assumes that the extractvalue is the only 14155 // use of the load; that's okay because we don't want to perform this 14156 // transformation in other cases anyway. 14157 SDValue Load; 14158 SDValue Chain; 14159 if (ResultVT.bitsGT(VecEltVT)) { 14160 // If the result type of vextract is wider than the load, then issue an 14161 // extending load instead. 14162 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 14163 VecEltVT) 14164 ? ISD::ZEXTLOAD 14165 : ISD::EXTLOAD; 14166 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 14167 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 14168 Align, OriginalLoad->getMemOperand()->getFlags(), 14169 OriginalLoad->getAAInfo()); 14170 Chain = Load.getValue(1); 14171 } else { 14172 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, 14173 MPI, Align, OriginalLoad->getMemOperand()->getFlags(), 14174 OriginalLoad->getAAInfo()); 14175 Chain = Load.getValue(1); 14176 if (ResultVT.bitsLT(VecEltVT)) 14177 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 14178 else 14179 Load = DAG.getBitcast(ResultVT, Load); 14180 } 14181 WorklistRemover DeadNodes(*this); 14182 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 14183 SDValue To[] = { Load, Chain }; 14184 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 14185 // Since we're explicitly calling ReplaceAllUses, add the new node to the 14186 // worklist explicitly as well. 14187 AddToWorklist(Load.getNode()); 14188 AddUsersToWorklist(Load.getNode()); // Add users too 14189 // Make sure to revisit this node to clean it up; it will usually be dead. 14190 AddToWorklist(EVE); 14191 ++OpsNarrowed; 14192 return SDValue(EVE, 0); 14193 } 14194 14195 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 14196 // (vextract (scalar_to_vector val, 0) -> val 14197 SDValue InVec = N->getOperand(0); 14198 EVT VT = InVec.getValueType(); 14199 EVT NVT = N->getValueType(0); 14200 14201 if (InVec.isUndef()) 14202 return DAG.getUNDEF(NVT); 14203 14204 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 14205 // Check if the result type doesn't match the inserted element type. A 14206 // SCALAR_TO_VECTOR may truncate the inserted element and the 14207 // EXTRACT_VECTOR_ELT may widen the extracted vector. 14208 SDValue InOp = InVec.getOperand(0); 14209 if (InOp.getValueType() != NVT) { 14210 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 14211 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 14212 } 14213 return InOp; 14214 } 14215 14216 SDValue EltNo = N->getOperand(1); 14217 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 14218 14219 // extract_vector_elt (build_vector x, y), 1 -> y 14220 if (ConstEltNo && 14221 InVec.getOpcode() == ISD::BUILD_VECTOR && 14222 TLI.isTypeLegal(VT) && 14223 (InVec.hasOneUse() || 14224 TLI.aggressivelyPreferBuildVectorSources(VT))) { 14225 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 14226 EVT InEltVT = Elt.getValueType(); 14227 14228 // Sometimes build_vector's scalar input types do not match result type. 14229 if (NVT == InEltVT) 14230 return Elt; 14231 14232 // TODO: It may be useful to truncate if free if the build_vector implicitly 14233 // converts. 14234 } 14235 14236 // extract_vector_elt (v2i32 (bitcast i64:x)), EltTrunc -> i32 (trunc i64:x) 14237 bool isLE = DAG.getDataLayout().isLittleEndian(); 14238 unsigned EltTrunc = isLE ? 0 : VT.getVectorNumElements() - 1; 14239 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 14240 ConstEltNo->getZExtValue() == EltTrunc && VT.isInteger()) { 14241 SDValue BCSrc = InVec.getOperand(0); 14242 if (BCSrc.getValueType().isScalarInteger()) 14243 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 14244 } 14245 14246 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 14247 // 14248 // This only really matters if the index is non-constant since other combines 14249 // on the constant elements already work. 14250 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && 14251 EltNo == InVec.getOperand(2)) { 14252 SDValue Elt = InVec.getOperand(1); 14253 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt; 14254 } 14255 14256 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 14257 // We only perform this optimization before the op legalization phase because 14258 // we may introduce new vector instructions which are not backed by TD 14259 // patterns. For example on AVX, extracting elements from a wide vector 14260 // without using extract_subvector. However, if we can find an underlying 14261 // scalar value, then we can always use that. 14262 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 14263 int NumElem = VT.getVectorNumElements(); 14264 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 14265 // Find the new index to extract from. 14266 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 14267 14268 // Extracting an undef index is undef. 14269 if (OrigElt == -1) 14270 return DAG.getUNDEF(NVT); 14271 14272 // Select the right vector half to extract from. 14273 SDValue SVInVec; 14274 if (OrigElt < NumElem) { 14275 SVInVec = InVec->getOperand(0); 14276 } else { 14277 SVInVec = InVec->getOperand(1); 14278 OrigElt -= NumElem; 14279 } 14280 14281 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 14282 SDValue InOp = SVInVec.getOperand(OrigElt); 14283 if (InOp.getValueType() != NVT) { 14284 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 14285 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 14286 } 14287 14288 return InOp; 14289 } 14290 14291 // FIXME: We should handle recursing on other vector shuffles and 14292 // scalar_to_vector here as well. 14293 14294 if (!LegalOperations || 14295 // FIXME: Should really be just isOperationLegalOrCustom. 14296 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VT) || 14297 TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VT)) { 14298 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 14299 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 14300 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 14301 } 14302 } 14303 14304 bool BCNumEltsChanged = false; 14305 EVT ExtVT = VT.getVectorElementType(); 14306 EVT LVT = ExtVT; 14307 14308 // If the result of load has to be truncated, then it's not necessarily 14309 // profitable. 14310 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 14311 return SDValue(); 14312 14313 if (InVec.getOpcode() == ISD::BITCAST) { 14314 // Don't duplicate a load with other uses. 14315 if (!InVec.hasOneUse()) 14316 return SDValue(); 14317 14318 EVT BCVT = InVec.getOperand(0).getValueType(); 14319 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 14320 return SDValue(); 14321 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 14322 BCNumEltsChanged = true; 14323 InVec = InVec.getOperand(0); 14324 ExtVT = BCVT.getVectorElementType(); 14325 } 14326 14327 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 14328 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 14329 ISD::isNormalLoad(InVec.getNode()) && 14330 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 14331 SDValue Index = N->getOperand(1); 14332 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) { 14333 if (!OrigLoad->isVolatile()) { 14334 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 14335 OrigLoad); 14336 } 14337 } 14338 } 14339 14340 // Perform only after legalization to ensure build_vector / vector_shuffle 14341 // optimizations have already been done. 14342 if (!LegalOperations) return SDValue(); 14343 14344 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 14345 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 14346 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 14347 14348 if (ConstEltNo) { 14349 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 14350 14351 LoadSDNode *LN0 = nullptr; 14352 const ShuffleVectorSDNode *SVN = nullptr; 14353 if (ISD::isNormalLoad(InVec.getNode())) { 14354 LN0 = cast<LoadSDNode>(InVec); 14355 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 14356 InVec.getOperand(0).getValueType() == ExtVT && 14357 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 14358 // Don't duplicate a load with other uses. 14359 if (!InVec.hasOneUse()) 14360 return SDValue(); 14361 14362 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 14363 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 14364 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 14365 // => 14366 // (load $addr+1*size) 14367 14368 // Don't duplicate a load with other uses. 14369 if (!InVec.hasOneUse()) 14370 return SDValue(); 14371 14372 // If the bit convert changed the number of elements, it is unsafe 14373 // to examine the mask. 14374 if (BCNumEltsChanged) 14375 return SDValue(); 14376 14377 // Select the input vector, guarding against out of range extract vector. 14378 unsigned NumElems = VT.getVectorNumElements(); 14379 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 14380 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 14381 14382 if (InVec.getOpcode() == ISD::BITCAST) { 14383 // Don't duplicate a load with other uses. 14384 if (!InVec.hasOneUse()) 14385 return SDValue(); 14386 14387 InVec = InVec.getOperand(0); 14388 } 14389 if (ISD::isNormalLoad(InVec.getNode())) { 14390 LN0 = cast<LoadSDNode>(InVec); 14391 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 14392 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 14393 } 14394 } 14395 14396 // Make sure we found a non-volatile load and the extractelement is 14397 // the only use. 14398 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 14399 return SDValue(); 14400 14401 // If Idx was -1 above, Elt is going to be -1, so just return undef. 14402 if (Elt == -1) 14403 return DAG.getUNDEF(LVT); 14404 14405 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 14406 } 14407 14408 return SDValue(); 14409 } 14410 14411 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 14412 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 14413 // We perform this optimization post type-legalization because 14414 // the type-legalizer often scalarizes integer-promoted vectors. 14415 // Performing this optimization before may create bit-casts which 14416 // will be type-legalized to complex code sequences. 14417 // We perform this optimization only before the operation legalizer because we 14418 // may introduce illegal operations. 14419 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 14420 return SDValue(); 14421 14422 unsigned NumInScalars = N->getNumOperands(); 14423 SDLoc DL(N); 14424 EVT VT = N->getValueType(0); 14425 14426 // Check to see if this is a BUILD_VECTOR of a bunch of values 14427 // which come from any_extend or zero_extend nodes. If so, we can create 14428 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 14429 // optimizations. We do not handle sign-extend because we can't fill the sign 14430 // using shuffles. 14431 EVT SourceType = MVT::Other; 14432 bool AllAnyExt = true; 14433 14434 for (unsigned i = 0; i != NumInScalars; ++i) { 14435 SDValue In = N->getOperand(i); 14436 // Ignore undef inputs. 14437 if (In.isUndef()) continue; 14438 14439 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 14440 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 14441 14442 // Abort if the element is not an extension. 14443 if (!ZeroExt && !AnyExt) { 14444 SourceType = MVT::Other; 14445 break; 14446 } 14447 14448 // The input is a ZeroExt or AnyExt. Check the original type. 14449 EVT InTy = In.getOperand(0).getValueType(); 14450 14451 // Check that all of the widened source types are the same. 14452 if (SourceType == MVT::Other) 14453 // First time. 14454 SourceType = InTy; 14455 else if (InTy != SourceType) { 14456 // Multiple income types. Abort. 14457 SourceType = MVT::Other; 14458 break; 14459 } 14460 14461 // Check if all of the extends are ANY_EXTENDs. 14462 AllAnyExt &= AnyExt; 14463 } 14464 14465 // In order to have valid types, all of the inputs must be extended from the 14466 // same source type and all of the inputs must be any or zero extend. 14467 // Scalar sizes must be a power of two. 14468 EVT OutScalarTy = VT.getScalarType(); 14469 bool ValidTypes = SourceType != MVT::Other && 14470 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 14471 isPowerOf2_32(SourceType.getSizeInBits()); 14472 14473 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 14474 // turn into a single shuffle instruction. 14475 if (!ValidTypes) 14476 return SDValue(); 14477 14478 bool isLE = DAG.getDataLayout().isLittleEndian(); 14479 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 14480 assert(ElemRatio > 1 && "Invalid element size ratio"); 14481 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 14482 DAG.getConstant(0, DL, SourceType); 14483 14484 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 14485 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 14486 14487 // Populate the new build_vector 14488 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 14489 SDValue Cast = N->getOperand(i); 14490 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 14491 Cast.getOpcode() == ISD::ZERO_EXTEND || 14492 Cast.isUndef()) && "Invalid cast opcode"); 14493 SDValue In; 14494 if (Cast.isUndef()) 14495 In = DAG.getUNDEF(SourceType); 14496 else 14497 In = Cast->getOperand(0); 14498 unsigned Index = isLE ? (i * ElemRatio) : 14499 (i * ElemRatio + (ElemRatio - 1)); 14500 14501 assert(Index < Ops.size() && "Invalid index"); 14502 Ops[Index] = In; 14503 } 14504 14505 // The type of the new BUILD_VECTOR node. 14506 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 14507 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 14508 "Invalid vector size"); 14509 // Check if the new vector type is legal. 14510 if (!isTypeLegal(VecVT)) return SDValue(); 14511 14512 // Make the new BUILD_VECTOR. 14513 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops); 14514 14515 // The new BUILD_VECTOR node has the potential to be further optimized. 14516 AddToWorklist(BV.getNode()); 14517 // Bitcast to the desired type. 14518 return DAG.getBitcast(VT, BV); 14519 } 14520 14521 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 14522 EVT VT = N->getValueType(0); 14523 14524 unsigned NumInScalars = N->getNumOperands(); 14525 SDLoc DL(N); 14526 14527 EVT SrcVT = MVT::Other; 14528 unsigned Opcode = ISD::DELETED_NODE; 14529 unsigned NumDefs = 0; 14530 14531 for (unsigned i = 0; i != NumInScalars; ++i) { 14532 SDValue In = N->getOperand(i); 14533 unsigned Opc = In.getOpcode(); 14534 14535 if (Opc == ISD::UNDEF) 14536 continue; 14537 14538 // If all scalar values are floats and converted from integers. 14539 if (Opcode == ISD::DELETED_NODE && 14540 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 14541 Opcode = Opc; 14542 } 14543 14544 if (Opc != Opcode) 14545 return SDValue(); 14546 14547 EVT InVT = In.getOperand(0).getValueType(); 14548 14549 // If all scalar values are typed differently, bail out. It's chosen to 14550 // simplify BUILD_VECTOR of integer types. 14551 if (SrcVT == MVT::Other) 14552 SrcVT = InVT; 14553 if (SrcVT != InVT) 14554 return SDValue(); 14555 NumDefs++; 14556 } 14557 14558 // If the vector has just one element defined, it's not worth to fold it into 14559 // a vectorized one. 14560 if (NumDefs < 2) 14561 return SDValue(); 14562 14563 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 14564 && "Should only handle conversion from integer to float."); 14565 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 14566 14567 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 14568 14569 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 14570 return SDValue(); 14571 14572 // Just because the floating-point vector type is legal does not necessarily 14573 // mean that the corresponding integer vector type is. 14574 if (!isTypeLegal(NVT)) 14575 return SDValue(); 14576 14577 SmallVector<SDValue, 8> Opnds; 14578 for (unsigned i = 0; i != NumInScalars; ++i) { 14579 SDValue In = N->getOperand(i); 14580 14581 if (In.isUndef()) 14582 Opnds.push_back(DAG.getUNDEF(SrcVT)); 14583 else 14584 Opnds.push_back(In.getOperand(0)); 14585 } 14586 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds); 14587 AddToWorklist(BV.getNode()); 14588 14589 return DAG.getNode(Opcode, DL, VT, BV); 14590 } 14591 14592 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N, 14593 ArrayRef<int> VectorMask, 14594 SDValue VecIn1, SDValue VecIn2, 14595 unsigned LeftIdx) { 14596 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 14597 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy); 14598 14599 EVT VT = N->getValueType(0); 14600 EVT InVT1 = VecIn1.getValueType(); 14601 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1; 14602 14603 unsigned Vec2Offset = 0; 14604 unsigned NumElems = VT.getVectorNumElements(); 14605 unsigned ShuffleNumElems = NumElems; 14606 14607 // In case both the input vectors are extracted from same base 14608 // vector we do not need extra addend (Vec2Offset) while 14609 // computing shuffle mask. 14610 if (!VecIn2 || !(VecIn1.getOpcode() == ISD::EXTRACT_SUBVECTOR) || 14611 !(VecIn2.getOpcode() == ISD::EXTRACT_SUBVECTOR) || 14612 !(VecIn1.getOperand(0) == VecIn2.getOperand(0))) 14613 Vec2Offset = InVT1.getVectorNumElements(); 14614 14615 // We can't generate a shuffle node with mismatched input and output types. 14616 // Try to make the types match the type of the output. 14617 if (InVT1 != VT || InVT2 != VT) { 14618 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) { 14619 // If the output vector length is a multiple of both input lengths, 14620 // we can concatenate them and pad the rest with undefs. 14621 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits(); 14622 assert(NumConcats >= 2 && "Concat needs at least two inputs!"); 14623 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1)); 14624 ConcatOps[0] = VecIn1; 14625 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1); 14626 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 14627 VecIn2 = SDValue(); 14628 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) { 14629 if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems)) 14630 return SDValue(); 14631 14632 if (!VecIn2.getNode()) { 14633 // If we only have one input vector, and it's twice the size of the 14634 // output, split it in two. 14635 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, 14636 DAG.getConstant(NumElems, DL, IdxTy)); 14637 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx); 14638 // Since we now have shorter input vectors, adjust the offset of the 14639 // second vector's start. 14640 Vec2Offset = NumElems; 14641 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) { 14642 // VecIn1 is wider than the output, and we have another, possibly 14643 // smaller input. Pad the smaller input with undefs, shuffle at the 14644 // input vector width, and extract the output. 14645 // The shuffle type is different than VT, so check legality again. 14646 if (LegalOperations && 14647 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1)) 14648 return SDValue(); 14649 14650 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to 14651 // lower it back into a BUILD_VECTOR. So if the inserted type is 14652 // illegal, don't even try. 14653 if (InVT1 != InVT2) { 14654 if (!TLI.isTypeLegal(InVT2)) 14655 return SDValue(); 14656 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1, 14657 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx); 14658 } 14659 ShuffleNumElems = NumElems * 2; 14660 } else { 14661 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider 14662 // than VecIn1. We can't handle this for now - this case will disappear 14663 // when we start sorting the vectors by type. 14664 return SDValue(); 14665 } 14666 } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() && 14667 InVT1.getSizeInBits() == VT.getSizeInBits()) { 14668 SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2)); 14669 ConcatOps[0] = VecIn2; 14670 VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 14671 } else { 14672 // TODO: Support cases where the length mismatch isn't exactly by a 14673 // factor of 2. 14674 // TODO: Move this check upwards, so that if we have bad type 14675 // mismatches, we don't create any DAG nodes. 14676 return SDValue(); 14677 } 14678 } 14679 14680 // Initialize mask to undef. 14681 SmallVector<int, 8> Mask(ShuffleNumElems, -1); 14682 14683 // Only need to run up to the number of elements actually used, not the 14684 // total number of elements in the shuffle - if we are shuffling a wider 14685 // vector, the high lanes should be set to undef. 14686 for (unsigned i = 0; i != NumElems; ++i) { 14687 if (VectorMask[i] <= 0) 14688 continue; 14689 14690 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1); 14691 if (VectorMask[i] == (int)LeftIdx) { 14692 Mask[i] = ExtIndex; 14693 } else if (VectorMask[i] == (int)LeftIdx + 1) { 14694 Mask[i] = Vec2Offset + ExtIndex; 14695 } 14696 } 14697 14698 // The type the input vectors may have changed above. 14699 InVT1 = VecIn1.getValueType(); 14700 14701 // If we already have a VecIn2, it should have the same type as VecIn1. 14702 // If we don't, get an undef/zero vector of the appropriate type. 14703 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1); 14704 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type."); 14705 14706 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask); 14707 if (ShuffleNumElems > NumElems) 14708 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx); 14709 14710 return Shuffle; 14711 } 14712 14713 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 14714 // operations. If the types of the vectors we're extracting from allow it, 14715 // turn this into a vector_shuffle node. 14716 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) { 14717 SDLoc DL(N); 14718 EVT VT = N->getValueType(0); 14719 14720 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 14721 if (!isTypeLegal(VT)) 14722 return SDValue(); 14723 14724 // May only combine to shuffle after legalize if shuffle is legal. 14725 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 14726 return SDValue(); 14727 14728 bool UsesZeroVector = false; 14729 unsigned NumElems = N->getNumOperands(); 14730 14731 // Record, for each element of the newly built vector, which input vector 14732 // that element comes from. -1 stands for undef, 0 for the zero vector, 14733 // and positive values for the input vectors. 14734 // VectorMask maps each element to its vector number, and VecIn maps vector 14735 // numbers to their initial SDValues. 14736 14737 SmallVector<int, 8> VectorMask(NumElems, -1); 14738 SmallVector<SDValue, 8> VecIn; 14739 VecIn.push_back(SDValue()); 14740 14741 for (unsigned i = 0; i != NumElems; ++i) { 14742 SDValue Op = N->getOperand(i); 14743 14744 if (Op.isUndef()) 14745 continue; 14746 14747 // See if we can use a blend with a zero vector. 14748 // TODO: Should we generalize this to a blend with an arbitrary constant 14749 // vector? 14750 if (isNullConstant(Op) || isNullFPConstant(Op)) { 14751 UsesZeroVector = true; 14752 VectorMask[i] = 0; 14753 continue; 14754 } 14755 14756 // Not an undef or zero. If the input is something other than an 14757 // EXTRACT_VECTOR_ELT with a constant index, bail out. 14758 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14759 !isa<ConstantSDNode>(Op.getOperand(1))) 14760 return SDValue(); 14761 SDValue ExtractedFromVec = Op.getOperand(0); 14762 14763 // All inputs must have the same element type as the output. 14764 if (VT.getVectorElementType() != 14765 ExtractedFromVec.getValueType().getVectorElementType()) 14766 return SDValue(); 14767 14768 // Have we seen this input vector before? 14769 // The vectors are expected to be tiny (usually 1 or 2 elements), so using 14770 // a map back from SDValues to numbers isn't worth it. 14771 unsigned Idx = std::distance( 14772 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec)); 14773 if (Idx == VecIn.size()) 14774 VecIn.push_back(ExtractedFromVec); 14775 14776 VectorMask[i] = Idx; 14777 } 14778 14779 // If we didn't find at least one input vector, bail out. 14780 if (VecIn.size() < 2) 14781 return SDValue(); 14782 14783 // If all the Operands of BUILD_VECTOR extract from same 14784 // vector, then split the vector efficiently based on the maximum 14785 // vector access index and adjust the VectorMask and 14786 // VecIn accordingly. 14787 if (VecIn.size() == 2) { 14788 unsigned MaxIndex = 0; 14789 unsigned NearestPow2 = 0; 14790 SDValue Vec = VecIn.back(); 14791 EVT InVT = Vec.getValueType(); 14792 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 14793 SmallVector<unsigned, 8> IndexVec(NumElems, 0); 14794 14795 for (unsigned i = 0; i < NumElems; i++) { 14796 if (VectorMask[i] <= 0) 14797 continue; 14798 unsigned Index = N->getOperand(i).getConstantOperandVal(1); 14799 IndexVec[i] = Index; 14800 MaxIndex = std::max(MaxIndex, Index); 14801 } 14802 14803 NearestPow2 = PowerOf2Ceil(MaxIndex); 14804 if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 && 14805 NumElems * 2 < NearestPow2) { 14806 unsigned SplitSize = NearestPow2 / 2; 14807 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), 14808 InVT.getVectorElementType(), SplitSize); 14809 if (TLI.isTypeLegal(SplitVT)) { 14810 SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, 14811 DAG.getConstant(SplitSize, DL, IdxTy)); 14812 SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, 14813 DAG.getConstant(0, DL, IdxTy)); 14814 VecIn.pop_back(); 14815 VecIn.push_back(VecIn1); 14816 VecIn.push_back(VecIn2); 14817 14818 for (unsigned i = 0; i < NumElems; i++) { 14819 if (VectorMask[i] <= 0) 14820 continue; 14821 VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2; 14822 } 14823 } 14824 } 14825 } 14826 14827 // TODO: We want to sort the vectors by descending length, so that adjacent 14828 // pairs have similar length, and the longer vector is always first in the 14829 // pair. 14830 14831 // TODO: Should this fire if some of the input vectors has illegal type (like 14832 // it does now), or should we let legalization run its course first? 14833 14834 // Shuffle phase: 14835 // Take pairs of vectors, and shuffle them so that the result has elements 14836 // from these vectors in the correct places. 14837 // For example, given: 14838 // t10: i32 = extract_vector_elt t1, Constant:i64<0> 14839 // t11: i32 = extract_vector_elt t2, Constant:i64<0> 14840 // t12: i32 = extract_vector_elt t3, Constant:i64<0> 14841 // t13: i32 = extract_vector_elt t1, Constant:i64<1> 14842 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13 14843 // We will generate: 14844 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2 14845 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef 14846 SmallVector<SDValue, 4> Shuffles; 14847 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) { 14848 unsigned LeftIdx = 2 * In + 1; 14849 SDValue VecLeft = VecIn[LeftIdx]; 14850 SDValue VecRight = 14851 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue(); 14852 14853 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft, 14854 VecRight, LeftIdx)) 14855 Shuffles.push_back(Shuffle); 14856 else 14857 return SDValue(); 14858 } 14859 14860 // If we need the zero vector as an "ingredient" in the blend tree, add it 14861 // to the list of shuffles. 14862 if (UsesZeroVector) 14863 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT) 14864 : DAG.getConstantFP(0.0, DL, VT)); 14865 14866 // If we only have one shuffle, we're done. 14867 if (Shuffles.size() == 1) 14868 return Shuffles[0]; 14869 14870 // Update the vector mask to point to the post-shuffle vectors. 14871 for (int &Vec : VectorMask) 14872 if (Vec == 0) 14873 Vec = Shuffles.size() - 1; 14874 else 14875 Vec = (Vec - 1) / 2; 14876 14877 // More than one shuffle. Generate a binary tree of blends, e.g. if from 14878 // the previous step we got the set of shuffles t10, t11, t12, t13, we will 14879 // generate: 14880 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2 14881 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4 14882 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6 14883 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8 14884 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11 14885 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13 14886 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21 14887 14888 // Make sure the initial size of the shuffle list is even. 14889 if (Shuffles.size() % 2) 14890 Shuffles.push_back(DAG.getUNDEF(VT)); 14891 14892 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) { 14893 if (CurSize % 2) { 14894 Shuffles[CurSize] = DAG.getUNDEF(VT); 14895 CurSize++; 14896 } 14897 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) { 14898 int Left = 2 * In; 14899 int Right = 2 * In + 1; 14900 SmallVector<int, 8> Mask(NumElems, -1); 14901 for (unsigned i = 0; i != NumElems; ++i) { 14902 if (VectorMask[i] == Left) { 14903 Mask[i] = i; 14904 VectorMask[i] = In; 14905 } else if (VectorMask[i] == Right) { 14906 Mask[i] = i + NumElems; 14907 VectorMask[i] = In; 14908 } 14909 } 14910 14911 Shuffles[In] = 14912 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask); 14913 } 14914 } 14915 return Shuffles[0]; 14916 } 14917 14918 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 14919 EVT VT = N->getValueType(0); 14920 14921 // A vector built entirely of undefs is undef. 14922 if (ISD::allOperandsUndef(N)) 14923 return DAG.getUNDEF(VT); 14924 14925 // Check if we can express BUILD VECTOR via subvector extract. 14926 if (!LegalTypes && (N->getNumOperands() > 1)) { 14927 SDValue Op0 = N->getOperand(0); 14928 auto checkElem = [&](SDValue Op) -> uint64_t { 14929 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) && 14930 (Op0.getOperand(0) == Op.getOperand(0))) 14931 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 14932 return CNode->getZExtValue(); 14933 return -1; 14934 }; 14935 14936 int Offset = checkElem(Op0); 14937 for (unsigned i = 0; i < N->getNumOperands(); ++i) { 14938 if (Offset + i != checkElem(N->getOperand(i))) { 14939 Offset = -1; 14940 break; 14941 } 14942 } 14943 14944 if ((Offset == 0) && 14945 (Op0.getOperand(0).getValueType() == N->getValueType(0))) 14946 return Op0.getOperand(0); 14947 if ((Offset != -1) && 14948 ((Offset % N->getValueType(0).getVectorNumElements()) == 14949 0)) // IDX must be multiple of output size. 14950 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0), 14951 Op0.getOperand(0), Op0.getOperand(1)); 14952 } 14953 14954 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 14955 return V; 14956 14957 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 14958 return V; 14959 14960 if (SDValue V = reduceBuildVecToShuffle(N)) 14961 return V; 14962 14963 return SDValue(); 14964 } 14965 14966 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 14967 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14968 EVT OpVT = N->getOperand(0).getValueType(); 14969 14970 // If the operands are legal vectors, leave them alone. 14971 if (TLI.isTypeLegal(OpVT)) 14972 return SDValue(); 14973 14974 SDLoc DL(N); 14975 EVT VT = N->getValueType(0); 14976 SmallVector<SDValue, 8> Ops; 14977 14978 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 14979 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 14980 14981 // Keep track of what we encounter. 14982 bool AnyInteger = false; 14983 bool AnyFP = false; 14984 for (const SDValue &Op : N->ops()) { 14985 if (ISD::BITCAST == Op.getOpcode() && 14986 !Op.getOperand(0).getValueType().isVector()) 14987 Ops.push_back(Op.getOperand(0)); 14988 else if (ISD::UNDEF == Op.getOpcode()) 14989 Ops.push_back(ScalarUndef); 14990 else 14991 return SDValue(); 14992 14993 // Note whether we encounter an integer or floating point scalar. 14994 // If it's neither, bail out, it could be something weird like x86mmx. 14995 EVT LastOpVT = Ops.back().getValueType(); 14996 if (LastOpVT.isFloatingPoint()) 14997 AnyFP = true; 14998 else if (LastOpVT.isInteger()) 14999 AnyInteger = true; 15000 else 15001 return SDValue(); 15002 } 15003 15004 // If any of the operands is a floating point scalar bitcast to a vector, 15005 // use floating point types throughout, and bitcast everything. 15006 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 15007 if (AnyFP) { 15008 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 15009 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 15010 if (AnyInteger) { 15011 for (SDValue &Op : Ops) { 15012 if (Op.getValueType() == SVT) 15013 continue; 15014 if (Op.isUndef()) 15015 Op = ScalarUndef; 15016 else 15017 Op = DAG.getBitcast(SVT, Op); 15018 } 15019 } 15020 } 15021 15022 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 15023 VT.getSizeInBits() / SVT.getSizeInBits()); 15024 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 15025 } 15026 15027 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 15028 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 15029 // most two distinct vectors the same size as the result, attempt to turn this 15030 // into a legal shuffle. 15031 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 15032 EVT VT = N->getValueType(0); 15033 EVT OpVT = N->getOperand(0).getValueType(); 15034 int NumElts = VT.getVectorNumElements(); 15035 int NumOpElts = OpVT.getVectorNumElements(); 15036 15037 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 15038 SmallVector<int, 8> Mask; 15039 15040 for (SDValue Op : N->ops()) { 15041 // Peek through any bitcast. 15042 Op = peekThroughBitcast(Op); 15043 15044 // UNDEF nodes convert to UNDEF shuffle mask values. 15045 if (Op.isUndef()) { 15046 Mask.append((unsigned)NumOpElts, -1); 15047 continue; 15048 } 15049 15050 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 15051 return SDValue(); 15052 15053 // What vector are we extracting the subvector from and at what index? 15054 SDValue ExtVec = Op.getOperand(0); 15055 15056 // We want the EVT of the original extraction to correctly scale the 15057 // extraction index. 15058 EVT ExtVT = ExtVec.getValueType(); 15059 15060 // Peek through any bitcast. 15061 ExtVec = peekThroughBitcast(ExtVec); 15062 15063 // UNDEF nodes convert to UNDEF shuffle mask values. 15064 if (ExtVec.isUndef()) { 15065 Mask.append((unsigned)NumOpElts, -1); 15066 continue; 15067 } 15068 15069 if (!isa<ConstantSDNode>(Op.getOperand(1))) 15070 return SDValue(); 15071 int ExtIdx = Op.getConstantOperandVal(1); 15072 15073 // Ensure that we are extracting a subvector from a vector the same 15074 // size as the result. 15075 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 15076 return SDValue(); 15077 15078 // Scale the subvector index to account for any bitcast. 15079 int NumExtElts = ExtVT.getVectorNumElements(); 15080 if (0 == (NumExtElts % NumElts)) 15081 ExtIdx /= (NumExtElts / NumElts); 15082 else if (0 == (NumElts % NumExtElts)) 15083 ExtIdx *= (NumElts / NumExtElts); 15084 else 15085 return SDValue(); 15086 15087 // At most we can reference 2 inputs in the final shuffle. 15088 if (SV0.isUndef() || SV0 == ExtVec) { 15089 SV0 = ExtVec; 15090 for (int i = 0; i != NumOpElts; ++i) 15091 Mask.push_back(i + ExtIdx); 15092 } else if (SV1.isUndef() || SV1 == ExtVec) { 15093 SV1 = ExtVec; 15094 for (int i = 0; i != NumOpElts; ++i) 15095 Mask.push_back(i + ExtIdx + NumElts); 15096 } else { 15097 return SDValue(); 15098 } 15099 } 15100 15101 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 15102 return SDValue(); 15103 15104 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 15105 DAG.getBitcast(VT, SV1), Mask); 15106 } 15107 15108 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 15109 // If we only have one input vector, we don't need to do any concatenation. 15110 if (N->getNumOperands() == 1) 15111 return N->getOperand(0); 15112 15113 // Check if all of the operands are undefs. 15114 EVT VT = N->getValueType(0); 15115 if (ISD::allOperandsUndef(N)) 15116 return DAG.getUNDEF(VT); 15117 15118 // Optimize concat_vectors where all but the first of the vectors are undef. 15119 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 15120 return Op.isUndef(); 15121 })) { 15122 SDValue In = N->getOperand(0); 15123 assert(In.getValueType().isVector() && "Must concat vectors"); 15124 15125 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 15126 if (In->getOpcode() == ISD::BITCAST && 15127 !In->getOperand(0).getValueType().isVector()) { 15128 SDValue Scalar = In->getOperand(0); 15129 15130 // If the bitcast type isn't legal, it might be a trunc of a legal type; 15131 // look through the trunc so we can still do the transform: 15132 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 15133 if (Scalar->getOpcode() == ISD::TRUNCATE && 15134 !TLI.isTypeLegal(Scalar.getValueType()) && 15135 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 15136 Scalar = Scalar->getOperand(0); 15137 15138 EVT SclTy = Scalar->getValueType(0); 15139 15140 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 15141 return SDValue(); 15142 15143 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits(); 15144 if (VNTNumElms < 2) 15145 return SDValue(); 15146 15147 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms); 15148 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 15149 return SDValue(); 15150 15151 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar); 15152 return DAG.getBitcast(VT, Res); 15153 } 15154 } 15155 15156 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 15157 // We have already tested above for an UNDEF only concatenation. 15158 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 15159 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 15160 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 15161 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 15162 }; 15163 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 15164 SmallVector<SDValue, 8> Opnds; 15165 EVT SVT = VT.getScalarType(); 15166 15167 EVT MinVT = SVT; 15168 if (!SVT.isFloatingPoint()) { 15169 // If BUILD_VECTOR are from built from integer, they may have different 15170 // operand types. Get the smallest type and truncate all operands to it. 15171 bool FoundMinVT = false; 15172 for (const SDValue &Op : N->ops()) 15173 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 15174 EVT OpSVT = Op.getOperand(0).getValueType(); 15175 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 15176 FoundMinVT = true; 15177 } 15178 assert(FoundMinVT && "Concat vector type mismatch"); 15179 } 15180 15181 for (const SDValue &Op : N->ops()) { 15182 EVT OpVT = Op.getValueType(); 15183 unsigned NumElts = OpVT.getVectorNumElements(); 15184 15185 if (ISD::UNDEF == Op.getOpcode()) 15186 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 15187 15188 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 15189 if (SVT.isFloatingPoint()) { 15190 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 15191 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 15192 } else { 15193 for (unsigned i = 0; i != NumElts; ++i) 15194 Opnds.push_back( 15195 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 15196 } 15197 } 15198 } 15199 15200 assert(VT.getVectorNumElements() == Opnds.size() && 15201 "Concat vector type mismatch"); 15202 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 15203 } 15204 15205 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 15206 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 15207 return V; 15208 15209 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 15210 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 15211 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 15212 return V; 15213 15214 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 15215 // nodes often generate nop CONCAT_VECTOR nodes. 15216 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 15217 // place the incoming vectors at the exact same location. 15218 SDValue SingleSource = SDValue(); 15219 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 15220 15221 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 15222 SDValue Op = N->getOperand(i); 15223 15224 if (Op.isUndef()) 15225 continue; 15226 15227 // Check if this is the identity extract: 15228 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 15229 return SDValue(); 15230 15231 // Find the single incoming vector for the extract_subvector. 15232 if (SingleSource.getNode()) { 15233 if (Op.getOperand(0) != SingleSource) 15234 return SDValue(); 15235 } else { 15236 SingleSource = Op.getOperand(0); 15237 15238 // Check the source type is the same as the type of the result. 15239 // If not, this concat may extend the vector, so we can not 15240 // optimize it away. 15241 if (SingleSource.getValueType() != N->getValueType(0)) 15242 return SDValue(); 15243 } 15244 15245 unsigned IdentityIndex = i * PartNumElem; 15246 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 15247 // The extract index must be constant. 15248 if (!CS) 15249 return SDValue(); 15250 15251 // Check that we are reading from the identity index. 15252 if (CS->getZExtValue() != IdentityIndex) 15253 return SDValue(); 15254 } 15255 15256 if (SingleSource.getNode()) 15257 return SingleSource; 15258 15259 return SDValue(); 15260 } 15261 15262 /// If we are extracting a subvector produced by a wide binary operator with at 15263 /// at least one operand that was the result of a vector concatenation, then try 15264 /// to use the narrow vector operands directly to avoid the concatenation and 15265 /// extraction. 15266 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) { 15267 // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share 15268 // some of these bailouts with other transforms. 15269 15270 // The extract index must be a constant, so we can map it to a concat operand. 15271 auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 15272 if (!ExtractIndex) 15273 return SDValue(); 15274 15275 // Only handle the case where we are doubling and then halving. A larger ratio 15276 // may require more than two narrow binops to replace the wide binop. 15277 EVT VT = Extract->getValueType(0); 15278 unsigned NumElems = VT.getVectorNumElements(); 15279 assert((ExtractIndex->getZExtValue() % NumElems) == 0 && 15280 "Extract index is not a multiple of the vector length."); 15281 if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2) 15282 return SDValue(); 15283 15284 // We are looking for an optionally bitcasted wide vector binary operator 15285 // feeding an extract subvector. 15286 SDValue BinOp = peekThroughBitcast(Extract->getOperand(0)); 15287 15288 // TODO: The motivating case for this transform is an x86 AVX1 target. That 15289 // target has temptingly almost legal versions of bitwise logic ops in 256-bit 15290 // flavors, but no other 256-bit integer support. This could be extended to 15291 // handle any binop, but that may require fixing/adding other folds to avoid 15292 // codegen regressions. 15293 unsigned BOpcode = BinOp.getOpcode(); 15294 if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR) 15295 return SDValue(); 15296 15297 // The binop must be a vector type, so we can chop it in half. 15298 EVT WideBVT = BinOp.getValueType(); 15299 if (!WideBVT.isVector()) 15300 return SDValue(); 15301 15302 // Bail out if the target does not support a narrower version of the binop. 15303 EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(), 15304 WideBVT.getVectorNumElements() / 2); 15305 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15306 if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT)) 15307 return SDValue(); 15308 15309 // Peek through bitcasts of the binary operator operands if needed. 15310 SDValue LHS = peekThroughBitcast(BinOp.getOperand(0)); 15311 SDValue RHS = peekThroughBitcast(BinOp.getOperand(1)); 15312 15313 // We need at least one concatenation operation of a binop operand to make 15314 // this transform worthwhile. The concat must double the input vector sizes. 15315 // TODO: Should we also handle INSERT_SUBVECTOR patterns? 15316 bool ConcatL = 15317 LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2; 15318 bool ConcatR = 15319 RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2; 15320 if (!ConcatL && !ConcatR) 15321 return SDValue(); 15322 15323 // If one of the binop operands was not the result of a concat, we must 15324 // extract a half-sized operand for our new narrow binop. We can't just reuse 15325 // the original extract index operand because we may have bitcasted. 15326 unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems; 15327 unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements(); 15328 EVT ExtBOIdxVT = Extract->getOperand(1).getValueType(); 15329 SDLoc DL(Extract); 15330 15331 // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN 15332 // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N) 15333 // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN 15334 SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum)) 15335 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 15336 BinOp.getOperand(0), 15337 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT)); 15338 15339 SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum)) 15340 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 15341 BinOp.getOperand(1), 15342 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT)); 15343 15344 SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y); 15345 return DAG.getBitcast(VT, NarrowBinOp); 15346 } 15347 15348 /// If we are extracting a subvector from a wide vector load, convert to a 15349 /// narrow load to eliminate the extraction: 15350 /// (extract_subvector (load wide vector)) --> (load narrow vector) 15351 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) { 15352 // TODO: Add support for big-endian. The offset calculation must be adjusted. 15353 if (DAG.getDataLayout().isBigEndian()) 15354 return SDValue(); 15355 15356 // TODO: The one-use check is overly conservative. Check the cost of the 15357 // extract instead or remove that condition entirely. 15358 auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0)); 15359 auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 15360 if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() || 15361 !ExtIdx) 15362 return SDValue(); 15363 15364 // The narrow load will be offset from the base address of the old load if 15365 // we are extracting from something besides index 0 (little-endian). 15366 EVT VT = Extract->getValueType(0); 15367 SDLoc DL(Extract); 15368 SDValue BaseAddr = Ld->getOperand(1); 15369 unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize(); 15370 15371 // TODO: Use "BaseIndexOffset" to make this more effective. 15372 SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL); 15373 MachineFunction &MF = DAG.getMachineFunction(); 15374 MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset, 15375 VT.getStoreSize()); 15376 SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO); 15377 DAG.makeEquivalentMemoryOrdering(Ld, NewLd); 15378 return NewLd; 15379 } 15380 15381 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 15382 EVT NVT = N->getValueType(0); 15383 SDValue V = N->getOperand(0); 15384 15385 // Extract from UNDEF is UNDEF. 15386 if (V.isUndef()) 15387 return DAG.getUNDEF(NVT); 15388 15389 if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT)) 15390 if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG)) 15391 return NarrowLoad; 15392 15393 // Combine: 15394 // (extract_subvec (concat V1, V2, ...), i) 15395 // Into: 15396 // Vi if possible 15397 // Only operand 0 is checked as 'concat' assumes all inputs of the same 15398 // type. 15399 if (V->getOpcode() == ISD::CONCAT_VECTORS && 15400 isa<ConstantSDNode>(N->getOperand(1)) && 15401 V->getOperand(0).getValueType() == NVT) { 15402 unsigned Idx = N->getConstantOperandVal(1); 15403 unsigned NumElems = NVT.getVectorNumElements(); 15404 assert((Idx % NumElems) == 0 && 15405 "IDX in concat is not a multiple of the result vector length."); 15406 return V->getOperand(Idx / NumElems); 15407 } 15408 15409 // Skip bitcasting 15410 V = peekThroughBitcast(V); 15411 15412 // If the input is a build vector. Try to make a smaller build vector. 15413 if (V->getOpcode() == ISD::BUILD_VECTOR) { 15414 if (auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))) { 15415 EVT InVT = V->getValueType(0); 15416 unsigned ExtractSize = NVT.getSizeInBits(); 15417 unsigned EltSize = InVT.getScalarSizeInBits(); 15418 // Only do this if we won't split any elements. 15419 if (ExtractSize % EltSize == 0) { 15420 unsigned NumElems = ExtractSize / EltSize; 15421 EVT ExtractVT = EVT::getVectorVT(*DAG.getContext(), 15422 InVT.getVectorElementType(), NumElems); 15423 if ((!LegalOperations || 15424 TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT)) && 15425 (!LegalTypes || TLI.isTypeLegal(ExtractVT))) { 15426 unsigned IdxVal = (Idx->getZExtValue() * NVT.getScalarSizeInBits()) / 15427 EltSize; 15428 15429 // Extract the pieces from the original build_vector. 15430 SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N), 15431 makeArrayRef(V->op_begin() + IdxVal, 15432 NumElems)); 15433 return DAG.getBitcast(NVT, BuildVec); 15434 } 15435 } 15436 } 15437 } 15438 15439 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 15440 // Handle only simple case where vector being inserted and vector 15441 // being extracted are of same size. 15442 EVT SmallVT = V->getOperand(1).getValueType(); 15443 if (!NVT.bitsEq(SmallVT)) 15444 return SDValue(); 15445 15446 // Only handle cases where both indexes are constants. 15447 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15448 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 15449 15450 if (InsIdx && ExtIdx) { 15451 // Combine: 15452 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 15453 // Into: 15454 // indices are equal or bit offsets are equal => V1 15455 // otherwise => (extract_subvec V1, ExtIdx) 15456 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() == 15457 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits()) 15458 return DAG.getBitcast(NVT, V->getOperand(1)); 15459 return DAG.getNode( 15460 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, 15461 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)), 15462 N->getOperand(1)); 15463 } 15464 } 15465 15466 if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG)) 15467 return NarrowBOp; 15468 15469 return SDValue(); 15470 } 15471 15472 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 15473 SDValue V, SelectionDAG &DAG) { 15474 SDLoc DL(V); 15475 EVT VT = V.getValueType(); 15476 15477 switch (V.getOpcode()) { 15478 default: 15479 return V; 15480 15481 case ISD::CONCAT_VECTORS: { 15482 EVT OpVT = V->getOperand(0).getValueType(); 15483 int OpSize = OpVT.getVectorNumElements(); 15484 SmallBitVector OpUsedElements(OpSize, false); 15485 bool FoundSimplification = false; 15486 SmallVector<SDValue, 4> NewOps; 15487 NewOps.reserve(V->getNumOperands()); 15488 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 15489 SDValue Op = V->getOperand(i); 15490 bool OpUsed = false; 15491 for (int j = 0; j < OpSize; ++j) 15492 if (UsedElements[i * OpSize + j]) { 15493 OpUsedElements[j] = true; 15494 OpUsed = true; 15495 } 15496 NewOps.push_back( 15497 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 15498 : DAG.getUNDEF(OpVT)); 15499 FoundSimplification |= Op == NewOps.back(); 15500 OpUsedElements.reset(); 15501 } 15502 if (FoundSimplification) 15503 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 15504 return V; 15505 } 15506 15507 case ISD::INSERT_SUBVECTOR: { 15508 SDValue BaseV = V->getOperand(0); 15509 SDValue SubV = V->getOperand(1); 15510 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 15511 if (!IdxN) 15512 return V; 15513 15514 int SubSize = SubV.getValueType().getVectorNumElements(); 15515 int Idx = IdxN->getZExtValue(); 15516 bool SubVectorUsed = false; 15517 SmallBitVector SubUsedElements(SubSize, false); 15518 for (int i = 0; i < SubSize; ++i) 15519 if (UsedElements[i + Idx]) { 15520 SubVectorUsed = true; 15521 SubUsedElements[i] = true; 15522 UsedElements[i + Idx] = false; 15523 } 15524 15525 // Now recurse on both the base and sub vectors. 15526 SDValue SimplifiedSubV = 15527 SubVectorUsed 15528 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 15529 : DAG.getUNDEF(SubV.getValueType()); 15530 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 15531 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 15532 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 15533 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 15534 return V; 15535 } 15536 } 15537 } 15538 15539 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 15540 SDValue N1, SelectionDAG &DAG) { 15541 EVT VT = SVN->getValueType(0); 15542 int NumElts = VT.getVectorNumElements(); 15543 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 15544 for (int M : SVN->getMask()) 15545 if (M >= 0 && M < NumElts) 15546 N0UsedElements[M] = true; 15547 else if (M >= NumElts) 15548 N1UsedElements[M - NumElts] = true; 15549 15550 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 15551 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 15552 if (S0 == N0 && S1 == N1) 15553 return SDValue(); 15554 15555 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 15556 } 15557 15558 static SDValue simplifyShuffleMask(ShuffleVectorSDNode *SVN, SDValue N0, 15559 SDValue N1, SelectionDAG &DAG) { 15560 auto isUndefElt = [](SDValue V, int Idx) { 15561 // TODO - handle more cases as required. 15562 if (V.getOpcode() == ISD::BUILD_VECTOR) 15563 return V.getOperand(Idx).isUndef(); 15564 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) 15565 return (Idx != 0) || V.getOperand(0).isUndef(); 15566 return false; 15567 }; 15568 15569 EVT VT = SVN->getValueType(0); 15570 unsigned NumElts = VT.getVectorNumElements(); 15571 15572 bool Changed = false; 15573 SmallVector<int, 8> NewMask; 15574 for (unsigned i = 0; i != NumElts; ++i) { 15575 int Idx = SVN->getMaskElt(i); 15576 if ((0 <= Idx && Idx < (int)NumElts && isUndefElt(N0, Idx)) || 15577 ((int)NumElts < Idx && isUndefElt(N1, Idx - NumElts))) { 15578 Changed = true; 15579 Idx = -1; 15580 } 15581 NewMask.push_back(Idx); 15582 } 15583 if (Changed) 15584 return DAG.getVectorShuffle(VT, SDLoc(SVN), N0, N1, NewMask); 15585 15586 return SDValue(); 15587 } 15588 15589 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 15590 // or turn a shuffle of a single concat into simpler shuffle then concat. 15591 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 15592 EVT VT = N->getValueType(0); 15593 unsigned NumElts = VT.getVectorNumElements(); 15594 15595 SDValue N0 = N->getOperand(0); 15596 SDValue N1 = N->getOperand(1); 15597 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 15598 15599 SmallVector<SDValue, 4> Ops; 15600 EVT ConcatVT = N0.getOperand(0).getValueType(); 15601 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 15602 unsigned NumConcats = NumElts / NumElemsPerConcat; 15603 15604 // Special case: shuffle(concat(A,B)) can be more efficiently represented 15605 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 15606 // half vector elements. 15607 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 15608 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 15609 SVN->getMask().end(), [](int i) { return i == -1; })) { 15610 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 15611 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 15612 N1 = DAG.getUNDEF(ConcatVT); 15613 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 15614 } 15615 15616 // Look at every vector that's inserted. We're looking for exact 15617 // subvector-sized copies from a concatenated vector 15618 for (unsigned I = 0; I != NumConcats; ++I) { 15619 // Make sure we're dealing with a copy. 15620 unsigned Begin = I * NumElemsPerConcat; 15621 bool AllUndef = true, NoUndef = true; 15622 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 15623 if (SVN->getMaskElt(J) >= 0) 15624 AllUndef = false; 15625 else 15626 NoUndef = false; 15627 } 15628 15629 if (NoUndef) { 15630 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 15631 return SDValue(); 15632 15633 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 15634 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 15635 return SDValue(); 15636 15637 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 15638 if (FirstElt < N0.getNumOperands()) 15639 Ops.push_back(N0.getOperand(FirstElt)); 15640 else 15641 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 15642 15643 } else if (AllUndef) { 15644 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 15645 } else { // Mixed with general masks and undefs, can't do optimization. 15646 return SDValue(); 15647 } 15648 } 15649 15650 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 15651 } 15652 15653 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 15654 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 15655 // 15656 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always 15657 // a simplification in some sense, but it isn't appropriate in general: some 15658 // BUILD_VECTORs are substantially cheaper than others. The general case 15659 // of a BUILD_VECTOR requires inserting each element individually (or 15660 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of 15661 // all constants is a single constant pool load. A BUILD_VECTOR where each 15662 // element is identical is a splat. A BUILD_VECTOR where most of the operands 15663 // are undef lowers to a small number of element insertions. 15664 // 15665 // To deal with this, we currently use a bunch of mostly arbitrary heuristics. 15666 // We don't fold shuffles where one side is a non-zero constant, and we don't 15667 // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate 15668 // non-constant operands. This seems to work out reasonably well in practice. 15669 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN, 15670 SelectionDAG &DAG, 15671 const TargetLowering &TLI) { 15672 EVT VT = SVN->getValueType(0); 15673 unsigned NumElts = VT.getVectorNumElements(); 15674 SDValue N0 = SVN->getOperand(0); 15675 SDValue N1 = SVN->getOperand(1); 15676 15677 if (!N0->hasOneUse() || !N1->hasOneUse()) 15678 return SDValue(); 15679 15680 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as 15681 // discussed above. 15682 if (!N1.isUndef()) { 15683 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode()); 15684 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode()); 15685 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode())) 15686 return SDValue(); 15687 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode())) 15688 return SDValue(); 15689 } 15690 15691 // If both inputs are splats of the same value then we can safely merge this 15692 // to a single BUILD_VECTOR with undef elements based on the shuffle mask. 15693 bool IsSplat = false; 15694 auto *BV0 = dyn_cast<BuildVectorSDNode>(N0); 15695 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 15696 if (BV0 && BV1) 15697 if (SDValue Splat0 = BV0->getSplatValue()) 15698 IsSplat = (Splat0 == BV1->getSplatValue()); 15699 15700 SmallVector<SDValue, 8> Ops; 15701 SmallSet<SDValue, 16> DuplicateOps; 15702 for (int M : SVN->getMask()) { 15703 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 15704 if (M >= 0) { 15705 int Idx = M < (int)NumElts ? M : M - NumElts; 15706 SDValue &S = (M < (int)NumElts ? N0 : N1); 15707 if (S.getOpcode() == ISD::BUILD_VECTOR) { 15708 Op = S.getOperand(Idx); 15709 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) { 15710 assert(Idx == 0 && "Unexpected SCALAR_TO_VECTOR operand index."); 15711 Op = S.getOperand(0); 15712 } else { 15713 // Operand can't be combined - bail out. 15714 return SDValue(); 15715 } 15716 } 15717 15718 // Don't duplicate a non-constant BUILD_VECTOR operand unless we're 15719 // generating a splat; semantically, this is fine, but it's likely to 15720 // generate low-quality code if the target can't reconstruct an appropriate 15721 // shuffle. 15722 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op)) 15723 if (!IsSplat && !DuplicateOps.insert(Op).second) 15724 return SDValue(); 15725 15726 Ops.push_back(Op); 15727 } 15728 15729 // BUILD_VECTOR requires all inputs to be of the same type, find the 15730 // maximum type and extend them all. 15731 EVT SVT = VT.getScalarType(); 15732 if (SVT.isInteger()) 15733 for (SDValue &Op : Ops) 15734 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 15735 if (SVT != VT.getScalarType()) 15736 for (SDValue &Op : Ops) 15737 Op = TLI.isZExtFree(Op.getValueType(), SVT) 15738 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT) 15739 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT); 15740 return DAG.getBuildVector(VT, SDLoc(SVN), Ops); 15741 } 15742 15743 // Match shuffles that can be converted to any_vector_extend_in_reg. 15744 // This is often generated during legalization. 15745 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src)) 15746 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case. 15747 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN, 15748 SelectionDAG &DAG, 15749 const TargetLowering &TLI, 15750 bool LegalOperations, 15751 bool LegalTypes) { 15752 EVT VT = SVN->getValueType(0); 15753 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 15754 15755 // TODO Add support for big-endian when we have a test case. 15756 if (!VT.isInteger() || IsBigEndian) 15757 return SDValue(); 15758 15759 unsigned NumElts = VT.getVectorNumElements(); 15760 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 15761 ArrayRef<int> Mask = SVN->getMask(); 15762 SDValue N0 = SVN->getOperand(0); 15763 15764 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32)) 15765 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) { 15766 for (unsigned i = 0; i != NumElts; ++i) { 15767 if (Mask[i] < 0) 15768 continue; 15769 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale)) 15770 continue; 15771 return false; 15772 } 15773 return true; 15774 }; 15775 15776 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for 15777 // power-of-2 extensions as they are the most likely. 15778 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) { 15779 // Check for non power of 2 vector sizes 15780 if (NumElts % Scale != 0) 15781 continue; 15782 if (!isAnyExtend(Scale)) 15783 continue; 15784 15785 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale); 15786 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale); 15787 if (!LegalTypes || TLI.isTypeLegal(OutVT)) 15788 if (!LegalOperations || 15789 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT)) 15790 return DAG.getBitcast(VT, 15791 DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT)); 15792 } 15793 15794 return SDValue(); 15795 } 15796 15797 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of 15798 // each source element of a large type into the lowest elements of a smaller 15799 // destination type. This is often generated during legalization. 15800 // If the source node itself was a '*_extend_vector_inreg' node then we should 15801 // then be able to remove it. 15802 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, 15803 SelectionDAG &DAG) { 15804 EVT VT = SVN->getValueType(0); 15805 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 15806 15807 // TODO Add support for big-endian when we have a test case. 15808 if (!VT.isInteger() || IsBigEndian) 15809 return SDValue(); 15810 15811 SDValue N0 = peekThroughBitcast(SVN->getOperand(0)); 15812 15813 unsigned Opcode = N0.getOpcode(); 15814 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG && 15815 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG && 15816 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG) 15817 return SDValue(); 15818 15819 SDValue N00 = N0.getOperand(0); 15820 ArrayRef<int> Mask = SVN->getMask(); 15821 unsigned NumElts = VT.getVectorNumElements(); 15822 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 15823 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits(); 15824 unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits(); 15825 15826 if (ExtDstSizeInBits % ExtSrcSizeInBits != 0) 15827 return SDValue(); 15828 unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits; 15829 15830 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1> 15831 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1> 15832 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1> 15833 auto isTruncate = [&Mask, &NumElts](unsigned Scale) { 15834 for (unsigned i = 0; i != NumElts; ++i) { 15835 if (Mask[i] < 0) 15836 continue; 15837 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale)) 15838 continue; 15839 return false; 15840 } 15841 return true; 15842 }; 15843 15844 // At the moment we just handle the case where we've truncated back to the 15845 // same size as before the extension. 15846 // TODO: handle more extension/truncation cases as cases arise. 15847 if (EltSizeInBits != ExtSrcSizeInBits) 15848 return SDValue(); 15849 15850 // We can remove *extend_vector_inreg only if the truncation happens at 15851 // the same scale as the extension. 15852 if (isTruncate(ExtScale)) 15853 return DAG.getBitcast(VT, N00); 15854 15855 return SDValue(); 15856 } 15857 15858 // Combine shuffles of splat-shuffles of the form: 15859 // shuffle (shuffle V, undef, splat-mask), undef, M 15860 // If splat-mask contains undef elements, we need to be careful about 15861 // introducing undef's in the folded mask which are not the result of composing 15862 // the masks of the shuffles. 15863 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask, 15864 ShuffleVectorSDNode *Splat, 15865 SelectionDAG &DAG) { 15866 ArrayRef<int> SplatMask = Splat->getMask(); 15867 assert(UserMask.size() == SplatMask.size() && "Mask length mismatch"); 15868 15869 // Prefer simplifying to the splat-shuffle, if possible. This is legal if 15870 // every undef mask element in the splat-shuffle has a corresponding undef 15871 // element in the user-shuffle's mask or if the composition of mask elements 15872 // would result in undef. 15873 // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask): 15874 // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u] 15875 // In this case it is not legal to simplify to the splat-shuffle because we 15876 // may be exposing the users of the shuffle an undef element at index 1 15877 // which was not there before the combine. 15878 // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u] 15879 // In this case the composition of masks yields SplatMask, so it's ok to 15880 // simplify to the splat-shuffle. 15881 // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u] 15882 // In this case the composed mask includes all undef elements of SplatMask 15883 // and in addition sets element zero to undef. It is safe to simplify to 15884 // the splat-shuffle. 15885 auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask, 15886 ArrayRef<int> SplatMask) { 15887 for (unsigned i = 0, e = UserMask.size(); i != e; ++i) 15888 if (UserMask[i] != -1 && SplatMask[i] == -1 && 15889 SplatMask[UserMask[i]] != -1) 15890 return false; 15891 return true; 15892 }; 15893 if (CanSimplifyToExistingSplat(UserMask, SplatMask)) 15894 return SDValue(Splat, 0); 15895 15896 // Create a new shuffle with a mask that is composed of the two shuffles' 15897 // masks. 15898 SmallVector<int, 32> NewMask; 15899 for (int Idx : UserMask) 15900 NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]); 15901 15902 return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat), 15903 Splat->getOperand(0), Splat->getOperand(1), 15904 NewMask); 15905 } 15906 15907 /// If the shuffle mask is taking exactly one element from the first vector 15908 /// operand and passing through all other elements from the second vector 15909 /// operand, return the index of the mask element that is choosing an element 15910 /// from the first operand. Otherwise, return -1. 15911 static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) { 15912 int MaskSize = Mask.size(); 15913 int EltFromOp0 = -1; 15914 // TODO: This does not match if there are undef elements in the shuffle mask. 15915 // Should we ignore undefs in the shuffle mask instead? The trade-off is 15916 // removing an instruction (a shuffle), but losing the knowledge that some 15917 // vector lanes are not needed. 15918 for (int i = 0; i != MaskSize; ++i) { 15919 if (Mask[i] >= 0 && Mask[i] < MaskSize) { 15920 // We're looking for a shuffle of exactly one element from operand 0. 15921 if (EltFromOp0 != -1) 15922 return -1; 15923 EltFromOp0 = i; 15924 } else if (Mask[i] != i + MaskSize) { 15925 // Nothing from operand 1 can change lanes. 15926 return -1; 15927 } 15928 } 15929 return EltFromOp0; 15930 } 15931 15932 /// If a shuffle inserts exactly one element from a source vector operand into 15933 /// another vector operand and we can access the specified element as a scalar, 15934 /// then we can eliminate the shuffle. 15935 static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf, 15936 SelectionDAG &DAG) { 15937 // First, check if we are taking one element of a vector and shuffling that 15938 // element into another vector. 15939 ArrayRef<int> Mask = Shuf->getMask(); 15940 SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end()); 15941 SDValue Op0 = Shuf->getOperand(0); 15942 SDValue Op1 = Shuf->getOperand(1); 15943 int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask); 15944 if (ShufOp0Index == -1) { 15945 // Commute mask and check again. 15946 ShuffleVectorSDNode::commuteMask(CommutedMask); 15947 ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask); 15948 if (ShufOp0Index == -1) 15949 return SDValue(); 15950 // Commute operands to match the commuted shuffle mask. 15951 std::swap(Op0, Op1); 15952 Mask = CommutedMask; 15953 } 15954 15955 // The shuffle inserts exactly one element from operand 0 into operand 1. 15956 // Now see if we can access that element as a scalar via a real insert element 15957 // instruction. 15958 // TODO: We can try harder to locate the element as a scalar. Examples: it 15959 // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant. 15960 assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() && 15961 "Shuffle mask value must be from operand 0"); 15962 if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT) 15963 return SDValue(); 15964 15965 auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2)); 15966 if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index]) 15967 return SDValue(); 15968 15969 // There's an existing insertelement with constant insertion index, so we 15970 // don't need to check the legality/profitability of a replacement operation 15971 // that differs at most in the constant value. The target should be able to 15972 // lower any of those in a similar way. If not, legalization will expand this 15973 // to a scalar-to-vector plus shuffle. 15974 // 15975 // Note that the shuffle may move the scalar from the position that the insert 15976 // element used. Therefore, our new insert element occurs at the shuffle's 15977 // mask index value, not the insert's index value. 15978 // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C' 15979 SDValue NewInsIndex = DAG.getConstant(ShufOp0Index, SDLoc(Shuf), 15980 Op0.getOperand(2).getValueType()); 15981 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(), 15982 Op1, Op0.getOperand(1), NewInsIndex); 15983 } 15984 15985 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 15986 EVT VT = N->getValueType(0); 15987 unsigned NumElts = VT.getVectorNumElements(); 15988 15989 SDValue N0 = N->getOperand(0); 15990 SDValue N1 = N->getOperand(1); 15991 15992 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 15993 15994 // Canonicalize shuffle undef, undef -> undef 15995 if (N0.isUndef() && N1.isUndef()) 15996 return DAG.getUNDEF(VT); 15997 15998 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 15999 16000 // Canonicalize shuffle v, v -> v, undef 16001 if (N0 == N1) { 16002 SmallVector<int, 8> NewMask; 16003 for (unsigned i = 0; i != NumElts; ++i) { 16004 int Idx = SVN->getMaskElt(i); 16005 if (Idx >= (int)NumElts) Idx -= NumElts; 16006 NewMask.push_back(Idx); 16007 } 16008 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 16009 } 16010 16011 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 16012 if (N0.isUndef()) 16013 return DAG.getCommutedVectorShuffle(*SVN); 16014 16015 // Remove references to rhs if it is undef 16016 if (N1.isUndef()) { 16017 bool Changed = false; 16018 SmallVector<int, 8> NewMask; 16019 for (unsigned i = 0; i != NumElts; ++i) { 16020 int Idx = SVN->getMaskElt(i); 16021 if (Idx >= (int)NumElts) { 16022 Idx = -1; 16023 Changed = true; 16024 } 16025 NewMask.push_back(Idx); 16026 } 16027 if (Changed) 16028 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 16029 } 16030 16031 // Simplify shuffle mask if a referenced element is UNDEF. 16032 if (SDValue V = simplifyShuffleMask(SVN, N0, N1, DAG)) 16033 return V; 16034 16035 if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG)) 16036 return InsElt; 16037 16038 // A shuffle of a single vector that is a splat can always be folded. 16039 if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0)) 16040 if (N1->isUndef() && N0Shuf->isSplat()) 16041 return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG); 16042 16043 // If it is a splat, check if the argument vector is another splat or a 16044 // build_vector. 16045 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 16046 SDNode *V = N0.getNode(); 16047 16048 // If this is a bit convert that changes the element type of the vector but 16049 // not the number of vector elements, look through it. Be careful not to 16050 // look though conversions that change things like v4f32 to v2f64. 16051 if (V->getOpcode() == ISD::BITCAST) { 16052 SDValue ConvInput = V->getOperand(0); 16053 if (ConvInput.getValueType().isVector() && 16054 ConvInput.getValueType().getVectorNumElements() == NumElts) 16055 V = ConvInput.getNode(); 16056 } 16057 16058 if (V->getOpcode() == ISD::BUILD_VECTOR) { 16059 assert(V->getNumOperands() == NumElts && 16060 "BUILD_VECTOR has wrong number of operands"); 16061 SDValue Base; 16062 bool AllSame = true; 16063 for (unsigned i = 0; i != NumElts; ++i) { 16064 if (!V->getOperand(i).isUndef()) { 16065 Base = V->getOperand(i); 16066 break; 16067 } 16068 } 16069 // Splat of <u, u, u, u>, return <u, u, u, u> 16070 if (!Base.getNode()) 16071 return N0; 16072 for (unsigned i = 0; i != NumElts; ++i) { 16073 if (V->getOperand(i) != Base) { 16074 AllSame = false; 16075 break; 16076 } 16077 } 16078 // Splat of <x, x, x, x>, return <x, x, x, x> 16079 if (AllSame) 16080 return N0; 16081 16082 // Canonicalize any other splat as a build_vector. 16083 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 16084 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 16085 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 16086 16087 // We may have jumped through bitcasts, so the type of the 16088 // BUILD_VECTOR may not match the type of the shuffle. 16089 if (V->getValueType(0) != VT) 16090 NewBV = DAG.getBitcast(VT, NewBV); 16091 return NewBV; 16092 } 16093 } 16094 16095 // There are various patterns used to build up a vector from smaller vectors, 16096 // subvectors, or elements. Scan chains of these and replace unused insertions 16097 // or components with undef. 16098 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 16099 return S; 16100 16101 // Match shuffles that can be converted to any_vector_extend_in_reg. 16102 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations, LegalTypes)) 16103 return V; 16104 16105 // Combine "truncate_vector_in_reg" style shuffles. 16106 if (SDValue V = combineTruncationShuffle(SVN, DAG)) 16107 return V; 16108 16109 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 16110 Level < AfterLegalizeVectorOps && 16111 (N1.isUndef() || 16112 (N1.getOpcode() == ISD::CONCAT_VECTORS && 16113 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 16114 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 16115 return V; 16116 } 16117 16118 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 16119 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 16120 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 16121 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI)) 16122 return Res; 16123 16124 // If this shuffle only has a single input that is a bitcasted shuffle, 16125 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 16126 // back to their original types. 16127 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 16128 N1.isUndef() && Level < AfterLegalizeVectorOps && 16129 TLI.isTypeLegal(VT)) { 16130 16131 // Peek through the bitcast only if there is one user. 16132 SDValue BC0 = N0; 16133 while (BC0.getOpcode() == ISD::BITCAST) { 16134 if (!BC0.hasOneUse()) 16135 break; 16136 BC0 = BC0.getOperand(0); 16137 } 16138 16139 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 16140 if (Scale == 1) 16141 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 16142 16143 SmallVector<int, 8> NewMask; 16144 for (int M : Mask) 16145 for (int s = 0; s != Scale; ++s) 16146 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 16147 return NewMask; 16148 }; 16149 16150 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 16151 EVT SVT = VT.getScalarType(); 16152 EVT InnerVT = BC0->getValueType(0); 16153 EVT InnerSVT = InnerVT.getScalarType(); 16154 16155 // Determine which shuffle works with the smaller scalar type. 16156 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 16157 EVT ScaleSVT = ScaleVT.getScalarType(); 16158 16159 if (TLI.isTypeLegal(ScaleVT) && 16160 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 16161 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 16162 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 16163 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 16164 16165 // Scale the shuffle masks to the smaller scalar type. 16166 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 16167 SmallVector<int, 8> InnerMask = 16168 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 16169 SmallVector<int, 8> OuterMask = 16170 ScaleShuffleMask(SVN->getMask(), OuterScale); 16171 16172 // Merge the shuffle masks. 16173 SmallVector<int, 8> NewMask; 16174 for (int M : OuterMask) 16175 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 16176 16177 // Test for shuffle mask legality over both commutations. 16178 SDValue SV0 = BC0->getOperand(0); 16179 SDValue SV1 = BC0->getOperand(1); 16180 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 16181 if (!LegalMask) { 16182 std::swap(SV0, SV1); 16183 ShuffleVectorSDNode::commuteMask(NewMask); 16184 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 16185 } 16186 16187 if (LegalMask) { 16188 SV0 = DAG.getBitcast(ScaleVT, SV0); 16189 SV1 = DAG.getBitcast(ScaleVT, SV1); 16190 return DAG.getBitcast( 16191 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 16192 } 16193 } 16194 } 16195 } 16196 16197 // Canonicalize shuffles according to rules: 16198 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 16199 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 16200 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 16201 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 16202 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 16203 TLI.isTypeLegal(VT)) { 16204 // The incoming shuffle must be of the same type as the result of the 16205 // current shuffle. 16206 assert(N1->getOperand(0).getValueType() == VT && 16207 "Shuffle types don't match"); 16208 16209 SDValue SV0 = N1->getOperand(0); 16210 SDValue SV1 = N1->getOperand(1); 16211 bool HasSameOp0 = N0 == SV0; 16212 bool IsSV1Undef = SV1.isUndef(); 16213 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 16214 // Commute the operands of this shuffle so that next rule 16215 // will trigger. 16216 return DAG.getCommutedVectorShuffle(*SVN); 16217 } 16218 16219 // Try to fold according to rules: 16220 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 16221 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 16222 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 16223 // Don't try to fold shuffles with illegal type. 16224 // Only fold if this shuffle is the only user of the other shuffle. 16225 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 16226 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 16227 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 16228 16229 // Don't try to fold splats; they're likely to simplify somehow, or they 16230 // might be free. 16231 if (OtherSV->isSplat()) 16232 return SDValue(); 16233 16234 // The incoming shuffle must be of the same type as the result of the 16235 // current shuffle. 16236 assert(OtherSV->getOperand(0).getValueType() == VT && 16237 "Shuffle types don't match"); 16238 16239 SDValue SV0, SV1; 16240 SmallVector<int, 4> Mask; 16241 // Compute the combined shuffle mask for a shuffle with SV0 as the first 16242 // operand, and SV1 as the second operand. 16243 for (unsigned i = 0; i != NumElts; ++i) { 16244 int Idx = SVN->getMaskElt(i); 16245 if (Idx < 0) { 16246 // Propagate Undef. 16247 Mask.push_back(Idx); 16248 continue; 16249 } 16250 16251 SDValue CurrentVec; 16252 if (Idx < (int)NumElts) { 16253 // This shuffle index refers to the inner shuffle N0. Lookup the inner 16254 // shuffle mask to identify which vector is actually referenced. 16255 Idx = OtherSV->getMaskElt(Idx); 16256 if (Idx < 0) { 16257 // Propagate Undef. 16258 Mask.push_back(Idx); 16259 continue; 16260 } 16261 16262 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 16263 : OtherSV->getOperand(1); 16264 } else { 16265 // This shuffle index references an element within N1. 16266 CurrentVec = N1; 16267 } 16268 16269 // Simple case where 'CurrentVec' is UNDEF. 16270 if (CurrentVec.isUndef()) { 16271 Mask.push_back(-1); 16272 continue; 16273 } 16274 16275 // Canonicalize the shuffle index. We don't know yet if CurrentVec 16276 // will be the first or second operand of the combined shuffle. 16277 Idx = Idx % NumElts; 16278 if (!SV0.getNode() || SV0 == CurrentVec) { 16279 // Ok. CurrentVec is the left hand side. 16280 // Update the mask accordingly. 16281 SV0 = CurrentVec; 16282 Mask.push_back(Idx); 16283 continue; 16284 } 16285 16286 // Bail out if we cannot convert the shuffle pair into a single shuffle. 16287 if (SV1.getNode() && SV1 != CurrentVec) 16288 return SDValue(); 16289 16290 // Ok. CurrentVec is the right hand side. 16291 // Update the mask accordingly. 16292 SV1 = CurrentVec; 16293 Mask.push_back(Idx + NumElts); 16294 } 16295 16296 // Check if all indices in Mask are Undef. In case, propagate Undef. 16297 bool isUndefMask = true; 16298 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 16299 isUndefMask &= Mask[i] < 0; 16300 16301 if (isUndefMask) 16302 return DAG.getUNDEF(VT); 16303 16304 if (!SV0.getNode()) 16305 SV0 = DAG.getUNDEF(VT); 16306 if (!SV1.getNode()) 16307 SV1 = DAG.getUNDEF(VT); 16308 16309 // Avoid introducing shuffles with illegal mask. 16310 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 16311 ShuffleVectorSDNode::commuteMask(Mask); 16312 16313 if (!TLI.isShuffleMaskLegal(Mask, VT)) 16314 return SDValue(); 16315 16316 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 16317 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 16318 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 16319 std::swap(SV0, SV1); 16320 } 16321 16322 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 16323 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 16324 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 16325 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask); 16326 } 16327 16328 return SDValue(); 16329 } 16330 16331 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 16332 SDValue InVal = N->getOperand(0); 16333 EVT VT = N->getValueType(0); 16334 16335 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 16336 // with a VECTOR_SHUFFLE and possible truncate. 16337 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 16338 SDValue InVec = InVal->getOperand(0); 16339 SDValue EltNo = InVal->getOperand(1); 16340 auto InVecT = InVec.getValueType(); 16341 if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) { 16342 SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1); 16343 int Elt = C0->getZExtValue(); 16344 NewMask[0] = Elt; 16345 SDValue Val; 16346 // If we have an implict truncate do truncate here as long as it's legal. 16347 // if it's not legal, this should 16348 if (VT.getScalarType() != InVal.getValueType() && 16349 InVal.getValueType().isScalarInteger() && 16350 isTypeLegal(VT.getScalarType())) { 16351 Val = 16352 DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal); 16353 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val); 16354 } 16355 if (VT.getScalarType() == InVecT.getScalarType() && 16356 VT.getVectorNumElements() <= InVecT.getVectorNumElements() && 16357 TLI.isShuffleMaskLegal(NewMask, VT)) { 16358 Val = DAG.getVectorShuffle(InVecT, SDLoc(N), InVec, 16359 DAG.getUNDEF(InVecT), NewMask); 16360 // If the initial vector is the correct size this shuffle is a 16361 // valid result. 16362 if (VT == InVecT) 16363 return Val; 16364 // If not we must truncate the vector. 16365 if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) { 16366 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 16367 SDValue ZeroIdx = DAG.getConstant(0, SDLoc(N), IdxTy); 16368 EVT SubVT = 16369 EVT::getVectorVT(*DAG.getContext(), InVecT.getVectorElementType(), 16370 VT.getVectorNumElements()); 16371 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, Val, 16372 ZeroIdx); 16373 return Val; 16374 } 16375 } 16376 } 16377 } 16378 16379 return SDValue(); 16380 } 16381 16382 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 16383 EVT VT = N->getValueType(0); 16384 SDValue N0 = N->getOperand(0); 16385 SDValue N1 = N->getOperand(1); 16386 SDValue N2 = N->getOperand(2); 16387 16388 // If inserting an UNDEF, just return the original vector. 16389 if (N1.isUndef()) 16390 return N0; 16391 16392 // For nested INSERT_SUBVECTORs, attempt to combine inner node first to allow 16393 // us to pull BITCASTs from input to output. 16394 if (N0.hasOneUse() && N0->getOpcode() == ISD::INSERT_SUBVECTOR) 16395 if (SDValue NN0 = visitINSERT_SUBVECTOR(N0.getNode())) 16396 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, NN0, N1, N2); 16397 16398 // If this is an insert of an extracted vector into an undef vector, we can 16399 // just use the input to the extract. 16400 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 16401 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT) 16402 return N1.getOperand(0); 16403 16404 // If we are inserting a bitcast value into an undef, with the same 16405 // number of elements, just use the bitcast input of the extract. 16406 // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 -> 16407 // BITCAST (INSERT_SUBVECTOR UNDEF N1 N2) 16408 if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST && 16409 N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR && 16410 N1.getOperand(0).getOperand(1) == N2 && 16411 N1.getOperand(0).getOperand(0).getValueType().getVectorNumElements() == 16412 VT.getVectorNumElements() && 16413 N1.getOperand(0).getOperand(0).getValueType().getSizeInBits() == 16414 VT.getSizeInBits()) { 16415 return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0)); 16416 } 16417 16418 // If both N1 and N2 are bitcast values on which insert_subvector 16419 // would makes sense, pull the bitcast through. 16420 // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 -> 16421 // BITCAST (INSERT_SUBVECTOR N0 N1 N2) 16422 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) { 16423 SDValue CN0 = N0.getOperand(0); 16424 SDValue CN1 = N1.getOperand(0); 16425 if (CN0.getValueType().getVectorElementType() == 16426 CN1.getValueType().getVectorElementType() && 16427 CN0.getValueType().getVectorNumElements() == 16428 VT.getVectorNumElements()) { 16429 SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), 16430 CN0.getValueType(), CN0, CN1, N2); 16431 return DAG.getBitcast(VT, NewINSERT); 16432 } 16433 } 16434 16435 // Combine INSERT_SUBVECTORs where we are inserting to the same index. 16436 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) 16437 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) 16438 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && 16439 N0.getOperand(1).getValueType() == N1.getValueType() && 16440 N0.getOperand(2) == N2) 16441 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), 16442 N1, N2); 16443 16444 if (!isa<ConstantSDNode>(N2)) 16445 return SDValue(); 16446 16447 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue(); 16448 16449 // Canonicalize insert_subvector dag nodes. 16450 // Example: 16451 // (insert_subvector (insert_subvector A, Idx0), Idx1) 16452 // -> (insert_subvector (insert_subvector A, Idx1), Idx0) 16453 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() && 16454 N1.getValueType() == N0.getOperand(1).getValueType() && 16455 isa<ConstantSDNode>(N0.getOperand(2))) { 16456 unsigned OtherIdx = N0.getConstantOperandVal(2); 16457 if (InsIdx < OtherIdx) { 16458 // Swap nodes. 16459 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, 16460 N0.getOperand(0), N1, N2); 16461 AddToWorklist(NewOp.getNode()); 16462 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()), 16463 VT, NewOp, N0.getOperand(1), N0.getOperand(2)); 16464 } 16465 } 16466 16467 // If the input vector is a concatenation, and the insert replaces 16468 // one of the pieces, we can optimize into a single concat_vectors. 16469 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() && 16470 N0.getOperand(0).getValueType() == N1.getValueType()) { 16471 unsigned Factor = N1.getValueType().getVectorNumElements(); 16472 16473 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end()); 16474 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1; 16475 16476 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 16477 } 16478 16479 return SDValue(); 16480 } 16481 16482 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 16483 SDValue N0 = N->getOperand(0); 16484 16485 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 16486 if (N0->getOpcode() == ISD::FP16_TO_FP) 16487 return N0->getOperand(0); 16488 16489 return SDValue(); 16490 } 16491 16492 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 16493 SDValue N0 = N->getOperand(0); 16494 16495 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 16496 if (N0->getOpcode() == ISD::AND) { 16497 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 16498 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 16499 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 16500 N0.getOperand(0)); 16501 } 16502 } 16503 16504 return SDValue(); 16505 } 16506 16507 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 16508 /// with the destination vector and a zero vector. 16509 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 16510 /// vector_shuffle V, Zero, <0, 4, 2, 4> 16511 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 16512 assert(N->getOpcode() == ISD::AND && "Unexpected opcode!"); 16513 16514 EVT VT = N->getValueType(0); 16515 SDValue LHS = N->getOperand(0); 16516 SDValue RHS = peekThroughBitcast(N->getOperand(1)); 16517 SDLoc DL(N); 16518 16519 // Make sure we're not running after operation legalization where it 16520 // may have custom lowered the vector shuffles. 16521 if (LegalOperations) 16522 return SDValue(); 16523 16524 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 16525 return SDValue(); 16526 16527 EVT RVT = RHS.getValueType(); 16528 unsigned NumElts = RHS.getNumOperands(); 16529 16530 // Attempt to create a valid clear mask, splitting the mask into 16531 // sub elements and checking to see if each is 16532 // all zeros or all ones - suitable for shuffle masking. 16533 auto BuildClearMask = [&](int Split) { 16534 int NumSubElts = NumElts * Split; 16535 int NumSubBits = RVT.getScalarSizeInBits() / Split; 16536 16537 SmallVector<int, 8> Indices; 16538 for (int i = 0; i != NumSubElts; ++i) { 16539 int EltIdx = i / Split; 16540 int SubIdx = i % Split; 16541 SDValue Elt = RHS.getOperand(EltIdx); 16542 if (Elt.isUndef()) { 16543 Indices.push_back(-1); 16544 continue; 16545 } 16546 16547 APInt Bits; 16548 if (isa<ConstantSDNode>(Elt)) 16549 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 16550 else if (isa<ConstantFPSDNode>(Elt)) 16551 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 16552 else 16553 return SDValue(); 16554 16555 // Extract the sub element from the constant bit mask. 16556 if (DAG.getDataLayout().isBigEndian()) { 16557 Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits); 16558 } else { 16559 Bits.lshrInPlace(SubIdx * NumSubBits); 16560 } 16561 16562 if (Split > 1) 16563 Bits = Bits.trunc(NumSubBits); 16564 16565 if (Bits.isAllOnesValue()) 16566 Indices.push_back(i); 16567 else if (Bits == 0) 16568 Indices.push_back(i + NumSubElts); 16569 else 16570 return SDValue(); 16571 } 16572 16573 // Let's see if the target supports this vector_shuffle. 16574 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 16575 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 16576 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 16577 return SDValue(); 16578 16579 SDValue Zero = DAG.getConstant(0, DL, ClearVT); 16580 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL, 16581 DAG.getBitcast(ClearVT, LHS), 16582 Zero, Indices)); 16583 }; 16584 16585 // Determine maximum split level (byte level masking). 16586 int MaxSplit = 1; 16587 if (RVT.getScalarSizeInBits() % 8 == 0) 16588 MaxSplit = RVT.getScalarSizeInBits() / 8; 16589 16590 for (int Split = 1; Split <= MaxSplit; ++Split) 16591 if (RVT.getScalarSizeInBits() % Split == 0) 16592 if (SDValue S = BuildClearMask(Split)) 16593 return S; 16594 16595 return SDValue(); 16596 } 16597 16598 /// Visit a binary vector operation, like ADD. 16599 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 16600 assert(N->getValueType(0).isVector() && 16601 "SimplifyVBinOp only works on vectors!"); 16602 16603 SDValue LHS = N->getOperand(0); 16604 SDValue RHS = N->getOperand(1); 16605 SDValue Ops[] = {LHS, RHS}; 16606 16607 // See if we can constant fold the vector operation. 16608 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 16609 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 16610 return Fold; 16611 16612 // Type legalization might introduce new shuffles in the DAG. 16613 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 16614 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 16615 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 16616 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 16617 LHS.getOperand(1).isUndef() && 16618 RHS.getOperand(1).isUndef()) { 16619 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 16620 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 16621 16622 if (SVN0->getMask().equals(SVN1->getMask())) { 16623 EVT VT = N->getValueType(0); 16624 SDValue UndefVector = LHS.getOperand(1); 16625 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 16626 LHS.getOperand(0), RHS.getOperand(0), 16627 N->getFlags()); 16628 AddUsersToWorklist(N); 16629 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 16630 SVN0->getMask()); 16631 } 16632 } 16633 16634 return SDValue(); 16635 } 16636 16637 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 16638 SDValue N2) { 16639 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 16640 16641 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 16642 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 16643 16644 // If we got a simplified select_cc node back from SimplifySelectCC, then 16645 // break it down into a new SETCC node, and a new SELECT node, and then return 16646 // the SELECT node, since we were called with a SELECT node. 16647 if (SCC.getNode()) { 16648 // Check to see if we got a select_cc back (to turn into setcc/select). 16649 // Otherwise, just return whatever node we got back, like fabs. 16650 if (SCC.getOpcode() == ISD::SELECT_CC) { 16651 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 16652 N0.getValueType(), 16653 SCC.getOperand(0), SCC.getOperand(1), 16654 SCC.getOperand(4)); 16655 AddToWorklist(SETCC.getNode()); 16656 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 16657 SCC.getOperand(2), SCC.getOperand(3)); 16658 } 16659 16660 return SCC; 16661 } 16662 return SDValue(); 16663 } 16664 16665 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 16666 /// being selected between, see if we can simplify the select. Callers of this 16667 /// should assume that TheSelect is deleted if this returns true. As such, they 16668 /// should return the appropriate thing (e.g. the node) back to the top-level of 16669 /// the DAG combiner loop to avoid it being looked at. 16670 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 16671 SDValue RHS) { 16672 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 16673 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 16674 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 16675 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 16676 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 16677 SDValue Sqrt = RHS; 16678 ISD::CondCode CC; 16679 SDValue CmpLHS; 16680 const ConstantFPSDNode *Zero = nullptr; 16681 16682 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 16683 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 16684 CmpLHS = TheSelect->getOperand(0); 16685 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 16686 } else { 16687 // SELECT or VSELECT 16688 SDValue Cmp = TheSelect->getOperand(0); 16689 if (Cmp.getOpcode() == ISD::SETCC) { 16690 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 16691 CmpLHS = Cmp.getOperand(0); 16692 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 16693 } 16694 } 16695 if (Zero && Zero->isZero() && 16696 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 16697 CC == ISD::SETULT || CC == ISD::SETLT)) { 16698 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 16699 CombineTo(TheSelect, Sqrt); 16700 return true; 16701 } 16702 } 16703 } 16704 // Cannot simplify select with vector condition 16705 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 16706 16707 // If this is a select from two identical things, try to pull the operation 16708 // through the select. 16709 if (LHS.getOpcode() != RHS.getOpcode() || 16710 !LHS.hasOneUse() || !RHS.hasOneUse()) 16711 return false; 16712 16713 // If this is a load and the token chain is identical, replace the select 16714 // of two loads with a load through a select of the address to load from. 16715 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 16716 // constants have been dropped into the constant pool. 16717 if (LHS.getOpcode() == ISD::LOAD) { 16718 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 16719 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 16720 16721 // Token chains must be identical. 16722 if (LHS.getOperand(0) != RHS.getOperand(0) || 16723 // Do not let this transformation reduce the number of volatile loads. 16724 LLD->isVolatile() || RLD->isVolatile() || 16725 // FIXME: If either is a pre/post inc/dec load, 16726 // we'd need to split out the address adjustment. 16727 LLD->isIndexed() || RLD->isIndexed() || 16728 // If this is an EXTLOAD, the VT's must match. 16729 LLD->getMemoryVT() != RLD->getMemoryVT() || 16730 // If this is an EXTLOAD, the kind of extension must match. 16731 (LLD->getExtensionType() != RLD->getExtensionType() && 16732 // The only exception is if one of the extensions is anyext. 16733 LLD->getExtensionType() != ISD::EXTLOAD && 16734 RLD->getExtensionType() != ISD::EXTLOAD) || 16735 // FIXME: this discards src value information. This is 16736 // over-conservative. It would be beneficial to be able to remember 16737 // both potential memory locations. Since we are discarding 16738 // src value info, don't do the transformation if the memory 16739 // locations are not in the default address space. 16740 LLD->getPointerInfo().getAddrSpace() != 0 || 16741 RLD->getPointerInfo().getAddrSpace() != 0 || 16742 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 16743 LLD->getBasePtr().getValueType())) 16744 return false; 16745 16746 // Check that the select condition doesn't reach either load. If so, 16747 // folding this will induce a cycle into the DAG. If not, this is safe to 16748 // xform, so create a select of the addresses. 16749 SDValue Addr; 16750 if (TheSelect->getOpcode() == ISD::SELECT) { 16751 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 16752 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 16753 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 16754 return false; 16755 // The loads must not depend on one another. 16756 if (LLD->isPredecessorOf(RLD) || 16757 RLD->isPredecessorOf(LLD)) 16758 return false; 16759 Addr = DAG.getSelect(SDLoc(TheSelect), 16760 LLD->getBasePtr().getValueType(), 16761 TheSelect->getOperand(0), LLD->getBasePtr(), 16762 RLD->getBasePtr()); 16763 } else { // Otherwise SELECT_CC 16764 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 16765 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 16766 16767 if ((LLD->hasAnyUseOfValue(1) && 16768 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 16769 (RLD->hasAnyUseOfValue(1) && 16770 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 16771 return false; 16772 16773 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 16774 LLD->getBasePtr().getValueType(), 16775 TheSelect->getOperand(0), 16776 TheSelect->getOperand(1), 16777 LLD->getBasePtr(), RLD->getBasePtr(), 16778 TheSelect->getOperand(4)); 16779 } 16780 16781 SDValue Load; 16782 // It is safe to replace the two loads if they have different alignments, 16783 // but the new load must be the minimum (most restrictive) alignment of the 16784 // inputs. 16785 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 16786 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 16787 if (!RLD->isInvariant()) 16788 MMOFlags &= ~MachineMemOperand::MOInvariant; 16789 if (!RLD->isDereferenceable()) 16790 MMOFlags &= ~MachineMemOperand::MODereferenceable; 16791 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 16792 // FIXME: Discards pointer and AA info. 16793 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 16794 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 16795 MMOFlags); 16796 } else { 16797 // FIXME: Discards pointer and AA info. 16798 Load = DAG.getExtLoad( 16799 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 16800 : LLD->getExtensionType(), 16801 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 16802 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 16803 } 16804 16805 // Users of the select now use the result of the load. 16806 CombineTo(TheSelect, Load); 16807 16808 // Users of the old loads now use the new load's chain. We know the 16809 // old-load value is dead now. 16810 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 16811 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 16812 return true; 16813 } 16814 16815 return false; 16816 } 16817 16818 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and 16819 /// bitwise 'and'. 16820 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, 16821 SDValue N1, SDValue N2, SDValue N3, 16822 ISD::CondCode CC) { 16823 // If this is a select where the false operand is zero and the compare is a 16824 // check of the sign bit, see if we can perform the "gzip trick": 16825 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A 16826 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A 16827 EVT XType = N0.getValueType(); 16828 EVT AType = N2.getValueType(); 16829 if (!isNullConstant(N3) || !XType.bitsGE(AType)) 16830 return SDValue(); 16831 16832 // If the comparison is testing for a positive value, we have to invert 16833 // the sign bit mask, so only do that transform if the target has a bitwise 16834 // 'and not' instruction (the invert is free). 16835 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) { 16836 // (X > -1) ? A : 0 16837 // (X > 0) ? X : 0 <-- This is canonical signed max. 16838 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2))) 16839 return SDValue(); 16840 } else if (CC == ISD::SETLT) { 16841 // (X < 0) ? A : 0 16842 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min. 16843 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2))) 16844 return SDValue(); 16845 } else { 16846 return SDValue(); 16847 } 16848 16849 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit 16850 // constant. 16851 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 16852 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 16853 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 16854 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1; 16855 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); 16856 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt); 16857 AddToWorklist(Shift.getNode()); 16858 16859 if (XType.bitsGT(AType)) { 16860 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 16861 AddToWorklist(Shift.getNode()); 16862 } 16863 16864 if (CC == ISD::SETGT) 16865 Shift = DAG.getNOT(DL, Shift, AType); 16866 16867 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 16868 } 16869 16870 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy); 16871 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt); 16872 AddToWorklist(Shift.getNode()); 16873 16874 if (XType.bitsGT(AType)) { 16875 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 16876 AddToWorklist(Shift.getNode()); 16877 } 16878 16879 if (CC == ISD::SETGT) 16880 Shift = DAG.getNOT(DL, Shift, AType); 16881 16882 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 16883 } 16884 16885 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 16886 /// where 'cond' is the comparison specified by CC. 16887 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 16888 SDValue N2, SDValue N3, ISD::CondCode CC, 16889 bool NotExtCompare) { 16890 // (x ? y : y) -> y. 16891 if (N2 == N3) return N2; 16892 16893 EVT VT = N2.getValueType(); 16894 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 16895 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 16896 16897 // Determine if the condition we're dealing with is constant 16898 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 16899 N0, N1, CC, DL, false); 16900 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 16901 16902 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 16903 // fold select_cc true, x, y -> x 16904 // fold select_cc false, x, y -> y 16905 return !SCCC->isNullValue() ? N2 : N3; 16906 } 16907 16908 // Check to see if we can simplify the select into an fabs node 16909 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 16910 // Allow either -0.0 or 0.0 16911 if (CFP->isZero()) { 16912 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 16913 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 16914 N0 == N2 && N3.getOpcode() == ISD::FNEG && 16915 N2 == N3.getOperand(0)) 16916 return DAG.getNode(ISD::FABS, DL, VT, N0); 16917 16918 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 16919 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 16920 N0 == N3 && N2.getOpcode() == ISD::FNEG && 16921 N2.getOperand(0) == N3) 16922 return DAG.getNode(ISD::FABS, DL, VT, N3); 16923 } 16924 } 16925 16926 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 16927 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 16928 // in it. This is a win when the constant is not otherwise available because 16929 // it replaces two constant pool loads with one. We only do this if the FP 16930 // type is known to be legal, because if it isn't, then we are before legalize 16931 // types an we want the other legalization to happen first (e.g. to avoid 16932 // messing with soft float) and if the ConstantFP is not legal, because if 16933 // it is legal, we may not need to store the FP constant in a constant pool. 16934 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 16935 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 16936 if (TLI.isTypeLegal(N2.getValueType()) && 16937 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 16938 TargetLowering::Legal && 16939 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 16940 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 16941 // If both constants have multiple uses, then we won't need to do an 16942 // extra load, they are likely around in registers for other users. 16943 (TV->hasOneUse() || FV->hasOneUse())) { 16944 Constant *Elts[] = { 16945 const_cast<ConstantFP*>(FV->getConstantFPValue()), 16946 const_cast<ConstantFP*>(TV->getConstantFPValue()) 16947 }; 16948 Type *FPTy = Elts[0]->getType(); 16949 const DataLayout &TD = DAG.getDataLayout(); 16950 16951 // Create a ConstantArray of the two constants. 16952 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 16953 SDValue CPIdx = 16954 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 16955 TD.getPrefTypeAlignment(FPTy)); 16956 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 16957 16958 // Get the offsets to the 0 and 1 element of the array so that we can 16959 // select between them. 16960 SDValue Zero = DAG.getIntPtrConstant(0, DL); 16961 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 16962 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 16963 16964 SDValue Cond = DAG.getSetCC(DL, 16965 getSetCCResultType(N0.getValueType()), 16966 N0, N1, CC); 16967 AddToWorklist(Cond.getNode()); 16968 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 16969 Cond, One, Zero); 16970 AddToWorklist(CstOffset.getNode()); 16971 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 16972 CstOffset); 16973 AddToWorklist(CPIdx.getNode()); 16974 return DAG.getLoad( 16975 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 16976 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 16977 Alignment); 16978 } 16979 } 16980 16981 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC)) 16982 return V; 16983 16984 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 16985 // where y is has a single bit set. 16986 // A plaintext description would be, we can turn the SELECT_CC into an AND 16987 // when the condition can be materialized as an all-ones register. Any 16988 // single bit-test can be materialized as an all-ones register with 16989 // shift-left and shift-right-arith. 16990 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 16991 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 16992 SDValue AndLHS = N0->getOperand(0); 16993 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 16994 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 16995 // Shift the tested bit over the sign bit. 16996 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 16997 SDValue ShlAmt = 16998 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 16999 getShiftAmountTy(AndLHS.getValueType())); 17000 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 17001 17002 // Now arithmetic right shift it all the way over, so the result is either 17003 // all-ones, or zero. 17004 SDValue ShrAmt = 17005 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 17006 getShiftAmountTy(Shl.getValueType())); 17007 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 17008 17009 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 17010 } 17011 } 17012 17013 // fold select C, 16, 0 -> shl C, 4 17014 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 17015 TLI.getBooleanContents(N0.getValueType()) == 17016 TargetLowering::ZeroOrOneBooleanContent) { 17017 17018 // If the caller doesn't want us to simplify this into a zext of a compare, 17019 // don't do it. 17020 if (NotExtCompare && N2C->isOne()) 17021 return SDValue(); 17022 17023 // Get a SetCC of the condition 17024 // NOTE: Don't create a SETCC if it's not legal on this target. 17025 if (!LegalOperations || 17026 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 17027 SDValue Temp, SCC; 17028 // cast from setcc result type to select result type 17029 if (LegalTypes) { 17030 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 17031 N0, N1, CC); 17032 if (N2.getValueType().bitsLT(SCC.getValueType())) 17033 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 17034 N2.getValueType()); 17035 else 17036 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 17037 N2.getValueType(), SCC); 17038 } else { 17039 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 17040 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 17041 N2.getValueType(), SCC); 17042 } 17043 17044 AddToWorklist(SCC.getNode()); 17045 AddToWorklist(Temp.getNode()); 17046 17047 if (N2C->isOne()) 17048 return Temp; 17049 17050 // shl setcc result by log2 n2c 17051 return DAG.getNode( 17052 ISD::SHL, DL, N2.getValueType(), Temp, 17053 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 17054 getShiftAmountTy(Temp.getValueType()))); 17055 } 17056 } 17057 17058 // Check to see if this is an integer abs. 17059 // select_cc setg[te] X, 0, X, -X -> 17060 // select_cc setgt X, -1, X, -X -> 17061 // select_cc setl[te] X, 0, -X, X -> 17062 // select_cc setlt X, 1, -X, X -> 17063 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 17064 if (N1C) { 17065 ConstantSDNode *SubC = nullptr; 17066 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 17067 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 17068 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 17069 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 17070 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 17071 (N1C->isOne() && CC == ISD::SETLT)) && 17072 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 17073 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 17074 17075 EVT XType = N0.getValueType(); 17076 if (SubC && SubC->isNullValue() && XType.isInteger()) { 17077 SDLoc DL(N0); 17078 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 17079 N0, 17080 DAG.getConstant(XType.getSizeInBits() - 1, DL, 17081 getShiftAmountTy(N0.getValueType()))); 17082 SDValue Add = DAG.getNode(ISD::ADD, DL, 17083 XType, N0, Shift); 17084 AddToWorklist(Shift.getNode()); 17085 AddToWorklist(Add.getNode()); 17086 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 17087 } 17088 } 17089 17090 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 17091 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 17092 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 17093 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 17094 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 17095 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 17096 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 17097 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 17098 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 17099 SDValue ValueOnZero = N2; 17100 SDValue Count = N3; 17101 // If the condition is NE instead of E, swap the operands. 17102 if (CC == ISD::SETNE) 17103 std::swap(ValueOnZero, Count); 17104 // Check if the value on zero is a constant equal to the bits in the type. 17105 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 17106 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 17107 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 17108 // legal, combine to just cttz. 17109 if ((Count.getOpcode() == ISD::CTTZ || 17110 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 17111 N0 == Count.getOperand(0) && 17112 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 17113 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 17114 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 17115 // legal, combine to just ctlz. 17116 if ((Count.getOpcode() == ISD::CTLZ || 17117 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 17118 N0 == Count.getOperand(0) && 17119 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 17120 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 17121 } 17122 } 17123 } 17124 17125 return SDValue(); 17126 } 17127 17128 /// This is a stub for TargetLowering::SimplifySetCC. 17129 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 17130 ISD::CondCode Cond, const SDLoc &DL, 17131 bool foldBooleans) { 17132 TargetLowering::DAGCombinerInfo 17133 DagCombineInfo(DAG, Level, false, this); 17134 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 17135 } 17136 17137 /// Given an ISD::SDIV node expressing a divide by constant, return 17138 /// a DAG expression to select that will generate the same value by multiplying 17139 /// by a magic number. 17140 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 17141 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 17142 // when optimising for minimum size, we don't want to expand a div to a mul 17143 // and a shift. 17144 if (DAG.getMachineFunction().getFunction().optForMinSize()) 17145 return SDValue(); 17146 17147 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 17148 if (!C) 17149 return SDValue(); 17150 17151 // Avoid division by zero. 17152 if (C->isNullValue()) 17153 return SDValue(); 17154 17155 std::vector<SDNode *> Built; 17156 SDValue S = 17157 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 17158 17159 for (SDNode *N : Built) 17160 AddToWorklist(N); 17161 return S; 17162 } 17163 17164 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 17165 /// DAG expression that will generate the same value by right shifting. 17166 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 17167 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 17168 if (!C) 17169 return SDValue(); 17170 17171 // Avoid division by zero. 17172 if (C->isNullValue()) 17173 return SDValue(); 17174 17175 std::vector<SDNode *> Built; 17176 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 17177 17178 for (SDNode *N : Built) 17179 AddToWorklist(N); 17180 return S; 17181 } 17182 17183 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 17184 /// expression that will generate the same value by multiplying by a magic 17185 /// number. 17186 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 17187 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 17188 // when optimising for minimum size, we don't want to expand a div to a mul 17189 // and a shift. 17190 if (DAG.getMachineFunction().getFunction().optForMinSize()) 17191 return SDValue(); 17192 17193 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 17194 if (!C) 17195 return SDValue(); 17196 17197 // Avoid division by zero. 17198 if (C->isNullValue()) 17199 return SDValue(); 17200 17201 std::vector<SDNode *> Built; 17202 SDValue S = 17203 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 17204 17205 for (SDNode *N : Built) 17206 AddToWorklist(N); 17207 return S; 17208 } 17209 17210 /// Determines the LogBase2 value for a non-null input value using the 17211 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V). 17212 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) { 17213 EVT VT = V.getValueType(); 17214 unsigned EltBits = VT.getScalarSizeInBits(); 17215 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V); 17216 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT); 17217 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz); 17218 return LogBase2; 17219 } 17220 17221 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 17222 /// For the reciprocal, we need to find the zero of the function: 17223 /// F(X) = A X - 1 [which has a zero at X = 1/A] 17224 /// => 17225 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 17226 /// does not require additional intermediate precision] 17227 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) { 17228 if (Level >= AfterLegalizeDAG) 17229 return SDValue(); 17230 17231 // TODO: Handle half and/or extended types? 17232 EVT VT = Op.getValueType(); 17233 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 17234 return SDValue(); 17235 17236 // If estimates are explicitly disabled for this function, we're done. 17237 MachineFunction &MF = DAG.getMachineFunction(); 17238 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF); 17239 if (Enabled == TLI.ReciprocalEstimate::Disabled) 17240 return SDValue(); 17241 17242 // Estimates may be explicitly enabled for this type with a custom number of 17243 // refinement steps. 17244 int Iterations = TLI.getDivRefinementSteps(VT, MF); 17245 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) { 17246 AddToWorklist(Est.getNode()); 17247 17248 if (Iterations) { 17249 EVT VT = Op.getValueType(); 17250 SDLoc DL(Op); 17251 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 17252 17253 // Newton iterations: Est = Est + Est (1 - Arg * Est) 17254 for (int i = 0; i < Iterations; ++i) { 17255 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 17256 AddToWorklist(NewEst.getNode()); 17257 17258 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 17259 AddToWorklist(NewEst.getNode()); 17260 17261 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 17262 AddToWorklist(NewEst.getNode()); 17263 17264 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 17265 AddToWorklist(Est.getNode()); 17266 } 17267 } 17268 return Est; 17269 } 17270 17271 return SDValue(); 17272 } 17273 17274 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 17275 /// For the reciprocal sqrt, we need to find the zero of the function: 17276 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 17277 /// => 17278 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 17279 /// As a result, we precompute A/2 prior to the iteration loop. 17280 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 17281 unsigned Iterations, 17282 SDNodeFlags Flags, bool Reciprocal) { 17283 EVT VT = Arg.getValueType(); 17284 SDLoc DL(Arg); 17285 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 17286 17287 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 17288 // this entire sequence requires only one FP constant. 17289 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 17290 AddToWorklist(HalfArg.getNode()); 17291 17292 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 17293 AddToWorklist(HalfArg.getNode()); 17294 17295 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 17296 for (unsigned i = 0; i < Iterations; ++i) { 17297 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 17298 AddToWorklist(NewEst.getNode()); 17299 17300 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 17301 AddToWorklist(NewEst.getNode()); 17302 17303 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 17304 AddToWorklist(NewEst.getNode()); 17305 17306 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 17307 AddToWorklist(Est.getNode()); 17308 } 17309 17310 // If non-reciprocal square root is requested, multiply the result by Arg. 17311 if (!Reciprocal) { 17312 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 17313 AddToWorklist(Est.getNode()); 17314 } 17315 17316 return Est; 17317 } 17318 17319 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 17320 /// For the reciprocal sqrt, we need to find the zero of the function: 17321 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 17322 /// => 17323 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 17324 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 17325 unsigned Iterations, 17326 SDNodeFlags Flags, bool Reciprocal) { 17327 EVT VT = Arg.getValueType(); 17328 SDLoc DL(Arg); 17329 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 17330 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 17331 17332 // This routine must enter the loop below to work correctly 17333 // when (Reciprocal == false). 17334 assert(Iterations > 0); 17335 17336 // Newton iterations for reciprocal square root: 17337 // E = (E * -0.5) * ((A * E) * E + -3.0) 17338 for (unsigned i = 0; i < Iterations; ++i) { 17339 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 17340 AddToWorklist(AE.getNode()); 17341 17342 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 17343 AddToWorklist(AEE.getNode()); 17344 17345 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 17346 AddToWorklist(RHS.getNode()); 17347 17348 // When calculating a square root at the last iteration build: 17349 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 17350 // (notice a common subexpression) 17351 SDValue LHS; 17352 if (Reciprocal || (i + 1) < Iterations) { 17353 // RSQRT: LHS = (E * -0.5) 17354 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 17355 } else { 17356 // SQRT: LHS = (A * E) * -0.5 17357 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 17358 } 17359 AddToWorklist(LHS.getNode()); 17360 17361 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 17362 AddToWorklist(Est.getNode()); 17363 } 17364 17365 return Est; 17366 } 17367 17368 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 17369 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 17370 /// Op can be zero. 17371 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, 17372 bool Reciprocal) { 17373 if (Level >= AfterLegalizeDAG) 17374 return SDValue(); 17375 17376 // TODO: Handle half and/or extended types? 17377 EVT VT = Op.getValueType(); 17378 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 17379 return SDValue(); 17380 17381 // If estimates are explicitly disabled for this function, we're done. 17382 MachineFunction &MF = DAG.getMachineFunction(); 17383 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF); 17384 if (Enabled == TLI.ReciprocalEstimate::Disabled) 17385 return SDValue(); 17386 17387 // Estimates may be explicitly enabled for this type with a custom number of 17388 // refinement steps. 17389 int Iterations = TLI.getSqrtRefinementSteps(VT, MF); 17390 17391 bool UseOneConstNR = false; 17392 if (SDValue Est = 17393 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR, 17394 Reciprocal)) { 17395 AddToWorklist(Est.getNode()); 17396 17397 if (Iterations) { 17398 Est = UseOneConstNR 17399 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 17400 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 17401 17402 if (!Reciprocal) { 17403 // Unfortunately, Est is now NaN if the input was exactly 0.0. 17404 // Select out this case and force the answer to 0.0. 17405 EVT VT = Op.getValueType(); 17406 SDLoc DL(Op); 17407 17408 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 17409 EVT CCVT = getSetCCResultType(VT); 17410 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 17411 AddToWorklist(ZeroCmp.getNode()); 17412 17413 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 17414 ZeroCmp, FPZero, Est); 17415 AddToWorklist(Est.getNode()); 17416 } 17417 } 17418 return Est; 17419 } 17420 17421 return SDValue(); 17422 } 17423 17424 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) { 17425 return buildSqrtEstimateImpl(Op, Flags, true); 17426 } 17427 17428 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) { 17429 return buildSqrtEstimateImpl(Op, Flags, false); 17430 } 17431 17432 /// Return true if there is any possibility that the two addresses overlap. 17433 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 17434 // If they are the same then they must be aliases. 17435 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 17436 17437 // If they are both volatile then they cannot be reordered. 17438 if (Op0->isVolatile() && Op1->isVolatile()) return true; 17439 17440 // If one operation reads from invariant memory, and the other may store, they 17441 // cannot alias. These should really be checking the equivalent of mayWrite, 17442 // but it only matters for memory nodes other than load /store. 17443 if (Op0->isInvariant() && Op1->writeMem()) 17444 return false; 17445 17446 if (Op1->isInvariant() && Op0->writeMem()) 17447 return false; 17448 17449 unsigned NumBytes0 = Op0->getMemoryVT().getStoreSize(); 17450 unsigned NumBytes1 = Op1->getMemoryVT().getStoreSize(); 17451 17452 // Check for BaseIndexOffset matching. 17453 BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0, DAG); 17454 BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1, DAG); 17455 int64_t PtrDiff; 17456 if (BasePtr0.getBase().getNode() && BasePtr1.getBase().getNode()) { 17457 if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff)) 17458 return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0)); 17459 17460 // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be 17461 // able to calculate their relative offset if at least one arises 17462 // from an alloca. However, these allocas cannot overlap and we 17463 // can infer there is no alias. 17464 if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase())) 17465 if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) { 17466 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 17467 // If the base are the same frame index but the we couldn't find a 17468 // constant offset, (indices are different) be conservative. 17469 if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) || 17470 !MFI.isFixedObjectIndex(B->getIndex()))) 17471 return false; 17472 } 17473 17474 bool IsFI0 = isa<FrameIndexSDNode>(BasePtr0.getBase()); 17475 bool IsFI1 = isa<FrameIndexSDNode>(BasePtr1.getBase()); 17476 bool IsGV0 = isa<GlobalAddressSDNode>(BasePtr0.getBase()); 17477 bool IsGV1 = isa<GlobalAddressSDNode>(BasePtr1.getBase()); 17478 bool IsCV0 = isa<ConstantPoolSDNode>(BasePtr0.getBase()); 17479 bool IsCV1 = isa<ConstantPoolSDNode>(BasePtr1.getBase()); 17480 17481 // If of mismatched base types or checkable indices we can check 17482 // they do not alias. 17483 if ((BasePtr0.getIndex() == BasePtr1.getIndex() || (IsFI0 != IsFI1) || 17484 (IsGV0 != IsGV1) || (IsCV0 != IsCV1)) && 17485 (IsFI0 || IsGV0 || IsCV0) && (IsFI1 || IsGV1 || IsCV1)) 17486 return false; 17487 } 17488 17489 // If we know required SrcValue1 and SrcValue2 have relatively large 17490 // alignment compared to the size and offset of the access, we may be able 17491 // to prove they do not alias. This check is conservative for now to catch 17492 // cases created by splitting vector types. 17493 int64_t SrcValOffset0 = Op0->getSrcValueOffset(); 17494 int64_t SrcValOffset1 = Op1->getSrcValueOffset(); 17495 unsigned OrigAlignment0 = Op0->getOriginalAlignment(); 17496 unsigned OrigAlignment1 = Op1->getOriginalAlignment(); 17497 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 && 17498 NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) { 17499 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0; 17500 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1; 17501 17502 // There is no overlap between these relatively aligned accesses of 17503 // similar size. Return no alias. 17504 if ((OffAlign0 + NumBytes0) <= OffAlign1 || 17505 (OffAlign1 + NumBytes1) <= OffAlign0) 17506 return false; 17507 } 17508 17509 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 17510 ? CombinerGlobalAA 17511 : DAG.getSubtarget().useAA(); 17512 #ifndef NDEBUG 17513 if (CombinerAAOnlyFunc.getNumOccurrences() && 17514 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 17515 UseAA = false; 17516 #endif 17517 17518 if (UseAA && AA && 17519 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 17520 // Use alias analysis information. 17521 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1); 17522 int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset; 17523 int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset; 17524 AliasResult AAResult = 17525 AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0, 17526 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 17527 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1, 17528 UseTBAA ? Op1->getAAInfo() : AAMDNodes()) ); 17529 if (AAResult == NoAlias) 17530 return false; 17531 } 17532 17533 // Otherwise we have to assume they alias. 17534 return true; 17535 } 17536 17537 /// Walk up chain skipping non-aliasing memory nodes, 17538 /// looking for aliasing nodes and adding them to the Aliases vector. 17539 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 17540 SmallVectorImpl<SDValue> &Aliases) { 17541 SmallVector<SDValue, 8> Chains; // List of chains to visit. 17542 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 17543 17544 // Get alias information for node. 17545 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 17546 17547 // Starting off. 17548 Chains.push_back(OriginalChain); 17549 unsigned Depth = 0; 17550 17551 // Look at each chain and determine if it is an alias. If so, add it to the 17552 // aliases list. If not, then continue up the chain looking for the next 17553 // candidate. 17554 while (!Chains.empty()) { 17555 SDValue Chain = Chains.pop_back_val(); 17556 17557 // For TokenFactor nodes, look at each operand and only continue up the 17558 // chain until we reach the depth limit. 17559 // 17560 // FIXME: The depth check could be made to return the last non-aliasing 17561 // chain we found before we hit a tokenfactor rather than the original 17562 // chain. 17563 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 17564 Aliases.clear(); 17565 Aliases.push_back(OriginalChain); 17566 return; 17567 } 17568 17569 // Don't bother if we've been before. 17570 if (!Visited.insert(Chain.getNode()).second) 17571 continue; 17572 17573 switch (Chain.getOpcode()) { 17574 case ISD::EntryToken: 17575 // Entry token is ideal chain operand, but handled in FindBetterChain. 17576 break; 17577 17578 case ISD::LOAD: 17579 case ISD::STORE: { 17580 // Get alias information for Chain. 17581 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 17582 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 17583 17584 // If chain is alias then stop here. 17585 if (!(IsLoad && IsOpLoad) && 17586 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 17587 Aliases.push_back(Chain); 17588 } else { 17589 // Look further up the chain. 17590 Chains.push_back(Chain.getOperand(0)); 17591 ++Depth; 17592 } 17593 break; 17594 } 17595 17596 case ISD::TokenFactor: 17597 // We have to check each of the operands of the token factor for "small" 17598 // token factors, so we queue them up. Adding the operands to the queue 17599 // (stack) in reverse order maintains the original order and increases the 17600 // likelihood that getNode will find a matching token factor (CSE.) 17601 if (Chain.getNumOperands() > 16) { 17602 Aliases.push_back(Chain); 17603 break; 17604 } 17605 for (unsigned n = Chain.getNumOperands(); n;) 17606 Chains.push_back(Chain.getOperand(--n)); 17607 ++Depth; 17608 break; 17609 17610 case ISD::CopyFromReg: 17611 // Forward past CopyFromReg. 17612 Chains.push_back(Chain.getOperand(0)); 17613 ++Depth; 17614 break; 17615 17616 default: 17617 // For all other instructions we will just have to take what we can get. 17618 Aliases.push_back(Chain); 17619 break; 17620 } 17621 } 17622 } 17623 17624 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 17625 /// (aliasing node.) 17626 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 17627 if (OptLevel == CodeGenOpt::None) 17628 return OldChain; 17629 17630 // Ops for replacing token factor. 17631 SmallVector<SDValue, 8> Aliases; 17632 17633 // Accumulate all the aliases to this node. 17634 GatherAllAliases(N, OldChain, Aliases); 17635 17636 // If no operands then chain to entry token. 17637 if (Aliases.size() == 0) 17638 return DAG.getEntryNode(); 17639 17640 // If a single operand then chain to it. We don't need to revisit it. 17641 if (Aliases.size() == 1) 17642 return Aliases[0]; 17643 17644 // Construct a custom tailored token factor. 17645 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 17646 } 17647 17648 // This function tries to collect a bunch of potentially interesting 17649 // nodes to improve the chains of, all at once. This might seem 17650 // redundant, as this function gets called when visiting every store 17651 // node, so why not let the work be done on each store as it's visited? 17652 // 17653 // I believe this is mainly important because MergeConsecutiveStores 17654 // is unable to deal with merging stores of different sizes, so unless 17655 // we improve the chains of all the potential candidates up-front 17656 // before running MergeConsecutiveStores, it might only see some of 17657 // the nodes that will eventually be candidates, and then not be able 17658 // to go from a partially-merged state to the desired final 17659 // fully-merged state. 17660 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 17661 if (OptLevel == CodeGenOpt::None) 17662 return false; 17663 17664 // This holds the base pointer, index, and the offset in bytes from the base 17665 // pointer. 17666 BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); 17667 17668 // We must have a base and an offset. 17669 if (!BasePtr.getBase().getNode()) 17670 return false; 17671 17672 // Do not handle stores to undef base pointers. 17673 if (BasePtr.getBase().isUndef()) 17674 return false; 17675 17676 SmallVector<StoreSDNode *, 8> ChainedStores; 17677 ChainedStores.push_back(St); 17678 17679 // Walk up the chain and look for nodes with offsets from the same 17680 // base pointer. Stop when reaching an instruction with a different kind 17681 // or instruction which has a different base pointer. 17682 StoreSDNode *Index = St; 17683 while (Index) { 17684 // If the chain has more than one use, then we can't reorder the mem ops. 17685 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 17686 break; 17687 17688 if (Index->isVolatile() || Index->isIndexed()) 17689 break; 17690 17691 // Find the base pointer and offset for this memory node. 17692 BaseIndexOffset Ptr = BaseIndexOffset::match(Index, DAG); 17693 17694 // Check that the base pointer is the same as the original one. 17695 if (!BasePtr.equalBaseIndex(Ptr, DAG)) 17696 break; 17697 17698 // Walk up the chain to find the next store node, ignoring any 17699 // intermediate loads. Any other kind of node will halt the loop. 17700 SDNode *NextInChain = Index->getChain().getNode(); 17701 while (true) { 17702 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 17703 // We found a store node. Use it for the next iteration. 17704 if (STn->isVolatile() || STn->isIndexed()) { 17705 Index = nullptr; 17706 break; 17707 } 17708 ChainedStores.push_back(STn); 17709 Index = STn; 17710 break; 17711 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 17712 NextInChain = Ldn->getChain().getNode(); 17713 continue; 17714 } else { 17715 Index = nullptr; 17716 break; 17717 } 17718 } // end while 17719 } 17720 17721 // At this point, ChainedStores lists all of the Store nodes 17722 // reachable by iterating up through chain nodes matching the above 17723 // conditions. For each such store identified, try to find an 17724 // earlier chain to attach the store to which won't violate the 17725 // required ordering. 17726 bool MadeChangeToSt = false; 17727 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 17728 17729 for (StoreSDNode *ChainedStore : ChainedStores) { 17730 SDValue Chain = ChainedStore->getChain(); 17731 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 17732 17733 if (Chain != BetterChain) { 17734 if (ChainedStore == St) 17735 MadeChangeToSt = true; 17736 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 17737 } 17738 } 17739 17740 // Do all replacements after finding the replacements to make to avoid making 17741 // the chains more complicated by introducing new TokenFactors. 17742 for (auto Replacement : BetterChains) 17743 replaceStoreChain(Replacement.first, Replacement.second); 17744 17745 return MadeChangeToSt; 17746 } 17747 17748 /// This is the entry point for the file. 17749 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA, 17750 CodeGenOpt::Level OptLevel) { 17751 /// This is the main entry point to this class. 17752 DAGCombiner(*this, AA, OptLevel).Run(Level); 17753 } 17754