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/SetVector.h" 20 #include "llvm/ADT/SmallBitVector.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallSet.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/Analysis/AliasAnalysis.h" 25 #include "llvm/CodeGen/MachineFrameInfo.h" 26 #include "llvm/CodeGen/MachineFunction.h" 27 #include "llvm/CodeGen/SelectionDAG.h" 28 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 29 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 30 #include "llvm/IR/DataLayout.h" 31 #include "llvm/IR/DerivedTypes.h" 32 #include "llvm/IR/Function.h" 33 #include "llvm/IR/LLVMContext.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/KnownBits.h" 38 #include "llvm/Support/MathExtras.h" 39 #include "llvm/Support/raw_ostream.h" 40 #include "llvm/Target/TargetLowering.h" 41 #include "llvm/Target/TargetOptions.h" 42 #include "llvm/Target/TargetRegisterInfo.h" 43 #include "llvm/Target/TargetSubtargetInfo.h" 44 #include <algorithm> 45 using namespace llvm; 46 47 #define DEBUG_TYPE "dagcombine" 48 49 STATISTIC(NodesCombined , "Number of dag nodes combined"); 50 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 51 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 52 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 53 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 54 STATISTIC(SlicedLoads, "Number of load sliced"); 55 56 namespace { 57 static cl::opt<bool> 58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 59 cl::desc("Enable DAG combiner's use of IR alias analysis")); 60 61 static cl::opt<bool> 62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 63 cl::desc("Enable DAG combiner's use of TBAA")); 64 65 #ifndef NDEBUG 66 static cl::opt<std::string> 67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 68 cl::desc("Only use DAG-combiner alias analysis in this" 69 " function")); 70 #endif 71 72 /// Hidden option to stress test load slicing, i.e., when this option 73 /// is enabled, load slicing bypasses most of its profitability guards. 74 static cl::opt<bool> 75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 76 cl::desc("Bypass the profitability model of load " 77 "slicing"), 78 cl::init(false)); 79 80 static cl::opt<bool> 81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 82 cl::desc("DAG combiner may split indexing from loads")); 83 84 //------------------------------ DAGCombiner ---------------------------------// 85 86 class DAGCombiner { 87 SelectionDAG &DAG; 88 const TargetLowering &TLI; 89 CombineLevel Level; 90 CodeGenOpt::Level OptLevel; 91 bool LegalOperations; 92 bool LegalTypes; 93 bool ForCodeSize; 94 95 /// \brief Worklist of all of the nodes that need to be simplified. 96 /// 97 /// This must behave as a stack -- new nodes to process are pushed onto the 98 /// back and when processing we pop off of the back. 99 /// 100 /// The worklist will not contain duplicates but may contain null entries 101 /// due to nodes being deleted from the underlying DAG. 102 SmallVector<SDNode *, 64> Worklist; 103 104 /// \brief Mapping from an SDNode to its position on the worklist. 105 /// 106 /// This is used to find and remove nodes from the worklist (by nulling 107 /// them) when they are deleted from the underlying DAG. It relies on 108 /// stable indices of nodes within the worklist. 109 DenseMap<SDNode *, unsigned> WorklistMap; 110 111 /// \brief Set of nodes which have been combined (at least once). 112 /// 113 /// This is used to allow us to reliably add any operands of a DAG node 114 /// which have not yet been combined to the worklist. 115 SmallPtrSet<SDNode *, 32> CombinedNodes; 116 117 // AA - Used for DAG load/store alias analysis. 118 AliasAnalysis *AA; 119 120 /// When an instruction is simplified, add all users of the instruction to 121 /// the work lists because they might get more simplified now. 122 void AddUsersToWorklist(SDNode *N) { 123 for (SDNode *Node : N->uses()) 124 AddToWorklist(Node); 125 } 126 127 /// Call the node-specific routine that folds each particular type of node. 128 SDValue visit(SDNode *N); 129 130 public: 131 /// Add to the worklist making sure its instance is at the back (next to be 132 /// processed.) 133 void AddToWorklist(SDNode *N) { 134 assert(N->getOpcode() != ISD::DELETED_NODE && 135 "Deleted Node added to Worklist"); 136 137 // Skip handle nodes as they can't usefully be combined and confuse the 138 // zero-use deletion strategy. 139 if (N->getOpcode() == ISD::HANDLENODE) 140 return; 141 142 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 143 Worklist.push_back(N); 144 } 145 146 /// Remove all instances of N from the worklist. 147 void removeFromWorklist(SDNode *N) { 148 CombinedNodes.erase(N); 149 150 auto It = WorklistMap.find(N); 151 if (It == WorklistMap.end()) 152 return; // Not in the worklist. 153 154 // Null out the entry rather than erasing it to avoid a linear operation. 155 Worklist[It->second] = nullptr; 156 WorklistMap.erase(It); 157 } 158 159 void deleteAndRecombine(SDNode *N); 160 bool recursivelyDeleteUnusedNodes(SDNode *N); 161 162 /// Replaces all uses of the results of one DAG node with new values. 163 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 164 bool AddTo = true); 165 166 /// Replaces all uses of the results of one DAG node with new values. 167 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 168 return CombineTo(N, &Res, 1, AddTo); 169 } 170 171 /// Replaces all uses of the results of one DAG node with new values. 172 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 173 bool AddTo = true) { 174 SDValue To[] = { Res0, Res1 }; 175 return CombineTo(N, To, 2, AddTo); 176 } 177 178 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 179 180 private: 181 unsigned MaximumLegalStoreInBits; 182 183 /// Check the specified integer node value to see if it can be simplified or 184 /// if things it uses can be simplified by bit propagation. 185 /// If so, return true. 186 bool SimplifyDemandedBits(SDValue Op) { 187 unsigned BitWidth = Op.getScalarValueSizeInBits(); 188 APInt Demanded = APInt::getAllOnesValue(BitWidth); 189 return SimplifyDemandedBits(Op, Demanded); 190 } 191 192 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 193 194 bool CombineToPreIndexedLoadStore(SDNode *N); 195 bool CombineToPostIndexedLoadStore(SDNode *N); 196 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 197 bool SliceUpLoad(SDNode *N); 198 199 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 200 /// load. 201 /// 202 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 203 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 204 /// \param EltNo index of the vector element to load. 205 /// \param OriginalLoad load that EVE came from to be replaced. 206 /// \returns EVE on success SDValue() on failure. 207 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 208 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 209 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 210 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 211 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 212 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 213 SDValue PromoteIntBinOp(SDValue Op); 214 SDValue PromoteIntShiftOp(SDValue Op); 215 SDValue PromoteExtend(SDValue Op); 216 bool PromoteLoad(SDValue Op); 217 218 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc, 219 SDValue ExtLoad, const SDLoc &DL, 220 ISD::NodeType ExtType); 221 222 /// Call the node-specific routine that knows how to fold each 223 /// particular type of node. If that doesn't do anything, try the 224 /// target-specific DAG combines. 225 SDValue combine(SDNode *N); 226 227 // Visitation implementation - Implement dag node combining for different 228 // node types. The semantics are as follows: 229 // Return Value: 230 // SDValue.getNode() == 0 - No change was made 231 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 232 // otherwise - N should be replaced by the returned Operand. 233 // 234 SDValue visitTokenFactor(SDNode *N); 235 SDValue visitMERGE_VALUES(SDNode *N); 236 SDValue visitADD(SDNode *N); 237 SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference); 238 SDValue visitSUB(SDNode *N); 239 SDValue visitADDC(SDNode *N); 240 SDValue visitUADDO(SDNode *N); 241 SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N); 242 SDValue visitSUBC(SDNode *N); 243 SDValue visitUSUBO(SDNode *N); 244 SDValue visitADDE(SDNode *N); 245 SDValue visitADDCARRY(SDNode *N); 246 SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N); 247 SDValue visitSUBE(SDNode *N); 248 SDValue visitSUBCARRY(SDNode *N); 249 SDValue visitMUL(SDNode *N); 250 SDValue useDivRem(SDNode *N); 251 SDValue visitSDIV(SDNode *N); 252 SDValue visitUDIV(SDNode *N); 253 SDValue visitREM(SDNode *N); 254 SDValue visitMULHU(SDNode *N); 255 SDValue visitMULHS(SDNode *N); 256 SDValue visitSMUL_LOHI(SDNode *N); 257 SDValue visitUMUL_LOHI(SDNode *N); 258 SDValue visitSMULO(SDNode *N); 259 SDValue visitUMULO(SDNode *N); 260 SDValue visitIMINMAX(SDNode *N); 261 SDValue visitAND(SDNode *N); 262 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference); 263 SDValue visitOR(SDNode *N); 264 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference); 265 SDValue visitXOR(SDNode *N); 266 SDValue SimplifyVBinOp(SDNode *N); 267 SDValue visitSHL(SDNode *N); 268 SDValue visitSRA(SDNode *N); 269 SDValue visitSRL(SDNode *N); 270 SDValue visitRotate(SDNode *N); 271 SDValue visitABS(SDNode *N); 272 SDValue visitBSWAP(SDNode *N); 273 SDValue visitBITREVERSE(SDNode *N); 274 SDValue visitCTLZ(SDNode *N); 275 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 276 SDValue visitCTTZ(SDNode *N); 277 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 278 SDValue visitCTPOP(SDNode *N); 279 SDValue visitSELECT(SDNode *N); 280 SDValue visitVSELECT(SDNode *N); 281 SDValue visitSELECT_CC(SDNode *N); 282 SDValue visitSETCC(SDNode *N); 283 SDValue visitSETCCE(SDNode *N); 284 SDValue visitSETCCCARRY(SDNode *N); 285 SDValue visitSIGN_EXTEND(SDNode *N); 286 SDValue visitZERO_EXTEND(SDNode *N); 287 SDValue visitANY_EXTEND(SDNode *N); 288 SDValue visitAssertZext(SDNode *N); 289 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 290 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 291 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N); 292 SDValue visitTRUNCATE(SDNode *N); 293 SDValue visitBITCAST(SDNode *N); 294 SDValue visitBUILD_PAIR(SDNode *N); 295 SDValue visitFADD(SDNode *N); 296 SDValue visitFSUB(SDNode *N); 297 SDValue visitFMUL(SDNode *N); 298 SDValue visitFMA(SDNode *N); 299 SDValue visitFDIV(SDNode *N); 300 SDValue visitFREM(SDNode *N); 301 SDValue visitFSQRT(SDNode *N); 302 SDValue visitFCOPYSIGN(SDNode *N); 303 SDValue visitSINT_TO_FP(SDNode *N); 304 SDValue visitUINT_TO_FP(SDNode *N); 305 SDValue visitFP_TO_SINT(SDNode *N); 306 SDValue visitFP_TO_UINT(SDNode *N); 307 SDValue visitFP_ROUND(SDNode *N); 308 SDValue visitFP_ROUND_INREG(SDNode *N); 309 SDValue visitFP_EXTEND(SDNode *N); 310 SDValue visitFNEG(SDNode *N); 311 SDValue visitFABS(SDNode *N); 312 SDValue visitFCEIL(SDNode *N); 313 SDValue visitFTRUNC(SDNode *N); 314 SDValue visitFFLOOR(SDNode *N); 315 SDValue visitFMINNUM(SDNode *N); 316 SDValue visitFMAXNUM(SDNode *N); 317 SDValue visitBRCOND(SDNode *N); 318 SDValue visitBR_CC(SDNode *N); 319 SDValue visitLOAD(SDNode *N); 320 321 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 322 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 323 324 SDValue visitSTORE(SDNode *N); 325 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 326 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 327 SDValue visitBUILD_VECTOR(SDNode *N); 328 SDValue visitCONCAT_VECTORS(SDNode *N); 329 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 330 SDValue visitVECTOR_SHUFFLE(SDNode *N); 331 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 332 SDValue visitINSERT_SUBVECTOR(SDNode *N); 333 SDValue visitMLOAD(SDNode *N); 334 SDValue visitMSTORE(SDNode *N); 335 SDValue visitMGATHER(SDNode *N); 336 SDValue visitMSCATTER(SDNode *N); 337 SDValue visitFP_TO_FP16(SDNode *N); 338 SDValue visitFP16_TO_FP(SDNode *N); 339 340 SDValue visitFADDForFMACombine(SDNode *N); 341 SDValue visitFSUBForFMACombine(SDNode *N); 342 SDValue visitFMULForFMADistributiveCombine(SDNode *N); 343 344 SDValue XformToShuffleWithZero(SDNode *N); 345 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS, 346 SDValue RHS); 347 348 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 349 350 SDValue foldSelectOfConstants(SDNode *N); 351 SDValue foldBinOpIntoSelect(SDNode *BO); 352 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 353 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 354 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2); 355 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 356 SDValue N2, SDValue N3, ISD::CondCode CC, 357 bool NotExtCompare = false); 358 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1, 359 SDValue N2, SDValue N3, ISD::CondCode CC); 360 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 361 const SDLoc &DL); 362 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 363 const SDLoc &DL, bool foldBooleans = true); 364 365 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 366 SDValue &CC) const; 367 bool isOneUseSetCC(SDValue N) const; 368 369 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 370 unsigned HiOp); 371 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 372 SDValue CombineExtLoad(SDNode *N); 373 SDValue combineRepeatedFPDivisors(SDNode *N); 374 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 375 SDValue BuildSDIV(SDNode *N); 376 SDValue BuildSDIVPow2(SDNode *N); 377 SDValue BuildUDIV(SDNode *N); 378 SDValue BuildLogBase2(SDValue Op, const SDLoc &DL); 379 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags); 380 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags); 381 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags); 382 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip); 383 SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations, 384 SDNodeFlags Flags, bool Reciprocal); 385 SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations, 386 SDNodeFlags Flags, bool Reciprocal); 387 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 388 bool DemandHighBits = true); 389 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 390 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 391 SDValue InnerPos, SDValue InnerNeg, 392 unsigned PosOpcode, unsigned NegOpcode, 393 const SDLoc &DL); 394 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL); 395 SDValue MatchLoadCombine(SDNode *N); 396 SDValue ReduceLoadWidth(SDNode *N); 397 SDValue ReduceLoadOpStoreWidth(SDNode *N); 398 SDValue splitMergedValStore(StoreSDNode *ST); 399 SDValue TransformFPLoadStorePair(SDNode *N); 400 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 401 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 402 SDValue reduceBuildVecToShuffle(SDNode *N); 403 SDValue reduceBuildVecToTrunc(SDNode *N); 404 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N, 405 ArrayRef<int> VectorMask, SDValue VecIn1, 406 SDValue VecIn2, unsigned LeftIdx); 407 SDValue matchVSelectOpSizesWithSetCC(SDNode *N); 408 409 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 410 411 /// Walk up chain skipping non-aliasing memory nodes, 412 /// looking for aliasing nodes and adding them to the Aliases vector. 413 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 414 SmallVectorImpl<SDValue> &Aliases); 415 416 /// Return true if there is any possibility that the two addresses overlap. 417 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 418 419 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 420 /// chain (aliasing node.) 421 SDValue FindBetterChain(SDNode *N, SDValue Chain); 422 423 /// Try to replace a store and any possibly adjacent stores on 424 /// consecutive chains with better chains. Return true only if St is 425 /// replaced. 426 /// 427 /// Notice that other chains may still be replaced even if the function 428 /// returns false. 429 bool findBetterNeighborChains(StoreSDNode *St); 430 431 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 432 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask); 433 434 /// Holds a pointer to an LSBaseSDNode as well as information on where it 435 /// is located in a sequence of memory operations connected by a chain. 436 struct MemOpLink { 437 MemOpLink(LSBaseSDNode *N, int64_t Offset) 438 : MemNode(N), OffsetFromBase(Offset) {} 439 // Ptr to the mem node. 440 LSBaseSDNode *MemNode; 441 // Offset from the base ptr. 442 int64_t OffsetFromBase; 443 }; 444 445 /// This is a helper function for visitMUL to check the profitability 446 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 447 /// MulNode is the original multiply, AddNode is (add x, c1), 448 /// and ConstNode is c2. 449 bool isMulAddWithConstProfitable(SDNode *MulNode, 450 SDValue &AddNode, 451 SDValue &ConstNode); 452 453 454 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 455 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 456 /// the type of the loaded value to be extended. LoadedVT returns the type 457 /// of the original loaded value. NarrowLoad returns whether the load would 458 /// need to be narrowed in order to match. 459 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 460 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 461 bool &NarrowLoad); 462 463 /// Helper function for MergeConsecutiveStores which merges the 464 /// component store chains. 465 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 466 unsigned NumStores); 467 468 /// This is a helper function for MergeConsecutiveStores. When the source 469 /// elements of the consecutive stores are all constants or all extracted 470 /// vector elements, try to merge them into one larger store. 471 /// \return True if a merged store was created. 472 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 473 EVT MemVT, unsigned NumStores, 474 bool IsConstantSrc, bool UseVector, 475 bool UseTrunc); 476 477 /// This is a helper function for MergeConsecutiveStores. 478 /// Stores that may be merged are placed in StoreNodes. 479 void getStoreMergeCandidates(StoreSDNode *St, 480 SmallVectorImpl<MemOpLink> &StoreNodes); 481 482 /// Helper function for MergeConsecutiveStores. Checks if 483 /// Candidate stores have indirect dependency through their 484 /// operands. \return True if safe to merge 485 bool checkMergeStoreCandidatesForDependencies( 486 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores); 487 488 /// Merge consecutive store operations into a wide store. 489 /// This optimization uses wide integers or vectors when possible. 490 /// \return number of stores that were merged into a merged store (the 491 /// affected nodes are stored as a prefix in \p StoreNodes). 492 bool MergeConsecutiveStores(StoreSDNode *N); 493 494 /// \brief Try to transform a truncation where C is a constant: 495 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 496 /// 497 /// \p N needs to be a truncation and its first operand an AND. Other 498 /// requirements are checked by the function (e.g. that trunc is 499 /// single-use) and if missed an empty SDValue is returned. 500 SDValue distributeTruncateThroughAnd(SDNode *N); 501 502 public: 503 DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL) 504 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 505 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(AA) { 506 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize(); 507 508 MaximumLegalStoreInBits = 0; 509 for (MVT VT : MVT::all_valuetypes()) 510 if (EVT(VT).isSimple() && VT != MVT::Other && 511 TLI.isTypeLegal(EVT(VT)) && 512 VT.getSizeInBits() >= MaximumLegalStoreInBits) 513 MaximumLegalStoreInBits = VT.getSizeInBits(); 514 } 515 516 /// Runs the dag combiner on all nodes in the work list 517 void Run(CombineLevel AtLevel); 518 519 SelectionDAG &getDAG() const { return DAG; } 520 521 /// Returns a type large enough to hold any valid shift amount - before type 522 /// legalization these can be huge. 523 EVT getShiftAmountTy(EVT LHSTy) { 524 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 525 if (LHSTy.isVector()) 526 return LHSTy; 527 auto &DL = DAG.getDataLayout(); 528 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 529 : TLI.getPointerTy(DL); 530 } 531 532 /// This method returns true if we are running before type legalization or 533 /// if the specified VT is legal. 534 bool isTypeLegal(const EVT &VT) { 535 if (!LegalTypes) return true; 536 return TLI.isTypeLegal(VT); 537 } 538 539 /// Convenience wrapper around TargetLowering::getSetCCResultType 540 EVT getSetCCResultType(EVT VT) const { 541 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 542 } 543 }; 544 } 545 546 547 namespace { 548 /// This class is a DAGUpdateListener that removes any deleted 549 /// nodes from the worklist. 550 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 551 DAGCombiner &DC; 552 public: 553 explicit WorklistRemover(DAGCombiner &dc) 554 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 555 556 void NodeDeleted(SDNode *N, SDNode *E) override { 557 DC.removeFromWorklist(N); 558 } 559 }; 560 } 561 562 //===----------------------------------------------------------------------===// 563 // TargetLowering::DAGCombinerInfo implementation 564 //===----------------------------------------------------------------------===// 565 566 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 567 ((DAGCombiner*)DC)->AddToWorklist(N); 568 } 569 570 SDValue TargetLowering::DAGCombinerInfo:: 571 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 572 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 573 } 574 575 SDValue TargetLowering::DAGCombinerInfo:: 576 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 577 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 578 } 579 580 581 SDValue TargetLowering::DAGCombinerInfo:: 582 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 583 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 584 } 585 586 void TargetLowering::DAGCombinerInfo:: 587 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 588 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 589 } 590 591 //===----------------------------------------------------------------------===// 592 // Helper Functions 593 //===----------------------------------------------------------------------===// 594 595 void DAGCombiner::deleteAndRecombine(SDNode *N) { 596 removeFromWorklist(N); 597 598 // If the operands of this node are only used by the node, they will now be 599 // dead. Make sure to re-visit them and recursively delete dead nodes. 600 for (const SDValue &Op : N->ops()) 601 // For an operand generating multiple values, one of the values may 602 // become dead allowing further simplification (e.g. split index 603 // arithmetic from an indexed load). 604 if (Op->hasOneUse() || Op->getNumValues() > 1) 605 AddToWorklist(Op.getNode()); 606 607 DAG.DeleteNode(N); 608 } 609 610 /// Return 1 if we can compute the negated form of the specified expression for 611 /// the same cost as the expression itself, or 2 if we can compute the negated 612 /// form more cheaply than the expression itself. 613 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 614 const TargetLowering &TLI, 615 const TargetOptions *Options, 616 unsigned Depth = 0) { 617 // fneg is removable even if it has multiple uses. 618 if (Op.getOpcode() == ISD::FNEG) return 2; 619 620 // Don't allow anything with multiple uses. 621 if (!Op.hasOneUse()) return 0; 622 623 // Don't recurse exponentially. 624 if (Depth > 6) return 0; 625 626 switch (Op.getOpcode()) { 627 default: return false; 628 case ISD::ConstantFP: { 629 if (!LegalOperations) 630 return 1; 631 632 // Don't invert constant FP values after legalization unless the target says 633 // the negated constant is legal. 634 EVT VT = Op.getValueType(); 635 return TLI.isOperationLegal(ISD::ConstantFP, VT) || 636 TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT); 637 } 638 case ISD::FADD: 639 // FIXME: determine better conditions for this xform. 640 if (!Options->UnsafeFPMath) return 0; 641 642 // After operation legalization, it might not be legal to create new FSUBs. 643 if (LegalOperations && 644 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 645 return 0; 646 647 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 648 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 649 Options, Depth + 1)) 650 return V; 651 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 652 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 653 Depth + 1); 654 case ISD::FSUB: 655 // We can't turn -(A-B) into B-A when we honor signed zeros. 656 if (!Options->NoSignedZerosFPMath && 657 !Op.getNode()->getFlags().hasNoSignedZeros()) 658 return 0; 659 660 // fold (fneg (fsub A, B)) -> (fsub B, A) 661 return 1; 662 663 case ISD::FMUL: 664 case ISD::FDIV: 665 if (Options->HonorSignDependentRoundingFPMath()) return 0; 666 667 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 668 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 669 Options, Depth + 1)) 670 return V; 671 672 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 673 Depth + 1); 674 675 case ISD::FP_EXTEND: 676 case ISD::FP_ROUND: 677 case ISD::FSIN: 678 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 679 Depth + 1); 680 } 681 } 682 683 /// If isNegatibleForFree returns true, return the newly negated expression. 684 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 685 bool LegalOperations, unsigned Depth = 0) { 686 const TargetOptions &Options = DAG.getTarget().Options; 687 // fneg is removable even if it has multiple uses. 688 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 689 690 // Don't allow anything with multiple uses. 691 assert(Op.hasOneUse() && "Unknown reuse!"); 692 693 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 694 695 const SDNodeFlags Flags = Op.getNode()->getFlags(); 696 697 switch (Op.getOpcode()) { 698 default: llvm_unreachable("Unknown code"); 699 case ISD::ConstantFP: { 700 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 701 V.changeSign(); 702 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 703 } 704 case ISD::FADD: 705 // FIXME: determine better conditions for this xform. 706 assert(Options.UnsafeFPMath); 707 708 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 709 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 710 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 711 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 712 GetNegatedExpression(Op.getOperand(0), DAG, 713 LegalOperations, Depth+1), 714 Op.getOperand(1), Flags); 715 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 716 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 717 GetNegatedExpression(Op.getOperand(1), DAG, 718 LegalOperations, Depth+1), 719 Op.getOperand(0), Flags); 720 case ISD::FSUB: 721 // fold (fneg (fsub 0, B)) -> B 722 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 723 if (N0CFP->isZero()) 724 return Op.getOperand(1); 725 726 // fold (fneg (fsub A, B)) -> (fsub B, A) 727 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 728 Op.getOperand(1), Op.getOperand(0), Flags); 729 730 case ISD::FMUL: 731 case ISD::FDIV: 732 assert(!Options.HonorSignDependentRoundingFPMath()); 733 734 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 735 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 736 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 737 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 738 GetNegatedExpression(Op.getOperand(0), DAG, 739 LegalOperations, Depth+1), 740 Op.getOperand(1), Flags); 741 742 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 743 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 744 Op.getOperand(0), 745 GetNegatedExpression(Op.getOperand(1), DAG, 746 LegalOperations, Depth+1), Flags); 747 748 case ISD::FP_EXTEND: 749 case ISD::FSIN: 750 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 751 GetNegatedExpression(Op.getOperand(0), DAG, 752 LegalOperations, Depth+1)); 753 case ISD::FP_ROUND: 754 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 755 GetNegatedExpression(Op.getOperand(0), DAG, 756 LegalOperations, Depth+1), 757 Op.getOperand(1)); 758 } 759 } 760 761 // APInts must be the same size for most operations, this helper 762 // function zero extends the shorter of the pair so that they match. 763 // We provide an Offset so that we can create bitwidths that won't overflow. 764 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) { 765 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth()); 766 LHS = LHS.zextOrSelf(Bits); 767 RHS = RHS.zextOrSelf(Bits); 768 } 769 770 // Return true if this node is a setcc, or is a select_cc 771 // that selects between the target values used for true and false, making it 772 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 773 // the appropriate nodes based on the type of node we are checking. This 774 // simplifies life a bit for the callers. 775 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 776 SDValue &CC) const { 777 if (N.getOpcode() == ISD::SETCC) { 778 LHS = N.getOperand(0); 779 RHS = N.getOperand(1); 780 CC = N.getOperand(2); 781 return true; 782 } 783 784 if (N.getOpcode() != ISD::SELECT_CC || 785 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 786 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 787 return false; 788 789 if (TLI.getBooleanContents(N.getValueType()) == 790 TargetLowering::UndefinedBooleanContent) 791 return false; 792 793 LHS = N.getOperand(0); 794 RHS = N.getOperand(1); 795 CC = N.getOperand(4); 796 return true; 797 } 798 799 /// Return true if this is a SetCC-equivalent operation with only one use. 800 /// If this is true, it allows the users to invert the operation for free when 801 /// it is profitable to do so. 802 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 803 SDValue N0, N1, N2; 804 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 805 return true; 806 return false; 807 } 808 809 // \brief Returns the SDNode if it is a constant float BuildVector 810 // or constant float. 811 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 812 if (isa<ConstantFPSDNode>(N)) 813 return N.getNode(); 814 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 815 return N.getNode(); 816 return nullptr; 817 } 818 819 // Determines if it is a constant integer or a build vector of constant 820 // integers (and undefs). 821 // Do not permit build vector implicit truncation. 822 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) { 823 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N)) 824 return !(Const->isOpaque() && NoOpaques); 825 if (N.getOpcode() != ISD::BUILD_VECTOR) 826 return false; 827 unsigned BitWidth = N.getScalarValueSizeInBits(); 828 for (const SDValue &Op : N->op_values()) { 829 if (Op.isUndef()) 830 continue; 831 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op); 832 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth || 833 (Const->isOpaque() && NoOpaques)) 834 return false; 835 } 836 return true; 837 } 838 839 // Determines if it is a constant null integer or a splatted vector of a 840 // constant null integer (with no undefs). 841 // Build vector implicit truncation is not an issue for null values. 842 static bool isNullConstantOrNullSplatConstant(SDValue N) { 843 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 844 return Splat->isNullValue(); 845 return false; 846 } 847 848 // Determines if it is a constant integer of one or a splatted vector of a 849 // constant integer of one (with no undefs). 850 // Do not permit build vector implicit truncation. 851 static bool isOneConstantOrOneSplatConstant(SDValue N) { 852 unsigned BitWidth = N.getScalarValueSizeInBits(); 853 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 854 return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth; 855 return false; 856 } 857 858 // Determines if it is a constant integer of all ones or a splatted vector of a 859 // constant integer of all ones (with no undefs). 860 // Do not permit build vector implicit truncation. 861 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) { 862 unsigned BitWidth = N.getScalarValueSizeInBits(); 863 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 864 return Splat->isAllOnesValue() && 865 Splat->getAPIntValue().getBitWidth() == BitWidth; 866 return false; 867 } 868 869 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with 870 // undef's. 871 static bool isAnyConstantBuildVector(const SDNode *N) { 872 return ISD::isBuildVectorOfConstantSDNodes(N) || 873 ISD::isBuildVectorOfConstantFPSDNodes(N); 874 } 875 876 // Attempt to match a unary predicate against a scalar/splat constant or 877 // every element of a constant BUILD_VECTOR. 878 static bool matchUnaryPredicate(SDValue Op, 879 std::function<bool(ConstantSDNode *)> Match) { 880 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) 881 return Match(Cst); 882 883 if (ISD::BUILD_VECTOR != Op.getOpcode()) 884 return false; 885 886 EVT SVT = Op.getValueType().getScalarType(); 887 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 888 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i)); 889 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 890 return false; 891 } 892 return true; 893 } 894 895 // Attempt to match a binary predicate against a pair of scalar/splat constants 896 // or every element of a pair of constant BUILD_VECTORs. 897 static bool matchBinaryPredicate( 898 SDValue LHS, SDValue RHS, 899 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match) { 900 if (LHS.getValueType() != RHS.getValueType()) 901 return false; 902 903 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 904 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 905 return Match(LHSCst, RHSCst); 906 907 if (ISD::BUILD_VECTOR != LHS.getOpcode() || 908 ISD::BUILD_VECTOR != RHS.getOpcode()) 909 return false; 910 911 EVT SVT = LHS.getValueType().getScalarType(); 912 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 913 auto *LHSCst = dyn_cast<ConstantSDNode>(LHS.getOperand(i)); 914 auto *RHSCst = dyn_cast<ConstantSDNode>(RHS.getOperand(i)); 915 if (!LHSCst || !RHSCst) 916 return false; 917 if (LHSCst->getValueType(0) != SVT || 918 LHSCst->getValueType(0) != RHSCst->getValueType(0)) 919 return false; 920 if (!Match(LHSCst, RHSCst)) 921 return false; 922 } 923 return true; 924 } 925 926 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 927 SDValue N1) { 928 EVT VT = N0.getValueType(); 929 if (N0.getOpcode() == Opc) { 930 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 931 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 932 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 933 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 934 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 935 return SDValue(); 936 } 937 if (N0.hasOneUse()) { 938 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 939 // use 940 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 941 if (!OpNode.getNode()) 942 return SDValue(); 943 AddToWorklist(OpNode.getNode()); 944 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 945 } 946 } 947 } 948 949 if (N1.getOpcode() == Opc) { 950 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 951 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 952 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 953 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 954 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 955 return SDValue(); 956 } 957 if (N1.hasOneUse()) { 958 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 959 // use 960 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 961 if (!OpNode.getNode()) 962 return SDValue(); 963 AddToWorklist(OpNode.getNode()); 964 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 965 } 966 } 967 } 968 969 return SDValue(); 970 } 971 972 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 973 bool AddTo) { 974 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 975 ++NodesCombined; 976 DEBUG(dbgs() << "\nReplacing.1 "; 977 N->dump(&DAG); 978 dbgs() << "\nWith: "; 979 To[0].getNode()->dump(&DAG); 980 dbgs() << " and " << NumTo-1 << " other values\n"); 981 for (unsigned i = 0, e = NumTo; i != e; ++i) 982 assert((!To[i].getNode() || 983 N->getValueType(i) == To[i].getValueType()) && 984 "Cannot combine value to value of different type!"); 985 986 WorklistRemover DeadNodes(*this); 987 DAG.ReplaceAllUsesWith(N, To); 988 if (AddTo) { 989 // Push the new nodes and any users onto the worklist 990 for (unsigned i = 0, e = NumTo; i != e; ++i) { 991 if (To[i].getNode()) { 992 AddToWorklist(To[i].getNode()); 993 AddUsersToWorklist(To[i].getNode()); 994 } 995 } 996 } 997 998 // Finally, if the node is now dead, remove it from the graph. The node 999 // may not be dead if the replacement process recursively simplified to 1000 // something else needing this node. 1001 if (N->use_empty()) 1002 deleteAndRecombine(N); 1003 return SDValue(N, 0); 1004 } 1005 1006 void DAGCombiner:: 1007 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 1008 // Replace all uses. If any nodes become isomorphic to other nodes and 1009 // are deleted, make sure to remove them from our worklist. 1010 WorklistRemover DeadNodes(*this); 1011 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 1012 1013 // Push the new node and any (possibly new) users onto the worklist. 1014 AddToWorklist(TLO.New.getNode()); 1015 AddUsersToWorklist(TLO.New.getNode()); 1016 1017 // Finally, if the node is now dead, remove it from the graph. The node 1018 // may not be dead if the replacement process recursively simplified to 1019 // something else needing this node. 1020 if (TLO.Old.getNode()->use_empty()) 1021 deleteAndRecombine(TLO.Old.getNode()); 1022 } 1023 1024 /// Check the specified integer node value to see if it can be simplified or if 1025 /// things it uses can be simplified by bit propagation. If so, return true. 1026 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 1027 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 1028 KnownBits Known; 1029 if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO)) 1030 return false; 1031 1032 // Revisit the node. 1033 AddToWorklist(Op.getNode()); 1034 1035 // Replace the old value with the new one. 1036 ++NodesCombined; 1037 DEBUG(dbgs() << "\nReplacing.2 "; 1038 TLO.Old.getNode()->dump(&DAG); 1039 dbgs() << "\nWith: "; 1040 TLO.New.getNode()->dump(&DAG); 1041 dbgs() << '\n'); 1042 1043 CommitTargetLoweringOpt(TLO); 1044 return true; 1045 } 1046 1047 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 1048 SDLoc DL(Load); 1049 EVT VT = Load->getValueType(0); 1050 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0)); 1051 1052 DEBUG(dbgs() << "\nReplacing.9 "; 1053 Load->dump(&DAG); 1054 dbgs() << "\nWith: "; 1055 Trunc.getNode()->dump(&DAG); 1056 dbgs() << '\n'); 1057 WorklistRemover DeadNodes(*this); 1058 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 1059 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 1060 deleteAndRecombine(Load); 1061 AddToWorklist(Trunc.getNode()); 1062 } 1063 1064 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 1065 Replace = false; 1066 SDLoc DL(Op); 1067 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 1068 LoadSDNode *LD = cast<LoadSDNode>(Op); 1069 EVT MemVT = LD->getMemoryVT(); 1070 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1071 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1072 : ISD::EXTLOAD) 1073 : LD->getExtensionType(); 1074 Replace = true; 1075 return DAG.getExtLoad(ExtType, DL, PVT, 1076 LD->getChain(), LD->getBasePtr(), 1077 MemVT, LD->getMemOperand()); 1078 } 1079 1080 unsigned Opc = Op.getOpcode(); 1081 switch (Opc) { 1082 default: break; 1083 case ISD::AssertSext: 1084 if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT)) 1085 return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1)); 1086 break; 1087 case ISD::AssertZext: 1088 if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT)) 1089 return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1)); 1090 break; 1091 case ISD::Constant: { 1092 unsigned ExtOpc = 1093 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1094 return DAG.getNode(ExtOpc, DL, PVT, Op); 1095 } 1096 } 1097 1098 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 1099 return SDValue(); 1100 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op); 1101 } 1102 1103 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1104 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1105 return SDValue(); 1106 EVT OldVT = Op.getValueType(); 1107 SDLoc DL(Op); 1108 bool Replace = false; 1109 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1110 if (!NewOp.getNode()) 1111 return SDValue(); 1112 AddToWorklist(NewOp.getNode()); 1113 1114 if (Replace) 1115 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1116 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp, 1117 DAG.getValueType(OldVT)); 1118 } 1119 1120 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1121 EVT OldVT = Op.getValueType(); 1122 SDLoc DL(Op); 1123 bool Replace = false; 1124 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1125 if (!NewOp.getNode()) 1126 return SDValue(); 1127 AddToWorklist(NewOp.getNode()); 1128 1129 if (Replace) 1130 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1131 return DAG.getZeroExtendInReg(NewOp, DL, OldVT); 1132 } 1133 1134 /// Promote the specified integer binary operation if the target indicates it is 1135 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1136 /// i32 since i16 instructions are longer. 1137 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1138 if (!LegalOperations) 1139 return SDValue(); 1140 1141 EVT VT = Op.getValueType(); 1142 if (VT.isVector() || !VT.isInteger()) 1143 return SDValue(); 1144 1145 // If operation type is 'undesirable', e.g. i16 on x86, consider 1146 // promoting it. 1147 unsigned Opc = Op.getOpcode(); 1148 if (TLI.isTypeDesirableForOp(Opc, VT)) 1149 return SDValue(); 1150 1151 EVT PVT = VT; 1152 // Consult target whether it is a good idea to promote this operation and 1153 // what's the right type to promote it to. 1154 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1155 assert(PVT != VT && "Don't know what type to promote to!"); 1156 1157 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1158 1159 bool Replace0 = false; 1160 SDValue N0 = Op.getOperand(0); 1161 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1162 1163 bool Replace1 = false; 1164 SDValue N1 = Op.getOperand(1); 1165 SDValue NN1 = PromoteOperand(N1, PVT, Replace1); 1166 SDLoc DL(Op); 1167 1168 SDValue RV = 1169 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1)); 1170 1171 // New replace instances of N0 and N1 1172 if (Replace0 && N0 && N0.getOpcode() != ISD::DELETED_NODE && NN0 && 1173 NN0.getOpcode() != ISD::DELETED_NODE) { 1174 AddToWorklist(NN0.getNode()); 1175 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1176 } 1177 1178 if (Replace1 && N1 && N1.getOpcode() != ISD::DELETED_NODE && NN1 && 1179 NN1.getOpcode() != ISD::DELETED_NODE) { 1180 AddToWorklist(NN1.getNode()); 1181 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1182 } 1183 1184 // Deal with Op being deleted. 1185 if (Op && Op.getOpcode() != ISD::DELETED_NODE) 1186 return RV; 1187 } 1188 return SDValue(); 1189 } 1190 1191 /// Promote the specified integer shift operation if the target indicates it is 1192 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1193 /// i32 since i16 instructions are longer. 1194 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1195 if (!LegalOperations) 1196 return SDValue(); 1197 1198 EVT VT = Op.getValueType(); 1199 if (VT.isVector() || !VT.isInteger()) 1200 return SDValue(); 1201 1202 // If operation type is 'undesirable', e.g. i16 on x86, consider 1203 // promoting it. 1204 unsigned Opc = Op.getOpcode(); 1205 if (TLI.isTypeDesirableForOp(Opc, VT)) 1206 return SDValue(); 1207 1208 EVT PVT = VT; 1209 // Consult target whether it is a good idea to promote this operation and 1210 // what's the right type to promote it to. 1211 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1212 assert(PVT != VT && "Don't know what type to promote to!"); 1213 1214 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1215 1216 bool Replace = false; 1217 SDValue N0 = Op.getOperand(0); 1218 SDValue N1 = Op.getOperand(1); 1219 if (Opc == ISD::SRA) 1220 N0 = SExtPromoteOperand(N0, PVT); 1221 else if (Opc == ISD::SRL) 1222 N0 = ZExtPromoteOperand(N0, PVT); 1223 else 1224 N0 = PromoteOperand(N0, PVT, Replace); 1225 1226 if (!N0.getNode()) 1227 return SDValue(); 1228 1229 SDLoc DL(Op); 1230 SDValue RV = 1231 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1)); 1232 1233 AddToWorklist(N0.getNode()); 1234 if (Replace) 1235 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1236 1237 // Deal with Op being deleted. 1238 if (Op && Op.getOpcode() != ISD::DELETED_NODE) 1239 return RV; 1240 } 1241 return SDValue(); 1242 } 1243 1244 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1245 if (!LegalOperations) 1246 return SDValue(); 1247 1248 EVT VT = Op.getValueType(); 1249 if (VT.isVector() || !VT.isInteger()) 1250 return SDValue(); 1251 1252 // If operation type is 'undesirable', e.g. i16 on x86, consider 1253 // promoting it. 1254 unsigned Opc = Op.getOpcode(); 1255 if (TLI.isTypeDesirableForOp(Opc, VT)) 1256 return SDValue(); 1257 1258 EVT PVT = VT; 1259 // Consult target whether it is a good idea to promote this operation and 1260 // what's the right type to promote it to. 1261 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1262 assert(PVT != VT && "Don't know what type to promote to!"); 1263 // fold (aext (aext x)) -> (aext x) 1264 // fold (aext (zext x)) -> (zext x) 1265 // fold (aext (sext x)) -> (sext x) 1266 DEBUG(dbgs() << "\nPromoting "; 1267 Op.getNode()->dump(&DAG)); 1268 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1269 } 1270 return SDValue(); 1271 } 1272 1273 bool DAGCombiner::PromoteLoad(SDValue Op) { 1274 if (!LegalOperations) 1275 return false; 1276 1277 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1278 return false; 1279 1280 EVT VT = Op.getValueType(); 1281 if (VT.isVector() || !VT.isInteger()) 1282 return false; 1283 1284 // If operation type is 'undesirable', e.g. i16 on x86, consider 1285 // promoting it. 1286 unsigned Opc = Op.getOpcode(); 1287 if (TLI.isTypeDesirableForOp(Opc, VT)) 1288 return false; 1289 1290 EVT PVT = VT; 1291 // Consult target whether it is a good idea to promote this operation and 1292 // what's the right type to promote it to. 1293 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1294 assert(PVT != VT && "Don't know what type to promote to!"); 1295 1296 SDLoc DL(Op); 1297 SDNode *N = Op.getNode(); 1298 LoadSDNode *LD = cast<LoadSDNode>(N); 1299 EVT MemVT = LD->getMemoryVT(); 1300 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1301 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1302 : ISD::EXTLOAD) 1303 : LD->getExtensionType(); 1304 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT, 1305 LD->getChain(), LD->getBasePtr(), 1306 MemVT, LD->getMemOperand()); 1307 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD); 1308 1309 DEBUG(dbgs() << "\nPromoting "; 1310 N->dump(&DAG); 1311 dbgs() << "\nTo: "; 1312 Result.getNode()->dump(&DAG); 1313 dbgs() << '\n'); 1314 WorklistRemover DeadNodes(*this); 1315 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1316 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1317 deleteAndRecombine(N); 1318 AddToWorklist(Result.getNode()); 1319 return true; 1320 } 1321 return false; 1322 } 1323 1324 /// \brief Recursively delete a node which has no uses and any operands for 1325 /// which it is the only use. 1326 /// 1327 /// Note that this both deletes the nodes and removes them from the worklist. 1328 /// It also adds any nodes who have had a user deleted to the worklist as they 1329 /// may now have only one use and subject to other combines. 1330 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1331 if (!N->use_empty()) 1332 return false; 1333 1334 SmallSetVector<SDNode *, 16> Nodes; 1335 Nodes.insert(N); 1336 do { 1337 N = Nodes.pop_back_val(); 1338 if (!N) 1339 continue; 1340 1341 if (N->use_empty()) { 1342 for (const SDValue &ChildN : N->op_values()) 1343 Nodes.insert(ChildN.getNode()); 1344 1345 removeFromWorklist(N); 1346 DAG.DeleteNode(N); 1347 } else { 1348 AddToWorklist(N); 1349 } 1350 } while (!Nodes.empty()); 1351 return true; 1352 } 1353 1354 //===----------------------------------------------------------------------===// 1355 // Main DAG Combiner implementation 1356 //===----------------------------------------------------------------------===// 1357 1358 void DAGCombiner::Run(CombineLevel AtLevel) { 1359 // set the instance variables, so that the various visit routines may use it. 1360 Level = AtLevel; 1361 LegalOperations = Level >= AfterLegalizeVectorOps; 1362 LegalTypes = Level >= AfterLegalizeTypes; 1363 1364 // Add all the dag nodes to the worklist. 1365 for (SDNode &Node : DAG.allnodes()) 1366 AddToWorklist(&Node); 1367 1368 // Create a dummy node (which is not added to allnodes), that adds a reference 1369 // to the root node, preventing it from being deleted, and tracking any 1370 // changes of the root. 1371 HandleSDNode Dummy(DAG.getRoot()); 1372 1373 // While the worklist isn't empty, find a node and try to combine it. 1374 while (!WorklistMap.empty()) { 1375 SDNode *N; 1376 // The Worklist holds the SDNodes in order, but it may contain null entries. 1377 do { 1378 N = Worklist.pop_back_val(); 1379 } while (!N); 1380 1381 bool GoodWorklistEntry = WorklistMap.erase(N); 1382 (void)GoodWorklistEntry; 1383 assert(GoodWorklistEntry && 1384 "Found a worklist entry without a corresponding map entry!"); 1385 1386 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1387 // N is deleted from the DAG, since they too may now be dead or may have a 1388 // reduced number of uses, allowing other xforms. 1389 if (recursivelyDeleteUnusedNodes(N)) 1390 continue; 1391 1392 WorklistRemover DeadNodes(*this); 1393 1394 // If this combine is running after legalizing the DAG, re-legalize any 1395 // nodes pulled off the worklist. 1396 if (Level == AfterLegalizeDAG) { 1397 SmallSetVector<SDNode *, 16> UpdatedNodes; 1398 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1399 1400 for (SDNode *LN : UpdatedNodes) { 1401 AddToWorklist(LN); 1402 AddUsersToWorklist(LN); 1403 } 1404 if (!NIsValid) 1405 continue; 1406 } 1407 1408 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1409 1410 // Add any operands of the new node which have not yet been combined to the 1411 // worklist as well. Because the worklist uniques things already, this 1412 // won't repeatedly process the same operand. 1413 CombinedNodes.insert(N); 1414 for (const SDValue &ChildN : N->op_values()) 1415 if (!CombinedNodes.count(ChildN.getNode())) 1416 AddToWorklist(ChildN.getNode()); 1417 1418 SDValue RV = combine(N); 1419 1420 if (!RV.getNode()) 1421 continue; 1422 1423 ++NodesCombined; 1424 1425 // If we get back the same node we passed in, rather than a new node or 1426 // zero, we know that the node must have defined multiple values and 1427 // CombineTo was used. Since CombineTo takes care of the worklist 1428 // mechanics for us, we have no work to do in this case. 1429 if (RV.getNode() == N) 1430 continue; 1431 1432 assert(N->getOpcode() != ISD::DELETED_NODE && 1433 RV.getOpcode() != ISD::DELETED_NODE && 1434 "Node was deleted but visit returned new node!"); 1435 1436 DEBUG(dbgs() << " ... into: "; 1437 RV.getNode()->dump(&DAG)); 1438 1439 if (N->getNumValues() == RV.getNode()->getNumValues()) 1440 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1441 else { 1442 assert(N->getValueType(0) == RV.getValueType() && 1443 N->getNumValues() == 1 && "Type mismatch"); 1444 DAG.ReplaceAllUsesWith(N, &RV); 1445 } 1446 1447 // Push the new node and any users onto the worklist 1448 AddToWorklist(RV.getNode()); 1449 AddUsersToWorklist(RV.getNode()); 1450 1451 // Finally, if the node is now dead, remove it from the graph. The node 1452 // may not be dead if the replacement process recursively simplified to 1453 // something else needing this node. This will also take care of adding any 1454 // operands which have lost a user to the worklist. 1455 recursivelyDeleteUnusedNodes(N); 1456 } 1457 1458 // If the root changed (e.g. it was a dead load, update the root). 1459 DAG.setRoot(Dummy.getValue()); 1460 DAG.RemoveDeadNodes(); 1461 } 1462 1463 SDValue DAGCombiner::visit(SDNode *N) { 1464 switch (N->getOpcode()) { 1465 default: break; 1466 case ISD::TokenFactor: return visitTokenFactor(N); 1467 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1468 case ISD::ADD: return visitADD(N); 1469 case ISD::SUB: return visitSUB(N); 1470 case ISD::ADDC: return visitADDC(N); 1471 case ISD::UADDO: return visitUADDO(N); 1472 case ISD::SUBC: return visitSUBC(N); 1473 case ISD::USUBO: return visitUSUBO(N); 1474 case ISD::ADDE: return visitADDE(N); 1475 case ISD::ADDCARRY: return visitADDCARRY(N); 1476 case ISD::SUBE: return visitSUBE(N); 1477 case ISD::SUBCARRY: return visitSUBCARRY(N); 1478 case ISD::MUL: return visitMUL(N); 1479 case ISD::SDIV: return visitSDIV(N); 1480 case ISD::UDIV: return visitUDIV(N); 1481 case ISD::SREM: 1482 case ISD::UREM: return visitREM(N); 1483 case ISD::MULHU: return visitMULHU(N); 1484 case ISD::MULHS: return visitMULHS(N); 1485 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1486 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1487 case ISD::SMULO: return visitSMULO(N); 1488 case ISD::UMULO: return visitUMULO(N); 1489 case ISD::SMIN: 1490 case ISD::SMAX: 1491 case ISD::UMIN: 1492 case ISD::UMAX: return visitIMINMAX(N); 1493 case ISD::AND: return visitAND(N); 1494 case ISD::OR: return visitOR(N); 1495 case ISD::XOR: return visitXOR(N); 1496 case ISD::SHL: return visitSHL(N); 1497 case ISD::SRA: return visitSRA(N); 1498 case ISD::SRL: return visitSRL(N); 1499 case ISD::ROTR: 1500 case ISD::ROTL: return visitRotate(N); 1501 case ISD::ABS: return visitABS(N); 1502 case ISD::BSWAP: return visitBSWAP(N); 1503 case ISD::BITREVERSE: return visitBITREVERSE(N); 1504 case ISD::CTLZ: return visitCTLZ(N); 1505 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1506 case ISD::CTTZ: return visitCTTZ(N); 1507 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1508 case ISD::CTPOP: return visitCTPOP(N); 1509 case ISD::SELECT: return visitSELECT(N); 1510 case ISD::VSELECT: return visitVSELECT(N); 1511 case ISD::SELECT_CC: return visitSELECT_CC(N); 1512 case ISD::SETCC: return visitSETCC(N); 1513 case ISD::SETCCE: return visitSETCCE(N); 1514 case ISD::SETCCCARRY: return visitSETCCCARRY(N); 1515 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1516 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1517 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1518 case ISD::AssertZext: return visitAssertZext(N); 1519 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1520 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1521 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1522 case ISD::TRUNCATE: return visitTRUNCATE(N); 1523 case ISD::BITCAST: return visitBITCAST(N); 1524 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1525 case ISD::FADD: return visitFADD(N); 1526 case ISD::FSUB: return visitFSUB(N); 1527 case ISD::FMUL: return visitFMUL(N); 1528 case ISD::FMA: return visitFMA(N); 1529 case ISD::FDIV: return visitFDIV(N); 1530 case ISD::FREM: return visitFREM(N); 1531 case ISD::FSQRT: return visitFSQRT(N); 1532 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1533 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1534 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1535 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1536 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1537 case ISD::FP_ROUND: return visitFP_ROUND(N); 1538 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1539 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1540 case ISD::FNEG: return visitFNEG(N); 1541 case ISD::FABS: return visitFABS(N); 1542 case ISD::FFLOOR: return visitFFLOOR(N); 1543 case ISD::FMINNUM: return visitFMINNUM(N); 1544 case ISD::FMAXNUM: return visitFMAXNUM(N); 1545 case ISD::FCEIL: return visitFCEIL(N); 1546 case ISD::FTRUNC: return visitFTRUNC(N); 1547 case ISD::BRCOND: return visitBRCOND(N); 1548 case ISD::BR_CC: return visitBR_CC(N); 1549 case ISD::LOAD: return visitLOAD(N); 1550 case ISD::STORE: return visitSTORE(N); 1551 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1552 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1553 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1554 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1555 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1556 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1557 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1558 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1559 case ISD::MGATHER: return visitMGATHER(N); 1560 case ISD::MLOAD: return visitMLOAD(N); 1561 case ISD::MSCATTER: return visitMSCATTER(N); 1562 case ISD::MSTORE: return visitMSTORE(N); 1563 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1564 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1565 } 1566 return SDValue(); 1567 } 1568 1569 SDValue DAGCombiner::combine(SDNode *N) { 1570 SDValue RV = visit(N); 1571 1572 // If nothing happened, try a target-specific DAG combine. 1573 if (!RV.getNode()) { 1574 assert(N->getOpcode() != ISD::DELETED_NODE && 1575 "Node was deleted but visit returned NULL!"); 1576 1577 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1578 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1579 1580 // Expose the DAG combiner to the target combiner impls. 1581 TargetLowering::DAGCombinerInfo 1582 DagCombineInfo(DAG, Level, false, this); 1583 1584 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1585 } 1586 } 1587 1588 // If nothing happened still, try promoting the operation. 1589 if (!RV.getNode()) { 1590 switch (N->getOpcode()) { 1591 default: break; 1592 case ISD::ADD: 1593 case ISD::SUB: 1594 case ISD::MUL: 1595 case ISD::AND: 1596 case ISD::OR: 1597 case ISD::XOR: 1598 RV = PromoteIntBinOp(SDValue(N, 0)); 1599 break; 1600 case ISD::SHL: 1601 case ISD::SRA: 1602 case ISD::SRL: 1603 RV = PromoteIntShiftOp(SDValue(N, 0)); 1604 break; 1605 case ISD::SIGN_EXTEND: 1606 case ISD::ZERO_EXTEND: 1607 case ISD::ANY_EXTEND: 1608 RV = PromoteExtend(SDValue(N, 0)); 1609 break; 1610 case ISD::LOAD: 1611 if (PromoteLoad(SDValue(N, 0))) 1612 RV = SDValue(N, 0); 1613 break; 1614 } 1615 } 1616 1617 // If N is a commutative binary node, try commuting it to enable more 1618 // sdisel CSE. 1619 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) && 1620 N->getNumValues() == 1) { 1621 SDValue N0 = N->getOperand(0); 1622 SDValue N1 = N->getOperand(1); 1623 1624 // Constant operands are canonicalized to RHS. 1625 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1626 SDValue Ops[] = {N1, N0}; 1627 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1628 N->getFlags()); 1629 if (CSENode) 1630 return SDValue(CSENode, 0); 1631 } 1632 } 1633 1634 return RV; 1635 } 1636 1637 /// Given a node, return its input chain if it has one, otherwise return a null 1638 /// sd operand. 1639 static SDValue getInputChainForNode(SDNode *N) { 1640 if (unsigned NumOps = N->getNumOperands()) { 1641 if (N->getOperand(0).getValueType() == MVT::Other) 1642 return N->getOperand(0); 1643 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1644 return N->getOperand(NumOps-1); 1645 for (unsigned i = 1; i < NumOps-1; ++i) 1646 if (N->getOperand(i).getValueType() == MVT::Other) 1647 return N->getOperand(i); 1648 } 1649 return SDValue(); 1650 } 1651 1652 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1653 // If N has two operands, where one has an input chain equal to the other, 1654 // the 'other' chain is redundant. 1655 if (N->getNumOperands() == 2) { 1656 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1657 return N->getOperand(0); 1658 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1659 return N->getOperand(1); 1660 } 1661 1662 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1663 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1664 SmallPtrSet<SDNode*, 16> SeenOps; 1665 bool Changed = false; // If we should replace this token factor. 1666 1667 // Start out with this token factor. 1668 TFs.push_back(N); 1669 1670 // Iterate through token factors. The TFs grows when new token factors are 1671 // encountered. 1672 for (unsigned i = 0; i < TFs.size(); ++i) { 1673 SDNode *TF = TFs[i]; 1674 1675 // Check each of the operands. 1676 for (const SDValue &Op : TF->op_values()) { 1677 1678 switch (Op.getOpcode()) { 1679 case ISD::EntryToken: 1680 // Entry tokens don't need to be added to the list. They are 1681 // redundant. 1682 Changed = true; 1683 break; 1684 1685 case ISD::TokenFactor: 1686 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) { 1687 // Queue up for processing. 1688 TFs.push_back(Op.getNode()); 1689 // Clean up in case the token factor is removed. 1690 AddToWorklist(Op.getNode()); 1691 Changed = true; 1692 break; 1693 } 1694 LLVM_FALLTHROUGH; 1695 1696 default: 1697 // Only add if it isn't already in the list. 1698 if (SeenOps.insert(Op.getNode()).second) 1699 Ops.push_back(Op); 1700 else 1701 Changed = true; 1702 break; 1703 } 1704 } 1705 } 1706 1707 // Remove Nodes that are chained to another node in the list. Do so 1708 // by walking up chains breath-first stopping when we've seen 1709 // another operand. In general we must climb to the EntryNode, but we can exit 1710 // early if we find all remaining work is associated with just one operand as 1711 // no further pruning is possible. 1712 1713 // List of nodes to search through and original Ops from which they originate. 1714 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist; 1715 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op. 1716 SmallPtrSet<SDNode *, 16> SeenChains; 1717 bool DidPruneOps = false; 1718 1719 unsigned NumLeftToConsider = 0; 1720 for (const SDValue &Op : Ops) { 1721 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++)); 1722 OpWorkCount.push_back(1); 1723 } 1724 1725 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) { 1726 // If this is an Op, we can remove the op from the list. Remark any 1727 // search associated with it as from the current OpNumber. 1728 if (SeenOps.count(Op) != 0) { 1729 Changed = true; 1730 DidPruneOps = true; 1731 unsigned OrigOpNumber = 0; 1732 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op) 1733 OrigOpNumber++; 1734 assert((OrigOpNumber != Ops.size()) && 1735 "expected to find TokenFactor Operand"); 1736 // Re-mark worklist from OrigOpNumber to OpNumber 1737 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) { 1738 if (Worklist[i].second == OrigOpNumber) { 1739 Worklist[i].second = OpNumber; 1740 } 1741 } 1742 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber]; 1743 OpWorkCount[OrigOpNumber] = 0; 1744 NumLeftToConsider--; 1745 } 1746 // Add if it's a new chain 1747 if (SeenChains.insert(Op).second) { 1748 OpWorkCount[OpNumber]++; 1749 Worklist.push_back(std::make_pair(Op, OpNumber)); 1750 } 1751 }; 1752 1753 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) { 1754 // We need at least be consider at least 2 Ops to prune. 1755 if (NumLeftToConsider <= 1) 1756 break; 1757 auto CurNode = Worklist[i].first; 1758 auto CurOpNumber = Worklist[i].second; 1759 assert((OpWorkCount[CurOpNumber] > 0) && 1760 "Node should not appear in worklist"); 1761 switch (CurNode->getOpcode()) { 1762 case ISD::EntryToken: 1763 // Hitting EntryToken is the only way for the search to terminate without 1764 // hitting 1765 // another operand's search. Prevent us from marking this operand 1766 // considered. 1767 NumLeftToConsider++; 1768 break; 1769 case ISD::TokenFactor: 1770 for (const SDValue &Op : CurNode->op_values()) 1771 AddToWorklist(i, Op.getNode(), CurOpNumber); 1772 break; 1773 case ISD::CopyFromReg: 1774 case ISD::CopyToReg: 1775 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber); 1776 break; 1777 default: 1778 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode)) 1779 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber); 1780 break; 1781 } 1782 OpWorkCount[CurOpNumber]--; 1783 if (OpWorkCount[CurOpNumber] == 0) 1784 NumLeftToConsider--; 1785 } 1786 1787 // If we've changed things around then replace token factor. 1788 if (Changed) { 1789 SDValue Result; 1790 if (Ops.empty()) { 1791 // The entry token is the only possible outcome. 1792 Result = DAG.getEntryNode(); 1793 } else { 1794 if (DidPruneOps) { 1795 SmallVector<SDValue, 8> PrunedOps; 1796 // 1797 for (const SDValue &Op : Ops) { 1798 if (SeenChains.count(Op.getNode()) == 0) 1799 PrunedOps.push_back(Op); 1800 } 1801 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps); 1802 } else { 1803 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1804 } 1805 } 1806 return Result; 1807 } 1808 return SDValue(); 1809 } 1810 1811 /// MERGE_VALUES can always be eliminated. 1812 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1813 WorklistRemover DeadNodes(*this); 1814 // Replacing results may cause a different MERGE_VALUES to suddenly 1815 // be CSE'd with N, and carry its uses with it. Iterate until no 1816 // uses remain, to ensure that the node can be safely deleted. 1817 // First add the users of this node to the work list so that they 1818 // can be tried again once they have new operands. 1819 AddUsersToWorklist(N); 1820 do { 1821 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1822 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1823 } while (!N->use_empty()); 1824 deleteAndRecombine(N); 1825 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1826 } 1827 1828 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1829 /// ConstantSDNode pointer else nullptr. 1830 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1831 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1832 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1833 } 1834 1835 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) { 1836 auto BinOpcode = BO->getOpcode(); 1837 assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB || 1838 BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV || 1839 BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || 1840 BinOpcode == ISD::UREM || BinOpcode == ISD::AND || 1841 BinOpcode == ISD::OR || BinOpcode == ISD::XOR || 1842 BinOpcode == ISD::SHL || BinOpcode == ISD::SRL || 1843 BinOpcode == ISD::SRA || BinOpcode == ISD::FADD || 1844 BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || 1845 BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) && 1846 "Unexpected binary operator"); 1847 1848 // Bail out if any constants are opaque because we can't constant fold those. 1849 SDValue C1 = BO->getOperand(1); 1850 if (!isConstantOrConstantVector(C1, true) && 1851 !isConstantFPBuildVectorOrConstantFP(C1)) 1852 return SDValue(); 1853 1854 // Don't do this unless the old select is going away. We want to eliminate the 1855 // binary operator, not replace a binop with a select. 1856 // TODO: Handle ISD::SELECT_CC. 1857 SDValue Sel = BO->getOperand(0); 1858 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) 1859 return SDValue(); 1860 1861 SDValue CT = Sel.getOperand(1); 1862 if (!isConstantOrConstantVector(CT, true) && 1863 !isConstantFPBuildVectorOrConstantFP(CT)) 1864 return SDValue(); 1865 1866 SDValue CF = Sel.getOperand(2); 1867 if (!isConstantOrConstantVector(CF, true) && 1868 !isConstantFPBuildVectorOrConstantFP(CF)) 1869 return SDValue(); 1870 1871 // We have a select-of-constants followed by a binary operator with a 1872 // constant. Eliminate the binop by pulling the constant math into the select. 1873 // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1 1874 EVT VT = Sel.getValueType(); 1875 SDLoc DL(Sel); 1876 SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1); 1877 assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) || 1878 isConstantFPBuildVectorOrConstantFP(NewCT)) && 1879 "Failed to constant fold a binop with constant operands"); 1880 1881 SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1); 1882 assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) || 1883 isConstantFPBuildVectorOrConstantFP(NewCF)) && 1884 "Failed to constant fold a binop with constant operands"); 1885 1886 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF); 1887 } 1888 1889 SDValue DAGCombiner::visitADD(SDNode *N) { 1890 SDValue N0 = N->getOperand(0); 1891 SDValue N1 = N->getOperand(1); 1892 EVT VT = N0.getValueType(); 1893 SDLoc DL(N); 1894 1895 // fold vector ops 1896 if (VT.isVector()) { 1897 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1898 return FoldedVOp; 1899 1900 // fold (add x, 0) -> x, vector edition 1901 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1902 return N0; 1903 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1904 return N1; 1905 } 1906 1907 // fold (add x, undef) -> undef 1908 if (N0.isUndef()) 1909 return N0; 1910 1911 if (N1.isUndef()) 1912 return N1; 1913 1914 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 1915 // canonicalize constant to RHS 1916 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 1917 return DAG.getNode(ISD::ADD, DL, VT, N1, N0); 1918 // fold (add c1, c2) -> c1+c2 1919 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(), 1920 N1.getNode()); 1921 } 1922 1923 // fold (add x, 0) -> x 1924 if (isNullConstant(N1)) 1925 return N0; 1926 1927 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) { 1928 // fold ((c1-A)+c2) -> (c1+c2)-A 1929 if (N0.getOpcode() == ISD::SUB && 1930 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) { 1931 // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic. 1932 return DAG.getNode(ISD::SUB, DL, VT, 1933 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)), 1934 N0.getOperand(1)); 1935 } 1936 1937 // add (sext i1 X), 1 -> zext (not i1 X) 1938 // We don't transform this pattern: 1939 // add (zext i1 X), -1 -> sext (not i1 X) 1940 // because most (?) targets generate better code for the zext form. 1941 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() && 1942 isOneConstantOrOneSplatConstant(N1)) { 1943 SDValue X = N0.getOperand(0); 1944 if ((!LegalOperations || 1945 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) && 1946 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) && 1947 X.getScalarValueSizeInBits() == 1) { 1948 SDValue Not = DAG.getNOT(DL, X, X.getValueType()); 1949 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not); 1950 } 1951 } 1952 } 1953 1954 if (SDValue NewSel = foldBinOpIntoSelect(N)) 1955 return NewSel; 1956 1957 // reassociate add 1958 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1)) 1959 return RADD; 1960 1961 // fold ((0-A) + B) -> B-A 1962 if (N0.getOpcode() == ISD::SUB && 1963 isNullConstantOrNullSplatConstant(N0.getOperand(0))) 1964 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); 1965 1966 // fold (A + (0-B)) -> A-B 1967 if (N1.getOpcode() == ISD::SUB && 1968 isNullConstantOrNullSplatConstant(N1.getOperand(0))) 1969 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1)); 1970 1971 // fold (A+(B-A)) -> B 1972 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1973 return N1.getOperand(0); 1974 1975 // fold ((B-A)+A) -> B 1976 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1977 return N0.getOperand(0); 1978 1979 // fold (A+(B-(A+C))) to (B-C) 1980 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1981 N0 == N1.getOperand(1).getOperand(0)) 1982 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 1983 N1.getOperand(1).getOperand(1)); 1984 1985 // fold (A+(B-(C+A))) to (B-C) 1986 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1987 N0 == N1.getOperand(1).getOperand(1)) 1988 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 1989 N1.getOperand(1).getOperand(0)); 1990 1991 // fold (A+((B-A)+or-C)) to (B+or-C) 1992 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1993 N1.getOperand(0).getOpcode() == ISD::SUB && 1994 N0 == N1.getOperand(0).getOperand(1)) 1995 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0), 1996 N1.getOperand(1)); 1997 1998 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1999 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 2000 SDValue N00 = N0.getOperand(0); 2001 SDValue N01 = N0.getOperand(1); 2002 SDValue N10 = N1.getOperand(0); 2003 SDValue N11 = N1.getOperand(1); 2004 2005 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10)) 2006 return DAG.getNode(ISD::SUB, DL, VT, 2007 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 2008 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 2009 } 2010 2011 if (SimplifyDemandedBits(SDValue(N, 0))) 2012 return SDValue(N, 0); 2013 2014 // fold (a+b) -> (a|b) iff a and b share no bits. 2015 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 2016 DAG.haveNoCommonBitsSet(N0, N1)) 2017 return DAG.getNode(ISD::OR, DL, VT, N0, N1); 2018 2019 if (SDValue Combined = visitADDLike(N0, N1, N)) 2020 return Combined; 2021 2022 if (SDValue Combined = visitADDLike(N1, N0, N)) 2023 return Combined; 2024 2025 return SDValue(); 2026 } 2027 2028 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) { 2029 bool Masked = false; 2030 2031 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization. 2032 while (true) { 2033 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) { 2034 V = V.getOperand(0); 2035 continue; 2036 } 2037 2038 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) { 2039 Masked = true; 2040 V = V.getOperand(0); 2041 continue; 2042 } 2043 2044 break; 2045 } 2046 2047 // If this is not a carry, return. 2048 if (V.getResNo() != 1) 2049 return SDValue(); 2050 2051 if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY && 2052 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO) 2053 return SDValue(); 2054 2055 // If the result is masked, then no matter what kind of bool it is we can 2056 // return. If it isn't, then we need to make sure the bool type is either 0 or 2057 // 1 and not other values. 2058 if (Masked || 2059 TLI.getBooleanContents(V.getValueType()) == 2060 TargetLoweringBase::ZeroOrOneBooleanContent) 2061 return V; 2062 2063 return SDValue(); 2064 } 2065 2066 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) { 2067 EVT VT = N0.getValueType(); 2068 SDLoc DL(LocReference); 2069 2070 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 2071 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 2072 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0))) 2073 return DAG.getNode(ISD::SUB, DL, VT, N0, 2074 DAG.getNode(ISD::SHL, DL, VT, 2075 N1.getOperand(0).getOperand(1), 2076 N1.getOperand(1))); 2077 2078 if (N1.getOpcode() == ISD::AND) { 2079 SDValue AndOp0 = N1.getOperand(0); 2080 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 2081 unsigned DestBits = VT.getScalarSizeInBits(); 2082 2083 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 2084 // and similar xforms where the inner op is either ~0 or 0. 2085 if (NumSignBits == DestBits && 2086 isOneConstantOrOneSplatConstant(N1->getOperand(1))) 2087 return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0); 2088 } 2089 2090 // add (sext i1), X -> sub X, (zext i1) 2091 if (N0.getOpcode() == ISD::SIGN_EXTEND && 2092 N0.getOperand(0).getValueType() == MVT::i1 && 2093 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 2094 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 2095 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 2096 } 2097 2098 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 2099 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2100 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2101 if (TN->getVT() == MVT::i1) { 2102 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2103 DAG.getConstant(1, DL, VT)); 2104 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 2105 } 2106 } 2107 2108 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2109 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) 2110 return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(), 2111 N0, N1.getOperand(0), N1.getOperand(2)); 2112 2113 // (add X, Carry) -> (addcarry X, 0, Carry) 2114 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2115 if (SDValue Carry = getAsCarry(TLI, N1)) 2116 return DAG.getNode(ISD::ADDCARRY, DL, 2117 DAG.getVTList(VT, Carry.getValueType()), N0, 2118 DAG.getConstant(0, DL, VT), Carry); 2119 2120 return SDValue(); 2121 } 2122 2123 SDValue DAGCombiner::visitADDC(SDNode *N) { 2124 SDValue N0 = N->getOperand(0); 2125 SDValue N1 = N->getOperand(1); 2126 EVT VT = N0.getValueType(); 2127 SDLoc DL(N); 2128 2129 // If the flag result is dead, turn this into an ADD. 2130 if (!N->hasAnyUseOfValue(1)) 2131 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2132 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2133 2134 // canonicalize constant to RHS. 2135 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2136 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2137 if (N0C && !N1C) 2138 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0); 2139 2140 // fold (addc x, 0) -> x + no carry out 2141 if (isNullConstant(N1)) 2142 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 2143 DL, MVT::Glue)); 2144 2145 // If it cannot overflow, transform into an add. 2146 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2147 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2148 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2149 2150 return SDValue(); 2151 } 2152 2153 SDValue DAGCombiner::visitUADDO(SDNode *N) { 2154 SDValue N0 = N->getOperand(0); 2155 SDValue N1 = N->getOperand(1); 2156 EVT VT = N0.getValueType(); 2157 if (VT.isVector()) 2158 return SDValue(); 2159 2160 EVT CarryVT = N->getValueType(1); 2161 SDLoc DL(N); 2162 2163 // If the flag result is dead, turn this into an ADD. 2164 if (!N->hasAnyUseOfValue(1)) 2165 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2166 DAG.getUNDEF(CarryVT)); 2167 2168 // canonicalize constant to RHS. 2169 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2170 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2171 if (N0C && !N1C) 2172 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0); 2173 2174 // fold (uaddo x, 0) -> x + no carry out 2175 if (isNullConstant(N1)) 2176 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2177 2178 // If it cannot overflow, transform into an add. 2179 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2180 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2181 DAG.getConstant(0, DL, CarryVT)); 2182 2183 if (SDValue Combined = visitUADDOLike(N0, N1, N)) 2184 return Combined; 2185 2186 if (SDValue Combined = visitUADDOLike(N1, N0, N)) 2187 return Combined; 2188 2189 return SDValue(); 2190 } 2191 2192 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) { 2193 auto VT = N0.getValueType(); 2194 2195 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2196 // If Y + 1 cannot overflow. 2197 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) { 2198 SDValue Y = N1.getOperand(0); 2199 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType()); 2200 if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never) 2201 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y, 2202 N1.getOperand(2)); 2203 } 2204 2205 // (uaddo X, Carry) -> (addcarry X, 0, Carry) 2206 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2207 if (SDValue Carry = getAsCarry(TLI, N1)) 2208 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, 2209 DAG.getConstant(0, SDLoc(N), VT), Carry); 2210 2211 return SDValue(); 2212 } 2213 2214 SDValue DAGCombiner::visitADDE(SDNode *N) { 2215 SDValue N0 = N->getOperand(0); 2216 SDValue N1 = N->getOperand(1); 2217 SDValue CarryIn = N->getOperand(2); 2218 2219 // canonicalize constant to RHS 2220 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2221 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2222 if (N0C && !N1C) 2223 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 2224 N1, N0, CarryIn); 2225 2226 // fold (adde x, y, false) -> (addc x, y) 2227 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2228 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 2229 2230 return SDValue(); 2231 } 2232 2233 SDValue DAGCombiner::visitADDCARRY(SDNode *N) { 2234 SDValue N0 = N->getOperand(0); 2235 SDValue N1 = N->getOperand(1); 2236 SDValue CarryIn = N->getOperand(2); 2237 SDLoc DL(N); 2238 2239 // canonicalize constant to RHS 2240 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2241 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2242 if (N0C && !N1C) 2243 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn); 2244 2245 // fold (addcarry x, y, false) -> (uaddo x, y) 2246 if (isNullConstant(CarryIn)) 2247 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1); 2248 2249 // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry. 2250 if (isNullConstant(N0) && isNullConstant(N1)) { 2251 EVT VT = N0.getValueType(); 2252 EVT CarryVT = CarryIn.getValueType(); 2253 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT); 2254 AddToWorklist(CarryExt.getNode()); 2255 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt, 2256 DAG.getConstant(1, DL, VT)), 2257 DAG.getConstant(0, DL, CarryVT)); 2258 } 2259 2260 if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N)) 2261 return Combined; 2262 2263 if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N)) 2264 return Combined; 2265 2266 return SDValue(); 2267 } 2268 2269 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, 2270 SDNode *N) { 2271 // Iff the flag result is dead: 2272 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry) 2273 if ((N0.getOpcode() == ISD::ADD || 2274 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) && 2275 isNullConstant(N1) && !N->hasAnyUseOfValue(1)) 2276 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), 2277 N0.getOperand(0), N0.getOperand(1), CarryIn); 2278 2279 /** 2280 * When one of the addcarry argument is itself a carry, we may be facing 2281 * a diamond carry propagation. In which case we try to transform the DAG 2282 * to ensure linear carry propagation if that is possible. 2283 * 2284 * We are trying to get: 2285 * (addcarry X, 0, (addcarry A, B, Z):Carry) 2286 */ 2287 if (auto Y = getAsCarry(TLI, N1)) { 2288 /** 2289 * (uaddo A, B) 2290 * / \ 2291 * Carry Sum 2292 * | \ 2293 * | (addcarry *, 0, Z) 2294 * | / 2295 * \ Carry 2296 * | / 2297 * (addcarry X, *, *) 2298 */ 2299 if (Y.getOpcode() == ISD::UADDO && 2300 CarryIn.getResNo() == 1 && 2301 CarryIn.getOpcode() == ISD::ADDCARRY && 2302 isNullConstant(CarryIn.getOperand(1)) && 2303 CarryIn.getOperand(0) == Y.getValue(0)) { 2304 auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(), 2305 Y.getOperand(0), Y.getOperand(1), 2306 CarryIn.getOperand(2)); 2307 AddToWorklist(NewY.getNode()); 2308 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, 2309 DAG.getConstant(0, SDLoc(N), N0.getValueType()), 2310 NewY.getValue(1)); 2311 } 2312 } 2313 2314 return SDValue(); 2315 } 2316 2317 // Since it may not be valid to emit a fold to zero for vector initializers 2318 // check if we can before folding. 2319 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 2320 SelectionDAG &DAG, bool LegalOperations, 2321 bool LegalTypes) { 2322 if (!VT.isVector()) 2323 return DAG.getConstant(0, DL, VT); 2324 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 2325 return DAG.getConstant(0, DL, VT); 2326 return SDValue(); 2327 } 2328 2329 SDValue DAGCombiner::visitSUB(SDNode *N) { 2330 SDValue N0 = N->getOperand(0); 2331 SDValue N1 = N->getOperand(1); 2332 EVT VT = N0.getValueType(); 2333 SDLoc DL(N); 2334 2335 // fold vector ops 2336 if (VT.isVector()) { 2337 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2338 return FoldedVOp; 2339 2340 // fold (sub x, 0) -> x, vector edition 2341 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2342 return N0; 2343 } 2344 2345 // fold (sub x, x) -> 0 2346 // FIXME: Refactor this and xor and other similar operations together. 2347 if (N0 == N1) 2348 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes); 2349 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2350 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 2351 // fold (sub c1, c2) -> c1-c2 2352 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(), 2353 N1.getNode()); 2354 } 2355 2356 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2357 return NewSel; 2358 2359 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2360 2361 // fold (sub x, c) -> (add x, -c) 2362 if (N1C) { 2363 return DAG.getNode(ISD::ADD, DL, VT, N0, 2364 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 2365 } 2366 2367 if (isNullConstantOrNullSplatConstant(N0)) { 2368 unsigned BitWidth = VT.getScalarSizeInBits(); 2369 // Right-shifting everything out but the sign bit followed by negation is 2370 // the same as flipping arithmetic/logical shift type without the negation: 2371 // -(X >>u 31) -> (X >>s 31) 2372 // -(X >>s 31) -> (X >>u 31) 2373 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) { 2374 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1)); 2375 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) { 2376 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA; 2377 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT)) 2378 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1)); 2379 } 2380 } 2381 2382 // 0 - X --> 0 if the sub is NUW. 2383 if (N->getFlags().hasNoUnsignedWrap()) 2384 return N0; 2385 2386 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) { 2387 // N1 is either 0 or the minimum signed value. If the sub is NSW, then 2388 // N1 must be 0 because negating the minimum signed value is undefined. 2389 if (N->getFlags().hasNoSignedWrap()) 2390 return N0; 2391 2392 // 0 - X --> X if X is 0 or the minimum signed value. 2393 return N1; 2394 } 2395 } 2396 2397 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 2398 if (isAllOnesConstantOrAllOnesSplatConstant(N0)) 2399 return DAG.getNode(ISD::XOR, DL, VT, N1, N0); 2400 2401 // fold A-(A-B) -> B 2402 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 2403 return N1.getOperand(1); 2404 2405 // fold (A+B)-A -> B 2406 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 2407 return N0.getOperand(1); 2408 2409 // fold (A+B)-B -> A 2410 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 2411 return N0.getOperand(0); 2412 2413 // fold C2-(A+C1) -> (C2-C1)-A 2414 if (N1.getOpcode() == ISD::ADD) { 2415 SDValue N11 = N1.getOperand(1); 2416 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) && 2417 isConstantOrConstantVector(N11, /* NoOpaques */ true)) { 2418 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11); 2419 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0)); 2420 } 2421 } 2422 2423 // fold ((A+(B+or-C))-B) -> A+or-C 2424 if (N0.getOpcode() == ISD::ADD && 2425 (N0.getOperand(1).getOpcode() == ISD::SUB || 2426 N0.getOperand(1).getOpcode() == ISD::ADD) && 2427 N0.getOperand(1).getOperand(0) == N1) 2428 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0), 2429 N0.getOperand(1).getOperand(1)); 2430 2431 // fold ((A+(C+B))-B) -> A+C 2432 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD && 2433 N0.getOperand(1).getOperand(1) == N1) 2434 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), 2435 N0.getOperand(1).getOperand(0)); 2436 2437 // fold ((A-(B-C))-C) -> A-B 2438 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB && 2439 N0.getOperand(1).getOperand(1) == N1) 2440 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), 2441 N0.getOperand(1).getOperand(0)); 2442 2443 // If either operand of a sub is undef, the result is undef 2444 if (N0.isUndef()) 2445 return N0; 2446 if (N1.isUndef()) 2447 return N1; 2448 2449 // If the relocation model supports it, consider symbol offsets. 2450 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 2451 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 2452 // fold (sub Sym, c) -> Sym-c 2453 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 2454 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 2455 GA->getOffset() - 2456 (uint64_t)N1C->getSExtValue()); 2457 // fold (sub Sym+c1, Sym+c2) -> c1-c2 2458 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 2459 if (GA->getGlobal() == GB->getGlobal()) 2460 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 2461 DL, VT); 2462 } 2463 2464 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 2465 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2466 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2467 if (TN->getVT() == MVT::i1) { 2468 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2469 DAG.getConstant(1, DL, VT)); 2470 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 2471 } 2472 } 2473 2474 return SDValue(); 2475 } 2476 2477 SDValue DAGCombiner::visitSUBC(SDNode *N) { 2478 SDValue N0 = N->getOperand(0); 2479 SDValue N1 = N->getOperand(1); 2480 EVT VT = N0.getValueType(); 2481 SDLoc DL(N); 2482 2483 // If the flag result is dead, turn this into an SUB. 2484 if (!N->hasAnyUseOfValue(1)) 2485 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2486 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2487 2488 // fold (subc x, x) -> 0 + no borrow 2489 if (N0 == N1) 2490 return CombineTo(N, DAG.getConstant(0, DL, VT), 2491 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2492 2493 // fold (subc x, 0) -> x + no borrow 2494 if (isNullConstant(N1)) 2495 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2496 2497 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2498 if (isAllOnesConstant(N0)) 2499 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2500 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2501 2502 return SDValue(); 2503 } 2504 2505 SDValue DAGCombiner::visitUSUBO(SDNode *N) { 2506 SDValue N0 = N->getOperand(0); 2507 SDValue N1 = N->getOperand(1); 2508 EVT VT = N0.getValueType(); 2509 if (VT.isVector()) 2510 return SDValue(); 2511 2512 EVT CarryVT = N->getValueType(1); 2513 SDLoc DL(N); 2514 2515 // If the flag result is dead, turn this into an SUB. 2516 if (!N->hasAnyUseOfValue(1)) 2517 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2518 DAG.getUNDEF(CarryVT)); 2519 2520 // fold (usubo x, x) -> 0 + no borrow 2521 if (N0 == N1) 2522 return CombineTo(N, DAG.getConstant(0, DL, VT), 2523 DAG.getConstant(0, DL, CarryVT)); 2524 2525 // fold (usubo x, 0) -> x + no borrow 2526 if (isNullConstant(N1)) 2527 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2528 2529 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2530 if (isAllOnesConstant(N0)) 2531 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2532 DAG.getConstant(0, DL, CarryVT)); 2533 2534 return SDValue(); 2535 } 2536 2537 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2538 SDValue N0 = N->getOperand(0); 2539 SDValue N1 = N->getOperand(1); 2540 SDValue CarryIn = N->getOperand(2); 2541 2542 // fold (sube x, y, false) -> (subc x, y) 2543 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2544 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2545 2546 return SDValue(); 2547 } 2548 2549 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) { 2550 SDValue N0 = N->getOperand(0); 2551 SDValue N1 = N->getOperand(1); 2552 SDValue CarryIn = N->getOperand(2); 2553 2554 // fold (subcarry x, y, false) -> (usubo x, y) 2555 if (isNullConstant(CarryIn)) 2556 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1); 2557 2558 return SDValue(); 2559 } 2560 2561 SDValue DAGCombiner::visitMUL(SDNode *N) { 2562 SDValue N0 = N->getOperand(0); 2563 SDValue N1 = N->getOperand(1); 2564 EVT VT = N0.getValueType(); 2565 2566 // fold (mul x, undef) -> 0 2567 if (N0.isUndef() || N1.isUndef()) 2568 return DAG.getConstant(0, SDLoc(N), VT); 2569 2570 bool N0IsConst = false; 2571 bool N1IsConst = false; 2572 bool N1IsOpaqueConst = false; 2573 bool N0IsOpaqueConst = false; 2574 APInt ConstValue0, ConstValue1; 2575 // fold vector ops 2576 if (VT.isVector()) { 2577 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2578 return FoldedVOp; 2579 2580 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0); 2581 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 2582 } else { 2583 N0IsConst = isa<ConstantSDNode>(N0); 2584 if (N0IsConst) { 2585 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2586 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2587 } 2588 N1IsConst = isa<ConstantSDNode>(N1); 2589 if (N1IsConst) { 2590 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2591 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2592 } 2593 } 2594 2595 // fold (mul c1, c2) -> c1*c2 2596 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2597 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2598 N0.getNode(), N1.getNode()); 2599 2600 // canonicalize constant to RHS (vector doesn't have to splat) 2601 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2602 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2603 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2604 // fold (mul x, 0) -> 0 2605 if (N1IsConst && ConstValue1.isNullValue()) 2606 return N1; 2607 // We require a splat of the entire scalar bit width for non-contiguous 2608 // bit patterns. 2609 bool IsFullSplat = 2610 ConstValue1.getBitWidth() == VT.getScalarSizeInBits(); 2611 // fold (mul x, 1) -> x 2612 if (N1IsConst && ConstValue1.isOneValue() && IsFullSplat) 2613 return N0; 2614 2615 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2616 return NewSel; 2617 2618 // fold (mul x, -1) -> 0-x 2619 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2620 SDLoc DL(N); 2621 return DAG.getNode(ISD::SUB, DL, VT, 2622 DAG.getConstant(0, DL, VT), N0); 2623 } 2624 // fold (mul x, (1 << c)) -> x << c 2625 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2626 IsFullSplat) { 2627 SDLoc DL(N); 2628 return DAG.getNode(ISD::SHL, DL, VT, N0, 2629 DAG.getConstant(ConstValue1.logBase2(), DL, 2630 getShiftAmountTy(N0.getValueType()))); 2631 } 2632 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2633 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2634 IsFullSplat) { 2635 unsigned Log2Val = (-ConstValue1).logBase2(); 2636 SDLoc DL(N); 2637 // FIXME: If the input is something that is easily negated (e.g. a 2638 // single-use add), we should put the negate there. 2639 return DAG.getNode(ISD::SUB, DL, VT, 2640 DAG.getConstant(0, DL, VT), 2641 DAG.getNode(ISD::SHL, DL, VT, N0, 2642 DAG.getConstant(Log2Val, DL, 2643 getShiftAmountTy(N0.getValueType())))); 2644 } 2645 2646 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2647 if (N0.getOpcode() == ISD::SHL && 2648 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 2649 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 2650 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 2651 if (isConstantOrConstantVector(C3)) 2652 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 2653 } 2654 2655 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2656 // use. 2657 { 2658 SDValue Sh(nullptr, 0), Y(nullptr, 0); 2659 2660 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2661 if (N0.getOpcode() == ISD::SHL && 2662 isConstantOrConstantVector(N0.getOperand(1)) && 2663 N0.getNode()->hasOneUse()) { 2664 Sh = N0; Y = N1; 2665 } else if (N1.getOpcode() == ISD::SHL && 2666 isConstantOrConstantVector(N1.getOperand(1)) && 2667 N1.getNode()->hasOneUse()) { 2668 Sh = N1; Y = N0; 2669 } 2670 2671 if (Sh.getNode()) { 2672 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 2673 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 2674 } 2675 } 2676 2677 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2678 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2679 N0.getOpcode() == ISD::ADD && 2680 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2681 isMulAddWithConstProfitable(N, N0, N1)) 2682 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2683 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2684 N0.getOperand(0), N1), 2685 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2686 N0.getOperand(1), N1)); 2687 2688 // reassociate mul 2689 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2690 return RMUL; 2691 2692 return SDValue(); 2693 } 2694 2695 /// Return true if divmod libcall is available. 2696 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2697 const TargetLowering &TLI) { 2698 RTLIB::Libcall LC; 2699 EVT NodeType = Node->getValueType(0); 2700 if (!NodeType.isSimple()) 2701 return false; 2702 switch (NodeType.getSimpleVT().SimpleTy) { 2703 default: return false; // No libcall for vector types. 2704 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2705 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2706 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2707 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2708 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2709 } 2710 2711 return TLI.getLibcallName(LC) != nullptr; 2712 } 2713 2714 /// Issue divrem if both quotient and remainder are needed. 2715 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2716 if (Node->use_empty()) 2717 return SDValue(); // This is a dead node, leave it alone. 2718 2719 unsigned Opcode = Node->getOpcode(); 2720 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2721 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2722 2723 // DivMod lib calls can still work on non-legal types if using lib-calls. 2724 EVT VT = Node->getValueType(0); 2725 if (VT.isVector() || !VT.isInteger()) 2726 return SDValue(); 2727 2728 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 2729 return SDValue(); 2730 2731 // If DIVREM is going to get expanded into a libcall, 2732 // but there is no libcall available, then don't combine. 2733 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2734 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2735 return SDValue(); 2736 2737 // If div is legal, it's better to do the normal expansion 2738 unsigned OtherOpcode = 0; 2739 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2740 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2741 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2742 return SDValue(); 2743 } else { 2744 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2745 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2746 return SDValue(); 2747 } 2748 2749 SDValue Op0 = Node->getOperand(0); 2750 SDValue Op1 = Node->getOperand(1); 2751 SDValue combined; 2752 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2753 UE = Op0.getNode()->use_end(); UI != UE;) { 2754 SDNode *User = *UI++; 2755 if (User == Node || User->use_empty()) 2756 continue; 2757 // Convert the other matching node(s), too; 2758 // otherwise, the DIVREM may get target-legalized into something 2759 // target-specific that we won't be able to recognize. 2760 unsigned UserOpc = User->getOpcode(); 2761 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2762 User->getOperand(0) == Op0 && 2763 User->getOperand(1) == Op1) { 2764 if (!combined) { 2765 if (UserOpc == OtherOpcode) { 2766 SDVTList VTs = DAG.getVTList(VT, VT); 2767 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2768 } else if (UserOpc == DivRemOpc) { 2769 combined = SDValue(User, 0); 2770 } else { 2771 assert(UserOpc == Opcode); 2772 continue; 2773 } 2774 } 2775 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2776 CombineTo(User, combined); 2777 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2778 CombineTo(User, combined.getValue(1)); 2779 } 2780 } 2781 return combined; 2782 } 2783 2784 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) { 2785 SDValue N0 = N->getOperand(0); 2786 SDValue N1 = N->getOperand(1); 2787 EVT VT = N->getValueType(0); 2788 SDLoc DL(N); 2789 2790 if (DAG.isUndef(N->getOpcode(), {N0, N1})) 2791 return DAG.getUNDEF(VT); 2792 2793 // undef / X -> 0 2794 // undef % X -> 0 2795 if (N0.isUndef()) 2796 return DAG.getConstant(0, DL, VT); 2797 2798 return SDValue(); 2799 } 2800 2801 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2802 SDValue N0 = N->getOperand(0); 2803 SDValue N1 = N->getOperand(1); 2804 EVT VT = N->getValueType(0); 2805 2806 // fold vector ops 2807 if (VT.isVector()) 2808 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2809 return FoldedVOp; 2810 2811 SDLoc DL(N); 2812 2813 // fold (sdiv c1, c2) -> c1/c2 2814 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2815 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2816 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2817 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2818 // fold (sdiv X, 1) -> X 2819 if (N1C && N1C->isOne()) 2820 return N0; 2821 // fold (sdiv X, -1) -> 0-X 2822 if (N1C && N1C->isAllOnesValue()) 2823 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0); 2824 2825 if (SDValue V = simplifyDivRem(N, DAG)) 2826 return V; 2827 2828 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2829 return NewSel; 2830 2831 // If we know the sign bits of both operands are zero, strength reduce to a 2832 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2833 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2834 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2835 2836 // fold (sdiv X, pow2) -> simple ops after legalize 2837 // FIXME: We check for the exact bit here because the generic lowering gives 2838 // better results in that case. The target-specific lowering should learn how 2839 // to handle exact sdivs efficiently. 2840 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2841 !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() || 2842 (-N1C->getAPIntValue()).isPowerOf2())) { 2843 // Target-specific implementation of sdiv x, pow2. 2844 if (SDValue Res = BuildSDIVPow2(N)) 2845 return Res; 2846 2847 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2848 2849 // Splat the sign bit into the register 2850 SDValue SGN = 2851 DAG.getNode(ISD::SRA, DL, VT, N0, 2852 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2853 getShiftAmountTy(N0.getValueType()))); 2854 AddToWorklist(SGN.getNode()); 2855 2856 // Add (N0 < 0) ? abs2 - 1 : 0; 2857 SDValue SRL = 2858 DAG.getNode(ISD::SRL, DL, VT, SGN, 2859 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2860 getShiftAmountTy(SGN.getValueType()))); 2861 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2862 AddToWorklist(SRL.getNode()); 2863 AddToWorklist(ADD.getNode()); // Divide by pow2 2864 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2865 DAG.getConstant(lg2, DL, 2866 getShiftAmountTy(ADD.getValueType()))); 2867 2868 // If we're dividing by a positive value, we're done. Otherwise, we must 2869 // negate the result. 2870 if (N1C->getAPIntValue().isNonNegative()) 2871 return SRA; 2872 2873 AddToWorklist(SRA.getNode()); 2874 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2875 } 2876 2877 // If integer divide is expensive and we satisfy the requirements, emit an 2878 // alternate sequence. Targets may check function attributes for size/speed 2879 // trade-offs. 2880 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2881 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2882 if (SDValue Op = BuildSDIV(N)) 2883 return Op; 2884 2885 // sdiv, srem -> sdivrem 2886 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 2887 // true. Otherwise, we break the simplification logic in visitREM(). 2888 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2889 if (SDValue DivRem = useDivRem(N)) 2890 return DivRem; 2891 2892 return SDValue(); 2893 } 2894 2895 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2896 SDValue N0 = N->getOperand(0); 2897 SDValue N1 = N->getOperand(1); 2898 EVT VT = N->getValueType(0); 2899 2900 // fold vector ops 2901 if (VT.isVector()) 2902 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2903 return FoldedVOp; 2904 2905 SDLoc DL(N); 2906 2907 // fold (udiv c1, c2) -> c1/c2 2908 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2909 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2910 if (N0C && N1C) 2911 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2912 N0C, N1C)) 2913 return Folded; 2914 2915 if (SDValue V = simplifyDivRem(N, DAG)) 2916 return V; 2917 2918 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2919 return NewSel; 2920 2921 // fold (udiv x, (1 << c)) -> x >>u c 2922 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 2923 DAG.isKnownToBeAPowerOfTwo(N1)) { 2924 SDValue LogBase2 = BuildLogBase2(N1, DL); 2925 AddToWorklist(LogBase2.getNode()); 2926 2927 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 2928 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 2929 AddToWorklist(Trunc.getNode()); 2930 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 2931 } 2932 2933 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2934 if (N1.getOpcode() == ISD::SHL) { 2935 SDValue N10 = N1.getOperand(0); 2936 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) && 2937 DAG.isKnownToBeAPowerOfTwo(N10)) { 2938 SDValue LogBase2 = BuildLogBase2(N10, DL); 2939 AddToWorklist(LogBase2.getNode()); 2940 2941 EVT ADDVT = N1.getOperand(1).getValueType(); 2942 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT); 2943 AddToWorklist(Trunc.getNode()); 2944 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc); 2945 AddToWorklist(Add.getNode()); 2946 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2947 } 2948 } 2949 2950 // fold (udiv x, c) -> alternate 2951 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2952 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2953 if (SDValue Op = BuildUDIV(N)) 2954 return Op; 2955 2956 // sdiv, srem -> sdivrem 2957 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 2958 // true. Otherwise, we break the simplification logic in visitREM(). 2959 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2960 if (SDValue DivRem = useDivRem(N)) 2961 return DivRem; 2962 2963 return SDValue(); 2964 } 2965 2966 // handles ISD::SREM and ISD::UREM 2967 SDValue DAGCombiner::visitREM(SDNode *N) { 2968 unsigned Opcode = N->getOpcode(); 2969 SDValue N0 = N->getOperand(0); 2970 SDValue N1 = N->getOperand(1); 2971 EVT VT = N->getValueType(0); 2972 bool isSigned = (Opcode == ISD::SREM); 2973 SDLoc DL(N); 2974 2975 // fold (rem c1, c2) -> c1%c2 2976 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2977 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2978 if (N0C && N1C) 2979 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 2980 return Folded; 2981 2982 if (SDValue V = simplifyDivRem(N, DAG)) 2983 return V; 2984 2985 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2986 return NewSel; 2987 2988 if (isSigned) { 2989 // If we know the sign bits of both operands are zero, strength reduce to a 2990 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2991 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2992 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 2993 } else { 2994 SDValue NegOne = DAG.getAllOnesConstant(DL, VT); 2995 if (DAG.isKnownToBeAPowerOfTwo(N1)) { 2996 // fold (urem x, pow2) -> (and x, pow2-1) 2997 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 2998 AddToWorklist(Add.getNode()); 2999 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 3000 } 3001 if (N1.getOpcode() == ISD::SHL && 3002 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) { 3003 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 3004 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 3005 AddToWorklist(Add.getNode()); 3006 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 3007 } 3008 } 3009 3010 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 3011 3012 // If X/C can be simplified by the division-by-constant logic, lower 3013 // X%C to the equivalent of X-X/C*C. 3014 // To avoid mangling nodes, this simplification requires that the combine() 3015 // call for the speculative DIV must not cause a DIVREM conversion. We guard 3016 // against this by skipping the simplification if isIntDivCheap(). When 3017 // div is not cheap, combine will not return a DIVREM. Regardless, 3018 // checking cheapness here makes sense since the simplification results in 3019 // fatter code. 3020 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 3021 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 3022 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 3023 AddToWorklist(Div.getNode()); 3024 SDValue OptimizedDiv = combine(Div.getNode()); 3025 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 3026 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 3027 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 3028 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 3029 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 3030 AddToWorklist(Mul.getNode()); 3031 return Sub; 3032 } 3033 } 3034 3035 // sdiv, srem -> sdivrem 3036 if (SDValue DivRem = useDivRem(N)) 3037 return DivRem.getValue(1); 3038 3039 return SDValue(); 3040 } 3041 3042 SDValue DAGCombiner::visitMULHS(SDNode *N) { 3043 SDValue N0 = N->getOperand(0); 3044 SDValue N1 = N->getOperand(1); 3045 EVT VT = N->getValueType(0); 3046 SDLoc DL(N); 3047 3048 // fold (mulhs x, 0) -> 0 3049 if (isNullConstant(N1)) 3050 return N1; 3051 // fold (mulhs x, 1) -> (sra x, size(x)-1) 3052 if (isOneConstant(N1)) { 3053 SDLoc DL(N); 3054 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 3055 DAG.getConstant(N0.getValueSizeInBits() - 1, DL, 3056 getShiftAmountTy(N0.getValueType()))); 3057 } 3058 // fold (mulhs x, undef) -> 0 3059 if (N0.isUndef() || N1.isUndef()) 3060 return DAG.getConstant(0, SDLoc(N), VT); 3061 3062 // If the type twice as wide is legal, transform the mulhs to a wider multiply 3063 // plus a shift. 3064 if (VT.isSimple() && !VT.isVector()) { 3065 MVT Simple = VT.getSimpleVT(); 3066 unsigned SimpleSize = Simple.getSizeInBits(); 3067 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3068 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3069 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 3070 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 3071 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 3072 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 3073 DAG.getConstant(SimpleSize, DL, 3074 getShiftAmountTy(N1.getValueType()))); 3075 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 3076 } 3077 } 3078 3079 return SDValue(); 3080 } 3081 3082 SDValue DAGCombiner::visitMULHU(SDNode *N) { 3083 SDValue N0 = N->getOperand(0); 3084 SDValue N1 = N->getOperand(1); 3085 EVT VT = N->getValueType(0); 3086 SDLoc DL(N); 3087 3088 // fold (mulhu x, 0) -> 0 3089 if (isNullConstant(N1)) 3090 return N1; 3091 // fold (mulhu x, 1) -> 0 3092 if (isOneConstant(N1)) 3093 return DAG.getConstant(0, DL, N0.getValueType()); 3094 // fold (mulhu x, undef) -> 0 3095 if (N0.isUndef() || N1.isUndef()) 3096 return DAG.getConstant(0, DL, VT); 3097 3098 // If the type twice as wide is legal, transform the mulhu to a wider multiply 3099 // plus a shift. 3100 if (VT.isSimple() && !VT.isVector()) { 3101 MVT Simple = VT.getSimpleVT(); 3102 unsigned SimpleSize = Simple.getSizeInBits(); 3103 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3104 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3105 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 3106 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 3107 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 3108 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 3109 DAG.getConstant(SimpleSize, DL, 3110 getShiftAmountTy(N1.getValueType()))); 3111 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 3112 } 3113 } 3114 3115 return SDValue(); 3116 } 3117 3118 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 3119 /// give the opcodes for the two computations that are being performed. Return 3120 /// true if a simplification was made. 3121 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 3122 unsigned HiOp) { 3123 // If the high half is not needed, just compute the low half. 3124 bool HiExists = N->hasAnyUseOfValue(1); 3125 if (!HiExists && 3126 (!LegalOperations || 3127 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 3128 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 3129 return CombineTo(N, Res, Res); 3130 } 3131 3132 // If the low half is not needed, just compute the high half. 3133 bool LoExists = N->hasAnyUseOfValue(0); 3134 if (!LoExists && 3135 (!LegalOperations || 3136 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 3137 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 3138 return CombineTo(N, Res, Res); 3139 } 3140 3141 // If both halves are used, return as it is. 3142 if (LoExists && HiExists) 3143 return SDValue(); 3144 3145 // If the two computed results can be simplified separately, separate them. 3146 if (LoExists) { 3147 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 3148 AddToWorklist(Lo.getNode()); 3149 SDValue LoOpt = combine(Lo.getNode()); 3150 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 3151 (!LegalOperations || 3152 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 3153 return CombineTo(N, LoOpt, LoOpt); 3154 } 3155 3156 if (HiExists) { 3157 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 3158 AddToWorklist(Hi.getNode()); 3159 SDValue HiOpt = combine(Hi.getNode()); 3160 if (HiOpt.getNode() && HiOpt != Hi && 3161 (!LegalOperations || 3162 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 3163 return CombineTo(N, HiOpt, HiOpt); 3164 } 3165 3166 return SDValue(); 3167 } 3168 3169 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 3170 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 3171 return Res; 3172 3173 EVT VT = N->getValueType(0); 3174 SDLoc DL(N); 3175 3176 // If the type is twice as wide is legal, transform the mulhu to a wider 3177 // multiply plus a shift. 3178 if (VT.isSimple() && !VT.isVector()) { 3179 MVT Simple = VT.getSimpleVT(); 3180 unsigned SimpleSize = Simple.getSizeInBits(); 3181 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3182 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3183 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 3184 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 3185 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3186 // Compute the high part as N1. 3187 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3188 DAG.getConstant(SimpleSize, DL, 3189 getShiftAmountTy(Lo.getValueType()))); 3190 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3191 // Compute the low part as N0. 3192 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3193 return CombineTo(N, Lo, Hi); 3194 } 3195 } 3196 3197 return SDValue(); 3198 } 3199 3200 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 3201 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 3202 return Res; 3203 3204 EVT VT = N->getValueType(0); 3205 SDLoc DL(N); 3206 3207 // If the type is twice as wide is legal, transform the mulhu to a wider 3208 // multiply plus a shift. 3209 if (VT.isSimple() && !VT.isVector()) { 3210 MVT Simple = VT.getSimpleVT(); 3211 unsigned SimpleSize = Simple.getSizeInBits(); 3212 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3213 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3214 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 3215 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 3216 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3217 // Compute the high part as N1. 3218 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3219 DAG.getConstant(SimpleSize, DL, 3220 getShiftAmountTy(Lo.getValueType()))); 3221 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3222 // Compute the low part as N0. 3223 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3224 return CombineTo(N, Lo, Hi); 3225 } 3226 } 3227 3228 return SDValue(); 3229 } 3230 3231 SDValue DAGCombiner::visitSMULO(SDNode *N) { 3232 // (smulo x, 2) -> (saddo x, x) 3233 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 3234 if (C2->getAPIntValue() == 2) 3235 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 3236 N->getOperand(0), N->getOperand(0)); 3237 3238 return SDValue(); 3239 } 3240 3241 SDValue DAGCombiner::visitUMULO(SDNode *N) { 3242 // (umulo x, 2) -> (uaddo x, x) 3243 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 3244 if (C2->getAPIntValue() == 2) 3245 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 3246 N->getOperand(0), N->getOperand(0)); 3247 3248 return SDValue(); 3249 } 3250 3251 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 3252 SDValue N0 = N->getOperand(0); 3253 SDValue N1 = N->getOperand(1); 3254 EVT VT = N0.getValueType(); 3255 3256 // fold vector ops 3257 if (VT.isVector()) 3258 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3259 return FoldedVOp; 3260 3261 // fold operation with constant operands. 3262 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3263 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 3264 if (N0C && N1C) 3265 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 3266 3267 // canonicalize constant to RHS 3268 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3269 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3270 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 3271 3272 return SDValue(); 3273 } 3274 3275 /// If this is a binary operator with two operands of the same opcode, try to 3276 /// simplify it. 3277 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 3278 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 3279 EVT VT = N0.getValueType(); 3280 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 3281 3282 // Bail early if none of these transforms apply. 3283 if (N0.getNumOperands() == 0) return SDValue(); 3284 3285 // For each of OP in AND/OR/XOR: 3286 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 3287 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 3288 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 3289 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 3290 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 3291 // 3292 // do not sink logical op inside of a vector extend, since it may combine 3293 // into a vsetcc. 3294 EVT Op0VT = N0.getOperand(0).getValueType(); 3295 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 3296 N0.getOpcode() == ISD::SIGN_EXTEND || 3297 N0.getOpcode() == ISD::BSWAP || 3298 // Avoid infinite looping with PromoteIntBinOp. 3299 (N0.getOpcode() == ISD::ANY_EXTEND && 3300 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 3301 (N0.getOpcode() == ISD::TRUNCATE && 3302 (!TLI.isZExtFree(VT, Op0VT) || 3303 !TLI.isTruncateFree(Op0VT, VT)) && 3304 TLI.isTypeLegal(Op0VT))) && 3305 !VT.isVector() && 3306 Op0VT == N1.getOperand(0).getValueType() && 3307 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 3308 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 3309 N0.getOperand(0).getValueType(), 3310 N0.getOperand(0), N1.getOperand(0)); 3311 AddToWorklist(ORNode.getNode()); 3312 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 3313 } 3314 3315 // For each of OP in SHL/SRL/SRA/AND... 3316 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 3317 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 3318 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 3319 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 3320 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 3321 N0.getOperand(1) == N1.getOperand(1)) { 3322 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 3323 N0.getOperand(0).getValueType(), 3324 N0.getOperand(0), N1.getOperand(0)); 3325 AddToWorklist(ORNode.getNode()); 3326 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 3327 ORNode, N0.getOperand(1)); 3328 } 3329 3330 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 3331 // Only perform this optimization up until type legalization, before 3332 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 3333 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 3334 // we don't want to undo this promotion. 3335 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 3336 // on scalars. 3337 if ((N0.getOpcode() == ISD::BITCAST || 3338 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 3339 Level <= AfterLegalizeTypes) { 3340 SDValue In0 = N0.getOperand(0); 3341 SDValue In1 = N1.getOperand(0); 3342 EVT In0Ty = In0.getValueType(); 3343 EVT In1Ty = In1.getValueType(); 3344 SDLoc DL(N); 3345 // If both incoming values are integers, and the original types are the 3346 // same. 3347 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 3348 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 3349 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 3350 AddToWorklist(Op.getNode()); 3351 return BC; 3352 } 3353 } 3354 3355 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 3356 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 3357 // If both shuffles use the same mask, and both shuffle within a single 3358 // vector, then it is worthwhile to move the swizzle after the operation. 3359 // The type-legalizer generates this pattern when loading illegal 3360 // vector types from memory. In many cases this allows additional shuffle 3361 // optimizations. 3362 // There are other cases where moving the shuffle after the xor/and/or 3363 // is profitable even if shuffles don't perform a swizzle. 3364 // If both shuffles use the same mask, and both shuffles have the same first 3365 // or second operand, then it might still be profitable to move the shuffle 3366 // after the xor/and/or operation. 3367 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 3368 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 3369 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 3370 3371 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 3372 "Inputs to shuffles are not the same type"); 3373 3374 // Check that both shuffles use the same mask. The masks are known to be of 3375 // the same length because the result vector type is the same. 3376 // Check also that shuffles have only one use to avoid introducing extra 3377 // instructions. 3378 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 3379 SVN0->getMask().equals(SVN1->getMask())) { 3380 SDValue ShOp = N0->getOperand(1); 3381 3382 // Don't try to fold this node if it requires introducing a 3383 // build vector of all zeros that might be illegal at this stage. 3384 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3385 if (!LegalTypes) 3386 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3387 else 3388 ShOp = SDValue(); 3389 } 3390 3391 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 3392 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 3393 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 3394 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 3395 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3396 N0->getOperand(0), N1->getOperand(0)); 3397 AddToWorklist(NewNode.getNode()); 3398 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 3399 SVN0->getMask()); 3400 } 3401 3402 // Don't try to fold this node if it requires introducing a 3403 // build vector of all zeros that might be illegal at this stage. 3404 ShOp = N0->getOperand(0); 3405 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3406 if (!LegalTypes) 3407 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3408 else 3409 ShOp = SDValue(); 3410 } 3411 3412 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 3413 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 3414 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 3415 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 3416 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3417 N0->getOperand(1), N1->getOperand(1)); 3418 AddToWorklist(NewNode.getNode()); 3419 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 3420 SVN0->getMask()); 3421 } 3422 } 3423 } 3424 3425 return SDValue(); 3426 } 3427 3428 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient. 3429 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 3430 const SDLoc &DL) { 3431 SDValue LL, LR, RL, RR, N0CC, N1CC; 3432 if (!isSetCCEquivalent(N0, LL, LR, N0CC) || 3433 !isSetCCEquivalent(N1, RL, RR, N1CC)) 3434 return SDValue(); 3435 3436 assert(N0.getValueType() == N1.getValueType() && 3437 "Unexpected operand types for bitwise logic op"); 3438 assert(LL.getValueType() == LR.getValueType() && 3439 RL.getValueType() == RR.getValueType() && 3440 "Unexpected operand types for setcc"); 3441 3442 // If we're here post-legalization or the logic op type is not i1, the logic 3443 // op type must match a setcc result type. Also, all folds require new 3444 // operations on the left and right operands, so those types must match. 3445 EVT VT = N0.getValueType(); 3446 EVT OpVT = LL.getValueType(); 3447 if (LegalOperations || VT != MVT::i1) 3448 if (VT != getSetCCResultType(OpVT)) 3449 return SDValue(); 3450 if (OpVT != RL.getValueType()) 3451 return SDValue(); 3452 3453 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get(); 3454 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get(); 3455 bool IsInteger = OpVT.isInteger(); 3456 if (LR == RR && CC0 == CC1 && IsInteger) { 3457 bool IsZero = isNullConstantOrNullSplatConstant(LR); 3458 bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR); 3459 3460 // All bits clear? 3461 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero; 3462 // All sign bits clear? 3463 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1; 3464 // Any bits set? 3465 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero; 3466 // Any sign bits set? 3467 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero; 3468 3469 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0) 3470 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1) 3471 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0) 3472 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0) 3473 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) { 3474 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL); 3475 AddToWorklist(Or.getNode()); 3476 return DAG.getSetCC(DL, VT, Or, LR, CC1); 3477 } 3478 3479 // All bits set? 3480 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1; 3481 // All sign bits set? 3482 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero; 3483 // Any bits clear? 3484 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1; 3485 // Any sign bits clear? 3486 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1; 3487 3488 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1) 3489 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0) 3490 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1) 3491 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1) 3492 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) { 3493 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL); 3494 AddToWorklist(And.getNode()); 3495 return DAG.getSetCC(DL, VT, And, LR, CC1); 3496 } 3497 } 3498 3499 // TODO: What is the 'or' equivalent of this fold? 3500 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2) 3501 if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE && 3502 ((isNullConstant(LR) && isAllOnesConstant(RR)) || 3503 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 3504 SDValue One = DAG.getConstant(1, DL, OpVT); 3505 SDValue Two = DAG.getConstant(2, DL, OpVT); 3506 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One); 3507 AddToWorklist(Add.getNode()); 3508 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE); 3509 } 3510 3511 // Try more general transforms if the predicates match and the only user of 3512 // the compares is the 'and' or 'or'. 3513 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 && 3514 N0.hasOneUse() && N1.hasOneUse()) { 3515 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0 3516 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0 3517 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) { 3518 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR); 3519 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR); 3520 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR); 3521 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3522 return DAG.getSetCC(DL, VT, Or, Zero, CC1); 3523 } 3524 } 3525 3526 // Canonicalize equivalent operands to LL == RL. 3527 if (LL == RR && LR == RL) { 3528 CC1 = ISD::getSetCCSwappedOperands(CC1); 3529 std::swap(RL, RR); 3530 } 3531 3532 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 3533 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 3534 if (LL == RL && LR == RR) { 3535 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger) 3536 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger); 3537 if (NewCC != ISD::SETCC_INVALID && 3538 (!LegalOperations || 3539 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) && 3540 TLI.isOperationLegal(ISD::SETCC, OpVT)))) 3541 return DAG.getSetCC(DL, VT, LL, LR, NewCC); 3542 } 3543 3544 return SDValue(); 3545 } 3546 3547 /// This contains all DAGCombine rules which reduce two values combined by 3548 /// an And operation to a single value. This makes them reusable in the context 3549 /// of visitSELECT(). Rules involving constants are not included as 3550 /// visitSELECT() already handles those cases. 3551 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) { 3552 EVT VT = N1.getValueType(); 3553 SDLoc DL(N); 3554 3555 // fold (and x, undef) -> 0 3556 if (N0.isUndef() || N1.isUndef()) 3557 return DAG.getConstant(0, DL, VT); 3558 3559 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL)) 3560 return V; 3561 3562 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 3563 VT.getSizeInBits() <= 64) { 3564 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3565 APInt ADDC = ADDI->getAPIntValue(); 3566 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3567 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 3568 // immediate for an add, but it is legal if its top c2 bits are set, 3569 // transform the ADD so the immediate doesn't need to be materialized 3570 // in a register. 3571 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 3572 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3573 SRLI->getZExtValue()); 3574 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 3575 ADDC |= Mask; 3576 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3577 SDLoc DL0(N0); 3578 SDValue NewAdd = 3579 DAG.getNode(ISD::ADD, DL0, VT, 3580 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 3581 CombineTo(N0.getNode(), NewAdd); 3582 // Return N so it doesn't get rechecked! 3583 return SDValue(N, 0); 3584 } 3585 } 3586 } 3587 } 3588 } 3589 } 3590 3591 // Reduce bit extract of low half of an integer to the narrower type. 3592 // (and (srl i64:x, K), KMask) -> 3593 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 3594 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 3595 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 3596 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3597 unsigned Size = VT.getSizeInBits(); 3598 const APInt &AndMask = CAnd->getAPIntValue(); 3599 unsigned ShiftBits = CShift->getZExtValue(); 3600 3601 // Bail out, this node will probably disappear anyway. 3602 if (ShiftBits == 0) 3603 return SDValue(); 3604 3605 unsigned MaskBits = AndMask.countTrailingOnes(); 3606 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 3607 3608 if (AndMask.isMask() && 3609 // Required bits must not span the two halves of the integer and 3610 // must fit in the half size type. 3611 (ShiftBits + MaskBits <= Size / 2) && 3612 TLI.isNarrowingProfitable(VT, HalfVT) && 3613 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 3614 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 3615 TLI.isTruncateFree(VT, HalfVT) && 3616 TLI.isZExtFree(HalfVT, VT)) { 3617 // The isNarrowingProfitable is to avoid regressions on PPC and 3618 // AArch64 which match a few 64-bit bit insert / bit extract patterns 3619 // on downstream users of this. Those patterns could probably be 3620 // extended to handle extensions mixed in. 3621 3622 SDValue SL(N0); 3623 assert(MaskBits <= Size); 3624 3625 // Extracting the highest bit of the low half. 3626 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 3627 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 3628 N0.getOperand(0)); 3629 3630 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 3631 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 3632 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 3633 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 3634 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 3635 } 3636 } 3637 } 3638 } 3639 3640 return SDValue(); 3641 } 3642 3643 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 3644 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 3645 bool &NarrowLoad) { 3646 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits(); 3647 3648 if (ActiveBits == 0 || !AndC->getAPIntValue().isMask(ActiveBits)) 3649 return false; 3650 3651 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3652 LoadedVT = LoadN->getMemoryVT(); 3653 3654 if (ExtVT == LoadedVT && 3655 (!LegalOperations || 3656 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 3657 // ZEXTLOAD will match without needing to change the size of the value being 3658 // loaded. 3659 NarrowLoad = false; 3660 return true; 3661 } 3662 3663 // Do not change the width of a volatile load. 3664 if (LoadN->isVolatile()) 3665 return false; 3666 3667 // Do not generate loads of non-round integer types since these can 3668 // be expensive (and would be wrong if the type is not byte sized). 3669 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 3670 return false; 3671 3672 if (LegalOperations && 3673 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 3674 return false; 3675 3676 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 3677 return false; 3678 3679 NarrowLoad = true; 3680 return true; 3681 } 3682 3683 SDValue DAGCombiner::visitAND(SDNode *N) { 3684 SDValue N0 = N->getOperand(0); 3685 SDValue N1 = N->getOperand(1); 3686 EVT VT = N1.getValueType(); 3687 3688 // x & x --> x 3689 if (N0 == N1) 3690 return N0; 3691 3692 // fold vector ops 3693 if (VT.isVector()) { 3694 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3695 return FoldedVOp; 3696 3697 // fold (and x, 0) -> 0, vector edition 3698 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3699 // do not return N0, because undef node may exist in N0 3700 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()), 3701 SDLoc(N), N0.getValueType()); 3702 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3703 // do not return N1, because undef node may exist in N1 3704 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()), 3705 SDLoc(N), N1.getValueType()); 3706 3707 // fold (and x, -1) -> x, vector edition 3708 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3709 return N1; 3710 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3711 return N0; 3712 } 3713 3714 // fold (and c1, c2) -> c1&c2 3715 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3716 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3717 if (N0C && N1C && !N1C->isOpaque()) 3718 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3719 // canonicalize constant to RHS 3720 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3721 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3722 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3723 // fold (and x, -1) -> x 3724 if (isAllOnesConstant(N1)) 3725 return N0; 3726 // if (and x, c) is known to be zero, return 0 3727 unsigned BitWidth = VT.getScalarSizeInBits(); 3728 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3729 APInt::getAllOnesValue(BitWidth))) 3730 return DAG.getConstant(0, SDLoc(N), VT); 3731 3732 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3733 return NewSel; 3734 3735 // reassociate and 3736 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3737 return RAND; 3738 // fold (and (or x, C), D) -> D if (C & D) == D 3739 if (N1C && N0.getOpcode() == ISD::OR) 3740 if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1))) 3741 if (N1C->getAPIntValue().isSubsetOf(ORI->getAPIntValue())) 3742 return N1; 3743 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 3744 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3745 SDValue N0Op0 = N0.getOperand(0); 3746 APInt Mask = ~N1C->getAPIntValue(); 3747 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits()); 3748 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 3749 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 3750 N0.getValueType(), N0Op0); 3751 3752 // Replace uses of the AND with uses of the Zero extend node. 3753 CombineTo(N, Zext); 3754 3755 // We actually want to replace all uses of the any_extend with the 3756 // zero_extend, to avoid duplicating things. This will later cause this 3757 // AND to be folded. 3758 CombineTo(N0.getNode(), Zext); 3759 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3760 } 3761 } 3762 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3763 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3764 // already be zero by virtue of the width of the base type of the load. 3765 // 3766 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3767 // more cases. 3768 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3769 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 3770 N0.getOperand(0).getOpcode() == ISD::LOAD && 3771 N0.getOperand(0).getResNo() == 0) || 3772 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 3773 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3774 N0 : N0.getOperand(0) ); 3775 3776 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3777 // This can be a pure constant or a vector splat, in which case we treat the 3778 // vector as a scalar and use the splat value. 3779 APInt Constant = APInt::getNullValue(1); 3780 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3781 Constant = C->getAPIntValue(); 3782 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3783 APInt SplatValue, SplatUndef; 3784 unsigned SplatBitSize; 3785 bool HasAnyUndefs; 3786 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3787 SplatBitSize, HasAnyUndefs); 3788 if (IsSplat) { 3789 // Undef bits can contribute to a possible optimisation if set, so 3790 // set them. 3791 SplatValue |= SplatUndef; 3792 3793 // The splat value may be something like "0x00FFFFFF", which means 0 for 3794 // the first vector value and FF for the rest, repeating. We need a mask 3795 // that will apply equally to all members of the vector, so AND all the 3796 // lanes of the constant together. 3797 EVT VT = Vector->getValueType(0); 3798 unsigned BitWidth = VT.getScalarSizeInBits(); 3799 3800 // If the splat value has been compressed to a bitlength lower 3801 // than the size of the vector lane, we need to re-expand it to 3802 // the lane size. 3803 if (BitWidth > SplatBitSize) 3804 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3805 SplatBitSize < BitWidth; 3806 SplatBitSize = SplatBitSize * 2) 3807 SplatValue |= SplatValue.shl(SplatBitSize); 3808 3809 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3810 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3811 if (SplatBitSize % BitWidth == 0) { 3812 Constant = APInt::getAllOnesValue(BitWidth); 3813 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3814 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3815 } 3816 } 3817 } 3818 3819 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3820 // actually legal and isn't going to get expanded, else this is a false 3821 // optimisation. 3822 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3823 Load->getValueType(0), 3824 Load->getMemoryVT()); 3825 3826 // Resize the constant to the same size as the original memory access before 3827 // extension. If it is still the AllOnesValue then this AND is completely 3828 // unneeded. 3829 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits()); 3830 3831 bool B; 3832 switch (Load->getExtensionType()) { 3833 default: B = false; break; 3834 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3835 case ISD::ZEXTLOAD: 3836 case ISD::NON_EXTLOAD: B = true; break; 3837 } 3838 3839 if (B && Constant.isAllOnesValue()) { 3840 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3841 // preserve semantics once we get rid of the AND. 3842 SDValue NewLoad(Load, 0); 3843 3844 // Fold the AND away. NewLoad may get replaced immediately. 3845 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3846 3847 if (Load->getExtensionType() == ISD::EXTLOAD) { 3848 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3849 Load->getValueType(0), SDLoc(Load), 3850 Load->getChain(), Load->getBasePtr(), 3851 Load->getOffset(), Load->getMemoryVT(), 3852 Load->getMemOperand()); 3853 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3854 if (Load->getNumValues() == 3) { 3855 // PRE/POST_INC loads have 3 values. 3856 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3857 NewLoad.getValue(2) }; 3858 CombineTo(Load, To, 3, true); 3859 } else { 3860 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3861 } 3862 } 3863 3864 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3865 } 3866 } 3867 3868 // fold (and (load x), 255) -> (zextload x, i8) 3869 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3870 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3871 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD || 3872 (N0.getOpcode() == ISD::ANY_EXTEND && 3873 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3874 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3875 LoadSDNode *LN0 = HasAnyExt 3876 ? cast<LoadSDNode>(N0.getOperand(0)) 3877 : cast<LoadSDNode>(N0); 3878 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3879 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3880 auto NarrowLoad = false; 3881 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3882 EVT ExtVT, LoadedVT; 3883 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT, 3884 NarrowLoad)) { 3885 if (!NarrowLoad) { 3886 SDValue NewLoad = 3887 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3888 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3889 LN0->getMemOperand()); 3890 AddToWorklist(N); 3891 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3892 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3893 } else { 3894 EVT PtrType = LN0->getOperand(1).getValueType(); 3895 3896 unsigned Alignment = LN0->getAlignment(); 3897 SDValue NewPtr = LN0->getBasePtr(); 3898 3899 // For big endian targets, we need to add an offset to the pointer 3900 // to load the correct bytes. For little endian systems, we merely 3901 // need to read fewer bytes from the same pointer. 3902 if (DAG.getDataLayout().isBigEndian()) { 3903 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3904 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3905 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3906 SDLoc DL(LN0); 3907 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3908 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3909 Alignment = MinAlign(Alignment, PtrOff); 3910 } 3911 3912 AddToWorklist(NewPtr.getNode()); 3913 3914 SDValue Load = DAG.getExtLoad( 3915 ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr, 3916 LN0->getPointerInfo(), ExtVT, Alignment, 3917 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 3918 AddToWorklist(N); 3919 CombineTo(LN0, Load, Load.getValue(1)); 3920 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3921 } 3922 } 3923 } 3924 } 3925 3926 if (SDValue Combined = visitANDLike(N0, N1, N)) 3927 return Combined; 3928 3929 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3930 if (N0.getOpcode() == N1.getOpcode()) 3931 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3932 return Tmp; 3933 3934 // Masking the negated extension of a boolean is just the zero-extended 3935 // boolean: 3936 // and (sub 0, zext(bool X)), 1 --> zext(bool X) 3937 // and (sub 0, sext(bool X)), 1 --> zext(bool X) 3938 // 3939 // Note: the SimplifyDemandedBits fold below can make an information-losing 3940 // transform, and then we have no way to find this better fold. 3941 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) { 3942 if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) { 3943 SDValue SubRHS = N0.getOperand(1); 3944 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND && 3945 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 3946 return SubRHS; 3947 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND && 3948 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 3949 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0)); 3950 } 3951 } 3952 3953 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3954 // fold (and (sra)) -> (and (srl)) when possible. 3955 if (SimplifyDemandedBits(SDValue(N, 0))) 3956 return SDValue(N, 0); 3957 3958 // fold (zext_inreg (extload x)) -> (zextload x) 3959 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3960 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3961 EVT MemVT = LN0->getMemoryVT(); 3962 // If we zero all the possible extended bits, then we can turn this into 3963 // a zextload if we are running before legalize or the operation is legal. 3964 unsigned BitWidth = N1.getScalarValueSizeInBits(); 3965 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3966 BitWidth - MemVT.getScalarSizeInBits())) && 3967 ((!LegalOperations && !LN0->isVolatile()) || 3968 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3969 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3970 LN0->getChain(), LN0->getBasePtr(), 3971 MemVT, LN0->getMemOperand()); 3972 AddToWorklist(N); 3973 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3974 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3975 } 3976 } 3977 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3978 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3979 N0.hasOneUse()) { 3980 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3981 EVT MemVT = LN0->getMemoryVT(); 3982 // If we zero all the possible extended bits, then we can turn this into 3983 // a zextload if we are running before legalize or the operation is legal. 3984 unsigned BitWidth = N1.getScalarValueSizeInBits(); 3985 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3986 BitWidth - MemVT.getScalarSizeInBits())) && 3987 ((!LegalOperations && !LN0->isVolatile()) || 3988 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3989 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3990 LN0->getChain(), LN0->getBasePtr(), 3991 MemVT, LN0->getMemOperand()); 3992 AddToWorklist(N); 3993 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3994 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3995 } 3996 } 3997 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3998 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3999 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 4000 N0.getOperand(1), false)) 4001 return BSwap; 4002 } 4003 4004 return SDValue(); 4005 } 4006 4007 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 4008 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 4009 bool DemandHighBits) { 4010 if (!LegalOperations) 4011 return SDValue(); 4012 4013 EVT VT = N->getValueType(0); 4014 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 4015 return SDValue(); 4016 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 4017 return SDValue(); 4018 4019 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 4020 bool LookPassAnd0 = false; 4021 bool LookPassAnd1 = false; 4022 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 4023 std::swap(N0, N1); 4024 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 4025 std::swap(N0, N1); 4026 if (N0.getOpcode() == ISD::AND) { 4027 if (!N0.getNode()->hasOneUse()) 4028 return SDValue(); 4029 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4030 if (!N01C || N01C->getZExtValue() != 0xFF00) 4031 return SDValue(); 4032 N0 = N0.getOperand(0); 4033 LookPassAnd0 = true; 4034 } 4035 4036 if (N1.getOpcode() == ISD::AND) { 4037 if (!N1.getNode()->hasOneUse()) 4038 return SDValue(); 4039 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 4040 if (!N11C || N11C->getZExtValue() != 0xFF) 4041 return SDValue(); 4042 N1 = N1.getOperand(0); 4043 LookPassAnd1 = true; 4044 } 4045 4046 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 4047 std::swap(N0, N1); 4048 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 4049 return SDValue(); 4050 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse()) 4051 return SDValue(); 4052 4053 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4054 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 4055 if (!N01C || !N11C) 4056 return SDValue(); 4057 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 4058 return SDValue(); 4059 4060 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 4061 SDValue N00 = N0->getOperand(0); 4062 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 4063 if (!N00.getNode()->hasOneUse()) 4064 return SDValue(); 4065 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 4066 if (!N001C || N001C->getZExtValue() != 0xFF) 4067 return SDValue(); 4068 N00 = N00.getOperand(0); 4069 LookPassAnd0 = true; 4070 } 4071 4072 SDValue N10 = N1->getOperand(0); 4073 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 4074 if (!N10.getNode()->hasOneUse()) 4075 return SDValue(); 4076 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 4077 if (!N101C || N101C->getZExtValue() != 0xFF00) 4078 return SDValue(); 4079 N10 = N10.getOperand(0); 4080 LookPassAnd1 = true; 4081 } 4082 4083 if (N00 != N10) 4084 return SDValue(); 4085 4086 // Make sure everything beyond the low halfword gets set to zero since the SRL 4087 // 16 will clear the top bits. 4088 unsigned OpSizeInBits = VT.getSizeInBits(); 4089 if (DemandHighBits && OpSizeInBits > 16) { 4090 // If the left-shift isn't masked out then the only way this is a bswap is 4091 // if all bits beyond the low 8 are 0. In that case the entire pattern 4092 // reduces to a left shift anyway: leave it for other parts of the combiner. 4093 if (!LookPassAnd0) 4094 return SDValue(); 4095 4096 // However, if the right shift isn't masked out then it might be because 4097 // it's not needed. See if we can spot that too. 4098 if (!LookPassAnd1 && 4099 !DAG.MaskedValueIsZero( 4100 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 4101 return SDValue(); 4102 } 4103 4104 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 4105 if (OpSizeInBits > 16) { 4106 SDLoc DL(N); 4107 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 4108 DAG.getConstant(OpSizeInBits - 16, DL, 4109 getShiftAmountTy(VT))); 4110 } 4111 return Res; 4112 } 4113 4114 /// Return true if the specified node is an element that makes up a 32-bit 4115 /// packed halfword byteswap. 4116 /// ((x & 0x000000ff) << 8) | 4117 /// ((x & 0x0000ff00) >> 8) | 4118 /// ((x & 0x00ff0000) << 8) | 4119 /// ((x & 0xff000000) >> 8) 4120 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 4121 if (!N.getNode()->hasOneUse()) 4122 return false; 4123 4124 unsigned Opc = N.getOpcode(); 4125 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 4126 return false; 4127 4128 SDValue N0 = N.getOperand(0); 4129 unsigned Opc0 = N0.getOpcode(); 4130 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL) 4131 return false; 4132 4133 ConstantSDNode *N1C = nullptr; 4134 // SHL or SRL: look upstream for AND mask operand 4135 if (Opc == ISD::AND) 4136 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4137 else if (Opc0 == ISD::AND) 4138 N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4139 if (!N1C) 4140 return false; 4141 4142 unsigned MaskByteOffset; 4143 switch (N1C->getZExtValue()) { 4144 default: 4145 return false; 4146 case 0xFF: MaskByteOffset = 0; break; 4147 case 0xFF00: MaskByteOffset = 1; break; 4148 case 0xFF0000: MaskByteOffset = 2; break; 4149 case 0xFF000000: MaskByteOffset = 3; break; 4150 } 4151 4152 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 4153 if (Opc == ISD::AND) { 4154 if (MaskByteOffset == 0 || MaskByteOffset == 2) { 4155 // (x >> 8) & 0xff 4156 // (x >> 8) & 0xff0000 4157 if (Opc0 != ISD::SRL) 4158 return false; 4159 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4160 if (!C || C->getZExtValue() != 8) 4161 return false; 4162 } else { 4163 // (x << 8) & 0xff00 4164 // (x << 8) & 0xff000000 4165 if (Opc0 != ISD::SHL) 4166 return false; 4167 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4168 if (!C || C->getZExtValue() != 8) 4169 return false; 4170 } 4171 } else if (Opc == ISD::SHL) { 4172 // (x & 0xff) << 8 4173 // (x & 0xff0000) << 8 4174 if (MaskByteOffset != 0 && MaskByteOffset != 2) 4175 return false; 4176 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4177 if (!C || C->getZExtValue() != 8) 4178 return false; 4179 } else { // Opc == ISD::SRL 4180 // (x & 0xff00) >> 8 4181 // (x & 0xff000000) >> 8 4182 if (MaskByteOffset != 1 && MaskByteOffset != 3) 4183 return false; 4184 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4185 if (!C || C->getZExtValue() != 8) 4186 return false; 4187 } 4188 4189 if (Parts[MaskByteOffset]) 4190 return false; 4191 4192 Parts[MaskByteOffset] = N0.getOperand(0).getNode(); 4193 return true; 4194 } 4195 4196 /// Match a 32-bit packed halfword bswap. That is 4197 /// ((x & 0x000000ff) << 8) | 4198 /// ((x & 0x0000ff00) >> 8) | 4199 /// ((x & 0x00ff0000) << 8) | 4200 /// ((x & 0xff000000) >> 8) 4201 /// => (rotl (bswap x), 16) 4202 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 4203 if (!LegalOperations) 4204 return SDValue(); 4205 4206 EVT VT = N->getValueType(0); 4207 if (VT != MVT::i32) 4208 return SDValue(); 4209 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 4210 return SDValue(); 4211 4212 // Look for either 4213 // (or (or (and), (and)), (or (and), (and))) 4214 // (or (or (or (and), (and)), (and)), (and)) 4215 if (N0.getOpcode() != ISD::OR) 4216 return SDValue(); 4217 SDValue N00 = N0.getOperand(0); 4218 SDValue N01 = N0.getOperand(1); 4219 SDNode *Parts[4] = {}; 4220 4221 if (N1.getOpcode() == ISD::OR && 4222 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 4223 // (or (or (and), (and)), (or (and), (and))) 4224 if (!isBSwapHWordElement(N00, Parts)) 4225 return SDValue(); 4226 4227 if (!isBSwapHWordElement(N01, Parts)) 4228 return SDValue(); 4229 SDValue N10 = N1.getOperand(0); 4230 if (!isBSwapHWordElement(N10, Parts)) 4231 return SDValue(); 4232 SDValue N11 = N1.getOperand(1); 4233 if (!isBSwapHWordElement(N11, Parts)) 4234 return SDValue(); 4235 } else { 4236 // (or (or (or (and), (and)), (and)), (and)) 4237 if (!isBSwapHWordElement(N1, Parts)) 4238 return SDValue(); 4239 if (!isBSwapHWordElement(N01, Parts)) 4240 return SDValue(); 4241 if (N00.getOpcode() != ISD::OR) 4242 return SDValue(); 4243 SDValue N000 = N00.getOperand(0); 4244 if (!isBSwapHWordElement(N000, Parts)) 4245 return SDValue(); 4246 SDValue N001 = N00.getOperand(1); 4247 if (!isBSwapHWordElement(N001, Parts)) 4248 return SDValue(); 4249 } 4250 4251 // Make sure the parts are all coming from the same node. 4252 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 4253 return SDValue(); 4254 4255 SDLoc DL(N); 4256 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 4257 SDValue(Parts[0], 0)); 4258 4259 // Result of the bswap should be rotated by 16. If it's not legal, then 4260 // do (x << 16) | (x >> 16). 4261 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 4262 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 4263 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 4264 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 4265 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 4266 return DAG.getNode(ISD::OR, DL, VT, 4267 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 4268 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 4269 } 4270 4271 /// This contains all DAGCombine rules which reduce two values combined by 4272 /// an Or operation to a single value \see visitANDLike(). 4273 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) { 4274 EVT VT = N1.getValueType(); 4275 SDLoc DL(N); 4276 4277 // fold (or x, undef) -> -1 4278 if (!LegalOperations && (N0.isUndef() || N1.isUndef())) 4279 return DAG.getAllOnesConstant(DL, VT); 4280 4281 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL)) 4282 return V; 4283 4284 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 4285 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 4286 // Don't increase # computations. 4287 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 4288 // We can only do this xform if we know that bits from X that are set in C2 4289 // but not in C1 are already zero. Likewise for Y. 4290 if (const ConstantSDNode *N0O1C = 4291 getAsNonOpaqueConstant(N0.getOperand(1))) { 4292 if (const ConstantSDNode *N1O1C = 4293 getAsNonOpaqueConstant(N1.getOperand(1))) { 4294 // We can only do this xform if we know that bits from X that are set in 4295 // C2 but not in C1 are already zero. Likewise for Y. 4296 const APInt &LHSMask = N0O1C->getAPIntValue(); 4297 const APInt &RHSMask = N1O1C->getAPIntValue(); 4298 4299 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 4300 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 4301 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 4302 N0.getOperand(0), N1.getOperand(0)); 4303 return DAG.getNode(ISD::AND, DL, VT, X, 4304 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 4305 } 4306 } 4307 } 4308 } 4309 4310 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 4311 if (N0.getOpcode() == ISD::AND && 4312 N1.getOpcode() == ISD::AND && 4313 N0.getOperand(0) == N1.getOperand(0) && 4314 // Don't increase # computations. 4315 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 4316 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 4317 N0.getOperand(1), N1.getOperand(1)); 4318 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X); 4319 } 4320 4321 return SDValue(); 4322 } 4323 4324 SDValue DAGCombiner::visitOR(SDNode *N) { 4325 SDValue N0 = N->getOperand(0); 4326 SDValue N1 = N->getOperand(1); 4327 EVT VT = N1.getValueType(); 4328 4329 // x | x --> x 4330 if (N0 == N1) 4331 return N0; 4332 4333 // fold vector ops 4334 if (VT.isVector()) { 4335 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4336 return FoldedVOp; 4337 4338 // fold (or x, 0) -> x, vector edition 4339 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4340 return N1; 4341 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4342 return N0; 4343 4344 // fold (or x, -1) -> -1, vector edition 4345 if (ISD::isBuildVectorAllOnes(N0.getNode())) 4346 // do not return N0, because undef node may exist in N0 4347 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType()); 4348 if (ISD::isBuildVectorAllOnes(N1.getNode())) 4349 // do not return N1, because undef node may exist in N1 4350 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType()); 4351 4352 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 4353 // Do this only if the resulting shuffle is legal. 4354 if (isa<ShuffleVectorSDNode>(N0) && 4355 isa<ShuffleVectorSDNode>(N1) && 4356 // Avoid folding a node with illegal type. 4357 TLI.isTypeLegal(VT)) { 4358 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 4359 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 4360 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 4361 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 4362 // Ensure both shuffles have a zero input. 4363 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) { 4364 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 4365 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 4366 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 4367 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 4368 bool CanFold = true; 4369 int NumElts = VT.getVectorNumElements(); 4370 SmallVector<int, 4> Mask(NumElts); 4371 4372 for (int i = 0; i != NumElts; ++i) { 4373 int M0 = SV0->getMaskElt(i); 4374 int M1 = SV1->getMaskElt(i); 4375 4376 // Determine if either index is pointing to a zero vector. 4377 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 4378 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 4379 4380 // If one element is zero and the otherside is undef, keep undef. 4381 // This also handles the case that both are undef. 4382 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 4383 Mask[i] = -1; 4384 continue; 4385 } 4386 4387 // Make sure only one of the elements is zero. 4388 if (M0Zero == M1Zero) { 4389 CanFold = false; 4390 break; 4391 } 4392 4393 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 4394 4395 // We have a zero and non-zero element. If the non-zero came from 4396 // SV0 make the index a LHS index. If it came from SV1, make it 4397 // a RHS index. We need to mod by NumElts because we don't care 4398 // which operand it came from in the original shuffles. 4399 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 4400 } 4401 4402 if (CanFold) { 4403 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 4404 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 4405 4406 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 4407 if (!LegalMask) { 4408 std::swap(NewLHS, NewRHS); 4409 ShuffleVectorSDNode::commuteMask(Mask); 4410 LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 4411 } 4412 4413 if (LegalMask) 4414 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask); 4415 } 4416 } 4417 } 4418 } 4419 4420 // fold (or c1, c2) -> c1|c2 4421 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4422 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4423 if (N0C && N1C && !N1C->isOpaque()) 4424 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 4425 // canonicalize constant to RHS 4426 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4427 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4428 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 4429 // fold (or x, 0) -> x 4430 if (isNullConstant(N1)) 4431 return N0; 4432 // fold (or x, -1) -> -1 4433 if (isAllOnesConstant(N1)) 4434 return N1; 4435 4436 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4437 return NewSel; 4438 4439 // fold (or x, c) -> c iff (x & ~c) == 0 4440 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 4441 return N1; 4442 4443 if (SDValue Combined = visitORLike(N0, N1, N)) 4444 return Combined; 4445 4446 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 4447 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 4448 return BSwap; 4449 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 4450 return BSwap; 4451 4452 // reassociate or 4453 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 4454 return ROR; 4455 4456 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 4457 // iff (c1 & c2) != 0. 4458 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse()) { 4459 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4460 if (C1->getAPIntValue().intersects(N1C->getAPIntValue())) { 4461 if (SDValue COR = 4462 DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, N1C, C1)) 4463 return DAG.getNode( 4464 ISD::AND, SDLoc(N), VT, 4465 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 4466 return SDValue(); 4467 } 4468 } 4469 } 4470 4471 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 4472 if (N0.getOpcode() == N1.getOpcode()) 4473 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4474 return Tmp; 4475 4476 // See if this is some rotate idiom. 4477 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 4478 return SDValue(Rot, 0); 4479 4480 if (SDValue Load = MatchLoadCombine(N)) 4481 return Load; 4482 4483 // Simplify the operands using demanded-bits information. 4484 if (SimplifyDemandedBits(SDValue(N, 0))) 4485 return SDValue(N, 0); 4486 4487 return SDValue(); 4488 } 4489 4490 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 4491 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 4492 if (Op.getOpcode() == ISD::AND) { 4493 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 4494 Mask = Op.getOperand(1); 4495 Op = Op.getOperand(0); 4496 } else { 4497 return false; 4498 } 4499 } 4500 4501 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 4502 Shift = Op; 4503 return true; 4504 } 4505 4506 return false; 4507 } 4508 4509 // Return true if we can prove that, whenever Neg and Pos are both in the 4510 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 4511 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 4512 // 4513 // (or (shift1 X, Neg), (shift2 X, Pos)) 4514 // 4515 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 4516 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 4517 // to consider shift amounts with defined behavior. 4518 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 4519 // If EltSize is a power of 2 then: 4520 // 4521 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 4522 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 4523 // 4524 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 4525 // for the stronger condition: 4526 // 4527 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 4528 // 4529 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 4530 // we can just replace Neg with Neg' for the rest of the function. 4531 // 4532 // In other cases we check for the even stronger condition: 4533 // 4534 // Neg == EltSize - Pos [B] 4535 // 4536 // for all Neg and Pos. Note that the (or ...) then invokes undefined 4537 // behavior if Pos == 0 (and consequently Neg == EltSize). 4538 // 4539 // We could actually use [A] whenever EltSize is a power of 2, but the 4540 // only extra cases that it would match are those uninteresting ones 4541 // where Neg and Pos are never in range at the same time. E.g. for 4542 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 4543 // as well as (sub 32, Pos), but: 4544 // 4545 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 4546 // 4547 // always invokes undefined behavior for 32-bit X. 4548 // 4549 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 4550 unsigned MaskLoBits = 0; 4551 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 4552 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 4553 if (NegC->getAPIntValue() == EltSize - 1) { 4554 Neg = Neg.getOperand(0); 4555 MaskLoBits = Log2_64(EltSize); 4556 } 4557 } 4558 } 4559 4560 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 4561 if (Neg.getOpcode() != ISD::SUB) 4562 return false; 4563 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 4564 if (!NegC) 4565 return false; 4566 SDValue NegOp1 = Neg.getOperand(1); 4567 4568 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 4569 // Pos'. The truncation is redundant for the purpose of the equality. 4570 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 4571 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4572 if (PosC->getAPIntValue() == EltSize - 1) 4573 Pos = Pos.getOperand(0); 4574 4575 // The condition we need is now: 4576 // 4577 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 4578 // 4579 // If NegOp1 == Pos then we need: 4580 // 4581 // EltSize & Mask == NegC & Mask 4582 // 4583 // (because "x & Mask" is a truncation and distributes through subtraction). 4584 APInt Width; 4585 if (Pos == NegOp1) 4586 Width = NegC->getAPIntValue(); 4587 4588 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 4589 // Then the condition we want to prove becomes: 4590 // 4591 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 4592 // 4593 // which, again because "x & Mask" is a truncation, becomes: 4594 // 4595 // NegC & Mask == (EltSize - PosC) & Mask 4596 // EltSize & Mask == (NegC + PosC) & Mask 4597 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 4598 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4599 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 4600 else 4601 return false; 4602 } else 4603 return false; 4604 4605 // Now we just need to check that EltSize & Mask == Width & Mask. 4606 if (MaskLoBits) 4607 // EltSize & Mask is 0 since Mask is EltSize - 1. 4608 return Width.getLoBits(MaskLoBits) == 0; 4609 return Width == EltSize; 4610 } 4611 4612 // A subroutine of MatchRotate used once we have found an OR of two opposite 4613 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 4614 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 4615 // former being preferred if supported. InnerPos and InnerNeg are Pos and 4616 // Neg with outer conversions stripped away. 4617 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 4618 SDValue Neg, SDValue InnerPos, 4619 SDValue InnerNeg, unsigned PosOpcode, 4620 unsigned NegOpcode, const SDLoc &DL) { 4621 // fold (or (shl x, (*ext y)), 4622 // (srl x, (*ext (sub 32, y)))) -> 4623 // (rotl x, y) or (rotr x, (sub 32, y)) 4624 // 4625 // fold (or (shl x, (*ext (sub 32, y))), 4626 // (srl x, (*ext y))) -> 4627 // (rotr x, y) or (rotl x, (sub 32, y)) 4628 EVT VT = Shifted.getValueType(); 4629 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 4630 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 4631 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 4632 HasPos ? Pos : Neg).getNode(); 4633 } 4634 4635 return nullptr; 4636 } 4637 4638 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 4639 // idioms for rotate, and if the target supports rotation instructions, generate 4640 // a rot[lr]. 4641 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 4642 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 4643 EVT VT = LHS.getValueType(); 4644 if (!TLI.isTypeLegal(VT)) return nullptr; 4645 4646 // The target must have at least one rotate flavor. 4647 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 4648 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 4649 if (!HasROTL && !HasROTR) return nullptr; 4650 4651 // Match "(X shl/srl V1) & V2" where V2 may not be present. 4652 SDValue LHSShift; // The shift. 4653 SDValue LHSMask; // AND value if any. 4654 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 4655 return nullptr; // Not part of a rotate. 4656 4657 SDValue RHSShift; // The shift. 4658 SDValue RHSMask; // AND value if any. 4659 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 4660 return nullptr; // Not part of a rotate. 4661 4662 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 4663 return nullptr; // Not shifting the same value. 4664 4665 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 4666 return nullptr; // Shifts must disagree. 4667 4668 // Canonicalize shl to left side in a shl/srl pair. 4669 if (RHSShift.getOpcode() == ISD::SHL) { 4670 std::swap(LHS, RHS); 4671 std::swap(LHSShift, RHSShift); 4672 std::swap(LHSMask, RHSMask); 4673 } 4674 4675 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4676 SDValue LHSShiftArg = LHSShift.getOperand(0); 4677 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4678 SDValue RHSShiftArg = RHSShift.getOperand(0); 4679 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4680 4681 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4682 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4683 auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS, 4684 ConstantSDNode *RHS) { 4685 return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits; 4686 }; 4687 if (matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) { 4688 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4689 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4690 4691 // If there is an AND of either shifted operand, apply it to the result. 4692 if (LHSMask.getNode() || RHSMask.getNode()) { 4693 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT); 4694 SDValue Mask = AllOnes; 4695 4696 if (LHSMask.getNode()) { 4697 SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt); 4698 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4699 DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits)); 4700 } 4701 if (RHSMask.getNode()) { 4702 SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt); 4703 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4704 DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits)); 4705 } 4706 4707 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4708 } 4709 4710 return Rot.getNode(); 4711 } 4712 4713 // If there is a mask here, and we have a variable shift, we can't be sure 4714 // that we're masking out the right stuff. 4715 if (LHSMask.getNode() || RHSMask.getNode()) 4716 return nullptr; 4717 4718 // If the shift amount is sign/zext/any-extended just peel it off. 4719 SDValue LExtOp0 = LHSShiftAmt; 4720 SDValue RExtOp0 = RHSShiftAmt; 4721 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4722 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4723 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4724 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4725 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4726 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4727 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4728 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4729 LExtOp0 = LHSShiftAmt.getOperand(0); 4730 RExtOp0 = RHSShiftAmt.getOperand(0); 4731 } 4732 4733 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4734 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4735 if (TryL) 4736 return TryL; 4737 4738 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4739 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4740 if (TryR) 4741 return TryR; 4742 4743 return nullptr; 4744 } 4745 4746 namespace { 4747 /// Represents known origin of an individual byte in load combine pattern. The 4748 /// value of the byte is either constant zero or comes from memory. 4749 struct ByteProvider { 4750 // For constant zero providers Load is set to nullptr. For memory providers 4751 // Load represents the node which loads the byte from memory. 4752 // ByteOffset is the offset of the byte in the value produced by the load. 4753 LoadSDNode *Load; 4754 unsigned ByteOffset; 4755 4756 ByteProvider() : Load(nullptr), ByteOffset(0) {} 4757 4758 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) { 4759 return ByteProvider(Load, ByteOffset); 4760 } 4761 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); } 4762 4763 bool isConstantZero() const { return !Load; } 4764 bool isMemory() const { return Load; } 4765 4766 bool operator==(const ByteProvider &Other) const { 4767 return Other.Load == Load && Other.ByteOffset == ByteOffset; 4768 } 4769 4770 private: 4771 ByteProvider(LoadSDNode *Load, unsigned ByteOffset) 4772 : Load(Load), ByteOffset(ByteOffset) {} 4773 }; 4774 4775 /// Recursively traverses the expression calculating the origin of the requested 4776 /// byte of the given value. Returns None if the provider can't be calculated. 4777 /// 4778 /// For all the values except the root of the expression verifies that the value 4779 /// has exactly one use and if it's not true return None. This way if the origin 4780 /// of the byte is returned it's guaranteed that the values which contribute to 4781 /// the byte are not used outside of this expression. 4782 /// 4783 /// Because the parts of the expression are not allowed to have more than one 4784 /// use this function iterates over trees, not DAGs. So it never visits the same 4785 /// node more than once. 4786 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index, 4787 unsigned Depth, 4788 bool Root = false) { 4789 // Typical i64 by i8 pattern requires recursion up to 8 calls depth 4790 if (Depth == 10) 4791 return None; 4792 4793 if (!Root && !Op.hasOneUse()) 4794 return None; 4795 4796 assert(Op.getValueType().isScalarInteger() && "can't handle other types"); 4797 unsigned BitWidth = Op.getValueSizeInBits(); 4798 if (BitWidth % 8 != 0) 4799 return None; 4800 unsigned ByteWidth = BitWidth / 8; 4801 assert(Index < ByteWidth && "invalid index requested"); 4802 (void) ByteWidth; 4803 4804 switch (Op.getOpcode()) { 4805 case ISD::OR: { 4806 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1); 4807 if (!LHS) 4808 return None; 4809 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1); 4810 if (!RHS) 4811 return None; 4812 4813 if (LHS->isConstantZero()) 4814 return RHS; 4815 if (RHS->isConstantZero()) 4816 return LHS; 4817 return None; 4818 } 4819 case ISD::SHL: { 4820 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 4821 if (!ShiftOp) 4822 return None; 4823 4824 uint64_t BitShift = ShiftOp->getZExtValue(); 4825 if (BitShift % 8 != 0) 4826 return None; 4827 uint64_t ByteShift = BitShift / 8; 4828 4829 return Index < ByteShift 4830 ? ByteProvider::getConstantZero() 4831 : calculateByteProvider(Op->getOperand(0), Index - ByteShift, 4832 Depth + 1); 4833 } 4834 case ISD::ANY_EXTEND: 4835 case ISD::SIGN_EXTEND: 4836 case ISD::ZERO_EXTEND: { 4837 SDValue NarrowOp = Op->getOperand(0); 4838 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits(); 4839 if (NarrowBitWidth % 8 != 0) 4840 return None; 4841 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 4842 4843 if (Index >= NarrowByteWidth) 4844 return Op.getOpcode() == ISD::ZERO_EXTEND 4845 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 4846 : None; 4847 return calculateByteProvider(NarrowOp, Index, Depth + 1); 4848 } 4849 case ISD::BSWAP: 4850 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1, 4851 Depth + 1); 4852 case ISD::LOAD: { 4853 auto L = cast<LoadSDNode>(Op.getNode()); 4854 if (L->isVolatile() || L->isIndexed()) 4855 return None; 4856 4857 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits(); 4858 if (NarrowBitWidth % 8 != 0) 4859 return None; 4860 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 4861 4862 if (Index >= NarrowByteWidth) 4863 return L->getExtensionType() == ISD::ZEXTLOAD 4864 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 4865 : None; 4866 return ByteProvider::getMemory(L, Index); 4867 } 4868 } 4869 4870 return None; 4871 } 4872 } // namespace 4873 4874 /// Match a pattern where a wide type scalar value is loaded by several narrow 4875 /// loads and combined by shifts and ors. Fold it into a single load or a load 4876 /// and a BSWAP if the targets supports it. 4877 /// 4878 /// Assuming little endian target: 4879 /// i8 *a = ... 4880 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24) 4881 /// => 4882 /// i32 val = *((i32)a) 4883 /// 4884 /// i8 *a = ... 4885 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3] 4886 /// => 4887 /// i32 val = BSWAP(*((i32)a)) 4888 /// 4889 /// TODO: This rule matches complex patterns with OR node roots and doesn't 4890 /// interact well with the worklist mechanism. When a part of the pattern is 4891 /// updated (e.g. one of the loads) its direct users are put into the worklist, 4892 /// but the root node of the pattern which triggers the load combine is not 4893 /// necessarily a direct user of the changed node. For example, once the address 4894 /// of t28 load is reassociated load combine won't be triggered: 4895 /// t25: i32 = add t4, Constant:i32<2> 4896 /// t26: i64 = sign_extend t25 4897 /// t27: i64 = add t2, t26 4898 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64 4899 /// t29: i32 = zero_extend t28 4900 /// t32: i32 = shl t29, Constant:i8<8> 4901 /// t33: i32 = or t23, t32 4902 /// As a possible fix visitLoad can check if the load can be a part of a load 4903 /// combine pattern and add corresponding OR roots to the worklist. 4904 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) { 4905 assert(N->getOpcode() == ISD::OR && 4906 "Can only match load combining against OR nodes"); 4907 4908 // Handles simple types only 4909 EVT VT = N->getValueType(0); 4910 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 4911 return SDValue(); 4912 unsigned ByteWidth = VT.getSizeInBits() / 8; 4913 4914 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4915 // Before legalize we can introduce too wide illegal loads which will be later 4916 // split into legal sized loads. This enables us to combine i64 load by i8 4917 // patterns to a couple of i32 loads on 32 bit targets. 4918 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT)) 4919 return SDValue(); 4920 4921 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = []( 4922 unsigned BW, unsigned i) { return i; }; 4923 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = []( 4924 unsigned BW, unsigned i) { return BW - i - 1; }; 4925 4926 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian(); 4927 auto MemoryByteOffset = [&] (ByteProvider P) { 4928 assert(P.isMemory() && "Must be a memory byte provider"); 4929 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits(); 4930 assert(LoadBitWidth % 8 == 0 && 4931 "can only analyze providers for individual bytes not bit"); 4932 unsigned LoadByteWidth = LoadBitWidth / 8; 4933 return IsBigEndianTarget 4934 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset) 4935 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset); 4936 }; 4937 4938 Optional<BaseIndexOffset> Base; 4939 SDValue Chain; 4940 4941 SmallSet<LoadSDNode *, 8> Loads; 4942 Optional<ByteProvider> FirstByteProvider; 4943 int64_t FirstOffset = INT64_MAX; 4944 4945 // Check if all the bytes of the OR we are looking at are loaded from the same 4946 // base address. Collect bytes offsets from Base address in ByteOffsets. 4947 SmallVector<int64_t, 4> ByteOffsets(ByteWidth); 4948 for (unsigned i = 0; i < ByteWidth; i++) { 4949 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true); 4950 if (!P || !P->isMemory()) // All the bytes must be loaded from memory 4951 return SDValue(); 4952 4953 LoadSDNode *L = P->Load; 4954 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() && 4955 "Must be enforced by calculateByteProvider"); 4956 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset"); 4957 4958 // All loads must share the same chain 4959 SDValue LChain = L->getChain(); 4960 if (!Chain) 4961 Chain = LChain; 4962 else if (Chain != LChain) 4963 return SDValue(); 4964 4965 // Loads must share the same base address 4966 BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG); 4967 int64_t ByteOffsetFromBase = 0; 4968 if (!Base) 4969 Base = Ptr; 4970 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase)) 4971 return SDValue(); 4972 4973 // Calculate the offset of the current byte from the base address 4974 ByteOffsetFromBase += MemoryByteOffset(*P); 4975 ByteOffsets[i] = ByteOffsetFromBase; 4976 4977 // Remember the first byte load 4978 if (ByteOffsetFromBase < FirstOffset) { 4979 FirstByteProvider = P; 4980 FirstOffset = ByteOffsetFromBase; 4981 } 4982 4983 Loads.insert(L); 4984 } 4985 assert(Loads.size() > 0 && "All the bytes of the value must be loaded from " 4986 "memory, so there must be at least one load which produces the value"); 4987 assert(Base && "Base address of the accessed memory location must be set"); 4988 assert(FirstOffset != INT64_MAX && "First byte offset must be set"); 4989 4990 // Check if the bytes of the OR we are looking at match with either big or 4991 // little endian value load 4992 bool BigEndian = true, LittleEndian = true; 4993 for (unsigned i = 0; i < ByteWidth; i++) { 4994 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset; 4995 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i); 4996 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i); 4997 if (!BigEndian && !LittleEndian) 4998 return SDValue(); 4999 } 5000 assert((BigEndian != LittleEndian) && "should be either or"); 5001 assert(FirstByteProvider && "must be set"); 5002 5003 // Ensure that the first byte is loaded from zero offset of the first load. 5004 // So the combined value can be loaded from the first load address. 5005 if (MemoryByteOffset(*FirstByteProvider) != 0) 5006 return SDValue(); 5007 LoadSDNode *FirstLoad = FirstByteProvider->Load; 5008 5009 // The node we are looking at matches with the pattern, check if we can 5010 // replace it with a single load and bswap if needed. 5011 5012 // If the load needs byte swap check if the target supports it 5013 bool NeedsBswap = IsBigEndianTarget != BigEndian; 5014 5015 // Before legalize we can introduce illegal bswaps which will be later 5016 // converted to an explicit bswap sequence. This way we end up with a single 5017 // load and byte shuffling instead of several loads and byte shuffling. 5018 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT)) 5019 return SDValue(); 5020 5021 // Check that a load of the wide type is both allowed and fast on the target 5022 bool Fast = false; 5023 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), 5024 VT, FirstLoad->getAddressSpace(), 5025 FirstLoad->getAlignment(), &Fast); 5026 if (!Allowed || !Fast) 5027 return SDValue(); 5028 5029 SDValue NewLoad = 5030 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(), 5031 FirstLoad->getPointerInfo(), FirstLoad->getAlignment()); 5032 5033 // Transfer chain users from old loads to the new load. 5034 for (LoadSDNode *L : Loads) 5035 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1)); 5036 5037 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad; 5038 } 5039 5040 SDValue DAGCombiner::visitXOR(SDNode *N) { 5041 SDValue N0 = N->getOperand(0); 5042 SDValue N1 = N->getOperand(1); 5043 EVT VT = N0.getValueType(); 5044 5045 // fold vector ops 5046 if (VT.isVector()) { 5047 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5048 return FoldedVOp; 5049 5050 // fold (xor x, 0) -> x, vector edition 5051 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5052 return N1; 5053 if (ISD::isBuildVectorAllZeros(N1.getNode())) 5054 return N0; 5055 } 5056 5057 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 5058 if (N0.isUndef() && N1.isUndef()) 5059 return DAG.getConstant(0, SDLoc(N), VT); 5060 // fold (xor x, undef) -> undef 5061 if (N0.isUndef()) 5062 return N0; 5063 if (N1.isUndef()) 5064 return N1; 5065 // fold (xor c1, c2) -> c1^c2 5066 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5067 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 5068 if (N0C && N1C) 5069 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 5070 // canonicalize constant to RHS 5071 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 5072 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 5073 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 5074 // fold (xor x, 0) -> x 5075 if (isNullConstant(N1)) 5076 return N0; 5077 5078 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5079 return NewSel; 5080 5081 // reassociate xor 5082 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 5083 return RXOR; 5084 5085 // fold !(x cc y) -> (x !cc y) 5086 SDValue LHS, RHS, CC; 5087 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 5088 bool isInt = LHS.getValueType().isInteger(); 5089 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 5090 isInt); 5091 5092 if (!LegalOperations || 5093 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 5094 switch (N0.getOpcode()) { 5095 default: 5096 llvm_unreachable("Unhandled SetCC Equivalent!"); 5097 case ISD::SETCC: 5098 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC); 5099 case ISD::SELECT_CC: 5100 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2), 5101 N0.getOperand(3), NotCC); 5102 } 5103 } 5104 } 5105 5106 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 5107 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 5108 N0.getNode()->hasOneUse() && 5109 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 5110 SDValue V = N0.getOperand(0); 5111 SDLoc DL(N0); 5112 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 5113 DAG.getConstant(1, DL, V.getValueType())); 5114 AddToWorklist(V.getNode()); 5115 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 5116 } 5117 5118 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 5119 if (isOneConstant(N1) && VT == MVT::i1 && 5120 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 5121 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5122 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 5123 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 5124 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 5125 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 5126 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 5127 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 5128 } 5129 } 5130 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 5131 if (isAllOnesConstant(N1) && 5132 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 5133 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5134 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 5135 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 5136 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 5137 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 5138 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 5139 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 5140 } 5141 } 5142 // fold (xor (and x, y), y) -> (and (not x), y) 5143 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 5144 N0->getOperand(1) == N1) { 5145 SDValue X = N0->getOperand(0); 5146 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 5147 AddToWorklist(NotX.getNode()); 5148 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 5149 } 5150 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 5151 if (N1C && N0.getOpcode() == ISD::XOR) { 5152 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 5153 SDLoc DL(N); 5154 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 5155 DAG.getConstant(N1C->getAPIntValue() ^ 5156 N00C->getAPIntValue(), DL, VT)); 5157 } 5158 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 5159 SDLoc DL(N); 5160 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 5161 DAG.getConstant(N1C->getAPIntValue() ^ 5162 N01C->getAPIntValue(), DL, VT)); 5163 } 5164 } 5165 5166 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X) 5167 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5168 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && 5169 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) && 5170 TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { 5171 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1))) 5172 if (C->getAPIntValue() == (OpSizeInBits - 1)) 5173 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0)); 5174 } 5175 5176 // fold (xor x, x) -> 0 5177 if (N0 == N1) 5178 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 5179 5180 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 5181 // Here is a concrete example of this equivalence: 5182 // i16 x == 14 5183 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 5184 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 5185 // 5186 // => 5187 // 5188 // i16 ~1 == 0b1111111111111110 5189 // i16 rol(~1, 14) == 0b1011111111111111 5190 // 5191 // Some additional tips to help conceptualize this transform: 5192 // - Try to see the operation as placing a single zero in a value of all ones. 5193 // - There exists no value for x which would allow the result to contain zero. 5194 // - Values of x larger than the bitwidth are undefined and do not require a 5195 // consistent result. 5196 // - Pushing the zero left requires shifting one bits in from the right. 5197 // A rotate left of ~1 is a nice way of achieving the desired result. 5198 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 5199 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 5200 SDLoc DL(N); 5201 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 5202 N0.getOperand(1)); 5203 } 5204 5205 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 5206 if (N0.getOpcode() == N1.getOpcode()) 5207 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 5208 return Tmp; 5209 5210 // Simplify the expression using non-local knowledge. 5211 if (SimplifyDemandedBits(SDValue(N, 0))) 5212 return SDValue(N, 0); 5213 5214 return SDValue(); 5215 } 5216 5217 /// Handle transforms common to the three shifts, when the shift amount is a 5218 /// constant. 5219 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 5220 SDNode *LHS = N->getOperand(0).getNode(); 5221 if (!LHS->hasOneUse()) return SDValue(); 5222 5223 // We want to pull some binops through shifts, so that we have (and (shift)) 5224 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 5225 // thing happens with address calculations, so it's important to canonicalize 5226 // it. 5227 bool HighBitSet = false; // Can we transform this if the high bit is set? 5228 5229 switch (LHS->getOpcode()) { 5230 default: return SDValue(); 5231 case ISD::OR: 5232 case ISD::XOR: 5233 HighBitSet = false; // We can only transform sra if the high bit is clear. 5234 break; 5235 case ISD::AND: 5236 HighBitSet = true; // We can only transform sra if the high bit is set. 5237 break; 5238 case ISD::ADD: 5239 if (N->getOpcode() != ISD::SHL) 5240 return SDValue(); // only shl(add) not sr[al](add). 5241 HighBitSet = false; // We can only transform sra if the high bit is clear. 5242 break; 5243 } 5244 5245 // We require the RHS of the binop to be a constant and not opaque as well. 5246 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 5247 if (!BinOpCst) return SDValue(); 5248 5249 // FIXME: disable this unless the input to the binop is a shift by a constant 5250 // or is copy/select.Enable this in other cases when figure out it's exactly profitable. 5251 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 5252 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL || 5253 BinOpLHSVal->getOpcode() == ISD::SRA || 5254 BinOpLHSVal->getOpcode() == ISD::SRL; 5255 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg || 5256 BinOpLHSVal->getOpcode() == ISD::SELECT; 5257 5258 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) && 5259 !isCopyOrSelect) 5260 return SDValue(); 5261 5262 if (isCopyOrSelect && N->hasOneUse()) 5263 return SDValue(); 5264 5265 EVT VT = N->getValueType(0); 5266 5267 // If this is a signed shift right, and the high bit is modified by the 5268 // logical operation, do not perform the transformation. The highBitSet 5269 // boolean indicates the value of the high bit of the constant which would 5270 // cause it to be modified for this operation. 5271 if (N->getOpcode() == ISD::SRA) { 5272 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 5273 if (BinOpRHSSignSet != HighBitSet) 5274 return SDValue(); 5275 } 5276 5277 if (!TLI.isDesirableToCommuteWithShift(LHS)) 5278 return SDValue(); 5279 5280 // Fold the constants, shifting the binop RHS by the shift amount. 5281 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 5282 N->getValueType(0), 5283 LHS->getOperand(1), N->getOperand(1)); 5284 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 5285 5286 // Create the new shift. 5287 SDValue NewShift = DAG.getNode(N->getOpcode(), 5288 SDLoc(LHS->getOperand(0)), 5289 VT, LHS->getOperand(0), N->getOperand(1)); 5290 5291 // Create the new binop. 5292 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 5293 } 5294 5295 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 5296 assert(N->getOpcode() == ISD::TRUNCATE); 5297 assert(N->getOperand(0).getOpcode() == ISD::AND); 5298 5299 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 5300 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 5301 SDValue N01 = N->getOperand(0).getOperand(1); 5302 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) { 5303 SDLoc DL(N); 5304 EVT TruncVT = N->getValueType(0); 5305 SDValue N00 = N->getOperand(0).getOperand(0); 5306 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00); 5307 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01); 5308 AddToWorklist(Trunc00.getNode()); 5309 AddToWorklist(Trunc01.getNode()); 5310 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01); 5311 } 5312 } 5313 5314 return SDValue(); 5315 } 5316 5317 SDValue DAGCombiner::visitRotate(SDNode *N) { 5318 SDLoc dl(N); 5319 SDValue N0 = N->getOperand(0); 5320 SDValue N1 = N->getOperand(1); 5321 EVT VT = N->getValueType(0); 5322 unsigned Bitsize = VT.getScalarSizeInBits(); 5323 5324 // fold (rot x, 0) -> x 5325 if (isNullConstantOrNullSplatConstant(N1)) 5326 return N0; 5327 5328 // fold (rot x, c) -> (rot x, c % BitSize) 5329 if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) { 5330 if (Cst->getAPIntValue().uge(Bitsize)) { 5331 uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize); 5332 return DAG.getNode(N->getOpcode(), dl, VT, N0, 5333 DAG.getConstant(RotAmt, dl, N1.getValueType())); 5334 } 5335 } 5336 5337 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 5338 if (N1.getOpcode() == ISD::TRUNCATE && 5339 N1.getOperand(0).getOpcode() == ISD::AND) { 5340 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5341 return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1); 5342 } 5343 5344 unsigned NextOp = N0.getOpcode(); 5345 // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize) 5346 if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) { 5347 SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1); 5348 SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)); 5349 if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) { 5350 EVT ShiftVT = C1->getValueType(0); 5351 bool SameSide = (N->getOpcode() == NextOp); 5352 unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB; 5353 if (SDValue CombinedShift = 5354 DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) { 5355 SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT); 5356 SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic( 5357 ISD::SREM, dl, ShiftVT, CombinedShift.getNode(), 5358 BitsizeC.getNode()); 5359 return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0), 5360 CombinedShiftNorm); 5361 } 5362 } 5363 } 5364 return SDValue(); 5365 } 5366 5367 SDValue DAGCombiner::visitSHL(SDNode *N) { 5368 SDValue N0 = N->getOperand(0); 5369 SDValue N1 = N->getOperand(1); 5370 EVT VT = N0.getValueType(); 5371 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5372 5373 // fold vector ops 5374 if (VT.isVector()) { 5375 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5376 return FoldedVOp; 5377 5378 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 5379 // If setcc produces all-one true value then: 5380 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 5381 if (N1CV && N1CV->isConstant()) { 5382 if (N0.getOpcode() == ISD::AND) { 5383 SDValue N00 = N0->getOperand(0); 5384 SDValue N01 = N0->getOperand(1); 5385 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 5386 5387 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 5388 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 5389 TargetLowering::ZeroOrNegativeOneBooleanContent) { 5390 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 5391 N01CV, N1CV)) 5392 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 5393 } 5394 } 5395 } 5396 } 5397 5398 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5399 5400 // fold (shl c1, c2) -> c1<<c2 5401 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5402 if (N0C && N1C && !N1C->isOpaque()) 5403 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 5404 // fold (shl 0, x) -> 0 5405 if (isNullConstantOrNullSplatConstant(N0)) 5406 return N0; 5407 // fold (shl x, c >= size(x)) -> undef 5408 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 5409 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 5410 return Val->getAPIntValue().uge(OpSizeInBits); 5411 }; 5412 if (matchUnaryPredicate(N1, MatchShiftTooBig)) 5413 return DAG.getUNDEF(VT); 5414 // fold (shl x, 0) -> x 5415 if (N1C && N1C->isNullValue()) 5416 return N0; 5417 // fold (shl undef, x) -> 0 5418 if (N0.isUndef()) 5419 return DAG.getConstant(0, SDLoc(N), VT); 5420 5421 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5422 return NewSel; 5423 5424 // if (shl x, c) is known to be zero, return 0 5425 if (DAG.MaskedValueIsZero(SDValue(N, 0), 5426 APInt::getAllOnesValue(OpSizeInBits))) 5427 return DAG.getConstant(0, SDLoc(N), VT); 5428 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 5429 if (N1.getOpcode() == ISD::TRUNCATE && 5430 N1.getOperand(0).getOpcode() == ISD::AND) { 5431 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5432 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 5433 } 5434 5435 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5436 return SDValue(N, 0); 5437 5438 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 5439 if (N0.getOpcode() == ISD::SHL) { 5440 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 5441 ConstantSDNode *RHS) { 5442 APInt c1 = LHS->getAPIntValue(); 5443 APInt c2 = RHS->getAPIntValue(); 5444 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5445 return (c1 + c2).uge(OpSizeInBits); 5446 }; 5447 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 5448 return DAG.getConstant(0, SDLoc(N), VT); 5449 5450 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 5451 ConstantSDNode *RHS) { 5452 APInt c1 = LHS->getAPIntValue(); 5453 APInt c2 = RHS->getAPIntValue(); 5454 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5455 return (c1 + c2).ult(OpSizeInBits); 5456 }; 5457 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 5458 SDLoc DL(N); 5459 EVT ShiftVT = N1.getValueType(); 5460 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 5461 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum); 5462 } 5463 } 5464 5465 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 5466 // For this to be valid, the second form must not preserve any of the bits 5467 // that are shifted out by the inner shift in the first form. This means 5468 // the outer shift size must be >= the number of bits added by the ext. 5469 // As a corollary, we don't care what kind of ext it is. 5470 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 5471 N0.getOpcode() == ISD::ANY_EXTEND || 5472 N0.getOpcode() == ISD::SIGN_EXTEND) && 5473 N0.getOperand(0).getOpcode() == ISD::SHL) { 5474 SDValue N0Op0 = N0.getOperand(0); 5475 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5476 APInt c1 = N0Op0C1->getAPIntValue(); 5477 APInt c2 = N1C->getAPIntValue(); 5478 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5479 5480 EVT InnerShiftVT = N0Op0.getValueType(); 5481 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 5482 if (c2.uge(OpSizeInBits - InnerShiftSize)) { 5483 SDLoc DL(N0); 5484 APInt Sum = c1 + c2; 5485 if (Sum.uge(OpSizeInBits)) 5486 return DAG.getConstant(0, DL, VT); 5487 5488 return DAG.getNode( 5489 ISD::SHL, DL, VT, 5490 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)), 5491 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5492 } 5493 } 5494 } 5495 5496 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 5497 // Only fold this if the inner zext has no other uses to avoid increasing 5498 // the total number of instructions. 5499 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 5500 N0.getOperand(0).getOpcode() == ISD::SRL) { 5501 SDValue N0Op0 = N0.getOperand(0); 5502 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5503 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) { 5504 uint64_t c1 = N0Op0C1->getZExtValue(); 5505 uint64_t c2 = N1C->getZExtValue(); 5506 if (c1 == c2) { 5507 SDValue NewOp0 = N0.getOperand(0); 5508 EVT CountVT = NewOp0.getOperand(1).getValueType(); 5509 SDLoc DL(N); 5510 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 5511 NewOp0, 5512 DAG.getConstant(c2, DL, CountVT)); 5513 AddToWorklist(NewSHL.getNode()); 5514 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 5515 } 5516 } 5517 } 5518 } 5519 5520 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 5521 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 5522 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 5523 N0->getFlags().hasExact()) { 5524 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5525 uint64_t C1 = N0C1->getZExtValue(); 5526 uint64_t C2 = N1C->getZExtValue(); 5527 SDLoc DL(N); 5528 if (C1 <= C2) 5529 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5530 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 5531 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 5532 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 5533 } 5534 } 5535 5536 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 5537 // (and (srl x, (sub c1, c2), MASK) 5538 // Only fold this if the inner shift has no other uses -- if it does, folding 5539 // this will increase the total number of instructions. 5540 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5541 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5542 uint64_t c1 = N0C1->getZExtValue(); 5543 if (c1 < OpSizeInBits) { 5544 uint64_t c2 = N1C->getZExtValue(); 5545 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 5546 SDValue Shift; 5547 if (c2 > c1) { 5548 Mask <<= c2 - c1; 5549 SDLoc DL(N); 5550 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5551 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 5552 } else { 5553 Mask.lshrInPlace(c1 - c2); 5554 SDLoc DL(N); 5555 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 5556 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 5557 } 5558 SDLoc DL(N0); 5559 return DAG.getNode(ISD::AND, DL, VT, Shift, 5560 DAG.getConstant(Mask, DL, VT)); 5561 } 5562 } 5563 } 5564 5565 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 5566 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) && 5567 isConstantOrConstantVector(N1, /* No Opaques */ true)) { 5568 SDLoc DL(N); 5569 SDValue AllBits = DAG.getAllOnesConstant(DL, VT); 5570 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1); 5571 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask); 5572 } 5573 5574 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 5575 // Variant of version done on multiply, except mul by a power of 2 is turned 5576 // into a shift. 5577 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 5578 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5579 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5580 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 5581 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5582 AddToWorklist(Shl0.getNode()); 5583 AddToWorklist(Shl1.getNode()); 5584 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 5585 } 5586 5587 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 5588 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() && 5589 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5590 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5591 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5592 if (isConstantOrConstantVector(Shl)) 5593 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl); 5594 } 5595 5596 if (N1C && !N1C->isOpaque()) 5597 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 5598 return NewSHL; 5599 5600 return SDValue(); 5601 } 5602 5603 SDValue DAGCombiner::visitSRA(SDNode *N) { 5604 SDValue N0 = N->getOperand(0); 5605 SDValue N1 = N->getOperand(1); 5606 EVT VT = N0.getValueType(); 5607 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5608 5609 // Arithmetic shifting an all-sign-bit value is a no-op. 5610 // fold (sra 0, x) -> 0 5611 // fold (sra -1, x) -> -1 5612 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits) 5613 return N0; 5614 5615 // fold vector ops 5616 if (VT.isVector()) 5617 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5618 return FoldedVOp; 5619 5620 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5621 5622 // fold (sra c1, c2) -> (sra c1, c2) 5623 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5624 if (N0C && N1C && !N1C->isOpaque()) 5625 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 5626 // fold (sra x, c >= size(x)) -> undef 5627 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 5628 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 5629 return Val->getAPIntValue().uge(OpSizeInBits); 5630 }; 5631 if (matchUnaryPredicate(N1, MatchShiftTooBig)) 5632 return DAG.getUNDEF(VT); 5633 // fold (sra x, 0) -> x 5634 if (N1C && N1C->isNullValue()) 5635 return N0; 5636 5637 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5638 return NewSel; 5639 5640 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 5641 // sext_inreg. 5642 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 5643 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 5644 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 5645 if (VT.isVector()) 5646 ExtVT = EVT::getVectorVT(*DAG.getContext(), 5647 ExtVT, VT.getVectorNumElements()); 5648 if ((!LegalOperations || 5649 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 5650 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5651 N0.getOperand(0), DAG.getValueType(ExtVT)); 5652 } 5653 5654 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 5655 if (N0.getOpcode() == ISD::SRA) { 5656 SDLoc DL(N); 5657 EVT ShiftVT = N1.getValueType(); 5658 5659 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 5660 ConstantSDNode *RHS) { 5661 APInt c1 = LHS->getAPIntValue(); 5662 APInt c2 = RHS->getAPIntValue(); 5663 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5664 return (c1 + c2).uge(OpSizeInBits); 5665 }; 5666 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 5667 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), 5668 DAG.getConstant(OpSizeInBits - 1, DL, ShiftVT)); 5669 5670 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 5671 ConstantSDNode *RHS) { 5672 APInt c1 = LHS->getAPIntValue(); 5673 APInt c2 = RHS->getAPIntValue(); 5674 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5675 return (c1 + c2).ult(OpSizeInBits); 5676 }; 5677 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 5678 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 5679 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), Sum); 5680 } 5681 } 5682 5683 // fold (sra (shl X, m), (sub result_size, n)) 5684 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 5685 // result_size - n != m. 5686 // If truncate is free for the target sext(shl) is likely to result in better 5687 // code. 5688 if (N0.getOpcode() == ISD::SHL && N1C) { 5689 // Get the two constanst of the shifts, CN0 = m, CN = n. 5690 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 5691 if (N01C) { 5692 LLVMContext &Ctx = *DAG.getContext(); 5693 // Determine what the truncate's result bitsize and type would be. 5694 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 5695 5696 if (VT.isVector()) 5697 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 5698 5699 // Determine the residual right-shift amount. 5700 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 5701 5702 // If the shift is not a no-op (in which case this should be just a sign 5703 // extend already), the truncated to type is legal, sign_extend is legal 5704 // on that type, and the truncate to that type is both legal and free, 5705 // perform the transform. 5706 if ((ShiftAmt > 0) && 5707 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 5708 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 5709 TLI.isTruncateFree(VT, TruncVT)) { 5710 5711 SDLoc DL(N); 5712 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 5713 getShiftAmountTy(N0.getOperand(0).getValueType())); 5714 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 5715 N0.getOperand(0), Amt); 5716 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 5717 Shift); 5718 return DAG.getNode(ISD::SIGN_EXTEND, DL, 5719 N->getValueType(0), Trunc); 5720 } 5721 } 5722 } 5723 5724 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 5725 if (N1.getOpcode() == ISD::TRUNCATE && 5726 N1.getOperand(0).getOpcode() == ISD::AND) { 5727 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5728 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 5729 } 5730 5731 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 5732 // if c1 is equal to the number of bits the trunc removes 5733 if (N0.getOpcode() == ISD::TRUNCATE && 5734 (N0.getOperand(0).getOpcode() == ISD::SRL || 5735 N0.getOperand(0).getOpcode() == ISD::SRA) && 5736 N0.getOperand(0).hasOneUse() && 5737 N0.getOperand(0).getOperand(1).hasOneUse() && 5738 N1C) { 5739 SDValue N0Op0 = N0.getOperand(0); 5740 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 5741 unsigned LargeShiftVal = LargeShift->getZExtValue(); 5742 EVT LargeVT = N0Op0.getValueType(); 5743 5744 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 5745 SDLoc DL(N); 5746 SDValue Amt = 5747 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 5748 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 5749 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 5750 N0Op0.getOperand(0), Amt); 5751 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 5752 } 5753 } 5754 } 5755 5756 // Simplify, based on bits shifted out of the LHS. 5757 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5758 return SDValue(N, 0); 5759 5760 5761 // If the sign bit is known to be zero, switch this to a SRL. 5762 if (DAG.SignBitIsZero(N0)) 5763 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 5764 5765 if (N1C && !N1C->isOpaque()) 5766 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 5767 return NewSRA; 5768 5769 return SDValue(); 5770 } 5771 5772 SDValue DAGCombiner::visitSRL(SDNode *N) { 5773 SDValue N0 = N->getOperand(0); 5774 SDValue N1 = N->getOperand(1); 5775 EVT VT = N0.getValueType(); 5776 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5777 5778 // fold vector ops 5779 if (VT.isVector()) 5780 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5781 return FoldedVOp; 5782 5783 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5784 5785 // fold (srl c1, c2) -> c1 >>u c2 5786 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5787 if (N0C && N1C && !N1C->isOpaque()) 5788 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 5789 // fold (srl 0, x) -> 0 5790 if (isNullConstantOrNullSplatConstant(N0)) 5791 return N0; 5792 // fold (srl x, c >= size(x)) -> undef 5793 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 5794 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 5795 return Val->getAPIntValue().uge(OpSizeInBits); 5796 }; 5797 if (matchUnaryPredicate(N1, MatchShiftTooBig)) 5798 return DAG.getUNDEF(VT); 5799 // fold (srl x, 0) -> x 5800 if (N1C && N1C->isNullValue()) 5801 return N0; 5802 5803 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5804 return NewSel; 5805 5806 // if (srl x, c) is known to be zero, return 0 5807 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 5808 APInt::getAllOnesValue(OpSizeInBits))) 5809 return DAG.getConstant(0, SDLoc(N), VT); 5810 5811 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 5812 if (N0.getOpcode() == ISD::SRL) { 5813 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 5814 ConstantSDNode *RHS) { 5815 APInt c1 = LHS->getAPIntValue(); 5816 APInt c2 = RHS->getAPIntValue(); 5817 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5818 return (c1 + c2).uge(OpSizeInBits); 5819 }; 5820 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 5821 return DAG.getConstant(0, SDLoc(N), VT); 5822 5823 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 5824 ConstantSDNode *RHS) { 5825 APInt c1 = LHS->getAPIntValue(); 5826 APInt c2 = RHS->getAPIntValue(); 5827 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5828 return (c1 + c2).ult(OpSizeInBits); 5829 }; 5830 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 5831 SDLoc DL(N); 5832 EVT ShiftVT = N1.getValueType(); 5833 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 5834 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum); 5835 } 5836 } 5837 5838 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 5839 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 5840 N0.getOperand(0).getOpcode() == ISD::SRL) { 5841 if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) { 5842 uint64_t c1 = N001C->getZExtValue(); 5843 uint64_t c2 = N1C->getZExtValue(); 5844 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 5845 EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType(); 5846 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 5847 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 5848 if (c1 + OpSizeInBits == InnerShiftSize) { 5849 SDLoc DL(N0); 5850 if (c1 + c2 >= InnerShiftSize) 5851 return DAG.getConstant(0, DL, VT); 5852 return DAG.getNode(ISD::TRUNCATE, DL, VT, 5853 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 5854 N0.getOperand(0).getOperand(0), 5855 DAG.getConstant(c1 + c2, DL, 5856 ShiftCountVT))); 5857 } 5858 } 5859 } 5860 5861 // fold (srl (shl x, c), c) -> (and x, cst2) 5862 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 5863 isConstantOrConstantVector(N1, /* NoOpaques */ true)) { 5864 SDLoc DL(N); 5865 SDValue Mask = 5866 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1); 5867 AddToWorklist(Mask.getNode()); 5868 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask); 5869 } 5870 5871 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 5872 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 5873 // Shifting in all undef bits? 5874 EVT SmallVT = N0.getOperand(0).getValueType(); 5875 unsigned BitSize = SmallVT.getScalarSizeInBits(); 5876 if (N1C->getZExtValue() >= BitSize) 5877 return DAG.getUNDEF(VT); 5878 5879 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 5880 uint64_t ShiftAmt = N1C->getZExtValue(); 5881 SDLoc DL0(N0); 5882 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 5883 N0.getOperand(0), 5884 DAG.getConstant(ShiftAmt, DL0, 5885 getShiftAmountTy(SmallVT))); 5886 AddToWorklist(SmallShift.getNode()); 5887 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt); 5888 SDLoc DL(N); 5889 return DAG.getNode(ISD::AND, DL, VT, 5890 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 5891 DAG.getConstant(Mask, DL, VT)); 5892 } 5893 } 5894 5895 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 5896 // bit, which is unmodified by sra. 5897 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 5898 if (N0.getOpcode() == ISD::SRA) 5899 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 5900 } 5901 5902 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 5903 if (N1C && N0.getOpcode() == ISD::CTLZ && 5904 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 5905 KnownBits Known; 5906 DAG.computeKnownBits(N0.getOperand(0), Known); 5907 5908 // If any of the input bits are KnownOne, then the input couldn't be all 5909 // zeros, thus the result of the srl will always be zero. 5910 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 5911 5912 // If all of the bits input the to ctlz node are known to be zero, then 5913 // the result of the ctlz is "32" and the result of the shift is one. 5914 APInt UnknownBits = ~Known.Zero; 5915 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 5916 5917 // Otherwise, check to see if there is exactly one bit input to the ctlz. 5918 if (UnknownBits.isPowerOf2()) { 5919 // Okay, we know that only that the single bit specified by UnknownBits 5920 // could be set on input to the CTLZ node. If this bit is set, the SRL 5921 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 5922 // to an SRL/XOR pair, which is likely to simplify more. 5923 unsigned ShAmt = UnknownBits.countTrailingZeros(); 5924 SDValue Op = N0.getOperand(0); 5925 5926 if (ShAmt) { 5927 SDLoc DL(N0); 5928 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 5929 DAG.getConstant(ShAmt, DL, 5930 getShiftAmountTy(Op.getValueType()))); 5931 AddToWorklist(Op.getNode()); 5932 } 5933 5934 SDLoc DL(N); 5935 return DAG.getNode(ISD::XOR, DL, VT, 5936 Op, DAG.getConstant(1, DL, VT)); 5937 } 5938 } 5939 5940 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 5941 if (N1.getOpcode() == ISD::TRUNCATE && 5942 N1.getOperand(0).getOpcode() == ISD::AND) { 5943 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5944 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 5945 } 5946 5947 // fold operands of srl based on knowledge that the low bits are not 5948 // demanded. 5949 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5950 return SDValue(N, 0); 5951 5952 if (N1C && !N1C->isOpaque()) 5953 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 5954 return NewSRL; 5955 5956 // Attempt to convert a srl of a load into a narrower zero-extending load. 5957 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 5958 return NarrowLoad; 5959 5960 // Here is a common situation. We want to optimize: 5961 // 5962 // %a = ... 5963 // %b = and i32 %a, 2 5964 // %c = srl i32 %b, 1 5965 // brcond i32 %c ... 5966 // 5967 // into 5968 // 5969 // %a = ... 5970 // %b = and %a, 2 5971 // %c = setcc eq %b, 0 5972 // brcond %c ... 5973 // 5974 // However when after the source operand of SRL is optimized into AND, the SRL 5975 // itself may not be optimized further. Look for it and add the BRCOND into 5976 // the worklist. 5977 if (N->hasOneUse()) { 5978 SDNode *Use = *N->use_begin(); 5979 if (Use->getOpcode() == ISD::BRCOND) 5980 AddToWorklist(Use); 5981 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 5982 // Also look pass the truncate. 5983 Use = *Use->use_begin(); 5984 if (Use->getOpcode() == ISD::BRCOND) 5985 AddToWorklist(Use); 5986 } 5987 } 5988 5989 return SDValue(); 5990 } 5991 5992 SDValue DAGCombiner::visitABS(SDNode *N) { 5993 SDValue N0 = N->getOperand(0); 5994 EVT VT = N->getValueType(0); 5995 5996 // fold (abs c1) -> c2 5997 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5998 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0); 5999 // fold (abs (abs x)) -> (abs x) 6000 if (N0.getOpcode() == ISD::ABS) 6001 return N0; 6002 // fold (abs x) -> x iff not-negative 6003 if (DAG.SignBitIsZero(N0)) 6004 return N0; 6005 return SDValue(); 6006 } 6007 6008 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 6009 SDValue N0 = N->getOperand(0); 6010 EVT VT = N->getValueType(0); 6011 6012 // fold (bswap c1) -> c2 6013 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6014 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 6015 // fold (bswap (bswap x)) -> x 6016 if (N0.getOpcode() == ISD::BSWAP) 6017 return N0->getOperand(0); 6018 return SDValue(); 6019 } 6020 6021 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 6022 SDValue N0 = N->getOperand(0); 6023 EVT VT = N->getValueType(0); 6024 6025 // fold (bitreverse c1) -> c2 6026 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6027 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0); 6028 // fold (bitreverse (bitreverse x)) -> x 6029 if (N0.getOpcode() == ISD::BITREVERSE) 6030 return N0.getOperand(0); 6031 return SDValue(); 6032 } 6033 6034 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 6035 SDValue N0 = N->getOperand(0); 6036 EVT VT = N->getValueType(0); 6037 6038 // fold (ctlz c1) -> c2 6039 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6040 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 6041 return SDValue(); 6042 } 6043 6044 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 6045 SDValue N0 = N->getOperand(0); 6046 EVT VT = N->getValueType(0); 6047 6048 // fold (ctlz_zero_undef c1) -> c2 6049 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6050 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 6051 return SDValue(); 6052 } 6053 6054 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 6055 SDValue N0 = N->getOperand(0); 6056 EVT VT = N->getValueType(0); 6057 6058 // fold (cttz c1) -> c2 6059 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6060 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 6061 return SDValue(); 6062 } 6063 6064 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 6065 SDValue N0 = N->getOperand(0); 6066 EVT VT = N->getValueType(0); 6067 6068 // fold (cttz_zero_undef c1) -> c2 6069 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6070 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 6071 return SDValue(); 6072 } 6073 6074 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 6075 SDValue N0 = N->getOperand(0); 6076 EVT VT = N->getValueType(0); 6077 6078 // fold (ctpop c1) -> c2 6079 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6080 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 6081 return SDValue(); 6082 } 6083 6084 6085 /// \brief Generate Min/Max node 6086 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 6087 SDValue RHS, SDValue True, SDValue False, 6088 ISD::CondCode CC, const TargetLowering &TLI, 6089 SelectionDAG &DAG) { 6090 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 6091 return SDValue(); 6092 6093 switch (CC) { 6094 case ISD::SETOLT: 6095 case ISD::SETOLE: 6096 case ISD::SETLT: 6097 case ISD::SETLE: 6098 case ISD::SETULT: 6099 case ISD::SETULE: { 6100 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 6101 if (TLI.isOperationLegal(Opcode, VT)) 6102 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 6103 return SDValue(); 6104 } 6105 case ISD::SETOGT: 6106 case ISD::SETOGE: 6107 case ISD::SETGT: 6108 case ISD::SETGE: 6109 case ISD::SETUGT: 6110 case ISD::SETUGE: { 6111 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 6112 if (TLI.isOperationLegal(Opcode, VT)) 6113 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 6114 return SDValue(); 6115 } 6116 default: 6117 return SDValue(); 6118 } 6119 } 6120 6121 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) { 6122 SDValue Cond = N->getOperand(0); 6123 SDValue N1 = N->getOperand(1); 6124 SDValue N2 = N->getOperand(2); 6125 EVT VT = N->getValueType(0); 6126 EVT CondVT = Cond.getValueType(); 6127 SDLoc DL(N); 6128 6129 if (!VT.isInteger()) 6130 return SDValue(); 6131 6132 auto *C1 = dyn_cast<ConstantSDNode>(N1); 6133 auto *C2 = dyn_cast<ConstantSDNode>(N2); 6134 if (!C1 || !C2) 6135 return SDValue(); 6136 6137 // Only do this before legalization to avoid conflicting with target-specific 6138 // transforms in the other direction (create a select from a zext/sext). There 6139 // is also a target-independent combine here in DAGCombiner in the other 6140 // direction for (select Cond, -1, 0) when the condition is not i1. 6141 if (CondVT == MVT::i1 && !LegalOperations) { 6142 if (C1->isNullValue() && C2->isOne()) { 6143 // select Cond, 0, 1 --> zext (!Cond) 6144 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 6145 if (VT != MVT::i1) 6146 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond); 6147 return NotCond; 6148 } 6149 if (C1->isNullValue() && C2->isAllOnesValue()) { 6150 // select Cond, 0, -1 --> sext (!Cond) 6151 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 6152 if (VT != MVT::i1) 6153 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond); 6154 return NotCond; 6155 } 6156 if (C1->isOne() && C2->isNullValue()) { 6157 // select Cond, 1, 0 --> zext (Cond) 6158 if (VT != MVT::i1) 6159 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 6160 return Cond; 6161 } 6162 if (C1->isAllOnesValue() && C2->isNullValue()) { 6163 // select Cond, -1, 0 --> sext (Cond) 6164 if (VT != MVT::i1) 6165 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 6166 return Cond; 6167 } 6168 6169 // For any constants that differ by 1, we can transform the select into an 6170 // extend and add. Use a target hook because some targets may prefer to 6171 // transform in the other direction. 6172 if (TLI.convertSelectOfConstantsToMath()) { 6173 if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) { 6174 // select Cond, C1, C1-1 --> add (zext Cond), C1-1 6175 if (VT != MVT::i1) 6176 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 6177 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 6178 } 6179 if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) { 6180 // select Cond, C1, C1+1 --> add (sext Cond), C1+1 6181 if (VT != MVT::i1) 6182 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 6183 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 6184 } 6185 } 6186 6187 return SDValue(); 6188 } 6189 6190 // fold (select Cond, 0, 1) -> (xor Cond, 1) 6191 // We can't do this reliably if integer based booleans have different contents 6192 // to floating point based booleans. This is because we can't tell whether we 6193 // have an integer-based boolean or a floating-point-based boolean unless we 6194 // can find the SETCC that produced it and inspect its operands. This is 6195 // fairly easy if C is the SETCC node, but it can potentially be 6196 // undiscoverable (or not reasonably discoverable). For example, it could be 6197 // in another basic block or it could require searching a complicated 6198 // expression. 6199 if (CondVT.isInteger() && 6200 TLI.getBooleanContents(false, true) == 6201 TargetLowering::ZeroOrOneBooleanContent && 6202 TLI.getBooleanContents(false, false) == 6203 TargetLowering::ZeroOrOneBooleanContent && 6204 C1->isNullValue() && C2->isOne()) { 6205 SDValue NotCond = 6206 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT)); 6207 if (VT.bitsEq(CondVT)) 6208 return NotCond; 6209 return DAG.getZExtOrTrunc(NotCond, DL, VT); 6210 } 6211 6212 return SDValue(); 6213 } 6214 6215 SDValue DAGCombiner::visitSELECT(SDNode *N) { 6216 SDValue N0 = N->getOperand(0); 6217 SDValue N1 = N->getOperand(1); 6218 SDValue N2 = N->getOperand(2); 6219 EVT VT = N->getValueType(0); 6220 EVT VT0 = N0.getValueType(); 6221 SDLoc DL(N); 6222 6223 // fold (select C, X, X) -> X 6224 if (N1 == N2) 6225 return N1; 6226 6227 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 6228 // fold (select true, X, Y) -> X 6229 // fold (select false, X, Y) -> Y 6230 return !N0C->isNullValue() ? N1 : N2; 6231 } 6232 6233 // fold (select X, X, Y) -> (or X, Y) 6234 // fold (select X, 1, Y) -> (or C, Y) 6235 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 6236 return DAG.getNode(ISD::OR, DL, VT, N0, N2); 6237 6238 if (SDValue V = foldSelectOfConstants(N)) 6239 return V; 6240 6241 // fold (select C, 0, X) -> (and (not C), X) 6242 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 6243 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 6244 AddToWorklist(NOTNode.getNode()); 6245 return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2); 6246 } 6247 // fold (select C, X, 1) -> (or (not C), X) 6248 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 6249 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 6250 AddToWorklist(NOTNode.getNode()); 6251 return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1); 6252 } 6253 // fold (select X, Y, X) -> (and X, Y) 6254 // fold (select X, Y, 0) -> (and X, Y) 6255 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 6256 return DAG.getNode(ISD::AND, DL, VT, N0, N1); 6257 6258 // If we can fold this based on the true/false value, do so. 6259 if (SimplifySelectOps(N, N1, N2)) 6260 return SDValue(N, 0); // Don't revisit N. 6261 6262 if (VT0 == MVT::i1) { 6263 // The code in this block deals with the following 2 equivalences: 6264 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 6265 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 6266 // The target can specify its preferred form with the 6267 // shouldNormalizeToSelectSequence() callback. However we always transform 6268 // to the right anyway if we find the inner select exists in the DAG anyway 6269 // and we always transform to the left side if we know that we can further 6270 // optimize the combination of the conditions. 6271 bool normalizeToSequence = 6272 TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 6273 // select (and Cond0, Cond1), X, Y 6274 // -> select Cond0, (select Cond1, X, Y), Y 6275 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 6276 SDValue Cond0 = N0->getOperand(0); 6277 SDValue Cond1 = N0->getOperand(1); 6278 SDValue InnerSelect = 6279 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2); 6280 if (normalizeToSequence || !InnerSelect.use_empty()) 6281 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, 6282 InnerSelect, N2); 6283 } 6284 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 6285 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 6286 SDValue Cond0 = N0->getOperand(0); 6287 SDValue Cond1 = N0->getOperand(1); 6288 SDValue InnerSelect = 6289 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2); 6290 if (normalizeToSequence || !InnerSelect.use_empty()) 6291 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1, 6292 InnerSelect); 6293 } 6294 6295 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 6296 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 6297 SDValue N1_0 = N1->getOperand(0); 6298 SDValue N1_1 = N1->getOperand(1); 6299 SDValue N1_2 = N1->getOperand(2); 6300 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 6301 // Create the actual and node if we can generate good code for it. 6302 if (!normalizeToSequence) { 6303 SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0); 6304 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2); 6305 } 6306 // Otherwise see if we can optimize the "and" to a better pattern. 6307 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 6308 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1, 6309 N2); 6310 } 6311 } 6312 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 6313 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 6314 SDValue N2_0 = N2->getOperand(0); 6315 SDValue N2_1 = N2->getOperand(1); 6316 SDValue N2_2 = N2->getOperand(2); 6317 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 6318 // Create the actual or node if we can generate good code for it. 6319 if (!normalizeToSequence) { 6320 SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0); 6321 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2); 6322 } 6323 // Otherwise see if we can optimize to a better pattern. 6324 if (SDValue Combined = visitORLike(N0, N2_0, N)) 6325 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1, 6326 N2_2); 6327 } 6328 } 6329 } 6330 6331 // select (xor Cond, 1), X, Y -> select Cond, Y, X 6332 if (VT0 == MVT::i1) { 6333 if (N0->getOpcode() == ISD::XOR) { 6334 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) { 6335 SDValue Cond0 = N0->getOperand(0); 6336 if (C->isOne()) 6337 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N2, N1); 6338 } 6339 } 6340 } 6341 6342 // fold selects based on a setcc into other things, such as min/max/abs 6343 if (N0.getOpcode() == ISD::SETCC) { 6344 // select x, y (fcmp lt x, y) -> fminnum x, y 6345 // select x, y (fcmp gt x, y) -> fmaxnum x, y 6346 // 6347 // This is OK if we don't care about what happens if either operand is a 6348 // NaN. 6349 // 6350 6351 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 6352 // no signed zeros as well as no nans. 6353 const TargetOptions &Options = DAG.getTarget().Options; 6354 if (Options.UnsafeFPMath && VT.isFloatingPoint() && N0.hasOneUse() && 6355 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 6356 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6357 6358 if (SDValue FMinMax = combineMinNumMaxNum( 6359 DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG)) 6360 return FMinMax; 6361 } 6362 6363 if ((!LegalOperations && 6364 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 6365 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 6366 return DAG.getNode(ISD::SELECT_CC, DL, VT, N0.getOperand(0), 6367 N0.getOperand(1), N1, N2, N0.getOperand(2)); 6368 return SimplifySelect(DL, N0, N1, N2); 6369 } 6370 6371 return SDValue(); 6372 } 6373 6374 static 6375 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 6376 SDLoc DL(N); 6377 EVT LoVT, HiVT; 6378 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 6379 6380 // Split the inputs. 6381 SDValue Lo, Hi, LL, LH, RL, RH; 6382 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 6383 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 6384 6385 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 6386 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 6387 6388 return std::make_pair(Lo, Hi); 6389 } 6390 6391 // This function assumes all the vselect's arguments are CONCAT_VECTOR 6392 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 6393 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 6394 SDLoc DL(N); 6395 SDValue Cond = N->getOperand(0); 6396 SDValue LHS = N->getOperand(1); 6397 SDValue RHS = N->getOperand(2); 6398 EVT VT = N->getValueType(0); 6399 int NumElems = VT.getVectorNumElements(); 6400 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 6401 RHS.getOpcode() == ISD::CONCAT_VECTORS && 6402 Cond.getOpcode() == ISD::BUILD_VECTOR); 6403 6404 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 6405 // binary ones here. 6406 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 6407 return SDValue(); 6408 6409 // We're sure we have an even number of elements due to the 6410 // concat_vectors we have as arguments to vselect. 6411 // Skip BV elements until we find one that's not an UNDEF 6412 // After we find an UNDEF element, keep looping until we get to half the 6413 // length of the BV and see if all the non-undef nodes are the same. 6414 ConstantSDNode *BottomHalf = nullptr; 6415 for (int i = 0; i < NumElems / 2; ++i) { 6416 if (Cond->getOperand(i)->isUndef()) 6417 continue; 6418 6419 if (BottomHalf == nullptr) 6420 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 6421 else if (Cond->getOperand(i).getNode() != BottomHalf) 6422 return SDValue(); 6423 } 6424 6425 // Do the same for the second half of the BuildVector 6426 ConstantSDNode *TopHalf = nullptr; 6427 for (int i = NumElems / 2; i < NumElems; ++i) { 6428 if (Cond->getOperand(i)->isUndef()) 6429 continue; 6430 6431 if (TopHalf == nullptr) 6432 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 6433 else if (Cond->getOperand(i).getNode() != TopHalf) 6434 return SDValue(); 6435 } 6436 6437 assert(TopHalf && BottomHalf && 6438 "One half of the selector was all UNDEFs and the other was all the " 6439 "same value. This should have been addressed before this function."); 6440 return DAG.getNode( 6441 ISD::CONCAT_VECTORS, DL, VT, 6442 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 6443 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 6444 } 6445 6446 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 6447 6448 if (Level >= AfterLegalizeTypes) 6449 return SDValue(); 6450 6451 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 6452 SDValue Mask = MSC->getMask(); 6453 SDValue Data = MSC->getValue(); 6454 SDLoc DL(N); 6455 6456 // If the MSCATTER data type requires splitting and the mask is provided by a 6457 // SETCC, then split both nodes and its operands before legalization. This 6458 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6459 // and enables future optimizations (e.g. min/max pattern matching on X86). 6460 if (Mask.getOpcode() != ISD::SETCC) 6461 return SDValue(); 6462 6463 // Check if any splitting is required. 6464 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 6465 TargetLowering::TypeSplitVector) 6466 return SDValue(); 6467 SDValue MaskLo, MaskHi, Lo, Hi; 6468 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6469 6470 EVT LoVT, HiVT; 6471 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 6472 6473 SDValue Chain = MSC->getChain(); 6474 6475 EVT MemoryVT = MSC->getMemoryVT(); 6476 unsigned Alignment = MSC->getOriginalAlignment(); 6477 6478 EVT LoMemVT, HiMemVT; 6479 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6480 6481 SDValue DataLo, DataHi; 6482 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6483 6484 SDValue BasePtr = MSC->getBasePtr(); 6485 SDValue IndexLo, IndexHi; 6486 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 6487 6488 MachineMemOperand *MMO = DAG.getMachineFunction(). 6489 getMachineMemOperand(MSC->getPointerInfo(), 6490 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6491 Alignment, MSC->getAAInfo(), MSC->getRanges()); 6492 6493 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 6494 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 6495 DL, OpsLo, MMO); 6496 6497 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 6498 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 6499 DL, OpsHi, MMO); 6500 6501 AddToWorklist(Lo.getNode()); 6502 AddToWorklist(Hi.getNode()); 6503 6504 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6505 } 6506 6507 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 6508 6509 if (Level >= AfterLegalizeTypes) 6510 return SDValue(); 6511 6512 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 6513 SDValue Mask = MST->getMask(); 6514 SDValue Data = MST->getValue(); 6515 EVT VT = Data.getValueType(); 6516 SDLoc DL(N); 6517 6518 // If the MSTORE data type requires splitting and the mask is provided by a 6519 // SETCC, then split both nodes and its operands before legalization. This 6520 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6521 // and enables future optimizations (e.g. min/max pattern matching on X86). 6522 if (Mask.getOpcode() == ISD::SETCC) { 6523 6524 // Check if any splitting is required. 6525 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6526 TargetLowering::TypeSplitVector) 6527 return SDValue(); 6528 6529 SDValue MaskLo, MaskHi, Lo, Hi; 6530 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6531 6532 SDValue Chain = MST->getChain(); 6533 SDValue Ptr = MST->getBasePtr(); 6534 6535 EVT MemoryVT = MST->getMemoryVT(); 6536 unsigned Alignment = MST->getOriginalAlignment(); 6537 6538 // if Alignment is equal to the vector size, 6539 // take the half of it for the second part 6540 unsigned SecondHalfAlignment = 6541 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment; 6542 6543 EVT LoMemVT, HiMemVT; 6544 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6545 6546 SDValue DataLo, DataHi; 6547 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6548 6549 MachineMemOperand *MMO = DAG.getMachineFunction(). 6550 getMachineMemOperand(MST->getPointerInfo(), 6551 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6552 Alignment, MST->getAAInfo(), MST->getRanges()); 6553 6554 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 6555 MST->isTruncatingStore(), 6556 MST->isCompressingStore()); 6557 6558 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6559 MST->isCompressingStore()); 6560 6561 MMO = DAG.getMachineFunction(). 6562 getMachineMemOperand(MST->getPointerInfo(), 6563 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 6564 SecondHalfAlignment, MST->getAAInfo(), 6565 MST->getRanges()); 6566 6567 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 6568 MST->isTruncatingStore(), 6569 MST->isCompressingStore()); 6570 6571 AddToWorklist(Lo.getNode()); 6572 AddToWorklist(Hi.getNode()); 6573 6574 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6575 } 6576 return SDValue(); 6577 } 6578 6579 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 6580 6581 if (Level >= AfterLegalizeTypes) 6582 return SDValue(); 6583 6584 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 6585 SDValue Mask = MGT->getMask(); 6586 SDLoc DL(N); 6587 6588 // If the MGATHER result requires splitting and the mask is provided by a 6589 // SETCC, then split both nodes and its operands before legalization. This 6590 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6591 // and enables future optimizations (e.g. min/max pattern matching on X86). 6592 6593 if (Mask.getOpcode() != ISD::SETCC) 6594 return SDValue(); 6595 6596 EVT VT = N->getValueType(0); 6597 6598 // Check if any splitting is required. 6599 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6600 TargetLowering::TypeSplitVector) 6601 return SDValue(); 6602 6603 SDValue MaskLo, MaskHi, Lo, Hi; 6604 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6605 6606 SDValue Src0 = MGT->getValue(); 6607 SDValue Src0Lo, Src0Hi; 6608 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6609 6610 EVT LoVT, HiVT; 6611 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 6612 6613 SDValue Chain = MGT->getChain(); 6614 EVT MemoryVT = MGT->getMemoryVT(); 6615 unsigned Alignment = MGT->getOriginalAlignment(); 6616 6617 EVT LoMemVT, HiMemVT; 6618 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6619 6620 SDValue BasePtr = MGT->getBasePtr(); 6621 SDValue Index = MGT->getIndex(); 6622 SDValue IndexLo, IndexHi; 6623 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 6624 6625 MachineMemOperand *MMO = DAG.getMachineFunction(). 6626 getMachineMemOperand(MGT->getPointerInfo(), 6627 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6628 Alignment, MGT->getAAInfo(), MGT->getRanges()); 6629 6630 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 6631 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 6632 MMO); 6633 6634 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 6635 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 6636 MMO); 6637 6638 AddToWorklist(Lo.getNode()); 6639 AddToWorklist(Hi.getNode()); 6640 6641 // Build a factor node to remember that this load is independent of the 6642 // other one. 6643 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6644 Hi.getValue(1)); 6645 6646 // Legalized the chain result - switch anything that used the old chain to 6647 // use the new one. 6648 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 6649 6650 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6651 6652 SDValue RetOps[] = { GatherRes, Chain }; 6653 return DAG.getMergeValues(RetOps, DL); 6654 } 6655 6656 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 6657 6658 if (Level >= AfterLegalizeTypes) 6659 return SDValue(); 6660 6661 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 6662 SDValue Mask = MLD->getMask(); 6663 SDLoc DL(N); 6664 6665 // If the MLOAD result requires splitting and the mask is provided by a 6666 // SETCC, then split both nodes and its operands before legalization. This 6667 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6668 // and enables future optimizations (e.g. min/max pattern matching on X86). 6669 6670 if (Mask.getOpcode() == ISD::SETCC) { 6671 EVT VT = N->getValueType(0); 6672 6673 // Check if any splitting is required. 6674 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6675 TargetLowering::TypeSplitVector) 6676 return SDValue(); 6677 6678 SDValue MaskLo, MaskHi, Lo, Hi; 6679 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6680 6681 SDValue Src0 = MLD->getSrc0(); 6682 SDValue Src0Lo, Src0Hi; 6683 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6684 6685 EVT LoVT, HiVT; 6686 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 6687 6688 SDValue Chain = MLD->getChain(); 6689 SDValue Ptr = MLD->getBasePtr(); 6690 EVT MemoryVT = MLD->getMemoryVT(); 6691 unsigned Alignment = MLD->getOriginalAlignment(); 6692 6693 // if Alignment is equal to the vector size, 6694 // take the half of it for the second part 6695 unsigned SecondHalfAlignment = 6696 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 6697 Alignment/2 : Alignment; 6698 6699 EVT LoMemVT, HiMemVT; 6700 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6701 6702 MachineMemOperand *MMO = DAG.getMachineFunction(). 6703 getMachineMemOperand(MLD->getPointerInfo(), 6704 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6705 Alignment, MLD->getAAInfo(), MLD->getRanges()); 6706 6707 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 6708 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6709 6710 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6711 MLD->isExpandingLoad()); 6712 6713 MMO = DAG.getMachineFunction(). 6714 getMachineMemOperand(MLD->getPointerInfo(), 6715 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 6716 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 6717 6718 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 6719 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6720 6721 AddToWorklist(Lo.getNode()); 6722 AddToWorklist(Hi.getNode()); 6723 6724 // Build a factor node to remember that this load is independent of the 6725 // other one. 6726 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6727 Hi.getValue(1)); 6728 6729 // Legalized the chain result - switch anything that used the old chain to 6730 // use the new one. 6731 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 6732 6733 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6734 6735 SDValue RetOps[] = { LoadRes, Chain }; 6736 return DAG.getMergeValues(RetOps, DL); 6737 } 6738 return SDValue(); 6739 } 6740 6741 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 6742 SDValue N0 = N->getOperand(0); 6743 SDValue N1 = N->getOperand(1); 6744 SDValue N2 = N->getOperand(2); 6745 SDLoc DL(N); 6746 6747 // fold (vselect C, X, X) -> X 6748 if (N1 == N2) 6749 return N1; 6750 6751 // Canonicalize integer abs. 6752 // vselect (setg[te] X, 0), X, -X -> 6753 // vselect (setgt X, -1), X, -X -> 6754 // vselect (setl[te] X, 0), -X, X -> 6755 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 6756 if (N0.getOpcode() == ISD::SETCC) { 6757 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 6758 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6759 bool isAbs = false; 6760 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 6761 6762 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 6763 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 6764 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 6765 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 6766 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 6767 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 6768 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 6769 6770 if (isAbs) { 6771 EVT VT = LHS.getValueType(); 6772 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) 6773 return DAG.getNode(ISD::ABS, DL, VT, LHS); 6774 6775 SDValue Shift = DAG.getNode( 6776 ISD::SRA, DL, VT, LHS, 6777 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT)); 6778 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 6779 AddToWorklist(Shift.getNode()); 6780 AddToWorklist(Add.getNode()); 6781 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 6782 } 6783 } 6784 6785 if (SimplifySelectOps(N, N1, N2)) 6786 return SDValue(N, 0); // Don't revisit N. 6787 6788 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 6789 if (ISD::isBuildVectorAllOnes(N0.getNode())) 6790 return N1; 6791 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 6792 if (ISD::isBuildVectorAllZeros(N0.getNode())) 6793 return N2; 6794 6795 // The ConvertSelectToConcatVector function is assuming both the above 6796 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 6797 // and addressed. 6798 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 6799 N2.getOpcode() == ISD::CONCAT_VECTORS && 6800 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 6801 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 6802 return CV; 6803 } 6804 6805 return SDValue(); 6806 } 6807 6808 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 6809 SDValue N0 = N->getOperand(0); 6810 SDValue N1 = N->getOperand(1); 6811 SDValue N2 = N->getOperand(2); 6812 SDValue N3 = N->getOperand(3); 6813 SDValue N4 = N->getOperand(4); 6814 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 6815 6816 // fold select_cc lhs, rhs, x, x, cc -> x 6817 if (N2 == N3) 6818 return N2; 6819 6820 // Determine if the condition we're dealing with is constant 6821 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 6822 CC, SDLoc(N), false)) { 6823 AddToWorklist(SCC.getNode()); 6824 6825 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 6826 if (!SCCC->isNullValue()) 6827 return N2; // cond always true -> true val 6828 else 6829 return N3; // cond always false -> false val 6830 } else if (SCC->isUndef()) { 6831 // When the condition is UNDEF, just return the first operand. This is 6832 // coherent the DAG creation, no setcc node is created in this case 6833 return N2; 6834 } else if (SCC.getOpcode() == ISD::SETCC) { 6835 // Fold to a simpler select_cc 6836 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 6837 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 6838 SCC.getOperand(2)); 6839 } 6840 } 6841 6842 // If we can fold this based on the true/false value, do so. 6843 if (SimplifySelectOps(N, N2, N3)) 6844 return SDValue(N, 0); // Don't revisit N. 6845 6846 // fold select_cc into other things, such as min/max/abs 6847 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 6848 } 6849 6850 SDValue DAGCombiner::visitSETCC(SDNode *N) { 6851 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 6852 cast<CondCodeSDNode>(N->getOperand(2))->get(), 6853 SDLoc(N)); 6854 } 6855 6856 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 6857 SDValue LHS = N->getOperand(0); 6858 SDValue RHS = N->getOperand(1); 6859 SDValue Carry = N->getOperand(2); 6860 SDValue Cond = N->getOperand(3); 6861 6862 // If Carry is false, fold to a regular SETCC. 6863 if (Carry.getOpcode() == ISD::CARRY_FALSE) 6864 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 6865 6866 return SDValue(); 6867 } 6868 6869 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) { 6870 SDValue LHS = N->getOperand(0); 6871 SDValue RHS = N->getOperand(1); 6872 SDValue Carry = N->getOperand(2); 6873 SDValue Cond = N->getOperand(3); 6874 6875 // If Carry is false, fold to a regular SETCC. 6876 if (isNullConstant(Carry)) 6877 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 6878 6879 return SDValue(); 6880 } 6881 6882 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 6883 /// a build_vector of constants. 6884 /// This function is called by the DAGCombiner when visiting sext/zext/aext 6885 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 6886 /// Vector extends are not folded if operations are legal; this is to 6887 /// avoid introducing illegal build_vector dag nodes. 6888 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 6889 SelectionDAG &DAG, bool LegalTypes, 6890 bool LegalOperations) { 6891 unsigned Opcode = N->getOpcode(); 6892 SDValue N0 = N->getOperand(0); 6893 EVT VT = N->getValueType(0); 6894 6895 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 6896 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 6897 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 6898 && "Expected EXTEND dag node in input!"); 6899 6900 // fold (sext c1) -> c1 6901 // fold (zext c1) -> c1 6902 // fold (aext c1) -> c1 6903 if (isa<ConstantSDNode>(N0)) 6904 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 6905 6906 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 6907 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 6908 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 6909 EVT SVT = VT.getScalarType(); 6910 if (!(VT.isVector() && 6911 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 6912 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 6913 return nullptr; 6914 6915 // We can fold this node into a build_vector. 6916 unsigned VTBits = SVT.getSizeInBits(); 6917 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits(); 6918 SmallVector<SDValue, 8> Elts; 6919 unsigned NumElts = VT.getVectorNumElements(); 6920 SDLoc DL(N); 6921 6922 for (unsigned i=0; i != NumElts; ++i) { 6923 SDValue Op = N0->getOperand(i); 6924 if (Op->isUndef()) { 6925 Elts.push_back(DAG.getUNDEF(SVT)); 6926 continue; 6927 } 6928 6929 SDLoc DL(Op); 6930 // Get the constant value and if needed trunc it to the size of the type. 6931 // Nodes like build_vector might have constants wider than the scalar type. 6932 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 6933 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 6934 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 6935 else 6936 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 6937 } 6938 6939 return DAG.getBuildVector(VT, DL, Elts).getNode(); 6940 } 6941 6942 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 6943 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 6944 // transformation. Returns true if extension are possible and the above 6945 // mentioned transformation is profitable. 6946 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 6947 unsigned ExtOpc, 6948 SmallVectorImpl<SDNode *> &ExtendNodes, 6949 const TargetLowering &TLI) { 6950 bool HasCopyToRegUses = false; 6951 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 6952 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 6953 UE = N0.getNode()->use_end(); 6954 UI != UE; ++UI) { 6955 SDNode *User = *UI; 6956 if (User == N) 6957 continue; 6958 if (UI.getUse().getResNo() != N0.getResNo()) 6959 continue; 6960 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 6961 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 6962 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 6963 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 6964 // Sign bits will be lost after a zext. 6965 return false; 6966 bool Add = false; 6967 for (unsigned i = 0; i != 2; ++i) { 6968 SDValue UseOp = User->getOperand(i); 6969 if (UseOp == N0) 6970 continue; 6971 if (!isa<ConstantSDNode>(UseOp)) 6972 return false; 6973 Add = true; 6974 } 6975 if (Add) 6976 ExtendNodes.push_back(User); 6977 continue; 6978 } 6979 // If truncates aren't free and there are users we can't 6980 // extend, it isn't worthwhile. 6981 if (!isTruncFree) 6982 return false; 6983 // Remember if this value is live-out. 6984 if (User->getOpcode() == ISD::CopyToReg) 6985 HasCopyToRegUses = true; 6986 } 6987 6988 if (HasCopyToRegUses) { 6989 bool BothLiveOut = false; 6990 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 6991 UI != UE; ++UI) { 6992 SDUse &Use = UI.getUse(); 6993 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 6994 BothLiveOut = true; 6995 break; 6996 } 6997 } 6998 if (BothLiveOut) 6999 // Both unextended and extended values are live out. There had better be 7000 // a good reason for the transformation. 7001 return ExtendNodes.size(); 7002 } 7003 return true; 7004 } 7005 7006 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 7007 SDValue Trunc, SDValue ExtLoad, 7008 const SDLoc &DL, ISD::NodeType ExtType) { 7009 // Extend SetCC uses if necessary. 7010 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 7011 SDNode *SetCC = SetCCs[i]; 7012 SmallVector<SDValue, 4> Ops; 7013 7014 for (unsigned j = 0; j != 2; ++j) { 7015 SDValue SOp = SetCC->getOperand(j); 7016 if (SOp == Trunc) 7017 Ops.push_back(ExtLoad); 7018 else 7019 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 7020 } 7021 7022 Ops.push_back(SetCC->getOperand(2)); 7023 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 7024 } 7025 } 7026 7027 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 7028 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 7029 SDValue N0 = N->getOperand(0); 7030 EVT DstVT = N->getValueType(0); 7031 EVT SrcVT = N0.getValueType(); 7032 7033 assert((N->getOpcode() == ISD::SIGN_EXTEND || 7034 N->getOpcode() == ISD::ZERO_EXTEND) && 7035 "Unexpected node type (not an extend)!"); 7036 7037 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 7038 // For example, on a target with legal v4i32, but illegal v8i32, turn: 7039 // (v8i32 (sext (v8i16 (load x)))) 7040 // into: 7041 // (v8i32 (concat_vectors (v4i32 (sextload x)), 7042 // (v4i32 (sextload (x + 16))))) 7043 // Where uses of the original load, i.e.: 7044 // (v8i16 (load x)) 7045 // are replaced with: 7046 // (v8i16 (truncate 7047 // (v8i32 (concat_vectors (v4i32 (sextload x)), 7048 // (v4i32 (sextload (x + 16))))))) 7049 // 7050 // This combine is only applicable to illegal, but splittable, vectors. 7051 // All legal types, and illegal non-vector types, are handled elsewhere. 7052 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 7053 // 7054 if (N0->getOpcode() != ISD::LOAD) 7055 return SDValue(); 7056 7057 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7058 7059 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 7060 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 7061 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 7062 return SDValue(); 7063 7064 SmallVector<SDNode *, 4> SetCCs; 7065 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 7066 return SDValue(); 7067 7068 ISD::LoadExtType ExtType = 7069 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 7070 7071 // Try to split the vector types to get down to legal types. 7072 EVT SplitSrcVT = SrcVT; 7073 EVT SplitDstVT = DstVT; 7074 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 7075 SplitSrcVT.getVectorNumElements() > 1) { 7076 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 7077 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 7078 } 7079 7080 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 7081 return SDValue(); 7082 7083 SDLoc DL(N); 7084 const unsigned NumSplits = 7085 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 7086 const unsigned Stride = SplitSrcVT.getStoreSize(); 7087 SmallVector<SDValue, 4> Loads; 7088 SmallVector<SDValue, 4> Chains; 7089 7090 SDValue BasePtr = LN0->getBasePtr(); 7091 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 7092 const unsigned Offset = Idx * Stride; 7093 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 7094 7095 SDValue SplitLoad = DAG.getExtLoad( 7096 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 7097 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 7098 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 7099 7100 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 7101 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 7102 7103 Loads.push_back(SplitLoad.getValue(0)); 7104 Chains.push_back(SplitLoad.getValue(1)); 7105 } 7106 7107 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 7108 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 7109 7110 // Simplify TF. 7111 AddToWorklist(NewChain.getNode()); 7112 7113 CombineTo(N, NewValue); 7114 7115 // Replace uses of the original load (before extension) 7116 // with a truncate of the concatenated sextloaded vectors. 7117 SDValue Trunc = 7118 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 7119 CombineTo(N0.getNode(), Trunc, NewChain); 7120 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 7121 (ISD::NodeType)N->getOpcode()); 7122 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7123 } 7124 7125 /// If we're narrowing or widening the result of a vector select and the final 7126 /// size is the same size as a setcc (compare) feeding the select, then try to 7127 /// apply the cast operation to the select's operands because matching vector 7128 /// sizes for a select condition and other operands should be more efficient. 7129 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) { 7130 unsigned CastOpcode = Cast->getOpcode(); 7131 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || 7132 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || 7133 CastOpcode == ISD::FP_ROUND) && 7134 "Unexpected opcode for vector select narrowing/widening"); 7135 7136 // We only do this transform before legal ops because the pattern may be 7137 // obfuscated by target-specific operations after legalization. Do not create 7138 // an illegal select op, however, because that may be difficult to lower. 7139 EVT VT = Cast->getValueType(0); 7140 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT)) 7141 return SDValue(); 7142 7143 SDValue VSel = Cast->getOperand(0); 7144 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() || 7145 VSel.getOperand(0).getOpcode() != ISD::SETCC) 7146 return SDValue(); 7147 7148 // Does the setcc have the same vector size as the casted select? 7149 SDValue SetCC = VSel.getOperand(0); 7150 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType()); 7151 if (SetCCVT.getSizeInBits() != VT.getSizeInBits()) 7152 return SDValue(); 7153 7154 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B) 7155 SDValue A = VSel.getOperand(1); 7156 SDValue B = VSel.getOperand(2); 7157 SDValue CastA, CastB; 7158 SDLoc DL(Cast); 7159 if (CastOpcode == ISD::FP_ROUND) { 7160 // FP_ROUND (fptrunc) has an extra flag operand to pass along. 7161 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1)); 7162 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1)); 7163 } else { 7164 CastA = DAG.getNode(CastOpcode, DL, VT, A); 7165 CastB = DAG.getNode(CastOpcode, DL, VT, B); 7166 } 7167 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB); 7168 } 7169 7170 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 7171 SDValue N0 = N->getOperand(0); 7172 EVT VT = N->getValueType(0); 7173 SDLoc DL(N); 7174 7175 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7176 LegalOperations)) 7177 return SDValue(Res, 0); 7178 7179 // fold (sext (sext x)) -> (sext x) 7180 // fold (sext (aext x)) -> (sext x) 7181 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 7182 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0)); 7183 7184 if (N0.getOpcode() == ISD::TRUNCATE) { 7185 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 7186 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 7187 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7188 SDNode *oye = N0.getOperand(0).getNode(); 7189 if (NarrowLoad.getNode() != N0.getNode()) { 7190 CombineTo(N0.getNode(), NarrowLoad); 7191 // CombineTo deleted the truncate, if needed, but not what's under it. 7192 AddToWorklist(oye); 7193 } 7194 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7195 } 7196 7197 // See if the value being truncated is already sign extended. If so, just 7198 // eliminate the trunc/sext pair. 7199 SDValue Op = N0.getOperand(0); 7200 unsigned OpBits = Op.getScalarValueSizeInBits(); 7201 unsigned MidBits = N0.getScalarValueSizeInBits(); 7202 unsigned DestBits = VT.getScalarSizeInBits(); 7203 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 7204 7205 if (OpBits == DestBits) { 7206 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 7207 // bits, it is already ready. 7208 if (NumSignBits > DestBits-MidBits) 7209 return Op; 7210 } else if (OpBits < DestBits) { 7211 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 7212 // bits, just sext from i32. 7213 if (NumSignBits > OpBits-MidBits) 7214 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op); 7215 } else { 7216 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 7217 // bits, just truncate to i32. 7218 if (NumSignBits > OpBits-MidBits) 7219 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 7220 } 7221 7222 // fold (sext (truncate x)) -> (sextinreg x). 7223 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 7224 N0.getValueType())) { 7225 if (OpBits < DestBits) 7226 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 7227 else if (OpBits > DestBits) 7228 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 7229 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op, 7230 DAG.getValueType(N0.getValueType())); 7231 } 7232 } 7233 7234 // fold (sext (load x)) -> (sext (truncate (sextload x))) 7235 // Only generate vector extloads when 1) they're legal, and 2) they are 7236 // deemed desirable by the target. 7237 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7238 ((!LegalOperations && !VT.isVector() && 7239 !cast<LoadSDNode>(N0)->isVolatile()) || 7240 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 7241 bool DoXform = true; 7242 SmallVector<SDNode*, 4> SetCCs; 7243 if (!N0.hasOneUse()) 7244 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 7245 if (VT.isVector()) 7246 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 7247 if (DoXform) { 7248 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7249 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 7250 LN0->getBasePtr(), N0.getValueType(), 7251 LN0->getMemOperand()); 7252 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7253 N0.getValueType(), ExtLoad); 7254 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND); 7255 // If the load value is used only by N, replace it via CombineTo N. 7256 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 7257 CombineTo(N, ExtLoad); 7258 if (NoReplaceTrunc) 7259 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7260 else 7261 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 7262 return SDValue(N, 0); 7263 } 7264 } 7265 7266 // fold (sext (load x)) to multiple smaller sextloads. 7267 // Only on illegal but splittable vectors. 7268 if (SDValue ExtLoad = CombineExtLoad(N)) 7269 return ExtLoad; 7270 7271 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 7272 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 7273 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 7274 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 7275 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7276 EVT MemVT = LN0->getMemoryVT(); 7277 if ((!LegalOperations && !LN0->isVolatile()) || 7278 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 7279 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 7280 LN0->getBasePtr(), MemVT, 7281 LN0->getMemOperand()); 7282 CombineTo(N, ExtLoad); 7283 CombineTo(N0.getNode(), 7284 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7285 N0.getValueType(), ExtLoad), 7286 ExtLoad.getValue(1)); 7287 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7288 } 7289 } 7290 7291 // fold (sext (and/or/xor (load x), cst)) -> 7292 // (and/or/xor (sextload x), (sext cst)) 7293 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 7294 N0.getOpcode() == ISD::XOR) && 7295 isa<LoadSDNode>(N0.getOperand(0)) && 7296 N0.getOperand(1).getOpcode() == ISD::Constant && 7297 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 7298 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 7299 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 7300 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 7301 bool DoXform = true; 7302 SmallVector<SDNode*, 4> SetCCs; 7303 if (!N0.hasOneUse()) 7304 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 7305 SetCCs, TLI); 7306 if (DoXform) { 7307 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 7308 LN0->getChain(), LN0->getBasePtr(), 7309 LN0->getMemoryVT(), 7310 LN0->getMemOperand()); 7311 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7312 Mask = Mask.sext(VT.getSizeInBits()); 7313 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 7314 ExtLoad, DAG.getConstant(Mask, DL, VT)); 7315 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 7316 SDLoc(N0.getOperand(0)), 7317 N0.getOperand(0).getValueType(), ExtLoad); 7318 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND); 7319 bool NoReplaceTruncAnd = !N0.hasOneUse(); 7320 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 7321 CombineTo(N, And); 7322 // If N0 has multiple uses, change other uses as well. 7323 if (NoReplaceTruncAnd) { 7324 SDValue TruncAnd = 7325 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 7326 CombineTo(N0.getNode(), TruncAnd); 7327 } 7328 if (NoReplaceTrunc) 7329 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7330 else 7331 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 7332 return SDValue(N,0); // Return N so it doesn't get rechecked! 7333 } 7334 } 7335 } 7336 7337 if (N0.getOpcode() == ISD::SETCC) { 7338 SDValue N00 = N0.getOperand(0); 7339 SDValue N01 = N0.getOperand(1); 7340 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 7341 EVT N00VT = N0.getOperand(0).getValueType(); 7342 7343 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 7344 // Only do this before legalize for now. 7345 if (VT.isVector() && !LegalOperations && 7346 TLI.getBooleanContents(N00VT) == 7347 TargetLowering::ZeroOrNegativeOneBooleanContent) { 7348 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 7349 // of the same size as the compared operands. Only optimize sext(setcc()) 7350 // if this is the case. 7351 EVT SVT = getSetCCResultType(N00VT); 7352 7353 // We know that the # elements of the results is the same as the 7354 // # elements of the compare (and the # elements of the compare result 7355 // for that matter). Check to see that they are the same size. If so, 7356 // we know that the element size of the sext'd result matches the 7357 // element size of the compare operands. 7358 if (VT.getSizeInBits() == SVT.getSizeInBits()) 7359 return DAG.getSetCC(DL, VT, N00, N01, CC); 7360 7361 // If the desired elements are smaller or larger than the source 7362 // elements, we can use a matching integer vector type and then 7363 // truncate/sign extend. 7364 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger(); 7365 if (SVT == MatchingVecType) { 7366 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC); 7367 return DAG.getSExtOrTrunc(VsetCC, DL, VT); 7368 } 7369 } 7370 7371 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 7372 // Here, T can be 1 or -1, depending on the type of the setcc and 7373 // getBooleanContents(). 7374 unsigned SetCCWidth = N0.getScalarValueSizeInBits(); 7375 7376 // To determine the "true" side of the select, we need to know the high bit 7377 // of the value returned by the setcc if it evaluates to true. 7378 // If the type of the setcc is i1, then the true case of the select is just 7379 // sext(i1 1), that is, -1. 7380 // If the type of the setcc is larger (say, i8) then the value of the high 7381 // bit depends on getBooleanContents(), so ask TLI for a real "true" value 7382 // of the appropriate width. 7383 SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT) 7384 : TLI.getConstTrueVal(DAG, VT, DL); 7385 SDValue Zero = DAG.getConstant(0, DL, VT); 7386 if (SDValue SCC = 7387 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true)) 7388 return SCC; 7389 7390 if (!VT.isVector()) { 7391 EVT SetCCVT = getSetCCResultType(N00VT); 7392 // Don't do this transform for i1 because there's a select transform 7393 // that would reverse it. 7394 // TODO: We should not do this transform at all without a target hook 7395 // because a sext is likely cheaper than a select? 7396 if (SetCCVT.getScalarSizeInBits() != 1 && 7397 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) { 7398 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC); 7399 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero); 7400 } 7401 } 7402 } 7403 7404 // fold (sext x) -> (zext x) if the sign bit is known zero. 7405 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 7406 DAG.SignBitIsZero(N0)) 7407 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0); 7408 7409 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 7410 return NewVSel; 7411 7412 return SDValue(); 7413 } 7414 7415 // isTruncateOf - If N is a truncate of some other value, return true, record 7416 // the value being truncated in Op and which of Op's bits are zero/one in Known. 7417 // This function computes KnownBits to avoid a duplicated call to 7418 // computeKnownBits in the caller. 7419 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 7420 KnownBits &Known) { 7421 if (N->getOpcode() == ISD::TRUNCATE) { 7422 Op = N->getOperand(0); 7423 DAG.computeKnownBits(Op, Known); 7424 return true; 7425 } 7426 7427 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 7428 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 7429 return false; 7430 7431 SDValue Op0 = N->getOperand(0); 7432 SDValue Op1 = N->getOperand(1); 7433 assert(Op0.getValueType() == Op1.getValueType()); 7434 7435 if (isNullConstant(Op0)) 7436 Op = Op1; 7437 else if (isNullConstant(Op1)) 7438 Op = Op0; 7439 else 7440 return false; 7441 7442 DAG.computeKnownBits(Op, Known); 7443 7444 if (!(Known.Zero | 1).isAllOnesValue()) 7445 return false; 7446 7447 return true; 7448 } 7449 7450 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 7451 SDValue N0 = N->getOperand(0); 7452 EVT VT = N->getValueType(0); 7453 7454 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7455 LegalOperations)) 7456 return SDValue(Res, 0); 7457 7458 // fold (zext (zext x)) -> (zext x) 7459 // fold (zext (aext x)) -> (zext x) 7460 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 7461 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 7462 N0.getOperand(0)); 7463 7464 // fold (zext (truncate x)) -> (zext x) or 7465 // (zext (truncate x)) -> (truncate x) 7466 // This is valid when the truncated bits of x are already zero. 7467 // FIXME: We should extend this to work for vectors too. 7468 SDValue Op; 7469 KnownBits Known; 7470 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) { 7471 APInt TruncatedBits = 7472 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 7473 APInt(Op.getValueSizeInBits(), 0) : 7474 APInt::getBitsSet(Op.getValueSizeInBits(), 7475 N0.getValueSizeInBits(), 7476 std::min(Op.getValueSizeInBits(), 7477 VT.getSizeInBits())); 7478 if (TruncatedBits.isSubsetOf(Known.Zero)) 7479 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 7480 } 7481 7482 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 7483 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 7484 if (N0.getOpcode() == ISD::TRUNCATE) { 7485 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7486 SDNode *oye = N0.getOperand(0).getNode(); 7487 if (NarrowLoad.getNode() != N0.getNode()) { 7488 CombineTo(N0.getNode(), NarrowLoad); 7489 // CombineTo deleted the truncate, if needed, but not what's under it. 7490 AddToWorklist(oye); 7491 } 7492 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7493 } 7494 } 7495 7496 // fold (zext (truncate x)) -> (and x, mask) 7497 if (N0.getOpcode() == ISD::TRUNCATE) { 7498 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 7499 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 7500 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7501 SDNode *oye = N0.getOperand(0).getNode(); 7502 if (NarrowLoad.getNode() != N0.getNode()) { 7503 CombineTo(N0.getNode(), NarrowLoad); 7504 // CombineTo deleted the truncate, if needed, but not what's under it. 7505 AddToWorklist(oye); 7506 } 7507 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7508 } 7509 7510 EVT SrcVT = N0.getOperand(0).getValueType(); 7511 EVT MinVT = N0.getValueType(); 7512 7513 // Try to mask before the extension to avoid having to generate a larger mask, 7514 // possibly over several sub-vectors. 7515 if (SrcVT.bitsLT(VT)) { 7516 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 7517 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 7518 SDValue Op = N0.getOperand(0); 7519 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 7520 AddToWorklist(Op.getNode()); 7521 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 7522 } 7523 } 7524 7525 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 7526 SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 7527 AddToWorklist(Op.getNode()); 7528 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 7529 } 7530 } 7531 7532 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 7533 // if either of the casts is not free. 7534 if (N0.getOpcode() == ISD::AND && 7535 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 7536 N0.getOperand(1).getOpcode() == ISD::Constant && 7537 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 7538 N0.getValueType()) || 7539 !TLI.isZExtFree(N0.getValueType(), VT))) { 7540 SDValue X = N0.getOperand(0).getOperand(0); 7541 X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT); 7542 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7543 Mask = Mask.zext(VT.getSizeInBits()); 7544 SDLoc DL(N); 7545 return DAG.getNode(ISD::AND, DL, VT, 7546 X, DAG.getConstant(Mask, DL, VT)); 7547 } 7548 7549 // fold (zext (load x)) -> (zext (truncate (zextload x))) 7550 // Only generate vector extloads when 1) they're legal, and 2) they are 7551 // deemed desirable by the target. 7552 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7553 ((!LegalOperations && !VT.isVector() && 7554 !cast<LoadSDNode>(N0)->isVolatile()) || 7555 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 7556 bool DoXform = true; 7557 SmallVector<SDNode*, 4> SetCCs; 7558 if (!N0.hasOneUse()) 7559 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 7560 if (VT.isVector()) 7561 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 7562 if (DoXform) { 7563 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7564 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 7565 LN0->getChain(), 7566 LN0->getBasePtr(), N0.getValueType(), 7567 LN0->getMemOperand()); 7568 7569 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7570 N0.getValueType(), ExtLoad); 7571 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), ISD::ZERO_EXTEND); 7572 // If the load value is used only by N, replace it via CombineTo N. 7573 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 7574 CombineTo(N, ExtLoad); 7575 if (NoReplaceTrunc) 7576 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7577 else 7578 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 7579 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7580 } 7581 } 7582 7583 // fold (zext (load x)) to multiple smaller zextloads. 7584 // Only on illegal but splittable vectors. 7585 if (SDValue ExtLoad = CombineExtLoad(N)) 7586 return ExtLoad; 7587 7588 // fold (zext (and/or/xor (load x), cst)) -> 7589 // (and/or/xor (zextload x), (zext cst)) 7590 // Unless (and (load x) cst) will match as a zextload already and has 7591 // additional users. 7592 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 7593 N0.getOpcode() == ISD::XOR) && 7594 isa<LoadSDNode>(N0.getOperand(0)) && 7595 N0.getOperand(1).getOpcode() == ISD::Constant && 7596 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 7597 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 7598 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 7599 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 7600 bool DoXform = true; 7601 SmallVector<SDNode*, 4> SetCCs; 7602 if (!N0.hasOneUse()) { 7603 if (N0.getOpcode() == ISD::AND) { 7604 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 7605 auto NarrowLoad = false; 7606 EVT LoadResultTy = AndC->getValueType(0); 7607 EVT ExtVT, LoadedVT; 7608 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT, 7609 NarrowLoad)) 7610 DoXform = false; 7611 } 7612 if (DoXform) 7613 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 7614 ISD::ZERO_EXTEND, SetCCs, TLI); 7615 } 7616 if (DoXform) { 7617 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 7618 LN0->getChain(), LN0->getBasePtr(), 7619 LN0->getMemoryVT(), 7620 LN0->getMemOperand()); 7621 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7622 Mask = Mask.zext(VT.getSizeInBits()); 7623 SDLoc DL(N); 7624 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 7625 ExtLoad, DAG.getConstant(Mask, DL, VT)); 7626 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 7627 SDLoc(N0.getOperand(0)), 7628 N0.getOperand(0).getValueType(), ExtLoad); 7629 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::ZERO_EXTEND); 7630 bool NoReplaceTruncAnd = !N0.hasOneUse(); 7631 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 7632 CombineTo(N, And); 7633 // If N0 has multiple uses, change other uses as well. 7634 if (NoReplaceTruncAnd) { 7635 SDValue TruncAnd = 7636 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 7637 CombineTo(N0.getNode(), TruncAnd); 7638 } 7639 if (NoReplaceTrunc) 7640 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7641 else 7642 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 7643 return SDValue(N,0); // Return N so it doesn't get rechecked! 7644 } 7645 } 7646 } 7647 7648 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 7649 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 7650 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 7651 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 7652 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7653 EVT MemVT = LN0->getMemoryVT(); 7654 if ((!LegalOperations && !LN0->isVolatile()) || 7655 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 7656 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 7657 LN0->getChain(), 7658 LN0->getBasePtr(), MemVT, 7659 LN0->getMemOperand()); 7660 CombineTo(N, ExtLoad); 7661 CombineTo(N0.getNode(), 7662 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 7663 ExtLoad), 7664 ExtLoad.getValue(1)); 7665 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7666 } 7667 } 7668 7669 if (N0.getOpcode() == ISD::SETCC) { 7670 // Only do this before legalize for now. 7671 if (!LegalOperations && VT.isVector() && 7672 N0.getValueType().getVectorElementType() == MVT::i1) { 7673 EVT N00VT = N0.getOperand(0).getValueType(); 7674 if (getSetCCResultType(N00VT) == N0.getValueType()) 7675 return SDValue(); 7676 7677 // We know that the # elements of the results is the same as the # 7678 // elements of the compare (and the # elements of the compare result for 7679 // that matter). Check to see that they are the same size. If so, we know 7680 // that the element size of the sext'd result matches the element size of 7681 // the compare operands. 7682 SDLoc DL(N); 7683 SDValue VecOnes = DAG.getConstant(1, DL, VT); 7684 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 7685 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 7686 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 7687 N0.getOperand(1), N0.getOperand(2)); 7688 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes); 7689 } 7690 7691 // If the desired elements are smaller or larger than the source 7692 // elements we can use a matching integer vector type and then 7693 // truncate/sign extend. 7694 EVT MatchingElementType = EVT::getIntegerVT( 7695 *DAG.getContext(), N00VT.getScalarSizeInBits()); 7696 EVT MatchingVectorType = EVT::getVectorVT( 7697 *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements()); 7698 SDValue VsetCC = 7699 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 7700 N0.getOperand(1), N0.getOperand(2)); 7701 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT), 7702 VecOnes); 7703 } 7704 7705 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 7706 SDLoc DL(N); 7707 if (SDValue SCC = SimplifySelectCC( 7708 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 7709 DAG.getConstant(0, DL, VT), 7710 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 7711 return SCC; 7712 } 7713 7714 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 7715 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 7716 isa<ConstantSDNode>(N0.getOperand(1)) && 7717 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 7718 N0.hasOneUse()) { 7719 SDValue ShAmt = N0.getOperand(1); 7720 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 7721 if (N0.getOpcode() == ISD::SHL) { 7722 SDValue InnerZExt = N0.getOperand(0); 7723 // If the original shl may be shifting out bits, do not perform this 7724 // transformation. 7725 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() - 7726 InnerZExt.getOperand(0).getValueSizeInBits(); 7727 if (ShAmtVal > KnownZeroBits) 7728 return SDValue(); 7729 } 7730 7731 SDLoc DL(N); 7732 7733 // Ensure that the shift amount is wide enough for the shifted value. 7734 if (VT.getSizeInBits() >= 256) 7735 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 7736 7737 return DAG.getNode(N0.getOpcode(), DL, VT, 7738 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 7739 ShAmt); 7740 } 7741 7742 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 7743 return NewVSel; 7744 7745 return SDValue(); 7746 } 7747 7748 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 7749 SDValue N0 = N->getOperand(0); 7750 EVT VT = N->getValueType(0); 7751 7752 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7753 LegalOperations)) 7754 return SDValue(Res, 0); 7755 7756 // fold (aext (aext x)) -> (aext x) 7757 // fold (aext (zext x)) -> (zext x) 7758 // fold (aext (sext x)) -> (sext x) 7759 if (N0.getOpcode() == ISD::ANY_EXTEND || 7760 N0.getOpcode() == ISD::ZERO_EXTEND || 7761 N0.getOpcode() == ISD::SIGN_EXTEND) 7762 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7763 7764 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 7765 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 7766 if (N0.getOpcode() == ISD::TRUNCATE) { 7767 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7768 SDNode *oye = N0.getOperand(0).getNode(); 7769 if (NarrowLoad.getNode() != N0.getNode()) { 7770 CombineTo(N0.getNode(), NarrowLoad); 7771 // CombineTo deleted the truncate, if needed, but not what's under it. 7772 AddToWorklist(oye); 7773 } 7774 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7775 } 7776 } 7777 7778 // fold (aext (truncate x)) 7779 if (N0.getOpcode() == ISD::TRUNCATE) 7780 return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 7781 7782 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 7783 // if the trunc is not free. 7784 if (N0.getOpcode() == ISD::AND && 7785 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 7786 N0.getOperand(1).getOpcode() == ISD::Constant && 7787 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 7788 N0.getValueType())) { 7789 SDLoc DL(N); 7790 SDValue X = N0.getOperand(0).getOperand(0); 7791 X = DAG.getAnyExtOrTrunc(X, DL, VT); 7792 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7793 Mask = Mask.zext(VT.getSizeInBits()); 7794 return DAG.getNode(ISD::AND, DL, VT, 7795 X, DAG.getConstant(Mask, DL, VT)); 7796 } 7797 7798 // fold (aext (load x)) -> (aext (truncate (extload x))) 7799 // None of the supported targets knows how to perform load and any_ext 7800 // on vectors in one instruction. We only perform this transformation on 7801 // scalars. 7802 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 7803 ISD::isUNINDEXEDLoad(N0.getNode()) && 7804 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 7805 bool DoXform = true; 7806 SmallVector<SDNode*, 4> SetCCs; 7807 if (!N0.hasOneUse()) 7808 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 7809 if (DoXform) { 7810 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7811 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 7812 LN0->getChain(), 7813 LN0->getBasePtr(), N0.getValueType(), 7814 LN0->getMemOperand()); 7815 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7816 N0.getValueType(), ExtLoad); 7817 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 7818 ISD::ANY_EXTEND); 7819 // If the load value is used only by N, replace it via CombineTo N. 7820 bool NoReplaceTrunc = N0.hasOneUse(); 7821 CombineTo(N, ExtLoad); 7822 if (NoReplaceTrunc) 7823 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7824 else 7825 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 7826 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7827 } 7828 } 7829 7830 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 7831 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 7832 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 7833 if (N0.getOpcode() == ISD::LOAD && 7834 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7835 N0.hasOneUse()) { 7836 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7837 ISD::LoadExtType ExtType = LN0->getExtensionType(); 7838 EVT MemVT = LN0->getMemoryVT(); 7839 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 7840 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 7841 VT, LN0->getChain(), LN0->getBasePtr(), 7842 MemVT, LN0->getMemOperand()); 7843 CombineTo(N, ExtLoad); 7844 CombineTo(N0.getNode(), 7845 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7846 N0.getValueType(), ExtLoad), 7847 ExtLoad.getValue(1)); 7848 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7849 } 7850 } 7851 7852 if (N0.getOpcode() == ISD::SETCC) { 7853 // For vectors: 7854 // aext(setcc) -> vsetcc 7855 // aext(setcc) -> truncate(vsetcc) 7856 // aext(setcc) -> aext(vsetcc) 7857 // Only do this before legalize for now. 7858 if (VT.isVector() && !LegalOperations) { 7859 EVT N0VT = N0.getOperand(0).getValueType(); 7860 // We know that the # elements of the results is the same as the 7861 // # elements of the compare (and the # elements of the compare result 7862 // for that matter). Check to see that they are the same size. If so, 7863 // we know that the element size of the sext'd result matches the 7864 // element size of the compare operands. 7865 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 7866 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 7867 N0.getOperand(1), 7868 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 7869 // If the desired elements are smaller or larger than the source 7870 // elements we can use a matching integer vector type and then 7871 // truncate/any extend 7872 else { 7873 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 7874 SDValue VsetCC = 7875 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 7876 N0.getOperand(1), 7877 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 7878 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 7879 } 7880 } 7881 7882 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 7883 SDLoc DL(N); 7884 if (SDValue SCC = SimplifySelectCC( 7885 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 7886 DAG.getConstant(0, DL, VT), 7887 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 7888 return SCC; 7889 } 7890 7891 return SDValue(); 7892 } 7893 7894 SDValue DAGCombiner::visitAssertZext(SDNode *N) { 7895 SDValue N0 = N->getOperand(0); 7896 SDValue N1 = N->getOperand(1); 7897 EVT EVT = cast<VTSDNode>(N1)->getVT(); 7898 7899 // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt) 7900 if (N0.getOpcode() == ISD::AssertZext && 7901 EVT == cast<VTSDNode>(N0.getOperand(1))->getVT()) 7902 return N0; 7903 7904 return SDValue(); 7905 } 7906 7907 /// See if the specified operand can be simplified with the knowledge that only 7908 /// the bits specified by Mask are used. If so, return the simpler operand, 7909 /// otherwise return a null SDValue. 7910 /// 7911 /// (This exists alongside SimplifyDemandedBits because GetDemandedBits can 7912 /// simplify nodes with multiple uses more aggressively.) 7913 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 7914 switch (V.getOpcode()) { 7915 default: break; 7916 case ISD::Constant: { 7917 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 7918 assert(CV && "Const value should be ConstSDNode."); 7919 const APInt &CVal = CV->getAPIntValue(); 7920 APInt NewVal = CVal & Mask; 7921 if (NewVal != CVal) 7922 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 7923 break; 7924 } 7925 case ISD::OR: 7926 case ISD::XOR: 7927 // If the LHS or RHS don't contribute bits to the or, drop them. 7928 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 7929 return V.getOperand(1); 7930 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 7931 return V.getOperand(0); 7932 break; 7933 case ISD::SRL: 7934 // Only look at single-use SRLs. 7935 if (!V.getNode()->hasOneUse()) 7936 break; 7937 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 7938 // See if we can recursively simplify the LHS. 7939 unsigned Amt = RHSC->getZExtValue(); 7940 7941 // Watch out for shift count overflow though. 7942 if (Amt >= Mask.getBitWidth()) break; 7943 APInt NewMask = Mask << Amt; 7944 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 7945 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 7946 SimplifyLHS, V.getOperand(1)); 7947 } 7948 break; 7949 case ISD::AND: { 7950 // X & -1 -> X (ignoring bits which aren't demanded). 7951 ConstantSDNode *AndVal = isConstOrConstSplat(V.getOperand(1)); 7952 if (AndVal && Mask.isSubsetOf(AndVal->getAPIntValue())) 7953 return V.getOperand(0); 7954 break; 7955 } 7956 } 7957 return SDValue(); 7958 } 7959 7960 /// If the result of a wider load is shifted to right of N bits and then 7961 /// truncated to a narrower type and where N is a multiple of number of bits of 7962 /// the narrower type, transform it to a narrower load from address + N / num of 7963 /// bits of new type. If the result is to be extended, also fold the extension 7964 /// to form a extending load. 7965 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 7966 unsigned Opc = N->getOpcode(); 7967 7968 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 7969 SDValue N0 = N->getOperand(0); 7970 EVT VT = N->getValueType(0); 7971 EVT ExtVT = VT; 7972 7973 // This transformation isn't valid for vector loads. 7974 if (VT.isVector()) 7975 return SDValue(); 7976 7977 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 7978 // extended to VT. 7979 if (Opc == ISD::SIGN_EXTEND_INREG) { 7980 ExtType = ISD::SEXTLOAD; 7981 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 7982 } else if (Opc == ISD::SRL) { 7983 // Another special-case: SRL is basically zero-extending a narrower value. 7984 ExtType = ISD::ZEXTLOAD; 7985 N0 = SDValue(N, 0); 7986 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7987 if (!N01) return SDValue(); 7988 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 7989 VT.getSizeInBits() - N01->getZExtValue()); 7990 } 7991 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 7992 return SDValue(); 7993 7994 unsigned EVTBits = ExtVT.getSizeInBits(); 7995 7996 // Do not generate loads of non-round integer types since these can 7997 // be expensive (and would be wrong if the type is not byte sized). 7998 if (!ExtVT.isRound()) 7999 return SDValue(); 8000 8001 unsigned ShAmt = 0; 8002 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 8003 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 8004 ShAmt = N01->getZExtValue(); 8005 // Is the shift amount a multiple of size of VT? 8006 if ((ShAmt & (EVTBits-1)) == 0) { 8007 N0 = N0.getOperand(0); 8008 // Is the load width a multiple of size of VT? 8009 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0) 8010 return SDValue(); 8011 } 8012 8013 // At this point, we must have a load or else we can't do the transform. 8014 if (!isa<LoadSDNode>(N0)) return SDValue(); 8015 8016 // Because a SRL must be assumed to *need* to zero-extend the high bits 8017 // (as opposed to anyext the high bits), we can't combine the zextload 8018 // lowering of SRL and an sextload. 8019 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 8020 return SDValue(); 8021 8022 // If the shift amount is larger than the input type then we're not 8023 // accessing any of the loaded bytes. If the load was a zextload/extload 8024 // then the result of the shift+trunc is zero/undef (handled elsewhere). 8025 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 8026 return SDValue(); 8027 } 8028 } 8029 8030 // If the load is shifted left (and the result isn't shifted back right), 8031 // we can fold the truncate through the shift. 8032 unsigned ShLeftAmt = 0; 8033 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 8034 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 8035 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 8036 ShLeftAmt = N01->getZExtValue(); 8037 N0 = N0.getOperand(0); 8038 } 8039 } 8040 8041 // If we haven't found a load, we can't narrow it. Don't transform one with 8042 // multiple uses, this would require adding a new load. 8043 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 8044 return SDValue(); 8045 8046 // Don't change the width of a volatile load. 8047 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8048 if (LN0->isVolatile()) 8049 return SDValue(); 8050 8051 // Verify that we are actually reducing a load width here. 8052 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 8053 return SDValue(); 8054 8055 // For the transform to be legal, the load must produce only two values 8056 // (the value loaded and the chain). Don't transform a pre-increment 8057 // load, for example, which produces an extra value. Otherwise the 8058 // transformation is not equivalent, and the downstream logic to replace 8059 // uses gets things wrong. 8060 if (LN0->getNumValues() > 2) 8061 return SDValue(); 8062 8063 // If the load that we're shrinking is an extload and we're not just 8064 // discarding the extension we can't simply shrink the load. Bail. 8065 // TODO: It would be possible to merge the extensions in some cases. 8066 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 8067 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 8068 return SDValue(); 8069 8070 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 8071 return SDValue(); 8072 8073 EVT PtrType = N0.getOperand(1).getValueType(); 8074 8075 if (PtrType == MVT::Untyped || PtrType.isExtended()) 8076 // It's not possible to generate a constant of extended or untyped type. 8077 return SDValue(); 8078 8079 // For big endian targets, we need to adjust the offset to the pointer to 8080 // load the correct bytes. 8081 if (DAG.getDataLayout().isBigEndian()) { 8082 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 8083 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 8084 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 8085 } 8086 8087 uint64_t PtrOff = ShAmt / 8; 8088 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 8089 SDLoc DL(LN0); 8090 // The original load itself didn't wrap, so an offset within it doesn't. 8091 SDNodeFlags Flags; 8092 Flags.setNoUnsignedWrap(true); 8093 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 8094 PtrType, LN0->getBasePtr(), 8095 DAG.getConstant(PtrOff, DL, PtrType), 8096 Flags); 8097 AddToWorklist(NewPtr.getNode()); 8098 8099 SDValue Load; 8100 if (ExtType == ISD::NON_EXTLOAD) 8101 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 8102 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 8103 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8104 else 8105 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr, 8106 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 8107 NewAlign, LN0->getMemOperand()->getFlags(), 8108 LN0->getAAInfo()); 8109 8110 // Replace the old load's chain with the new load's chain. 8111 WorklistRemover DeadNodes(*this); 8112 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 8113 8114 // Shift the result left, if we've swallowed a left shift. 8115 SDValue Result = Load; 8116 if (ShLeftAmt != 0) { 8117 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 8118 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 8119 ShImmTy = VT; 8120 // If the shift amount is as large as the result size (but, presumably, 8121 // no larger than the source) then the useful bits of the result are 8122 // zero; we can't simply return the shortened shift, because the result 8123 // of that operation is undefined. 8124 SDLoc DL(N0); 8125 if (ShLeftAmt >= VT.getSizeInBits()) 8126 Result = DAG.getConstant(0, DL, VT); 8127 else 8128 Result = DAG.getNode(ISD::SHL, DL, VT, 8129 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 8130 } 8131 8132 // Return the new loaded value. 8133 return Result; 8134 } 8135 8136 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 8137 SDValue N0 = N->getOperand(0); 8138 SDValue N1 = N->getOperand(1); 8139 EVT VT = N->getValueType(0); 8140 EVT EVT = cast<VTSDNode>(N1)->getVT(); 8141 unsigned VTBits = VT.getScalarSizeInBits(); 8142 unsigned EVTBits = EVT.getScalarSizeInBits(); 8143 8144 if (N0.isUndef()) 8145 return DAG.getUNDEF(VT); 8146 8147 // fold (sext_in_reg c1) -> c1 8148 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 8149 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 8150 8151 // If the input is already sign extended, just drop the extension. 8152 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 8153 return N0; 8154 8155 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 8156 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 8157 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 8158 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 8159 N0.getOperand(0), N1); 8160 8161 // fold (sext_in_reg (sext x)) -> (sext x) 8162 // fold (sext_in_reg (aext x)) -> (sext x) 8163 // if x is small enough. 8164 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 8165 SDValue N00 = N0.getOperand(0); 8166 if (N00.getScalarValueSizeInBits() <= EVTBits && 8167 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 8168 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 8169 } 8170 8171 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x) 8172 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG || 8173 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG || 8174 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) && 8175 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) { 8176 if (!LegalOperations || 8177 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT)) 8178 return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT); 8179 } 8180 8181 // fold (sext_in_reg (zext x)) -> (sext x) 8182 // iff we are extending the source sign bit. 8183 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 8184 SDValue N00 = N0.getOperand(0); 8185 if (N00.getScalarValueSizeInBits() == EVTBits && 8186 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 8187 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 8188 } 8189 8190 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 8191 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1))) 8192 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType()); 8193 8194 // fold operands of sext_in_reg based on knowledge that the top bits are not 8195 // demanded. 8196 if (SimplifyDemandedBits(SDValue(N, 0))) 8197 return SDValue(N, 0); 8198 8199 // fold (sext_in_reg (load x)) -> (smaller sextload x) 8200 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 8201 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 8202 return NarrowLoad; 8203 8204 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 8205 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 8206 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 8207 if (N0.getOpcode() == ISD::SRL) { 8208 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 8209 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 8210 // We can turn this into an SRA iff the input to the SRL is already sign 8211 // extended enough. 8212 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 8213 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 8214 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 8215 N0.getOperand(0), N0.getOperand(1)); 8216 } 8217 } 8218 8219 // fold (sext_inreg (extload x)) -> (sextload x) 8220 if (ISD::isEXTLoad(N0.getNode()) && 8221 ISD::isUNINDEXEDLoad(N0.getNode()) && 8222 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 8223 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 8224 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 8225 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8226 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 8227 LN0->getChain(), 8228 LN0->getBasePtr(), EVT, 8229 LN0->getMemOperand()); 8230 CombineTo(N, ExtLoad); 8231 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 8232 AddToWorklist(ExtLoad.getNode()); 8233 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8234 } 8235 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 8236 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 8237 N0.hasOneUse() && 8238 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 8239 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 8240 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 8241 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8242 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 8243 LN0->getChain(), 8244 LN0->getBasePtr(), EVT, 8245 LN0->getMemOperand()); 8246 CombineTo(N, ExtLoad); 8247 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 8248 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8249 } 8250 8251 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 8252 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 8253 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 8254 N0.getOperand(1), false)) 8255 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 8256 BSwap, N1); 8257 } 8258 8259 return SDValue(); 8260 } 8261 8262 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 8263 SDValue N0 = N->getOperand(0); 8264 EVT VT = N->getValueType(0); 8265 8266 if (N0.isUndef()) 8267 return DAG.getUNDEF(VT); 8268 8269 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8270 LegalOperations)) 8271 return SDValue(Res, 0); 8272 8273 return SDValue(); 8274 } 8275 8276 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 8277 SDValue N0 = N->getOperand(0); 8278 EVT VT = N->getValueType(0); 8279 8280 if (N0.isUndef()) 8281 return DAG.getUNDEF(VT); 8282 8283 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8284 LegalOperations)) 8285 return SDValue(Res, 0); 8286 8287 return SDValue(); 8288 } 8289 8290 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 8291 SDValue N0 = N->getOperand(0); 8292 EVT VT = N->getValueType(0); 8293 bool isLE = DAG.getDataLayout().isLittleEndian(); 8294 8295 // noop truncate 8296 if (N0.getValueType() == N->getValueType(0)) 8297 return N0; 8298 // fold (truncate c1) -> c1 8299 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 8300 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 8301 // fold (truncate (truncate x)) -> (truncate x) 8302 if (N0.getOpcode() == ISD::TRUNCATE) 8303 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 8304 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 8305 if (N0.getOpcode() == ISD::ZERO_EXTEND || 8306 N0.getOpcode() == ISD::SIGN_EXTEND || 8307 N0.getOpcode() == ISD::ANY_EXTEND) { 8308 // if the source is smaller than the dest, we still need an extend. 8309 if (N0.getOperand(0).getValueType().bitsLT(VT)) 8310 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 8311 // if the source is larger than the dest, than we just need the truncate. 8312 if (N0.getOperand(0).getValueType().bitsGT(VT)) 8313 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 8314 // if the source and dest are the same type, we can drop both the extend 8315 // and the truncate. 8316 return N0.getOperand(0); 8317 } 8318 8319 // If this is anyext(trunc), don't fold it, allow ourselves to be folded. 8320 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND)) 8321 return SDValue(); 8322 8323 // Fold extract-and-trunc into a narrow extract. For example: 8324 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 8325 // i32 y = TRUNCATE(i64 x) 8326 // -- becomes -- 8327 // v16i8 b = BITCAST (v2i64 val) 8328 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 8329 // 8330 // Note: We only run this optimization after type legalization (which often 8331 // creates this pattern) and before operation legalization after which 8332 // we need to be more careful about the vector instructions that we generate. 8333 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 8334 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 8335 8336 EVT VecTy = N0.getOperand(0).getValueType(); 8337 EVT ExTy = N0.getValueType(); 8338 EVT TrTy = N->getValueType(0); 8339 8340 unsigned NumElem = VecTy.getVectorNumElements(); 8341 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 8342 8343 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 8344 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 8345 8346 SDValue EltNo = N0->getOperand(1); 8347 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 8348 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 8349 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 8350 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 8351 8352 SDLoc DL(N); 8353 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 8354 DAG.getBitcast(NVT, N0.getOperand(0)), 8355 DAG.getConstant(Index, DL, IndexTy)); 8356 } 8357 } 8358 8359 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 8360 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) { 8361 EVT SrcVT = N0.getValueType(); 8362 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 8363 TLI.isTruncateFree(SrcVT, VT)) { 8364 SDLoc SL(N0); 8365 SDValue Cond = N0.getOperand(0); 8366 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 8367 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 8368 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 8369 } 8370 } 8371 8372 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits() 8373 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 8374 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 8375 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 8376 SDValue Amt = N0.getOperand(1); 8377 KnownBits Known; 8378 DAG.computeKnownBits(Amt, Known); 8379 unsigned Size = VT.getScalarSizeInBits(); 8380 if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) { 8381 SDLoc SL(N); 8382 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 8383 8384 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 8385 if (AmtVT != Amt.getValueType()) { 8386 Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT); 8387 AddToWorklist(Amt.getNode()); 8388 } 8389 return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt); 8390 } 8391 } 8392 8393 // Fold a series of buildvector, bitcast, and truncate if possible. 8394 // For example fold 8395 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 8396 // (2xi32 (buildvector x, y)). 8397 if (Level == AfterLegalizeVectorOps && VT.isVector() && 8398 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 8399 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 8400 N0.getOperand(0).hasOneUse()) { 8401 8402 SDValue BuildVect = N0.getOperand(0); 8403 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 8404 EVT TruncVecEltTy = VT.getVectorElementType(); 8405 8406 // Check that the element types match. 8407 if (BuildVectEltTy == TruncVecEltTy) { 8408 // Now we only need to compute the offset of the truncated elements. 8409 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 8410 unsigned TruncVecNumElts = VT.getVectorNumElements(); 8411 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 8412 8413 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 8414 "Invalid number of elements"); 8415 8416 SmallVector<SDValue, 8> Opnds; 8417 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 8418 Opnds.push_back(BuildVect.getOperand(i)); 8419 8420 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 8421 } 8422 } 8423 8424 // See if we can simplify the input to this truncate through knowledge that 8425 // only the low bits are being used. 8426 // For example "trunc (or (shl x, 8), y)" // -> trunc y 8427 // Currently we only perform this optimization on scalars because vectors 8428 // may have different active low bits. 8429 if (!VT.isVector()) { 8430 if (SDValue Shorter = 8431 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 8432 VT.getSizeInBits()))) 8433 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 8434 } 8435 8436 // fold (truncate (load x)) -> (smaller load x) 8437 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 8438 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 8439 if (SDValue Reduced = ReduceLoadWidth(N)) 8440 return Reduced; 8441 8442 // Handle the case where the load remains an extending load even 8443 // after truncation. 8444 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 8445 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8446 if (!LN0->isVolatile() && 8447 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 8448 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 8449 VT, LN0->getChain(), LN0->getBasePtr(), 8450 LN0->getMemoryVT(), 8451 LN0->getMemOperand()); 8452 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 8453 return NewLoad; 8454 } 8455 } 8456 } 8457 8458 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 8459 // where ... are all 'undef'. 8460 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 8461 SmallVector<EVT, 8> VTs; 8462 SDValue V; 8463 unsigned Idx = 0; 8464 unsigned NumDefs = 0; 8465 8466 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 8467 SDValue X = N0.getOperand(i); 8468 if (!X.isUndef()) { 8469 V = X; 8470 Idx = i; 8471 NumDefs++; 8472 } 8473 // Stop if more than one members are non-undef. 8474 if (NumDefs > 1) 8475 break; 8476 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 8477 VT.getVectorElementType(), 8478 X.getValueType().getVectorNumElements())); 8479 } 8480 8481 if (NumDefs == 0) 8482 return DAG.getUNDEF(VT); 8483 8484 if (NumDefs == 1) { 8485 assert(V.getNode() && "The single defined operand is empty!"); 8486 SmallVector<SDValue, 8> Opnds; 8487 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 8488 if (i != Idx) { 8489 Opnds.push_back(DAG.getUNDEF(VTs[i])); 8490 continue; 8491 } 8492 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 8493 AddToWorklist(NV.getNode()); 8494 Opnds.push_back(NV); 8495 } 8496 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 8497 } 8498 } 8499 8500 // Fold truncate of a bitcast of a vector to an extract of the low vector 8501 // element. 8502 // 8503 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0 8504 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 8505 SDValue VecSrc = N0.getOperand(0); 8506 EVT SrcVT = VecSrc.getValueType(); 8507 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 8508 (!LegalOperations || 8509 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 8510 SDLoc SL(N); 8511 8512 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 8513 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 8514 VecSrc, DAG.getConstant(0, SL, IdxVT)); 8515 } 8516 } 8517 8518 // Simplify the operands using demanded-bits information. 8519 if (!VT.isVector() && 8520 SimplifyDemandedBits(SDValue(N, 0))) 8521 return SDValue(N, 0); 8522 8523 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry) 8524 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry) 8525 // When the adde's carry is not used. 8526 if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) && 8527 N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) && 8528 (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) { 8529 SDLoc SL(N); 8530 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 8531 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 8532 auto VTs = DAG.getVTList(VT, N0->getValueType(1)); 8533 return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2)); 8534 } 8535 8536 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 8537 return NewVSel; 8538 8539 return SDValue(); 8540 } 8541 8542 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 8543 SDValue Elt = N->getOperand(i); 8544 if (Elt.getOpcode() != ISD::MERGE_VALUES) 8545 return Elt.getNode(); 8546 return Elt.getOperand(Elt.getResNo()).getNode(); 8547 } 8548 8549 /// build_pair (load, load) -> load 8550 /// if load locations are consecutive. 8551 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 8552 assert(N->getOpcode() == ISD::BUILD_PAIR); 8553 8554 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 8555 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 8556 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 8557 LD1->getAddressSpace() != LD2->getAddressSpace()) 8558 return SDValue(); 8559 EVT LD1VT = LD1->getValueType(0); 8560 unsigned LD1Bytes = LD1VT.getSizeInBits() / 8; 8561 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 8562 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 8563 unsigned Align = LD1->getAlignment(); 8564 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 8565 VT.getTypeForEVT(*DAG.getContext())); 8566 8567 if (NewAlign <= Align && 8568 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 8569 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 8570 LD1->getPointerInfo(), Align); 8571 } 8572 8573 return SDValue(); 8574 } 8575 8576 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 8577 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 8578 // and Lo parts; on big-endian machines it doesn't. 8579 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 8580 } 8581 8582 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 8583 const TargetLowering &TLI) { 8584 // If this is not a bitcast to an FP type or if the target doesn't have 8585 // IEEE754-compliant FP logic, we're done. 8586 EVT VT = N->getValueType(0); 8587 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 8588 return SDValue(); 8589 8590 // TODO: Use splat values for the constant-checking below and remove this 8591 // restriction. 8592 SDValue N0 = N->getOperand(0); 8593 EVT SourceVT = N0.getValueType(); 8594 if (SourceVT.isVector()) 8595 return SDValue(); 8596 8597 unsigned FPOpcode; 8598 APInt SignMask; 8599 switch (N0.getOpcode()) { 8600 case ISD::AND: 8601 FPOpcode = ISD::FABS; 8602 SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits()); 8603 break; 8604 case ISD::XOR: 8605 FPOpcode = ISD::FNEG; 8606 SignMask = APInt::getSignMask(SourceVT.getSizeInBits()); 8607 break; 8608 // TODO: ISD::OR --> ISD::FNABS? 8609 default: 8610 return SDValue(); 8611 } 8612 8613 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 8614 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 8615 SDValue LogicOp0 = N0.getOperand(0); 8616 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8617 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 8618 LogicOp0.getOpcode() == ISD::BITCAST && 8619 LogicOp0->getOperand(0).getValueType() == VT) 8620 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0)); 8621 8622 return SDValue(); 8623 } 8624 8625 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 8626 SDValue N0 = N->getOperand(0); 8627 EVT VT = N->getValueType(0); 8628 8629 if (N0.isUndef()) 8630 return DAG.getUNDEF(VT); 8631 8632 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 8633 // Only do this before legalize, since afterward the target may be depending 8634 // on the bitconvert. 8635 // First check to see if this is all constant. 8636 if (!LegalTypes && 8637 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 8638 VT.isVector()) { 8639 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 8640 8641 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 8642 assert(!DestEltVT.isVector() && 8643 "Element type of vector ValueType must not be vector!"); 8644 if (isSimple) 8645 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 8646 } 8647 8648 // If the input is a constant, let getNode fold it. 8649 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 8650 // If we can't allow illegal operations, we need to check that this is just 8651 // a fp -> int or int -> conversion and that the resulting operation will 8652 // be legal. 8653 if (!LegalOperations || 8654 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 8655 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 8656 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 8657 TLI.isOperationLegal(ISD::Constant, VT))) 8658 return DAG.getBitcast(VT, N0); 8659 } 8660 8661 // (conv (conv x, t1), t2) -> (conv x, t2) 8662 if (N0.getOpcode() == ISD::BITCAST) 8663 return DAG.getBitcast(VT, N0.getOperand(0)); 8664 8665 // fold (conv (load x)) -> (load (conv*)x) 8666 // If the resultant load doesn't need a higher alignment than the original! 8667 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8668 // Do not change the width of a volatile load. 8669 !cast<LoadSDNode>(N0)->isVolatile() && 8670 // Do not remove the cast if the types differ in endian layout. 8671 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 8672 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 8673 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 8674 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 8675 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8676 unsigned OrigAlign = LN0->getAlignment(); 8677 8678 bool Fast = false; 8679 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 8680 LN0->getAddressSpace(), OrigAlign, &Fast) && 8681 Fast) { 8682 SDValue Load = 8683 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 8684 LN0->getPointerInfo(), OrigAlign, 8685 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8686 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 8687 return Load; 8688 } 8689 } 8690 8691 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 8692 return V; 8693 8694 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8695 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8696 // 8697 // For ppc_fp128: 8698 // fold (bitcast (fneg x)) -> 8699 // flipbit = signbit 8700 // (xor (bitcast x) (build_pair flipbit, flipbit)) 8701 // 8702 // fold (bitcast (fabs x)) -> 8703 // flipbit = (and (extract_element (bitcast x), 0), signbit) 8704 // (xor (bitcast x) (build_pair flipbit, flipbit)) 8705 // This often reduces constant pool loads. 8706 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 8707 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 8708 N0.getNode()->hasOneUse() && VT.isInteger() && 8709 !VT.isVector() && !N0.getValueType().isVector()) { 8710 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 8711 AddToWorklist(NewConv.getNode()); 8712 8713 SDLoc DL(N); 8714 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 8715 assert(VT.getSizeInBits() == 128); 8716 SDValue SignBit = DAG.getConstant( 8717 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 8718 SDValue FlipBit; 8719 if (N0.getOpcode() == ISD::FNEG) { 8720 FlipBit = SignBit; 8721 AddToWorklist(FlipBit.getNode()); 8722 } else { 8723 assert(N0.getOpcode() == ISD::FABS); 8724 SDValue Hi = 8725 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 8726 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 8727 SDLoc(NewConv))); 8728 AddToWorklist(Hi.getNode()); 8729 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 8730 AddToWorklist(FlipBit.getNode()); 8731 } 8732 SDValue FlipBits = 8733 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 8734 AddToWorklist(FlipBits.getNode()); 8735 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 8736 } 8737 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 8738 if (N0.getOpcode() == ISD::FNEG) 8739 return DAG.getNode(ISD::XOR, DL, VT, 8740 NewConv, DAG.getConstant(SignBit, DL, VT)); 8741 assert(N0.getOpcode() == ISD::FABS); 8742 return DAG.getNode(ISD::AND, DL, VT, 8743 NewConv, DAG.getConstant(~SignBit, DL, VT)); 8744 } 8745 8746 // fold (bitconvert (fcopysign cst, x)) -> 8747 // (or (and (bitconvert x), sign), (and cst, (not sign))) 8748 // Note that we don't handle (copysign x, cst) because this can always be 8749 // folded to an fneg or fabs. 8750 // 8751 // For ppc_fp128: 8752 // fold (bitcast (fcopysign cst, x)) -> 8753 // flipbit = (and (extract_element 8754 // (xor (bitcast cst), (bitcast x)), 0), 8755 // signbit) 8756 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 8757 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 8758 isa<ConstantFPSDNode>(N0.getOperand(0)) && 8759 VT.isInteger() && !VT.isVector()) { 8760 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits(); 8761 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 8762 if (isTypeLegal(IntXVT)) { 8763 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 8764 AddToWorklist(X.getNode()); 8765 8766 // If X has a different width than the result/lhs, sext it or truncate it. 8767 unsigned VTWidth = VT.getSizeInBits(); 8768 if (OrigXWidth < VTWidth) { 8769 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 8770 AddToWorklist(X.getNode()); 8771 } else if (OrigXWidth > VTWidth) { 8772 // To get the sign bit in the right place, we have to shift it right 8773 // before truncating. 8774 SDLoc DL(X); 8775 X = DAG.getNode(ISD::SRL, DL, 8776 X.getValueType(), X, 8777 DAG.getConstant(OrigXWidth-VTWidth, DL, 8778 X.getValueType())); 8779 AddToWorklist(X.getNode()); 8780 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 8781 AddToWorklist(X.getNode()); 8782 } 8783 8784 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 8785 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2); 8786 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 8787 AddToWorklist(Cst.getNode()); 8788 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 8789 AddToWorklist(X.getNode()); 8790 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 8791 AddToWorklist(XorResult.getNode()); 8792 SDValue XorResult64 = DAG.getNode( 8793 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 8794 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 8795 SDLoc(XorResult))); 8796 AddToWorklist(XorResult64.getNode()); 8797 SDValue FlipBit = 8798 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 8799 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 8800 AddToWorklist(FlipBit.getNode()); 8801 SDValue FlipBits = 8802 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 8803 AddToWorklist(FlipBits.getNode()); 8804 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 8805 } 8806 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 8807 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 8808 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 8809 AddToWorklist(X.getNode()); 8810 8811 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 8812 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 8813 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 8814 AddToWorklist(Cst.getNode()); 8815 8816 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 8817 } 8818 } 8819 8820 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 8821 if (N0.getOpcode() == ISD::BUILD_PAIR) 8822 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 8823 return CombineLD; 8824 8825 // Remove double bitcasts from shuffles - this is often a legacy of 8826 // XformToShuffleWithZero being used to combine bitmaskings (of 8827 // float vectors bitcast to integer vectors) into shuffles. 8828 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 8829 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 8830 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 8831 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 8832 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 8833 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 8834 8835 // If operands are a bitcast, peek through if it casts the original VT. 8836 // If operands are a constant, just bitcast back to original VT. 8837 auto PeekThroughBitcast = [&](SDValue Op) { 8838 if (Op.getOpcode() == ISD::BITCAST && 8839 Op.getOperand(0).getValueType() == VT) 8840 return SDValue(Op.getOperand(0)); 8841 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 8842 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 8843 return DAG.getBitcast(VT, Op); 8844 return SDValue(); 8845 }; 8846 8847 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 8848 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 8849 if (!(SV0 && SV1)) 8850 return SDValue(); 8851 8852 int MaskScale = 8853 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 8854 SmallVector<int, 8> NewMask; 8855 for (int M : SVN->getMask()) 8856 for (int i = 0; i != MaskScale; ++i) 8857 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 8858 8859 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 8860 if (!LegalMask) { 8861 std::swap(SV0, SV1); 8862 ShuffleVectorSDNode::commuteMask(NewMask); 8863 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 8864 } 8865 8866 if (LegalMask) 8867 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 8868 } 8869 8870 return SDValue(); 8871 } 8872 8873 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 8874 EVT VT = N->getValueType(0); 8875 return CombineConsecutiveLoads(N, VT); 8876 } 8877 8878 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 8879 /// operands. DstEltVT indicates the destination element value type. 8880 SDValue DAGCombiner:: 8881 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 8882 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 8883 8884 // If this is already the right type, we're done. 8885 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 8886 8887 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 8888 unsigned DstBitSize = DstEltVT.getSizeInBits(); 8889 8890 // If this is a conversion of N elements of one type to N elements of another 8891 // type, convert each element. This handles FP<->INT cases. 8892 if (SrcBitSize == DstBitSize) { 8893 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 8894 BV->getValueType(0).getVectorNumElements()); 8895 8896 // Due to the FP element handling below calling this routine recursively, 8897 // we can end up with a scalar-to-vector node here. 8898 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 8899 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 8900 DAG.getBitcast(DstEltVT, BV->getOperand(0))); 8901 8902 SmallVector<SDValue, 8> Ops; 8903 for (SDValue Op : BV->op_values()) { 8904 // If the vector element type is not legal, the BUILD_VECTOR operands 8905 // are promoted and implicitly truncated. Make that explicit here. 8906 if (Op.getValueType() != SrcEltVT) 8907 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 8908 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 8909 AddToWorklist(Ops.back().getNode()); 8910 } 8911 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 8912 } 8913 8914 // Otherwise, we're growing or shrinking the elements. To avoid having to 8915 // handle annoying details of growing/shrinking FP values, we convert them to 8916 // int first. 8917 if (SrcEltVT.isFloatingPoint()) { 8918 // Convert the input float vector to a int vector where the elements are the 8919 // same sizes. 8920 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 8921 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 8922 SrcEltVT = IntVT; 8923 } 8924 8925 // Now we know the input is an integer vector. If the output is a FP type, 8926 // convert to integer first, then to FP of the right size. 8927 if (DstEltVT.isFloatingPoint()) { 8928 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 8929 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 8930 8931 // Next, convert to FP elements of the same size. 8932 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 8933 } 8934 8935 SDLoc DL(BV); 8936 8937 // Okay, we know the src/dst types are both integers of differing types. 8938 // Handling growing first. 8939 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 8940 if (SrcBitSize < DstBitSize) { 8941 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 8942 8943 SmallVector<SDValue, 8> Ops; 8944 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 8945 i += NumInputsPerOutput) { 8946 bool isLE = DAG.getDataLayout().isLittleEndian(); 8947 APInt NewBits = APInt(DstBitSize, 0); 8948 bool EltIsUndef = true; 8949 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 8950 // Shift the previously computed bits over. 8951 NewBits <<= SrcBitSize; 8952 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 8953 if (Op.isUndef()) continue; 8954 EltIsUndef = false; 8955 8956 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 8957 zextOrTrunc(SrcBitSize).zext(DstBitSize); 8958 } 8959 8960 if (EltIsUndef) 8961 Ops.push_back(DAG.getUNDEF(DstEltVT)); 8962 else 8963 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 8964 } 8965 8966 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 8967 return DAG.getBuildVector(VT, DL, Ops); 8968 } 8969 8970 // Finally, this must be the case where we are shrinking elements: each input 8971 // turns into multiple outputs. 8972 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 8973 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 8974 NumOutputsPerInput*BV->getNumOperands()); 8975 SmallVector<SDValue, 8> Ops; 8976 8977 for (const SDValue &Op : BV->op_values()) { 8978 if (Op.isUndef()) { 8979 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 8980 continue; 8981 } 8982 8983 APInt OpVal = cast<ConstantSDNode>(Op)-> 8984 getAPIntValue().zextOrTrunc(SrcBitSize); 8985 8986 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 8987 APInt ThisVal = OpVal.trunc(DstBitSize); 8988 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 8989 OpVal.lshrInPlace(DstBitSize); 8990 } 8991 8992 // For big endian targets, swap the order of the pieces of each element. 8993 if (DAG.getDataLayout().isBigEndian()) 8994 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 8995 } 8996 8997 return DAG.getBuildVector(VT, DL, Ops); 8998 } 8999 9000 static bool isContractable(SDNode *N) { 9001 SDNodeFlags F = N->getFlags(); 9002 return F.hasAllowContract() || F.hasUnsafeAlgebra(); 9003 } 9004 9005 /// Try to perform FMA combining on a given FADD node. 9006 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 9007 SDValue N0 = N->getOperand(0); 9008 SDValue N1 = N->getOperand(1); 9009 EVT VT = N->getValueType(0); 9010 SDLoc SL(N); 9011 9012 const TargetOptions &Options = DAG.getTarget().Options; 9013 9014 // Floating-point multiply-add with intermediate rounding. 9015 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9016 9017 // Floating-point multiply-add without intermediate rounding. 9018 bool HasFMA = 9019 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9020 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9021 9022 // No valid opcode, do not combine. 9023 if (!HasFMAD && !HasFMA) 9024 return SDValue(); 9025 9026 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 9027 Options.UnsafeFPMath || HasFMAD); 9028 // If the addition is not contractable, do not combine. 9029 if (!AllowFusionGlobally && !isContractable(N)) 9030 return SDValue(); 9031 9032 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 9033 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 9034 return SDValue(); 9035 9036 // Always prefer FMAD to FMA for precision. 9037 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9038 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9039 bool LookThroughFPExt = TLI.isFPExtFree(VT); 9040 9041 // Is the node an FMUL and contractable either due to global flags or 9042 // SDNodeFlags. 9043 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 9044 if (N.getOpcode() != ISD::FMUL) 9045 return false; 9046 return AllowFusionGlobally || isContractable(N.getNode()); 9047 }; 9048 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 9049 // prefer to fold the multiply with fewer uses. 9050 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) { 9051 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 9052 std::swap(N0, N1); 9053 } 9054 9055 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 9056 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 9057 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9058 N0.getOperand(0), N0.getOperand(1), N1); 9059 } 9060 9061 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 9062 // Note: Commutes FADD operands. 9063 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) { 9064 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9065 N1.getOperand(0), N1.getOperand(1), N0); 9066 } 9067 9068 // Look through FP_EXTEND nodes to do more combining. 9069 if (LookThroughFPExt) { 9070 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 9071 if (N0.getOpcode() == ISD::FP_EXTEND) { 9072 SDValue N00 = N0.getOperand(0); 9073 if (isContractableFMUL(N00)) 9074 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9075 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9076 N00.getOperand(0)), 9077 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9078 N00.getOperand(1)), N1); 9079 } 9080 9081 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 9082 // Note: Commutes FADD operands. 9083 if (N1.getOpcode() == ISD::FP_EXTEND) { 9084 SDValue N10 = N1.getOperand(0); 9085 if (isContractableFMUL(N10)) 9086 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9087 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9088 N10.getOperand(0)), 9089 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9090 N10.getOperand(1)), N0); 9091 } 9092 } 9093 9094 // More folding opportunities when target permits. 9095 if (Aggressive) { 9096 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 9097 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9098 // are currently only supported on binary nodes. 9099 if (Options.UnsafeFPMath && 9100 N0.getOpcode() == PreferredFusedOpcode && 9101 N0.getOperand(2).getOpcode() == ISD::FMUL && 9102 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) { 9103 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9104 N0.getOperand(0), N0.getOperand(1), 9105 DAG.getNode(PreferredFusedOpcode, SL, VT, 9106 N0.getOperand(2).getOperand(0), 9107 N0.getOperand(2).getOperand(1), 9108 N1)); 9109 } 9110 9111 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 9112 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9113 // are currently only supported on binary nodes. 9114 if (Options.UnsafeFPMath && 9115 N1->getOpcode() == PreferredFusedOpcode && 9116 N1.getOperand(2).getOpcode() == ISD::FMUL && 9117 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) { 9118 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9119 N1.getOperand(0), N1.getOperand(1), 9120 DAG.getNode(PreferredFusedOpcode, SL, VT, 9121 N1.getOperand(2).getOperand(0), 9122 N1.getOperand(2).getOperand(1), 9123 N0)); 9124 } 9125 9126 if (LookThroughFPExt) { 9127 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 9128 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 9129 auto FoldFAddFMAFPExtFMul = [&] ( 9130 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 9131 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 9132 DAG.getNode(PreferredFusedOpcode, SL, VT, 9133 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 9134 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 9135 Z)); 9136 }; 9137 if (N0.getOpcode() == PreferredFusedOpcode) { 9138 SDValue N02 = N0.getOperand(2); 9139 if (N02.getOpcode() == ISD::FP_EXTEND) { 9140 SDValue N020 = N02.getOperand(0); 9141 if (isContractableFMUL(N020)) 9142 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 9143 N020.getOperand(0), N020.getOperand(1), 9144 N1); 9145 } 9146 } 9147 9148 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 9149 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 9150 // FIXME: This turns two single-precision and one double-precision 9151 // operation into two double-precision operations, which might not be 9152 // interesting for all targets, especially GPUs. 9153 auto FoldFAddFPExtFMAFMul = [&] ( 9154 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 9155 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9156 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 9157 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 9158 DAG.getNode(PreferredFusedOpcode, SL, VT, 9159 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 9160 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 9161 Z)); 9162 }; 9163 if (N0.getOpcode() == ISD::FP_EXTEND) { 9164 SDValue N00 = N0.getOperand(0); 9165 if (N00.getOpcode() == PreferredFusedOpcode) { 9166 SDValue N002 = N00.getOperand(2); 9167 if (isContractableFMUL(N002)) 9168 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 9169 N002.getOperand(0), N002.getOperand(1), 9170 N1); 9171 } 9172 } 9173 9174 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 9175 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 9176 if (N1.getOpcode() == PreferredFusedOpcode) { 9177 SDValue N12 = N1.getOperand(2); 9178 if (N12.getOpcode() == ISD::FP_EXTEND) { 9179 SDValue N120 = N12.getOperand(0); 9180 if (isContractableFMUL(N120)) 9181 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 9182 N120.getOperand(0), N120.getOperand(1), 9183 N0); 9184 } 9185 } 9186 9187 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 9188 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 9189 // FIXME: This turns two single-precision and one double-precision 9190 // operation into two double-precision operations, which might not be 9191 // interesting for all targets, especially GPUs. 9192 if (N1.getOpcode() == ISD::FP_EXTEND) { 9193 SDValue N10 = N1.getOperand(0); 9194 if (N10.getOpcode() == PreferredFusedOpcode) { 9195 SDValue N102 = N10.getOperand(2); 9196 if (isContractableFMUL(N102)) 9197 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 9198 N102.getOperand(0), N102.getOperand(1), 9199 N0); 9200 } 9201 } 9202 } 9203 } 9204 9205 return SDValue(); 9206 } 9207 9208 /// Try to perform FMA combining on a given FSUB node. 9209 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 9210 SDValue N0 = N->getOperand(0); 9211 SDValue N1 = N->getOperand(1); 9212 EVT VT = N->getValueType(0); 9213 SDLoc SL(N); 9214 9215 const TargetOptions &Options = DAG.getTarget().Options; 9216 // Floating-point multiply-add with intermediate rounding. 9217 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9218 9219 // Floating-point multiply-add without intermediate rounding. 9220 bool HasFMA = 9221 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9222 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9223 9224 // No valid opcode, do not combine. 9225 if (!HasFMAD && !HasFMA) 9226 return SDValue(); 9227 9228 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 9229 Options.UnsafeFPMath || HasFMAD); 9230 // If the subtraction is not contractable, do not combine. 9231 if (!AllowFusionGlobally && !isContractable(N)) 9232 return SDValue(); 9233 9234 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 9235 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 9236 return SDValue(); 9237 9238 // Always prefer FMAD to FMA for precision. 9239 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9240 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9241 bool LookThroughFPExt = TLI.isFPExtFree(VT); 9242 9243 // Is the node an FMUL and contractable either due to global flags or 9244 // SDNodeFlags. 9245 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 9246 if (N.getOpcode() != ISD::FMUL) 9247 return false; 9248 return AllowFusionGlobally || isContractable(N.getNode()); 9249 }; 9250 9251 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 9252 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 9253 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9254 N0.getOperand(0), N0.getOperand(1), 9255 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9256 } 9257 9258 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 9259 // Note: Commutes FSUB operands. 9260 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) 9261 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9262 DAG.getNode(ISD::FNEG, SL, VT, 9263 N1.getOperand(0)), 9264 N1.getOperand(1), N0); 9265 9266 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 9267 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) && 9268 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 9269 SDValue N00 = N0.getOperand(0).getOperand(0); 9270 SDValue N01 = N0.getOperand(0).getOperand(1); 9271 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9272 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 9273 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9274 } 9275 9276 // Look through FP_EXTEND nodes to do more combining. 9277 if (LookThroughFPExt) { 9278 // fold (fsub (fpext (fmul x, y)), z) 9279 // -> (fma (fpext x), (fpext y), (fneg z)) 9280 if (N0.getOpcode() == ISD::FP_EXTEND) { 9281 SDValue N00 = N0.getOperand(0); 9282 if (isContractableFMUL(N00)) 9283 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9284 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9285 N00.getOperand(0)), 9286 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9287 N00.getOperand(1)), 9288 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9289 } 9290 9291 // fold (fsub x, (fpext (fmul y, z))) 9292 // -> (fma (fneg (fpext y)), (fpext z), x) 9293 // Note: Commutes FSUB operands. 9294 if (N1.getOpcode() == ISD::FP_EXTEND) { 9295 SDValue N10 = N1.getOperand(0); 9296 if (isContractableFMUL(N10)) 9297 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9298 DAG.getNode(ISD::FNEG, SL, VT, 9299 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9300 N10.getOperand(0))), 9301 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9302 N10.getOperand(1)), 9303 N0); 9304 } 9305 9306 // fold (fsub (fpext (fneg (fmul, x, y))), z) 9307 // -> (fneg (fma (fpext x), (fpext y), z)) 9308 // Note: This could be removed with appropriate canonicalization of the 9309 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 9310 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 9311 // from implementing the canonicalization in visitFSUB. 9312 if (N0.getOpcode() == ISD::FP_EXTEND) { 9313 SDValue N00 = N0.getOperand(0); 9314 if (N00.getOpcode() == ISD::FNEG) { 9315 SDValue N000 = N00.getOperand(0); 9316 if (isContractableFMUL(N000)) { 9317 return DAG.getNode(ISD::FNEG, SL, VT, 9318 DAG.getNode(PreferredFusedOpcode, SL, VT, 9319 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9320 N000.getOperand(0)), 9321 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9322 N000.getOperand(1)), 9323 N1)); 9324 } 9325 } 9326 } 9327 9328 // fold (fsub (fneg (fpext (fmul, x, y))), z) 9329 // -> (fneg (fma (fpext x)), (fpext y), z) 9330 // Note: This could be removed with appropriate canonicalization of the 9331 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 9332 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 9333 // from implementing the canonicalization in visitFSUB. 9334 if (N0.getOpcode() == ISD::FNEG) { 9335 SDValue N00 = N0.getOperand(0); 9336 if (N00.getOpcode() == ISD::FP_EXTEND) { 9337 SDValue N000 = N00.getOperand(0); 9338 if (isContractableFMUL(N000)) { 9339 return DAG.getNode(ISD::FNEG, SL, VT, 9340 DAG.getNode(PreferredFusedOpcode, SL, VT, 9341 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9342 N000.getOperand(0)), 9343 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9344 N000.getOperand(1)), 9345 N1)); 9346 } 9347 } 9348 } 9349 9350 } 9351 9352 // More folding opportunities when target permits. 9353 if (Aggressive) { 9354 // fold (fsub (fma x, y, (fmul u, v)), z) 9355 // -> (fma x, y (fma u, v, (fneg z))) 9356 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9357 // are currently only supported on binary nodes. 9358 if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode && 9359 isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() && 9360 N0.getOperand(2)->hasOneUse()) { 9361 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9362 N0.getOperand(0), N0.getOperand(1), 9363 DAG.getNode(PreferredFusedOpcode, SL, VT, 9364 N0.getOperand(2).getOperand(0), 9365 N0.getOperand(2).getOperand(1), 9366 DAG.getNode(ISD::FNEG, SL, VT, 9367 N1))); 9368 } 9369 9370 // fold (fsub x, (fma y, z, (fmul u, v))) 9371 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 9372 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9373 // are currently only supported on binary nodes. 9374 if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode && 9375 isContractableFMUL(N1.getOperand(2))) { 9376 SDValue N20 = N1.getOperand(2).getOperand(0); 9377 SDValue N21 = N1.getOperand(2).getOperand(1); 9378 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9379 DAG.getNode(ISD::FNEG, SL, VT, 9380 N1.getOperand(0)), 9381 N1.getOperand(1), 9382 DAG.getNode(PreferredFusedOpcode, SL, VT, 9383 DAG.getNode(ISD::FNEG, SL, VT, N20), 9384 9385 N21, N0)); 9386 } 9387 9388 if (LookThroughFPExt) { 9389 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 9390 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 9391 if (N0.getOpcode() == PreferredFusedOpcode) { 9392 SDValue N02 = N0.getOperand(2); 9393 if (N02.getOpcode() == ISD::FP_EXTEND) { 9394 SDValue N020 = N02.getOperand(0); 9395 if (isContractableFMUL(N020)) 9396 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9397 N0.getOperand(0), N0.getOperand(1), 9398 DAG.getNode(PreferredFusedOpcode, SL, VT, 9399 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9400 N020.getOperand(0)), 9401 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9402 N020.getOperand(1)), 9403 DAG.getNode(ISD::FNEG, SL, VT, 9404 N1))); 9405 } 9406 } 9407 9408 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 9409 // -> (fma (fpext x), (fpext y), 9410 // (fma (fpext u), (fpext v), (fneg z))) 9411 // FIXME: This turns two single-precision and one double-precision 9412 // operation into two double-precision operations, which might not be 9413 // interesting for all targets, especially GPUs. 9414 if (N0.getOpcode() == ISD::FP_EXTEND) { 9415 SDValue N00 = N0.getOperand(0); 9416 if (N00.getOpcode() == PreferredFusedOpcode) { 9417 SDValue N002 = N00.getOperand(2); 9418 if (isContractableFMUL(N002)) 9419 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9420 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9421 N00.getOperand(0)), 9422 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9423 N00.getOperand(1)), 9424 DAG.getNode(PreferredFusedOpcode, SL, VT, 9425 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9426 N002.getOperand(0)), 9427 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9428 N002.getOperand(1)), 9429 DAG.getNode(ISD::FNEG, SL, VT, 9430 N1))); 9431 } 9432 } 9433 9434 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 9435 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 9436 if (N1.getOpcode() == PreferredFusedOpcode && 9437 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 9438 SDValue N120 = N1.getOperand(2).getOperand(0); 9439 if (isContractableFMUL(N120)) { 9440 SDValue N1200 = N120.getOperand(0); 9441 SDValue N1201 = N120.getOperand(1); 9442 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9443 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 9444 N1.getOperand(1), 9445 DAG.getNode(PreferredFusedOpcode, SL, VT, 9446 DAG.getNode(ISD::FNEG, SL, VT, 9447 DAG.getNode(ISD::FP_EXTEND, SL, 9448 VT, N1200)), 9449 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9450 N1201), 9451 N0)); 9452 } 9453 } 9454 9455 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 9456 // -> (fma (fneg (fpext y)), (fpext z), 9457 // (fma (fneg (fpext u)), (fpext v), x)) 9458 // FIXME: This turns two single-precision and one double-precision 9459 // operation into two double-precision operations, which might not be 9460 // interesting for all targets, especially GPUs. 9461 if (N1.getOpcode() == ISD::FP_EXTEND && 9462 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 9463 SDValue N100 = N1.getOperand(0).getOperand(0); 9464 SDValue N101 = N1.getOperand(0).getOperand(1); 9465 SDValue N102 = N1.getOperand(0).getOperand(2); 9466 if (isContractableFMUL(N102)) { 9467 SDValue N1020 = N102.getOperand(0); 9468 SDValue N1021 = N102.getOperand(1); 9469 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9470 DAG.getNode(ISD::FNEG, SL, VT, 9471 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9472 N100)), 9473 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 9474 DAG.getNode(PreferredFusedOpcode, SL, VT, 9475 DAG.getNode(ISD::FNEG, SL, VT, 9476 DAG.getNode(ISD::FP_EXTEND, SL, 9477 VT, N1020)), 9478 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9479 N1021), 9480 N0)); 9481 } 9482 } 9483 } 9484 } 9485 9486 return SDValue(); 9487 } 9488 9489 /// Try to perform FMA combining on a given FMUL node based on the distributive 9490 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions, 9491 /// subtraction instead of addition). 9492 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) { 9493 SDValue N0 = N->getOperand(0); 9494 SDValue N1 = N->getOperand(1); 9495 EVT VT = N->getValueType(0); 9496 SDLoc SL(N); 9497 9498 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 9499 9500 const TargetOptions &Options = DAG.getTarget().Options; 9501 9502 // The transforms below are incorrect when x == 0 and y == inf, because the 9503 // intermediate multiplication produces a nan. 9504 if (!Options.NoInfsFPMath) 9505 return SDValue(); 9506 9507 // Floating-point multiply-add without intermediate rounding. 9508 bool HasFMA = 9509 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 9510 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9511 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9512 9513 // Floating-point multiply-add with intermediate rounding. This can result 9514 // in a less precise result due to the changed rounding order. 9515 bool HasFMAD = Options.UnsafeFPMath && 9516 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9517 9518 // No valid opcode, do not combine. 9519 if (!HasFMAD && !HasFMA) 9520 return SDValue(); 9521 9522 // Always prefer FMAD to FMA for precision. 9523 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9524 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9525 9526 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 9527 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 9528 auto FuseFADD = [&](SDValue X, SDValue Y) { 9529 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 9530 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 9531 if (XC1 && XC1->isExactlyValue(+1.0)) 9532 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 9533 if (XC1 && XC1->isExactlyValue(-1.0)) 9534 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 9535 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9536 } 9537 return SDValue(); 9538 }; 9539 9540 if (SDValue FMA = FuseFADD(N0, N1)) 9541 return FMA; 9542 if (SDValue FMA = FuseFADD(N1, N0)) 9543 return FMA; 9544 9545 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 9546 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 9547 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 9548 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 9549 auto FuseFSUB = [&](SDValue X, SDValue Y) { 9550 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 9551 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 9552 if (XC0 && XC0->isExactlyValue(+1.0)) 9553 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9554 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 9555 Y); 9556 if (XC0 && XC0->isExactlyValue(-1.0)) 9557 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9558 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 9559 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9560 9561 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 9562 if (XC1 && XC1->isExactlyValue(+1.0)) 9563 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 9564 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9565 if (XC1 && XC1->isExactlyValue(-1.0)) 9566 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 9567 } 9568 return SDValue(); 9569 }; 9570 9571 if (SDValue FMA = FuseFSUB(N0, N1)) 9572 return FMA; 9573 if (SDValue FMA = FuseFSUB(N1, N0)) 9574 return FMA; 9575 9576 return SDValue(); 9577 } 9578 9579 static bool isFMulNegTwo(SDValue &N) { 9580 if (N.getOpcode() != ISD::FMUL) 9581 return false; 9582 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1))) 9583 return CFP->isExactlyValue(-2.0); 9584 return false; 9585 } 9586 9587 SDValue DAGCombiner::visitFADD(SDNode *N) { 9588 SDValue N0 = N->getOperand(0); 9589 SDValue N1 = N->getOperand(1); 9590 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 9591 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 9592 EVT VT = N->getValueType(0); 9593 SDLoc DL(N); 9594 const TargetOptions &Options = DAG.getTarget().Options; 9595 const SDNodeFlags Flags = N->getFlags(); 9596 9597 // fold vector ops 9598 if (VT.isVector()) 9599 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9600 return FoldedVOp; 9601 9602 // fold (fadd c1, c2) -> c1 + c2 9603 if (N0CFP && N1CFP) 9604 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 9605 9606 // canonicalize constant to RHS 9607 if (N0CFP && !N1CFP) 9608 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 9609 9610 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9611 return NewSel; 9612 9613 // fold (fadd A, (fneg B)) -> (fsub A, B) 9614 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 9615 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 9616 return DAG.getNode(ISD::FSUB, DL, VT, N0, 9617 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 9618 9619 // fold (fadd (fneg A), B) -> (fsub B, A) 9620 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 9621 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 9622 return DAG.getNode(ISD::FSUB, DL, VT, N1, 9623 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 9624 9625 // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B)) 9626 // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B)) 9627 if ((isFMulNegTwo(N0) && N0.hasOneUse()) || 9628 (isFMulNegTwo(N1) && N1.hasOneUse())) { 9629 bool N1IsFMul = isFMulNegTwo(N1); 9630 SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0); 9631 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags); 9632 return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags); 9633 } 9634 9635 // FIXME: Auto-upgrade the target/function-level option. 9636 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) { 9637 // fold (fadd A, 0) -> A 9638 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 9639 if (N1C->isZero()) 9640 return N0; 9641 } 9642 9643 // If 'unsafe math' is enabled, fold lots of things. 9644 if (Options.UnsafeFPMath) { 9645 // No FP constant should be created after legalization as Instruction 9646 // Selection pass has a hard time dealing with FP constants. 9647 bool AllowNewConst = (Level < AfterLegalizeDAG); 9648 9649 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 9650 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 9651 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 9652 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 9653 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 9654 Flags), 9655 Flags); 9656 9657 // If allowed, fold (fadd (fneg x), x) -> 0.0 9658 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 9659 return DAG.getConstantFP(0.0, DL, VT); 9660 9661 // If allowed, fold (fadd x, (fneg x)) -> 0.0 9662 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 9663 return DAG.getConstantFP(0.0, DL, VT); 9664 9665 // We can fold chains of FADD's of the same value into multiplications. 9666 // This transform is not safe in general because we are reducing the number 9667 // of rounding steps. 9668 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 9669 if (N0.getOpcode() == ISD::FMUL) { 9670 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 9671 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 9672 9673 // (fadd (fmul x, c), x) -> (fmul x, c+1) 9674 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 9675 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 9676 DAG.getConstantFP(1.0, DL, VT), Flags); 9677 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 9678 } 9679 9680 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 9681 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 9682 N1.getOperand(0) == N1.getOperand(1) && 9683 N0.getOperand(0) == N1.getOperand(0)) { 9684 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 9685 DAG.getConstantFP(2.0, DL, VT), Flags); 9686 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 9687 } 9688 } 9689 9690 if (N1.getOpcode() == ISD::FMUL) { 9691 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 9692 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 9693 9694 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 9695 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 9696 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 9697 DAG.getConstantFP(1.0, DL, VT), Flags); 9698 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 9699 } 9700 9701 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 9702 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 9703 N0.getOperand(0) == N0.getOperand(1) && 9704 N1.getOperand(0) == N0.getOperand(0)) { 9705 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 9706 DAG.getConstantFP(2.0, DL, VT), Flags); 9707 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 9708 } 9709 } 9710 9711 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 9712 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 9713 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 9714 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 9715 (N0.getOperand(0) == N1)) { 9716 return DAG.getNode(ISD::FMUL, DL, VT, 9717 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 9718 } 9719 } 9720 9721 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 9722 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 9723 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 9724 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 9725 N1.getOperand(0) == N0) { 9726 return DAG.getNode(ISD::FMUL, DL, VT, 9727 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 9728 } 9729 } 9730 9731 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 9732 if (AllowNewConst && 9733 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 9734 N0.getOperand(0) == N0.getOperand(1) && 9735 N1.getOperand(0) == N1.getOperand(1) && 9736 N0.getOperand(0) == N1.getOperand(0)) { 9737 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 9738 DAG.getConstantFP(4.0, DL, VT), Flags); 9739 } 9740 } 9741 } // enable-unsafe-fp-math 9742 9743 // FADD -> FMA combines: 9744 if (SDValue Fused = visitFADDForFMACombine(N)) { 9745 AddToWorklist(Fused.getNode()); 9746 return Fused; 9747 } 9748 return SDValue(); 9749 } 9750 9751 SDValue DAGCombiner::visitFSUB(SDNode *N) { 9752 SDValue N0 = N->getOperand(0); 9753 SDValue N1 = N->getOperand(1); 9754 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9755 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9756 EVT VT = N->getValueType(0); 9757 SDLoc DL(N); 9758 const TargetOptions &Options = DAG.getTarget().Options; 9759 const SDNodeFlags Flags = N->getFlags(); 9760 9761 // fold vector ops 9762 if (VT.isVector()) 9763 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9764 return FoldedVOp; 9765 9766 // fold (fsub c1, c2) -> c1-c2 9767 if (N0CFP && N1CFP) 9768 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags); 9769 9770 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9771 return NewSel; 9772 9773 // fold (fsub A, (fneg B)) -> (fadd A, B) 9774 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 9775 return DAG.getNode(ISD::FADD, DL, VT, N0, 9776 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 9777 9778 // FIXME: Auto-upgrade the target/function-level option. 9779 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) { 9780 // (fsub 0, B) -> -B 9781 if (N0CFP && N0CFP->isZero()) { 9782 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 9783 return GetNegatedExpression(N1, DAG, LegalOperations); 9784 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9785 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags); 9786 } 9787 } 9788 9789 // If 'unsafe math' is enabled, fold lots of things. 9790 if (Options.UnsafeFPMath) { 9791 // (fsub A, 0) -> A 9792 if (N1CFP && N1CFP->isZero()) 9793 return N0; 9794 9795 // (fsub x, x) -> 0.0 9796 if (N0 == N1) 9797 return DAG.getConstantFP(0.0f, DL, VT); 9798 9799 // (fsub x, (fadd x, y)) -> (fneg y) 9800 // (fsub x, (fadd y, x)) -> (fneg y) 9801 if (N1.getOpcode() == ISD::FADD) { 9802 SDValue N10 = N1->getOperand(0); 9803 SDValue N11 = N1->getOperand(1); 9804 9805 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 9806 return GetNegatedExpression(N11, DAG, LegalOperations); 9807 9808 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 9809 return GetNegatedExpression(N10, DAG, LegalOperations); 9810 } 9811 } 9812 9813 // FSUB -> FMA combines: 9814 if (SDValue Fused = visitFSUBForFMACombine(N)) { 9815 AddToWorklist(Fused.getNode()); 9816 return Fused; 9817 } 9818 9819 return SDValue(); 9820 } 9821 9822 SDValue DAGCombiner::visitFMUL(SDNode *N) { 9823 SDValue N0 = N->getOperand(0); 9824 SDValue N1 = N->getOperand(1); 9825 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9826 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9827 EVT VT = N->getValueType(0); 9828 SDLoc DL(N); 9829 const TargetOptions &Options = DAG.getTarget().Options; 9830 const SDNodeFlags Flags = N->getFlags(); 9831 9832 // fold vector ops 9833 if (VT.isVector()) { 9834 // This just handles C1 * C2 for vectors. Other vector folds are below. 9835 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9836 return FoldedVOp; 9837 } 9838 9839 // fold (fmul c1, c2) -> c1*c2 9840 if (N0CFP && N1CFP) 9841 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 9842 9843 // canonicalize constant to RHS 9844 if (isConstantFPBuildVectorOrConstantFP(N0) && 9845 !isConstantFPBuildVectorOrConstantFP(N1)) 9846 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 9847 9848 // fold (fmul A, 1.0) -> A 9849 if (N1CFP && N1CFP->isExactlyValue(1.0)) 9850 return N0; 9851 9852 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9853 return NewSel; 9854 9855 if (Options.UnsafeFPMath) { 9856 // fold (fmul A, 0) -> 0 9857 if (N1CFP && N1CFP->isZero()) 9858 return N1; 9859 9860 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 9861 if (N0.getOpcode() == ISD::FMUL) { 9862 // Fold scalars or any vector constants (not just splats). 9863 // This fold is done in general by InstCombine, but extra fmul insts 9864 // may have been generated during lowering. 9865 SDValue N00 = N0.getOperand(0); 9866 SDValue N01 = N0.getOperand(1); 9867 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 9868 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 9869 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 9870 9871 // Check 1: Make sure that the first operand of the inner multiply is NOT 9872 // a constant. Otherwise, we may induce infinite looping. 9873 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 9874 // Check 2: Make sure that the second operand of the inner multiply and 9875 // the second operand of the outer multiply are constants. 9876 if ((N1CFP && isConstOrConstSplatFP(N01)) || 9877 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 9878 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 9879 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 9880 } 9881 } 9882 } 9883 9884 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 9885 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 9886 // during an early run of DAGCombiner can prevent folding with fmuls 9887 // inserted during lowering. 9888 if (N0.getOpcode() == ISD::FADD && 9889 (N0.getOperand(0) == N0.getOperand(1)) && 9890 N0.hasOneUse()) { 9891 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 9892 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 9893 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 9894 } 9895 } 9896 9897 // fold (fmul X, 2.0) -> (fadd X, X) 9898 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 9899 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 9900 9901 // fold (fmul X, -1.0) -> (fneg X) 9902 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 9903 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9904 return DAG.getNode(ISD::FNEG, DL, VT, N0); 9905 9906 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 9907 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 9908 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 9909 // Both can be negated for free, check to see if at least one is cheaper 9910 // negated. 9911 if (LHSNeg == 2 || RHSNeg == 2) 9912 return DAG.getNode(ISD::FMUL, DL, VT, 9913 GetNegatedExpression(N0, DAG, LegalOperations), 9914 GetNegatedExpression(N1, DAG, LegalOperations), 9915 Flags); 9916 } 9917 } 9918 9919 // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X)) 9920 // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X) 9921 if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() && 9922 (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) && 9923 TLI.isOperationLegal(ISD::FABS, VT)) { 9924 SDValue Select = N0, X = N1; 9925 if (Select.getOpcode() != ISD::SELECT) 9926 std::swap(Select, X); 9927 9928 SDValue Cond = Select.getOperand(0); 9929 auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1)); 9930 auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2)); 9931 9932 if (TrueOpnd && FalseOpnd && 9933 Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X && 9934 isa<ConstantFPSDNode>(Cond.getOperand(1)) && 9935 cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) { 9936 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 9937 switch (CC) { 9938 default: break; 9939 case ISD::SETOLT: 9940 case ISD::SETULT: 9941 case ISD::SETOLE: 9942 case ISD::SETULE: 9943 case ISD::SETLT: 9944 case ISD::SETLE: 9945 std::swap(TrueOpnd, FalseOpnd); 9946 // Fall through 9947 case ISD::SETOGT: 9948 case ISD::SETUGT: 9949 case ISD::SETOGE: 9950 case ISD::SETUGE: 9951 case ISD::SETGT: 9952 case ISD::SETGE: 9953 if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) && 9954 TLI.isOperationLegal(ISD::FNEG, VT)) 9955 return DAG.getNode(ISD::FNEG, DL, VT, 9956 DAG.getNode(ISD::FABS, DL, VT, X)); 9957 if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0)) 9958 return DAG.getNode(ISD::FABS, DL, VT, X); 9959 9960 break; 9961 } 9962 } 9963 } 9964 9965 // FMUL -> FMA combines: 9966 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) { 9967 AddToWorklist(Fused.getNode()); 9968 return Fused; 9969 } 9970 9971 return SDValue(); 9972 } 9973 9974 SDValue DAGCombiner::visitFMA(SDNode *N) { 9975 SDValue N0 = N->getOperand(0); 9976 SDValue N1 = N->getOperand(1); 9977 SDValue N2 = N->getOperand(2); 9978 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9979 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9980 EVT VT = N->getValueType(0); 9981 SDLoc DL(N); 9982 const TargetOptions &Options = DAG.getTarget().Options; 9983 9984 // Constant fold FMA. 9985 if (isa<ConstantFPSDNode>(N0) && 9986 isa<ConstantFPSDNode>(N1) && 9987 isa<ConstantFPSDNode>(N2)) { 9988 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2); 9989 } 9990 9991 if (Options.UnsafeFPMath) { 9992 if (N0CFP && N0CFP->isZero()) 9993 return N2; 9994 if (N1CFP && N1CFP->isZero()) 9995 return N2; 9996 } 9997 // TODO: The FMA node should have flags that propagate to these nodes. 9998 if (N0CFP && N0CFP->isExactlyValue(1.0)) 9999 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 10000 if (N1CFP && N1CFP->isExactlyValue(1.0)) 10001 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 10002 10003 // Canonicalize (fma c, x, y) -> (fma x, c, y) 10004 if (isConstantFPBuildVectorOrConstantFP(N0) && 10005 !isConstantFPBuildVectorOrConstantFP(N1)) 10006 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 10007 10008 // TODO: FMA nodes should have flags that propagate to the created nodes. 10009 // For now, create a Flags object for use with all unsafe math transforms. 10010 SDNodeFlags Flags; 10011 Flags.setUnsafeAlgebra(true); 10012 10013 if (Options.UnsafeFPMath) { 10014 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 10015 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 10016 isConstantFPBuildVectorOrConstantFP(N1) && 10017 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 10018 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10019 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1), 10020 Flags), Flags); 10021 } 10022 10023 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 10024 if (N0.getOpcode() == ISD::FMUL && 10025 isConstantFPBuildVectorOrConstantFP(N1) && 10026 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 10027 return DAG.getNode(ISD::FMA, DL, VT, 10028 N0.getOperand(0), 10029 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1), 10030 Flags), 10031 N2); 10032 } 10033 } 10034 10035 // (fma x, 1, y) -> (fadd x, y) 10036 // (fma x, -1, y) -> (fadd (fneg x), y) 10037 if (N1CFP) { 10038 if (N1CFP->isExactlyValue(1.0)) 10039 // TODO: The FMA node should have flags that propagate to this node. 10040 return DAG.getNode(ISD::FADD, DL, VT, N0, N2); 10041 10042 if (N1CFP->isExactlyValue(-1.0) && 10043 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 10044 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0); 10045 AddToWorklist(RHSNeg.getNode()); 10046 // TODO: The FMA node should have flags that propagate to this node. 10047 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg); 10048 } 10049 } 10050 10051 if (Options.UnsafeFPMath) { 10052 // (fma x, c, x) -> (fmul x, (c+1)) 10053 if (N1CFP && N0 == N2) { 10054 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10055 DAG.getNode(ISD::FADD, DL, VT, N1, 10056 DAG.getConstantFP(1.0, DL, VT), Flags), 10057 Flags); 10058 } 10059 10060 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 10061 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 10062 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10063 DAG.getNode(ISD::FADD, DL, VT, N1, 10064 DAG.getConstantFP(-1.0, DL, VT), Flags), 10065 Flags); 10066 } 10067 } 10068 10069 return SDValue(); 10070 } 10071 10072 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10073 // reciprocal. 10074 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 10075 // Notice that this is not always beneficial. One reason is different targets 10076 // may have different costs for FDIV and FMUL, so sometimes the cost of two 10077 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 10078 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 10079 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 10080 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 10081 const SDNodeFlags Flags = N->getFlags(); 10082 if (!UnsafeMath && !Flags.hasAllowReciprocal()) 10083 return SDValue(); 10084 10085 // Skip if current node is a reciprocal. 10086 SDValue N0 = N->getOperand(0); 10087 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10088 if (N0CFP && N0CFP->isExactlyValue(1.0)) 10089 return SDValue(); 10090 10091 // Exit early if the target does not want this transform or if there can't 10092 // possibly be enough uses of the divisor to make the transform worthwhile. 10093 SDValue N1 = N->getOperand(1); 10094 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 10095 if (!MinUses || N1->use_size() < MinUses) 10096 return SDValue(); 10097 10098 // Find all FDIV users of the same divisor. 10099 // Use a set because duplicates may be present in the user list. 10100 SetVector<SDNode *> Users; 10101 for (auto *U : N1->uses()) { 10102 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 10103 // This division is eligible for optimization only if global unsafe math 10104 // is enabled or if this division allows reciprocal formation. 10105 if (UnsafeMath || U->getFlags().hasAllowReciprocal()) 10106 Users.insert(U); 10107 } 10108 } 10109 10110 // Now that we have the actual number of divisor uses, make sure it meets 10111 // the minimum threshold specified by the target. 10112 if (Users.size() < MinUses) 10113 return SDValue(); 10114 10115 EVT VT = N->getValueType(0); 10116 SDLoc DL(N); 10117 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 10118 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 10119 10120 // Dividend / Divisor -> Dividend * Reciprocal 10121 for (auto *U : Users) { 10122 SDValue Dividend = U->getOperand(0); 10123 if (Dividend != FPOne) { 10124 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 10125 Reciprocal, Flags); 10126 CombineTo(U, NewNode); 10127 } else if (U != Reciprocal.getNode()) { 10128 // In the absence of fast-math-flags, this user node is always the 10129 // same node as Reciprocal, but with FMF they may be different nodes. 10130 CombineTo(U, Reciprocal); 10131 } 10132 } 10133 return SDValue(N, 0); // N was replaced. 10134 } 10135 10136 SDValue DAGCombiner::visitFDIV(SDNode *N) { 10137 SDValue N0 = N->getOperand(0); 10138 SDValue N1 = N->getOperand(1); 10139 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10140 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10141 EVT VT = N->getValueType(0); 10142 SDLoc DL(N); 10143 const TargetOptions &Options = DAG.getTarget().Options; 10144 SDNodeFlags Flags = N->getFlags(); 10145 10146 // fold vector ops 10147 if (VT.isVector()) 10148 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 10149 return FoldedVOp; 10150 10151 // fold (fdiv c1, c2) -> c1/c2 10152 if (N0CFP && N1CFP) 10153 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 10154 10155 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10156 return NewSel; 10157 10158 if (Options.UnsafeFPMath) { 10159 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 10160 if (N1CFP) { 10161 // Compute the reciprocal 1.0 / c2. 10162 const APFloat &N1APF = N1CFP->getValueAPF(); 10163 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 10164 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 10165 // Only do the transform if the reciprocal is a legal fp immediate that 10166 // isn't too nasty (eg NaN, denormal, ...). 10167 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 10168 (!LegalOperations || 10169 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 10170 // backend)... we should handle this gracefully after Legalize. 10171 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 10172 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 10173 TLI.isFPImmLegal(Recip, VT))) 10174 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10175 DAG.getConstantFP(Recip, DL, VT), Flags); 10176 } 10177 10178 // If this FDIV is part of a reciprocal square root, it may be folded 10179 // into a target-specific square root estimate instruction. 10180 if (N1.getOpcode() == ISD::FSQRT) { 10181 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) { 10182 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10183 } 10184 } else if (N1.getOpcode() == ISD::FP_EXTEND && 10185 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10186 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 10187 Flags)) { 10188 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 10189 AddToWorklist(RV.getNode()); 10190 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10191 } 10192 } else if (N1.getOpcode() == ISD::FP_ROUND && 10193 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10194 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 10195 Flags)) { 10196 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 10197 AddToWorklist(RV.getNode()); 10198 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10199 } 10200 } else if (N1.getOpcode() == ISD::FMUL) { 10201 // Look through an FMUL. Even though this won't remove the FDIV directly, 10202 // it's still worthwhile to get rid of the FSQRT if possible. 10203 SDValue SqrtOp; 10204 SDValue OtherOp; 10205 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10206 SqrtOp = N1.getOperand(0); 10207 OtherOp = N1.getOperand(1); 10208 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 10209 SqrtOp = N1.getOperand(1); 10210 OtherOp = N1.getOperand(0); 10211 } 10212 if (SqrtOp.getNode()) { 10213 // We found a FSQRT, so try to make this fold: 10214 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 10215 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 10216 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 10217 AddToWorklist(RV.getNode()); 10218 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10219 } 10220 } 10221 } 10222 10223 // Fold into a reciprocal estimate and multiply instead of a real divide. 10224 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 10225 AddToWorklist(RV.getNode()); 10226 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10227 } 10228 } 10229 10230 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 10231 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 10232 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 10233 // Both can be negated for free, check to see if at least one is cheaper 10234 // negated. 10235 if (LHSNeg == 2 || RHSNeg == 2) 10236 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 10237 GetNegatedExpression(N0, DAG, LegalOperations), 10238 GetNegatedExpression(N1, DAG, LegalOperations), 10239 Flags); 10240 } 10241 } 10242 10243 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 10244 return CombineRepeatedDivisors; 10245 10246 return SDValue(); 10247 } 10248 10249 SDValue DAGCombiner::visitFREM(SDNode *N) { 10250 SDValue N0 = N->getOperand(0); 10251 SDValue N1 = N->getOperand(1); 10252 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10253 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10254 EVT VT = N->getValueType(0); 10255 10256 // fold (frem c1, c2) -> fmod(c1,c2) 10257 if (N0CFP && N1CFP) 10258 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags()); 10259 10260 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10261 return NewSel; 10262 10263 return SDValue(); 10264 } 10265 10266 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 10267 if (!DAG.getTarget().Options.UnsafeFPMath) 10268 return SDValue(); 10269 10270 SDValue N0 = N->getOperand(0); 10271 if (TLI.isFsqrtCheap(N0, DAG)) 10272 return SDValue(); 10273 10274 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 10275 // For now, create a Flags object for use with all unsafe math transforms. 10276 SDNodeFlags Flags; 10277 Flags.setUnsafeAlgebra(true); 10278 return buildSqrtEstimate(N0, Flags); 10279 } 10280 10281 /// copysign(x, fp_extend(y)) -> copysign(x, y) 10282 /// copysign(x, fp_round(y)) -> copysign(x, y) 10283 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 10284 SDValue N1 = N->getOperand(1); 10285 if ((N1.getOpcode() == ISD::FP_EXTEND || 10286 N1.getOpcode() == ISD::FP_ROUND)) { 10287 // Do not optimize out type conversion of f128 type yet. 10288 // For some targets like x86_64, configuration is changed to keep one f128 10289 // value in one SSE register, but instruction selection cannot handle 10290 // FCOPYSIGN on SSE registers yet. 10291 EVT N1VT = N1->getValueType(0); 10292 EVT N1Op0VT = N1->getOperand(0)->getValueType(0); 10293 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 10294 } 10295 return false; 10296 } 10297 10298 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 10299 SDValue N0 = N->getOperand(0); 10300 SDValue N1 = N->getOperand(1); 10301 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10302 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10303 EVT VT = N->getValueType(0); 10304 10305 if (N0CFP && N1CFP) // Constant fold 10306 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 10307 10308 if (N1CFP) { 10309 const APFloat &V = N1CFP->getValueAPF(); 10310 // copysign(x, c1) -> fabs(x) iff ispos(c1) 10311 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 10312 if (!V.isNegative()) { 10313 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 10314 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10315 } else { 10316 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 10317 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 10318 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 10319 } 10320 } 10321 10322 // copysign(fabs(x), y) -> copysign(x, y) 10323 // copysign(fneg(x), y) -> copysign(x, y) 10324 // copysign(copysign(x,z), y) -> copysign(x, y) 10325 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 10326 N0.getOpcode() == ISD::FCOPYSIGN) 10327 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1); 10328 10329 // copysign(x, abs(y)) -> abs(x) 10330 if (N1.getOpcode() == ISD::FABS) 10331 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10332 10333 // copysign(x, copysign(y,z)) -> copysign(x, z) 10334 if (N1.getOpcode() == ISD::FCOPYSIGN) 10335 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1)); 10336 10337 // copysign(x, fp_extend(y)) -> copysign(x, y) 10338 // copysign(x, fp_round(y)) -> copysign(x, y) 10339 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 10340 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0)); 10341 10342 return SDValue(); 10343 } 10344 10345 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 10346 SDValue N0 = N->getOperand(0); 10347 EVT VT = N->getValueType(0); 10348 EVT OpVT = N0.getValueType(); 10349 10350 // fold (sint_to_fp c1) -> c1fp 10351 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 10352 // ...but only if the target supports immediate floating-point values 10353 (!LegalOperations || 10354 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 10355 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 10356 10357 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 10358 // but UINT_TO_FP is legal on this target, try to convert. 10359 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 10360 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 10361 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 10362 if (DAG.SignBitIsZero(N0)) 10363 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 10364 } 10365 10366 // The next optimizations are desirable only if SELECT_CC can be lowered. 10367 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 10368 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 10369 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 10370 !VT.isVector() && 10371 (!LegalOperations || 10372 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 10373 SDLoc DL(N); 10374 SDValue Ops[] = 10375 { N0.getOperand(0), N0.getOperand(1), 10376 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10377 N0.getOperand(2) }; 10378 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10379 } 10380 10381 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 10382 // (select_cc x, y, 1.0, 0.0,, cc) 10383 if (N0.getOpcode() == ISD::ZERO_EXTEND && 10384 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 10385 (!LegalOperations || 10386 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 10387 SDLoc DL(N); 10388 SDValue Ops[] = 10389 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 10390 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10391 N0.getOperand(0).getOperand(2) }; 10392 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10393 } 10394 } 10395 10396 return SDValue(); 10397 } 10398 10399 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 10400 SDValue N0 = N->getOperand(0); 10401 EVT VT = N->getValueType(0); 10402 EVT OpVT = N0.getValueType(); 10403 10404 // fold (uint_to_fp c1) -> c1fp 10405 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 10406 // ...but only if the target supports immediate floating-point values 10407 (!LegalOperations || 10408 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 10409 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 10410 10411 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 10412 // but SINT_TO_FP is legal on this target, try to convert. 10413 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 10414 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 10415 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 10416 if (DAG.SignBitIsZero(N0)) 10417 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 10418 } 10419 10420 // The next optimizations are desirable only if SELECT_CC can be lowered. 10421 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 10422 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 10423 10424 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 10425 (!LegalOperations || 10426 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 10427 SDLoc DL(N); 10428 SDValue Ops[] = 10429 { N0.getOperand(0), N0.getOperand(1), 10430 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10431 N0.getOperand(2) }; 10432 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10433 } 10434 } 10435 10436 return SDValue(); 10437 } 10438 10439 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 10440 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 10441 SDValue N0 = N->getOperand(0); 10442 EVT VT = N->getValueType(0); 10443 10444 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 10445 return SDValue(); 10446 10447 SDValue Src = N0.getOperand(0); 10448 EVT SrcVT = Src.getValueType(); 10449 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 10450 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 10451 10452 // We can safely assume the conversion won't overflow the output range, 10453 // because (for example) (uint8_t)18293.f is undefined behavior. 10454 10455 // Since we can assume the conversion won't overflow, our decision as to 10456 // whether the input will fit in the float should depend on the minimum 10457 // of the input range and output range. 10458 10459 // This means this is also safe for a signed input and unsigned output, since 10460 // a negative input would lead to undefined behavior. 10461 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 10462 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 10463 unsigned ActualSize = std::min(InputSize, OutputSize); 10464 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 10465 10466 // We can only fold away the float conversion if the input range can be 10467 // represented exactly in the float range. 10468 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 10469 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 10470 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 10471 : ISD::ZERO_EXTEND; 10472 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 10473 } 10474 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 10475 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 10476 return DAG.getBitcast(VT, Src); 10477 } 10478 return SDValue(); 10479 } 10480 10481 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 10482 SDValue N0 = N->getOperand(0); 10483 EVT VT = N->getValueType(0); 10484 10485 // fold (fp_to_sint c1fp) -> c1 10486 if (isConstantFPBuildVectorOrConstantFP(N0)) 10487 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 10488 10489 return FoldIntToFPToInt(N, DAG); 10490 } 10491 10492 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 10493 SDValue N0 = N->getOperand(0); 10494 EVT VT = N->getValueType(0); 10495 10496 // fold (fp_to_uint c1fp) -> c1 10497 if (isConstantFPBuildVectorOrConstantFP(N0)) 10498 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 10499 10500 return FoldIntToFPToInt(N, DAG); 10501 } 10502 10503 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 10504 SDValue N0 = N->getOperand(0); 10505 SDValue N1 = N->getOperand(1); 10506 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10507 EVT VT = N->getValueType(0); 10508 10509 // fold (fp_round c1fp) -> c1fp 10510 if (N0CFP) 10511 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 10512 10513 // fold (fp_round (fp_extend x)) -> x 10514 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 10515 return N0.getOperand(0); 10516 10517 // fold (fp_round (fp_round x)) -> (fp_round x) 10518 if (N0.getOpcode() == ISD::FP_ROUND) { 10519 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 10520 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1; 10521 10522 // Skip this folding if it results in an fp_round from f80 to f16. 10523 // 10524 // f80 to f16 always generates an expensive (and as yet, unimplemented) 10525 // libcall to __truncxfhf2 instead of selecting native f16 conversion 10526 // instructions from f32 or f64. Moreover, the first (value-preserving) 10527 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 10528 // x86. 10529 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 10530 return SDValue(); 10531 10532 // If the first fp_round isn't a value preserving truncation, it might 10533 // introduce a tie in the second fp_round, that wouldn't occur in the 10534 // single-step fp_round we want to fold to. 10535 // In other words, double rounding isn't the same as rounding. 10536 // Also, this is a value preserving truncation iff both fp_round's are. 10537 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 10538 SDLoc DL(N); 10539 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 10540 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 10541 } 10542 } 10543 10544 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 10545 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 10546 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 10547 N0.getOperand(0), N1); 10548 AddToWorklist(Tmp.getNode()); 10549 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 10550 Tmp, N0.getOperand(1)); 10551 } 10552 10553 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 10554 return NewVSel; 10555 10556 return SDValue(); 10557 } 10558 10559 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 10560 SDValue N0 = N->getOperand(0); 10561 EVT VT = N->getValueType(0); 10562 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 10563 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10564 10565 // fold (fp_round_inreg c1fp) -> c1fp 10566 if (N0CFP && isTypeLegal(EVT)) { 10567 SDLoc DL(N); 10568 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 10569 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 10570 } 10571 10572 return SDValue(); 10573 } 10574 10575 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 10576 SDValue N0 = N->getOperand(0); 10577 EVT VT = N->getValueType(0); 10578 10579 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 10580 if (N->hasOneUse() && 10581 N->use_begin()->getOpcode() == ISD::FP_ROUND) 10582 return SDValue(); 10583 10584 // fold (fp_extend c1fp) -> c1fp 10585 if (isConstantFPBuildVectorOrConstantFP(N0)) 10586 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 10587 10588 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 10589 if (N0.getOpcode() == ISD::FP16_TO_FP && 10590 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 10591 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 10592 10593 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 10594 // value of X. 10595 if (N0.getOpcode() == ISD::FP_ROUND 10596 && N0.getConstantOperandVal(1) == 1) { 10597 SDValue In = N0.getOperand(0); 10598 if (In.getValueType() == VT) return In; 10599 if (VT.bitsLT(In.getValueType())) 10600 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 10601 In, N0.getOperand(1)); 10602 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 10603 } 10604 10605 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 10606 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10607 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 10608 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10609 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 10610 LN0->getChain(), 10611 LN0->getBasePtr(), N0.getValueType(), 10612 LN0->getMemOperand()); 10613 CombineTo(N, ExtLoad); 10614 CombineTo(N0.getNode(), 10615 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 10616 N0.getValueType(), ExtLoad, 10617 DAG.getIntPtrConstant(1, SDLoc(N0))), 10618 ExtLoad.getValue(1)); 10619 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10620 } 10621 10622 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 10623 return NewVSel; 10624 10625 return SDValue(); 10626 } 10627 10628 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 10629 SDValue N0 = N->getOperand(0); 10630 EVT VT = N->getValueType(0); 10631 10632 // fold (fceil c1) -> fceil(c1) 10633 if (isConstantFPBuildVectorOrConstantFP(N0)) 10634 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 10635 10636 return SDValue(); 10637 } 10638 10639 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 10640 SDValue N0 = N->getOperand(0); 10641 EVT VT = N->getValueType(0); 10642 10643 // fold (ftrunc c1) -> ftrunc(c1) 10644 if (isConstantFPBuildVectorOrConstantFP(N0)) 10645 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 10646 10647 return SDValue(); 10648 } 10649 10650 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 10651 SDValue N0 = N->getOperand(0); 10652 EVT VT = N->getValueType(0); 10653 10654 // fold (ffloor c1) -> ffloor(c1) 10655 if (isConstantFPBuildVectorOrConstantFP(N0)) 10656 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 10657 10658 return SDValue(); 10659 } 10660 10661 // FIXME: FNEG and FABS have a lot in common; refactor. 10662 SDValue DAGCombiner::visitFNEG(SDNode *N) { 10663 SDValue N0 = N->getOperand(0); 10664 EVT VT = N->getValueType(0); 10665 10666 // Constant fold FNEG. 10667 if (isConstantFPBuildVectorOrConstantFP(N0)) 10668 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 10669 10670 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 10671 &DAG.getTarget().Options)) 10672 return GetNegatedExpression(N0, DAG, LegalOperations); 10673 10674 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 10675 // constant pool values. 10676 if (!TLI.isFNegFree(VT) && 10677 N0.getOpcode() == ISD::BITCAST && 10678 N0.getNode()->hasOneUse()) { 10679 SDValue Int = N0.getOperand(0); 10680 EVT IntVT = Int.getValueType(); 10681 if (IntVT.isInteger() && !IntVT.isVector()) { 10682 APInt SignMask; 10683 if (N0.getValueType().isVector()) { 10684 // For a vector, get a mask such as 0x80... per scalar element 10685 // and splat it. 10686 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits()); 10687 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 10688 } else { 10689 // For a scalar, just generate 0x80... 10690 SignMask = APInt::getSignMask(IntVT.getSizeInBits()); 10691 } 10692 SDLoc DL0(N0); 10693 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 10694 DAG.getConstant(SignMask, DL0, IntVT)); 10695 AddToWorklist(Int.getNode()); 10696 return DAG.getBitcast(VT, Int); 10697 } 10698 } 10699 10700 // (fneg (fmul c, x)) -> (fmul -c, x) 10701 if (N0.getOpcode() == ISD::FMUL && 10702 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 10703 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10704 if (CFP1) { 10705 APFloat CVal = CFP1->getValueAPF(); 10706 CVal.changeSign(); 10707 if (Level >= AfterLegalizeDAG && 10708 (TLI.isFPImmLegal(CVal, VT) || 10709 TLI.isOperationLegal(ISD::ConstantFP, VT))) 10710 return DAG.getNode( 10711 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 10712 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)), 10713 N0->getFlags()); 10714 } 10715 } 10716 10717 return SDValue(); 10718 } 10719 10720 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 10721 SDValue N0 = N->getOperand(0); 10722 SDValue N1 = N->getOperand(1); 10723 EVT VT = N->getValueType(0); 10724 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10725 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10726 10727 if (N0CFP && N1CFP) { 10728 const APFloat &C0 = N0CFP->getValueAPF(); 10729 const APFloat &C1 = N1CFP->getValueAPF(); 10730 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 10731 } 10732 10733 // Canonicalize to constant on RHS. 10734 if (isConstantFPBuildVectorOrConstantFP(N0) && 10735 !isConstantFPBuildVectorOrConstantFP(N1)) 10736 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 10737 10738 return SDValue(); 10739 } 10740 10741 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 10742 SDValue N0 = N->getOperand(0); 10743 SDValue N1 = N->getOperand(1); 10744 EVT VT = N->getValueType(0); 10745 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10746 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10747 10748 if (N0CFP && N1CFP) { 10749 const APFloat &C0 = N0CFP->getValueAPF(); 10750 const APFloat &C1 = N1CFP->getValueAPF(); 10751 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 10752 } 10753 10754 // Canonicalize to constant on RHS. 10755 if (isConstantFPBuildVectorOrConstantFP(N0) && 10756 !isConstantFPBuildVectorOrConstantFP(N1)) 10757 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 10758 10759 return SDValue(); 10760 } 10761 10762 SDValue DAGCombiner::visitFABS(SDNode *N) { 10763 SDValue N0 = N->getOperand(0); 10764 EVT VT = N->getValueType(0); 10765 10766 // fold (fabs c1) -> fabs(c1) 10767 if (isConstantFPBuildVectorOrConstantFP(N0)) 10768 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10769 10770 // fold (fabs (fabs x)) -> (fabs x) 10771 if (N0.getOpcode() == ISD::FABS) 10772 return N->getOperand(0); 10773 10774 // fold (fabs (fneg x)) -> (fabs x) 10775 // fold (fabs (fcopysign x, y)) -> (fabs x) 10776 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 10777 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 10778 10779 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 10780 // constant pool values. 10781 if (!TLI.isFAbsFree(VT) && 10782 N0.getOpcode() == ISD::BITCAST && 10783 N0.getNode()->hasOneUse()) { 10784 SDValue Int = N0.getOperand(0); 10785 EVT IntVT = Int.getValueType(); 10786 if (IntVT.isInteger() && !IntVT.isVector()) { 10787 APInt SignMask; 10788 if (N0.getValueType().isVector()) { 10789 // For a vector, get a mask such as 0x7f... per scalar element 10790 // and splat it. 10791 SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits()); 10792 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 10793 } else { 10794 // For a scalar, just generate 0x7f... 10795 SignMask = ~APInt::getSignMask(IntVT.getSizeInBits()); 10796 } 10797 SDLoc DL(N0); 10798 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 10799 DAG.getConstant(SignMask, DL, IntVT)); 10800 AddToWorklist(Int.getNode()); 10801 return DAG.getBitcast(N->getValueType(0), Int); 10802 } 10803 } 10804 10805 return SDValue(); 10806 } 10807 10808 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 10809 SDValue Chain = N->getOperand(0); 10810 SDValue N1 = N->getOperand(1); 10811 SDValue N2 = N->getOperand(2); 10812 10813 // If N is a constant we could fold this into a fallthrough or unconditional 10814 // branch. However that doesn't happen very often in normal code, because 10815 // Instcombine/SimplifyCFG should have handled the available opportunities. 10816 // If we did this folding here, it would be necessary to update the 10817 // MachineBasicBlock CFG, which is awkward. 10818 10819 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 10820 // on the target. 10821 if (N1.getOpcode() == ISD::SETCC && 10822 TLI.isOperationLegalOrCustom(ISD::BR_CC, 10823 N1.getOperand(0).getValueType())) { 10824 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 10825 Chain, N1.getOperand(2), 10826 N1.getOperand(0), N1.getOperand(1), N2); 10827 } 10828 10829 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 10830 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 10831 (N1.getOperand(0).hasOneUse() && 10832 N1.getOperand(0).getOpcode() == ISD::SRL))) { 10833 SDNode *Trunc = nullptr; 10834 if (N1.getOpcode() == ISD::TRUNCATE) { 10835 // Look pass the truncate. 10836 Trunc = N1.getNode(); 10837 N1 = N1.getOperand(0); 10838 } 10839 10840 // Match this pattern so that we can generate simpler code: 10841 // 10842 // %a = ... 10843 // %b = and i32 %a, 2 10844 // %c = srl i32 %b, 1 10845 // brcond i32 %c ... 10846 // 10847 // into 10848 // 10849 // %a = ... 10850 // %b = and i32 %a, 2 10851 // %c = setcc eq %b, 0 10852 // brcond %c ... 10853 // 10854 // This applies only when the AND constant value has one bit set and the 10855 // SRL constant is equal to the log2 of the AND constant. The back-end is 10856 // smart enough to convert the result into a TEST/JMP sequence. 10857 SDValue Op0 = N1.getOperand(0); 10858 SDValue Op1 = N1.getOperand(1); 10859 10860 if (Op0.getOpcode() == ISD::AND && 10861 Op1.getOpcode() == ISD::Constant) { 10862 SDValue AndOp1 = Op0.getOperand(1); 10863 10864 if (AndOp1.getOpcode() == ISD::Constant) { 10865 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 10866 10867 if (AndConst.isPowerOf2() && 10868 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 10869 SDLoc DL(N); 10870 SDValue SetCC = 10871 DAG.getSetCC(DL, 10872 getSetCCResultType(Op0.getValueType()), 10873 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 10874 ISD::SETNE); 10875 10876 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 10877 MVT::Other, Chain, SetCC, N2); 10878 // Don't add the new BRCond into the worklist or else SimplifySelectCC 10879 // will convert it back to (X & C1) >> C2. 10880 CombineTo(N, NewBRCond, false); 10881 // Truncate is dead. 10882 if (Trunc) 10883 deleteAndRecombine(Trunc); 10884 // Replace the uses of SRL with SETCC 10885 WorklistRemover DeadNodes(*this); 10886 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 10887 deleteAndRecombine(N1.getNode()); 10888 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10889 } 10890 } 10891 } 10892 10893 if (Trunc) 10894 // Restore N1 if the above transformation doesn't match. 10895 N1 = N->getOperand(1); 10896 } 10897 10898 // Transform br(xor(x, y)) -> br(x != y) 10899 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 10900 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 10901 SDNode *TheXor = N1.getNode(); 10902 SDValue Op0 = TheXor->getOperand(0); 10903 SDValue Op1 = TheXor->getOperand(1); 10904 if (Op0.getOpcode() == Op1.getOpcode()) { 10905 // Avoid missing important xor optimizations. 10906 if (SDValue Tmp = visitXOR(TheXor)) { 10907 if (Tmp.getNode() != TheXor) { 10908 DEBUG(dbgs() << "\nReplacing.8 "; 10909 TheXor->dump(&DAG); 10910 dbgs() << "\nWith: "; 10911 Tmp.getNode()->dump(&DAG); 10912 dbgs() << '\n'); 10913 WorklistRemover DeadNodes(*this); 10914 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 10915 deleteAndRecombine(TheXor); 10916 return DAG.getNode(ISD::BRCOND, SDLoc(N), 10917 MVT::Other, Chain, Tmp, N2); 10918 } 10919 10920 // visitXOR has changed XOR's operands or replaced the XOR completely, 10921 // bail out. 10922 return SDValue(N, 0); 10923 } 10924 } 10925 10926 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 10927 bool Equal = false; 10928 if (isOneConstant(Op0) && Op0.hasOneUse() && 10929 Op0.getOpcode() == ISD::XOR) { 10930 TheXor = Op0.getNode(); 10931 Equal = true; 10932 } 10933 10934 EVT SetCCVT = N1.getValueType(); 10935 if (LegalTypes) 10936 SetCCVT = getSetCCResultType(SetCCVT); 10937 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 10938 SetCCVT, 10939 Op0, Op1, 10940 Equal ? ISD::SETEQ : ISD::SETNE); 10941 // Replace the uses of XOR with SETCC 10942 WorklistRemover DeadNodes(*this); 10943 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 10944 deleteAndRecombine(N1.getNode()); 10945 return DAG.getNode(ISD::BRCOND, SDLoc(N), 10946 MVT::Other, Chain, SetCC, N2); 10947 } 10948 } 10949 10950 return SDValue(); 10951 } 10952 10953 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 10954 // 10955 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 10956 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 10957 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 10958 10959 // If N is a constant we could fold this into a fallthrough or unconditional 10960 // branch. However that doesn't happen very often in normal code, because 10961 // Instcombine/SimplifyCFG should have handled the available opportunities. 10962 // If we did this folding here, it would be necessary to update the 10963 // MachineBasicBlock CFG, which is awkward. 10964 10965 // Use SimplifySetCC to simplify SETCC's. 10966 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 10967 CondLHS, CondRHS, CC->get(), SDLoc(N), 10968 false); 10969 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 10970 10971 // fold to a simpler setcc 10972 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 10973 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 10974 N->getOperand(0), Simp.getOperand(2), 10975 Simp.getOperand(0), Simp.getOperand(1), 10976 N->getOperand(4)); 10977 10978 return SDValue(); 10979 } 10980 10981 /// Return true if 'Use' is a load or a store that uses N as its base pointer 10982 /// and that N may be folded in the load / store addressing mode. 10983 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 10984 SelectionDAG &DAG, 10985 const TargetLowering &TLI) { 10986 EVT VT; 10987 unsigned AS; 10988 10989 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 10990 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 10991 return false; 10992 VT = LD->getMemoryVT(); 10993 AS = LD->getAddressSpace(); 10994 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 10995 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 10996 return false; 10997 VT = ST->getMemoryVT(); 10998 AS = ST->getAddressSpace(); 10999 } else 11000 return false; 11001 11002 TargetLowering::AddrMode AM; 11003 if (N->getOpcode() == ISD::ADD) { 11004 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11005 if (Offset) 11006 // [reg +/- imm] 11007 AM.BaseOffs = Offset->getSExtValue(); 11008 else 11009 // [reg +/- reg] 11010 AM.Scale = 1; 11011 } else if (N->getOpcode() == ISD::SUB) { 11012 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11013 if (Offset) 11014 // [reg +/- imm] 11015 AM.BaseOffs = -Offset->getSExtValue(); 11016 else 11017 // [reg +/- reg] 11018 AM.Scale = 1; 11019 } else 11020 return false; 11021 11022 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 11023 VT.getTypeForEVT(*DAG.getContext()), AS); 11024 } 11025 11026 /// Try turning a load/store into a pre-indexed load/store when the base 11027 /// pointer is an add or subtract and it has other uses besides the load/store. 11028 /// After the transformation, the new indexed load/store has effectively folded 11029 /// the add/subtract in and all of its other uses are redirected to the 11030 /// new load/store. 11031 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 11032 if (Level < AfterLegalizeDAG) 11033 return false; 11034 11035 bool isLoad = true; 11036 SDValue Ptr; 11037 EVT VT; 11038 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11039 if (LD->isIndexed()) 11040 return false; 11041 VT = LD->getMemoryVT(); 11042 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 11043 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 11044 return false; 11045 Ptr = LD->getBasePtr(); 11046 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11047 if (ST->isIndexed()) 11048 return false; 11049 VT = ST->getMemoryVT(); 11050 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 11051 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 11052 return false; 11053 Ptr = ST->getBasePtr(); 11054 isLoad = false; 11055 } else { 11056 return false; 11057 } 11058 11059 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 11060 // out. There is no reason to make this a preinc/predec. 11061 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 11062 Ptr.getNode()->hasOneUse()) 11063 return false; 11064 11065 // Ask the target to do addressing mode selection. 11066 SDValue BasePtr; 11067 SDValue Offset; 11068 ISD::MemIndexedMode AM = ISD::UNINDEXED; 11069 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 11070 return false; 11071 11072 // Backends without true r+i pre-indexed forms may need to pass a 11073 // constant base with a variable offset so that constant coercion 11074 // will work with the patterns in canonical form. 11075 bool Swapped = false; 11076 if (isa<ConstantSDNode>(BasePtr)) { 11077 std::swap(BasePtr, Offset); 11078 Swapped = true; 11079 } 11080 11081 // Don't create a indexed load / store with zero offset. 11082 if (isNullConstant(Offset)) 11083 return false; 11084 11085 // Try turning it into a pre-indexed load / store except when: 11086 // 1) The new base ptr is a frame index. 11087 // 2) If N is a store and the new base ptr is either the same as or is a 11088 // predecessor of the value being stored. 11089 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 11090 // that would create a cycle. 11091 // 4) All uses are load / store ops that use it as old base ptr. 11092 11093 // Check #1. Preinc'ing a frame index would require copying the stack pointer 11094 // (plus the implicit offset) to a register to preinc anyway. 11095 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 11096 return false; 11097 11098 // Check #2. 11099 if (!isLoad) { 11100 SDValue Val = cast<StoreSDNode>(N)->getValue(); 11101 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 11102 return false; 11103 } 11104 11105 // Caches for hasPredecessorHelper. 11106 SmallPtrSet<const SDNode *, 32> Visited; 11107 SmallVector<const SDNode *, 16> Worklist; 11108 Worklist.push_back(N); 11109 11110 // If the offset is a constant, there may be other adds of constants that 11111 // can be folded with this one. We should do this to avoid having to keep 11112 // a copy of the original base pointer. 11113 SmallVector<SDNode *, 16> OtherUses; 11114 if (isa<ConstantSDNode>(Offset)) 11115 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 11116 UE = BasePtr.getNode()->use_end(); 11117 UI != UE; ++UI) { 11118 SDUse &Use = UI.getUse(); 11119 // Skip the use that is Ptr and uses of other results from BasePtr's 11120 // node (important for nodes that return multiple results). 11121 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 11122 continue; 11123 11124 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 11125 continue; 11126 11127 if (Use.getUser()->getOpcode() != ISD::ADD && 11128 Use.getUser()->getOpcode() != ISD::SUB) { 11129 OtherUses.clear(); 11130 break; 11131 } 11132 11133 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 11134 if (!isa<ConstantSDNode>(Op1)) { 11135 OtherUses.clear(); 11136 break; 11137 } 11138 11139 // FIXME: In some cases, we can be smarter about this. 11140 if (Op1.getValueType() != Offset.getValueType()) { 11141 OtherUses.clear(); 11142 break; 11143 } 11144 11145 OtherUses.push_back(Use.getUser()); 11146 } 11147 11148 if (Swapped) 11149 std::swap(BasePtr, Offset); 11150 11151 // Now check for #3 and #4. 11152 bool RealUse = false; 11153 11154 for (SDNode *Use : Ptr.getNode()->uses()) { 11155 if (Use == N) 11156 continue; 11157 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 11158 return false; 11159 11160 // If Ptr may be folded in addressing mode of other use, then it's 11161 // not profitable to do this transformation. 11162 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 11163 RealUse = true; 11164 } 11165 11166 if (!RealUse) 11167 return false; 11168 11169 SDValue Result; 11170 if (isLoad) 11171 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 11172 BasePtr, Offset, AM); 11173 else 11174 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 11175 BasePtr, Offset, AM); 11176 ++PreIndexedNodes; 11177 ++NodesCombined; 11178 DEBUG(dbgs() << "\nReplacing.4 "; 11179 N->dump(&DAG); 11180 dbgs() << "\nWith: "; 11181 Result.getNode()->dump(&DAG); 11182 dbgs() << '\n'); 11183 WorklistRemover DeadNodes(*this); 11184 if (isLoad) { 11185 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 11186 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 11187 } else { 11188 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 11189 } 11190 11191 // Finally, since the node is now dead, remove it from the graph. 11192 deleteAndRecombine(N); 11193 11194 if (Swapped) 11195 std::swap(BasePtr, Offset); 11196 11197 // Replace other uses of BasePtr that can be updated to use Ptr 11198 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 11199 unsigned OffsetIdx = 1; 11200 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 11201 OffsetIdx = 0; 11202 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 11203 BasePtr.getNode() && "Expected BasePtr operand"); 11204 11205 // We need to replace ptr0 in the following expression: 11206 // x0 * offset0 + y0 * ptr0 = t0 11207 // knowing that 11208 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 11209 // 11210 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 11211 // indexed load/store and the expression that needs to be re-written. 11212 // 11213 // Therefore, we have: 11214 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 11215 11216 ConstantSDNode *CN = 11217 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 11218 int X0, X1, Y0, Y1; 11219 const APInt &Offset0 = CN->getAPIntValue(); 11220 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 11221 11222 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 11223 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 11224 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 11225 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 11226 11227 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 11228 11229 APInt CNV = Offset0; 11230 if (X0 < 0) CNV = -CNV; 11231 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 11232 else CNV = CNV - Offset1; 11233 11234 SDLoc DL(OtherUses[i]); 11235 11236 // We can now generate the new expression. 11237 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 11238 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 11239 11240 SDValue NewUse = DAG.getNode(Opcode, 11241 DL, 11242 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 11243 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 11244 deleteAndRecombine(OtherUses[i]); 11245 } 11246 11247 // Replace the uses of Ptr with uses of the updated base value. 11248 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 11249 deleteAndRecombine(Ptr.getNode()); 11250 11251 return true; 11252 } 11253 11254 /// Try to combine a load/store with a add/sub of the base pointer node into a 11255 /// post-indexed load/store. The transformation folded the add/subtract into the 11256 /// new indexed load/store effectively and all of its uses are redirected to the 11257 /// new load/store. 11258 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 11259 if (Level < AfterLegalizeDAG) 11260 return false; 11261 11262 bool isLoad = true; 11263 SDValue Ptr; 11264 EVT VT; 11265 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11266 if (LD->isIndexed()) 11267 return false; 11268 VT = LD->getMemoryVT(); 11269 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 11270 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 11271 return false; 11272 Ptr = LD->getBasePtr(); 11273 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11274 if (ST->isIndexed()) 11275 return false; 11276 VT = ST->getMemoryVT(); 11277 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 11278 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 11279 return false; 11280 Ptr = ST->getBasePtr(); 11281 isLoad = false; 11282 } else { 11283 return false; 11284 } 11285 11286 if (Ptr.getNode()->hasOneUse()) 11287 return false; 11288 11289 for (SDNode *Op : Ptr.getNode()->uses()) { 11290 if (Op == N || 11291 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 11292 continue; 11293 11294 SDValue BasePtr; 11295 SDValue Offset; 11296 ISD::MemIndexedMode AM = ISD::UNINDEXED; 11297 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 11298 // Don't create a indexed load / store with zero offset. 11299 if (isNullConstant(Offset)) 11300 continue; 11301 11302 // Try turning it into a post-indexed load / store except when 11303 // 1) All uses are load / store ops that use it as base ptr (and 11304 // it may be folded as addressing mmode). 11305 // 2) Op must be independent of N, i.e. Op is neither a predecessor 11306 // nor a successor of N. Otherwise, if Op is folded that would 11307 // create a cycle. 11308 11309 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 11310 continue; 11311 11312 // Check for #1. 11313 bool TryNext = false; 11314 for (SDNode *Use : BasePtr.getNode()->uses()) { 11315 if (Use == Ptr.getNode()) 11316 continue; 11317 11318 // If all the uses are load / store addresses, then don't do the 11319 // transformation. 11320 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 11321 bool RealUse = false; 11322 for (SDNode *UseUse : Use->uses()) { 11323 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 11324 RealUse = true; 11325 } 11326 11327 if (!RealUse) { 11328 TryNext = true; 11329 break; 11330 } 11331 } 11332 } 11333 11334 if (TryNext) 11335 continue; 11336 11337 // Check for #2 11338 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 11339 SDValue Result = isLoad 11340 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 11341 BasePtr, Offset, AM) 11342 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 11343 BasePtr, Offset, AM); 11344 ++PostIndexedNodes; 11345 ++NodesCombined; 11346 DEBUG(dbgs() << "\nReplacing.5 "; 11347 N->dump(&DAG); 11348 dbgs() << "\nWith: "; 11349 Result.getNode()->dump(&DAG); 11350 dbgs() << '\n'); 11351 WorklistRemover DeadNodes(*this); 11352 if (isLoad) { 11353 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 11354 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 11355 } else { 11356 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 11357 } 11358 11359 // Finally, since the node is now dead, remove it from the graph. 11360 deleteAndRecombine(N); 11361 11362 // Replace the uses of Use with uses of the updated base value. 11363 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 11364 Result.getValue(isLoad ? 1 : 0)); 11365 deleteAndRecombine(Op); 11366 return true; 11367 } 11368 } 11369 } 11370 11371 return false; 11372 } 11373 11374 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 11375 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 11376 ISD::MemIndexedMode AM = LD->getAddressingMode(); 11377 assert(AM != ISD::UNINDEXED); 11378 SDValue BP = LD->getOperand(1); 11379 SDValue Inc = LD->getOperand(2); 11380 11381 // Some backends use TargetConstants for load offsets, but don't expect 11382 // TargetConstants in general ADD nodes. We can convert these constants into 11383 // regular Constants (if the constant is not opaque). 11384 assert((Inc.getOpcode() != ISD::TargetConstant || 11385 !cast<ConstantSDNode>(Inc)->isOpaque()) && 11386 "Cannot split out indexing using opaque target constants"); 11387 if (Inc.getOpcode() == ISD::TargetConstant) { 11388 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 11389 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 11390 ConstInc->getValueType(0)); 11391 } 11392 11393 unsigned Opc = 11394 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 11395 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 11396 } 11397 11398 SDValue DAGCombiner::visitLOAD(SDNode *N) { 11399 LoadSDNode *LD = cast<LoadSDNode>(N); 11400 SDValue Chain = LD->getChain(); 11401 SDValue Ptr = LD->getBasePtr(); 11402 11403 // If load is not volatile and there are no uses of the loaded value (and 11404 // the updated indexed value in case of indexed loads), change uses of the 11405 // chain value into uses of the chain input (i.e. delete the dead load). 11406 if (!LD->isVolatile()) { 11407 if (N->getValueType(1) == MVT::Other) { 11408 // Unindexed loads. 11409 if (!N->hasAnyUseOfValue(0)) { 11410 // It's not safe to use the two value CombineTo variant here. e.g. 11411 // v1, chain2 = load chain1, loc 11412 // v2, chain3 = load chain2, loc 11413 // v3 = add v2, c 11414 // Now we replace use of chain2 with chain1. This makes the second load 11415 // isomorphic to the one we are deleting, and thus makes this load live. 11416 DEBUG(dbgs() << "\nReplacing.6 "; 11417 N->dump(&DAG); 11418 dbgs() << "\nWith chain: "; 11419 Chain.getNode()->dump(&DAG); 11420 dbgs() << "\n"); 11421 WorklistRemover DeadNodes(*this); 11422 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 11423 AddUsersToWorklist(Chain.getNode()); 11424 if (N->use_empty()) 11425 deleteAndRecombine(N); 11426 11427 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11428 } 11429 } else { 11430 // Indexed loads. 11431 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 11432 11433 // If this load has an opaque TargetConstant offset, then we cannot split 11434 // the indexing into an add/sub directly (that TargetConstant may not be 11435 // valid for a different type of node, and we cannot convert an opaque 11436 // target constant into a regular constant). 11437 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 11438 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 11439 11440 if (!N->hasAnyUseOfValue(0) && 11441 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 11442 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 11443 SDValue Index; 11444 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 11445 Index = SplitIndexingFromLoad(LD); 11446 // Try to fold the base pointer arithmetic into subsequent loads and 11447 // stores. 11448 AddUsersToWorklist(N); 11449 } else 11450 Index = DAG.getUNDEF(N->getValueType(1)); 11451 DEBUG(dbgs() << "\nReplacing.7 "; 11452 N->dump(&DAG); 11453 dbgs() << "\nWith: "; 11454 Undef.getNode()->dump(&DAG); 11455 dbgs() << " and 2 other values\n"); 11456 WorklistRemover DeadNodes(*this); 11457 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 11458 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 11459 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 11460 deleteAndRecombine(N); 11461 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11462 } 11463 } 11464 } 11465 11466 // If this load is directly stored, replace the load value with the stored 11467 // value. 11468 // TODO: Handle store large -> read small portion. 11469 // TODO: Handle TRUNCSTORE/LOADEXT 11470 if (OptLevel != CodeGenOpt::None && 11471 ISD::isNormalLoad(N) && !LD->isVolatile()) { 11472 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 11473 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 11474 if (PrevST->getBasePtr() == Ptr && 11475 PrevST->getValue().getValueType() == N->getValueType(0)) 11476 return CombineTo(N, PrevST->getOperand(1), Chain); 11477 } 11478 } 11479 11480 // Try to infer better alignment information than the load already has. 11481 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 11482 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 11483 if (Align > LD->getMemOperand()->getBaseAlignment()) { 11484 SDValue NewLoad = DAG.getExtLoad( 11485 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 11486 LD->getPointerInfo(), LD->getMemoryVT(), Align, 11487 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 11488 if (NewLoad.getNode() != N) 11489 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 11490 } 11491 } 11492 } 11493 11494 if (LD->isUnindexed()) { 11495 // Walk up chain skipping non-aliasing memory nodes. 11496 SDValue BetterChain = FindBetterChain(N, Chain); 11497 11498 // If there is a better chain. 11499 if (Chain != BetterChain) { 11500 SDValue ReplLoad; 11501 11502 // Replace the chain to void dependency. 11503 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 11504 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 11505 BetterChain, Ptr, LD->getMemOperand()); 11506 } else { 11507 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 11508 LD->getValueType(0), 11509 BetterChain, Ptr, LD->getMemoryVT(), 11510 LD->getMemOperand()); 11511 } 11512 11513 // Create token factor to keep old chain connected. 11514 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 11515 MVT::Other, Chain, ReplLoad.getValue(1)); 11516 11517 // Replace uses with load result and token factor 11518 return CombineTo(N, ReplLoad.getValue(0), Token); 11519 } 11520 } 11521 11522 // Try transforming N to an indexed load. 11523 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 11524 return SDValue(N, 0); 11525 11526 // Try to slice up N to more direct loads if the slices are mapped to 11527 // different register banks or pairing can take place. 11528 if (SliceUpLoad(N)) 11529 return SDValue(N, 0); 11530 11531 return SDValue(); 11532 } 11533 11534 namespace { 11535 /// \brief Helper structure used to slice a load in smaller loads. 11536 /// Basically a slice is obtained from the following sequence: 11537 /// Origin = load Ty1, Base 11538 /// Shift = srl Ty1 Origin, CstTy Amount 11539 /// Inst = trunc Shift to Ty2 11540 /// 11541 /// Then, it will be rewritten into: 11542 /// Slice = load SliceTy, Base + SliceOffset 11543 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 11544 /// 11545 /// SliceTy is deduced from the number of bits that are actually used to 11546 /// build Inst. 11547 struct LoadedSlice { 11548 /// \brief Helper structure used to compute the cost of a slice. 11549 struct Cost { 11550 /// Are we optimizing for code size. 11551 bool ForCodeSize; 11552 /// Various cost. 11553 unsigned Loads; 11554 unsigned Truncates; 11555 unsigned CrossRegisterBanksCopies; 11556 unsigned ZExts; 11557 unsigned Shift; 11558 11559 Cost(bool ForCodeSize = false) 11560 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 11561 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 11562 11563 /// \brief Get the cost of one isolated slice. 11564 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 11565 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 11566 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 11567 EVT TruncType = LS.Inst->getValueType(0); 11568 EVT LoadedType = LS.getLoadedType(); 11569 if (TruncType != LoadedType && 11570 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 11571 ZExts = 1; 11572 } 11573 11574 /// \brief Account for slicing gain in the current cost. 11575 /// Slicing provide a few gains like removing a shift or a 11576 /// truncate. This method allows to grow the cost of the original 11577 /// load with the gain from this slice. 11578 void addSliceGain(const LoadedSlice &LS) { 11579 // Each slice saves a truncate. 11580 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 11581 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 11582 LS.Inst->getValueType(0))) 11583 ++Truncates; 11584 // If there is a shift amount, this slice gets rid of it. 11585 if (LS.Shift) 11586 ++Shift; 11587 // If this slice can merge a cross register bank copy, account for it. 11588 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 11589 ++CrossRegisterBanksCopies; 11590 } 11591 11592 Cost &operator+=(const Cost &RHS) { 11593 Loads += RHS.Loads; 11594 Truncates += RHS.Truncates; 11595 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 11596 ZExts += RHS.ZExts; 11597 Shift += RHS.Shift; 11598 return *this; 11599 } 11600 11601 bool operator==(const Cost &RHS) const { 11602 return Loads == RHS.Loads && Truncates == RHS.Truncates && 11603 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 11604 ZExts == RHS.ZExts && Shift == RHS.Shift; 11605 } 11606 11607 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 11608 11609 bool operator<(const Cost &RHS) const { 11610 // Assume cross register banks copies are as expensive as loads. 11611 // FIXME: Do we want some more target hooks? 11612 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 11613 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 11614 // Unless we are optimizing for code size, consider the 11615 // expensive operation first. 11616 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 11617 return ExpensiveOpsLHS < ExpensiveOpsRHS; 11618 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 11619 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 11620 } 11621 11622 bool operator>(const Cost &RHS) const { return RHS < *this; } 11623 11624 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 11625 11626 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 11627 }; 11628 // The last instruction that represent the slice. This should be a 11629 // truncate instruction. 11630 SDNode *Inst; 11631 // The original load instruction. 11632 LoadSDNode *Origin; 11633 // The right shift amount in bits from the original load. 11634 unsigned Shift; 11635 // The DAG from which Origin came from. 11636 // This is used to get some contextual information about legal types, etc. 11637 SelectionDAG *DAG; 11638 11639 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 11640 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 11641 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 11642 11643 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 11644 /// \return Result is \p BitWidth and has used bits set to 1 and 11645 /// not used bits set to 0. 11646 APInt getUsedBits() const { 11647 // Reproduce the trunc(lshr) sequence: 11648 // - Start from the truncated value. 11649 // - Zero extend to the desired bit width. 11650 // - Shift left. 11651 assert(Origin && "No original load to compare against."); 11652 unsigned BitWidth = Origin->getValueSizeInBits(0); 11653 assert(Inst && "This slice is not bound to an instruction"); 11654 assert(Inst->getValueSizeInBits(0) <= BitWidth && 11655 "Extracted slice is bigger than the whole type!"); 11656 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 11657 UsedBits.setAllBits(); 11658 UsedBits = UsedBits.zext(BitWidth); 11659 UsedBits <<= Shift; 11660 return UsedBits; 11661 } 11662 11663 /// \brief Get the size of the slice to be loaded in bytes. 11664 unsigned getLoadedSize() const { 11665 unsigned SliceSize = getUsedBits().countPopulation(); 11666 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 11667 return SliceSize / 8; 11668 } 11669 11670 /// \brief Get the type that will be loaded for this slice. 11671 /// Note: This may not be the final type for the slice. 11672 EVT getLoadedType() const { 11673 assert(DAG && "Missing context"); 11674 LLVMContext &Ctxt = *DAG->getContext(); 11675 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 11676 } 11677 11678 /// \brief Get the alignment of the load used for this slice. 11679 unsigned getAlignment() const { 11680 unsigned Alignment = Origin->getAlignment(); 11681 unsigned Offset = getOffsetFromBase(); 11682 if (Offset != 0) 11683 Alignment = MinAlign(Alignment, Alignment + Offset); 11684 return Alignment; 11685 } 11686 11687 /// \brief Check if this slice can be rewritten with legal operations. 11688 bool isLegal() const { 11689 // An invalid slice is not legal. 11690 if (!Origin || !Inst || !DAG) 11691 return false; 11692 11693 // Offsets are for indexed load only, we do not handle that. 11694 if (!Origin->getOffset().isUndef()) 11695 return false; 11696 11697 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 11698 11699 // Check that the type is legal. 11700 EVT SliceType = getLoadedType(); 11701 if (!TLI.isTypeLegal(SliceType)) 11702 return false; 11703 11704 // Check that the load is legal for this type. 11705 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 11706 return false; 11707 11708 // Check that the offset can be computed. 11709 // 1. Check its type. 11710 EVT PtrType = Origin->getBasePtr().getValueType(); 11711 if (PtrType == MVT::Untyped || PtrType.isExtended()) 11712 return false; 11713 11714 // 2. Check that it fits in the immediate. 11715 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 11716 return false; 11717 11718 // 3. Check that the computation is legal. 11719 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 11720 return false; 11721 11722 // Check that the zext is legal if it needs one. 11723 EVT TruncateType = Inst->getValueType(0); 11724 if (TruncateType != SliceType && 11725 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 11726 return false; 11727 11728 return true; 11729 } 11730 11731 /// \brief Get the offset in bytes of this slice in the original chunk of 11732 /// bits. 11733 /// \pre DAG != nullptr. 11734 uint64_t getOffsetFromBase() const { 11735 assert(DAG && "Missing context."); 11736 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 11737 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 11738 uint64_t Offset = Shift / 8; 11739 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 11740 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 11741 "The size of the original loaded type is not a multiple of a" 11742 " byte."); 11743 // If Offset is bigger than TySizeInBytes, it means we are loading all 11744 // zeros. This should have been optimized before in the process. 11745 assert(TySizeInBytes > Offset && 11746 "Invalid shift amount for given loaded size"); 11747 if (IsBigEndian) 11748 Offset = TySizeInBytes - Offset - getLoadedSize(); 11749 return Offset; 11750 } 11751 11752 /// \brief Generate the sequence of instructions to load the slice 11753 /// represented by this object and redirect the uses of this slice to 11754 /// this new sequence of instructions. 11755 /// \pre this->Inst && this->Origin are valid Instructions and this 11756 /// object passed the legal check: LoadedSlice::isLegal returned true. 11757 /// \return The last instruction of the sequence used to load the slice. 11758 SDValue loadSlice() const { 11759 assert(Inst && Origin && "Unable to replace a non-existing slice."); 11760 const SDValue &OldBaseAddr = Origin->getBasePtr(); 11761 SDValue BaseAddr = OldBaseAddr; 11762 // Get the offset in that chunk of bytes w.r.t. the endianness. 11763 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 11764 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 11765 if (Offset) { 11766 // BaseAddr = BaseAddr + Offset. 11767 EVT ArithType = BaseAddr.getValueType(); 11768 SDLoc DL(Origin); 11769 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 11770 DAG->getConstant(Offset, DL, ArithType)); 11771 } 11772 11773 // Create the type of the loaded slice according to its size. 11774 EVT SliceType = getLoadedType(); 11775 11776 // Create the load for the slice. 11777 SDValue LastInst = 11778 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 11779 Origin->getPointerInfo().getWithOffset(Offset), 11780 getAlignment(), Origin->getMemOperand()->getFlags()); 11781 // If the final type is not the same as the loaded type, this means that 11782 // we have to pad with zero. Create a zero extend for that. 11783 EVT FinalType = Inst->getValueType(0); 11784 if (SliceType != FinalType) 11785 LastInst = 11786 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 11787 return LastInst; 11788 } 11789 11790 /// \brief Check if this slice can be merged with an expensive cross register 11791 /// bank copy. E.g., 11792 /// i = load i32 11793 /// f = bitcast i32 i to float 11794 bool canMergeExpensiveCrossRegisterBankCopy() const { 11795 if (!Inst || !Inst->hasOneUse()) 11796 return false; 11797 SDNode *Use = *Inst->use_begin(); 11798 if (Use->getOpcode() != ISD::BITCAST) 11799 return false; 11800 assert(DAG && "Missing context"); 11801 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 11802 EVT ResVT = Use->getValueType(0); 11803 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 11804 const TargetRegisterClass *ArgRC = 11805 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 11806 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 11807 return false; 11808 11809 // At this point, we know that we perform a cross-register-bank copy. 11810 // Check if it is expensive. 11811 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 11812 // Assume bitcasts are cheap, unless both register classes do not 11813 // explicitly share a common sub class. 11814 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 11815 return false; 11816 11817 // Check if it will be merged with the load. 11818 // 1. Check the alignment constraint. 11819 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 11820 ResVT.getTypeForEVT(*DAG->getContext())); 11821 11822 if (RequiredAlignment > getAlignment()) 11823 return false; 11824 11825 // 2. Check that the load is a legal operation for that type. 11826 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 11827 return false; 11828 11829 // 3. Check that we do not have a zext in the way. 11830 if (Inst->getValueType(0) != getLoadedType()) 11831 return false; 11832 11833 return true; 11834 } 11835 }; 11836 } 11837 11838 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 11839 /// \p UsedBits looks like 0..0 1..1 0..0. 11840 static bool areUsedBitsDense(const APInt &UsedBits) { 11841 // If all the bits are one, this is dense! 11842 if (UsedBits.isAllOnesValue()) 11843 return true; 11844 11845 // Get rid of the unused bits on the right. 11846 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 11847 // Get rid of the unused bits on the left. 11848 if (NarrowedUsedBits.countLeadingZeros()) 11849 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 11850 // Check that the chunk of bits is completely used. 11851 return NarrowedUsedBits.isAllOnesValue(); 11852 } 11853 11854 /// \brief Check whether or not \p First and \p Second are next to each other 11855 /// in memory. This means that there is no hole between the bits loaded 11856 /// by \p First and the bits loaded by \p Second. 11857 static bool areSlicesNextToEachOther(const LoadedSlice &First, 11858 const LoadedSlice &Second) { 11859 assert(First.Origin == Second.Origin && First.Origin && 11860 "Unable to match different memory origins."); 11861 APInt UsedBits = First.getUsedBits(); 11862 assert((UsedBits & Second.getUsedBits()) == 0 && 11863 "Slices are not supposed to overlap."); 11864 UsedBits |= Second.getUsedBits(); 11865 return areUsedBitsDense(UsedBits); 11866 } 11867 11868 /// \brief Adjust the \p GlobalLSCost according to the target 11869 /// paring capabilities and the layout of the slices. 11870 /// \pre \p GlobalLSCost should account for at least as many loads as 11871 /// there is in the slices in \p LoadedSlices. 11872 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 11873 LoadedSlice::Cost &GlobalLSCost) { 11874 unsigned NumberOfSlices = LoadedSlices.size(); 11875 // If there is less than 2 elements, no pairing is possible. 11876 if (NumberOfSlices < 2) 11877 return; 11878 11879 // Sort the slices so that elements that are likely to be next to each 11880 // other in memory are next to each other in the list. 11881 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 11882 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 11883 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 11884 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 11885 }); 11886 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 11887 // First (resp. Second) is the first (resp. Second) potentially candidate 11888 // to be placed in a paired load. 11889 const LoadedSlice *First = nullptr; 11890 const LoadedSlice *Second = nullptr; 11891 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 11892 // Set the beginning of the pair. 11893 First = Second) { 11894 11895 Second = &LoadedSlices[CurrSlice]; 11896 11897 // If First is NULL, it means we start a new pair. 11898 // Get to the next slice. 11899 if (!First) 11900 continue; 11901 11902 EVT LoadedType = First->getLoadedType(); 11903 11904 // If the types of the slices are different, we cannot pair them. 11905 if (LoadedType != Second->getLoadedType()) 11906 continue; 11907 11908 // Check if the target supplies paired loads for this type. 11909 unsigned RequiredAlignment = 0; 11910 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 11911 // move to the next pair, this type is hopeless. 11912 Second = nullptr; 11913 continue; 11914 } 11915 // Check if we meet the alignment requirement. 11916 if (RequiredAlignment > First->getAlignment()) 11917 continue; 11918 11919 // Check that both loads are next to each other in memory. 11920 if (!areSlicesNextToEachOther(*First, *Second)) 11921 continue; 11922 11923 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 11924 --GlobalLSCost.Loads; 11925 // Move to the next pair. 11926 Second = nullptr; 11927 } 11928 } 11929 11930 /// \brief Check the profitability of all involved LoadedSlice. 11931 /// Currently, it is considered profitable if there is exactly two 11932 /// involved slices (1) which are (2) next to each other in memory, and 11933 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 11934 /// 11935 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 11936 /// the elements themselves. 11937 /// 11938 /// FIXME: When the cost model will be mature enough, we can relax 11939 /// constraints (1) and (2). 11940 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 11941 const APInt &UsedBits, bool ForCodeSize) { 11942 unsigned NumberOfSlices = LoadedSlices.size(); 11943 if (StressLoadSlicing) 11944 return NumberOfSlices > 1; 11945 11946 // Check (1). 11947 if (NumberOfSlices != 2) 11948 return false; 11949 11950 // Check (2). 11951 if (!areUsedBitsDense(UsedBits)) 11952 return false; 11953 11954 // Check (3). 11955 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 11956 // The original code has one big load. 11957 OrigCost.Loads = 1; 11958 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 11959 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 11960 // Accumulate the cost of all the slices. 11961 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 11962 GlobalSlicingCost += SliceCost; 11963 11964 // Account as cost in the original configuration the gain obtained 11965 // with the current slices. 11966 OrigCost.addSliceGain(LS); 11967 } 11968 11969 // If the target supports paired load, adjust the cost accordingly. 11970 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 11971 return OrigCost > GlobalSlicingCost; 11972 } 11973 11974 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 11975 /// operations, split it in the various pieces being extracted. 11976 /// 11977 /// This sort of thing is introduced by SROA. 11978 /// This slicing takes care not to insert overlapping loads. 11979 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 11980 bool DAGCombiner::SliceUpLoad(SDNode *N) { 11981 if (Level < AfterLegalizeDAG) 11982 return false; 11983 11984 LoadSDNode *LD = cast<LoadSDNode>(N); 11985 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 11986 !LD->getValueType(0).isInteger()) 11987 return false; 11988 11989 // Keep track of already used bits to detect overlapping values. 11990 // In that case, we will just abort the transformation. 11991 APInt UsedBits(LD->getValueSizeInBits(0), 0); 11992 11993 SmallVector<LoadedSlice, 4> LoadedSlices; 11994 11995 // Check if this load is used as several smaller chunks of bits. 11996 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 11997 // of computation for each trunc. 11998 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 11999 UI != UIEnd; ++UI) { 12000 // Skip the uses of the chain. 12001 if (UI.getUse().getResNo() != 0) 12002 continue; 12003 12004 SDNode *User = *UI; 12005 unsigned Shift = 0; 12006 12007 // Check if this is a trunc(lshr). 12008 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 12009 isa<ConstantSDNode>(User->getOperand(1))) { 12010 Shift = User->getConstantOperandVal(1); 12011 User = *User->use_begin(); 12012 } 12013 12014 // At this point, User is a Truncate, iff we encountered, trunc or 12015 // trunc(lshr). 12016 if (User->getOpcode() != ISD::TRUNCATE) 12017 return false; 12018 12019 // The width of the type must be a power of 2 and greater than 8-bits. 12020 // Otherwise the load cannot be represented in LLVM IR. 12021 // Moreover, if we shifted with a non-8-bits multiple, the slice 12022 // will be across several bytes. We do not support that. 12023 unsigned Width = User->getValueSizeInBits(0); 12024 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 12025 return 0; 12026 12027 // Build the slice for this chain of computations. 12028 LoadedSlice LS(User, LD, Shift, &DAG); 12029 APInt CurrentUsedBits = LS.getUsedBits(); 12030 12031 // Check if this slice overlaps with another. 12032 if ((CurrentUsedBits & UsedBits) != 0) 12033 return false; 12034 // Update the bits used globally. 12035 UsedBits |= CurrentUsedBits; 12036 12037 // Check if the new slice would be legal. 12038 if (!LS.isLegal()) 12039 return false; 12040 12041 // Record the slice. 12042 LoadedSlices.push_back(LS); 12043 } 12044 12045 // Abort slicing if it does not seem to be profitable. 12046 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 12047 return false; 12048 12049 ++SlicedLoads; 12050 12051 // Rewrite each chain to use an independent load. 12052 // By construction, each chain can be represented by a unique load. 12053 12054 // Prepare the argument for the new token factor for all the slices. 12055 SmallVector<SDValue, 8> ArgChains; 12056 for (SmallVectorImpl<LoadedSlice>::const_iterator 12057 LSIt = LoadedSlices.begin(), 12058 LSItEnd = LoadedSlices.end(); 12059 LSIt != LSItEnd; ++LSIt) { 12060 SDValue SliceInst = LSIt->loadSlice(); 12061 CombineTo(LSIt->Inst, SliceInst, true); 12062 if (SliceInst.getOpcode() != ISD::LOAD) 12063 SliceInst = SliceInst.getOperand(0); 12064 assert(SliceInst->getOpcode() == ISD::LOAD && 12065 "It takes more than a zext to get to the loaded slice!!"); 12066 ArgChains.push_back(SliceInst.getValue(1)); 12067 } 12068 12069 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 12070 ArgChains); 12071 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 12072 AddToWorklist(Chain.getNode()); 12073 return true; 12074 } 12075 12076 /// Check to see if V is (and load (ptr), imm), where the load is having 12077 /// specific bytes cleared out. If so, return the byte size being masked out 12078 /// and the shift amount. 12079 static std::pair<unsigned, unsigned> 12080 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 12081 std::pair<unsigned, unsigned> Result(0, 0); 12082 12083 // Check for the structure we're looking for. 12084 if (V->getOpcode() != ISD::AND || 12085 !isa<ConstantSDNode>(V->getOperand(1)) || 12086 !ISD::isNormalLoad(V->getOperand(0).getNode())) 12087 return Result; 12088 12089 // Check the chain and pointer. 12090 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 12091 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 12092 12093 // The store should be chained directly to the load or be an operand of a 12094 // tokenfactor. 12095 if (LD == Chain.getNode()) 12096 ; // ok. 12097 else if (Chain->getOpcode() != ISD::TokenFactor) 12098 return Result; // Fail. 12099 else { 12100 bool isOk = false; 12101 for (const SDValue &ChainOp : Chain->op_values()) 12102 if (ChainOp.getNode() == LD) { 12103 isOk = true; 12104 break; 12105 } 12106 if (!isOk) return Result; 12107 } 12108 12109 // This only handles simple types. 12110 if (V.getValueType() != MVT::i16 && 12111 V.getValueType() != MVT::i32 && 12112 V.getValueType() != MVT::i64) 12113 return Result; 12114 12115 // Check the constant mask. Invert it so that the bits being masked out are 12116 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 12117 // follow the sign bit for uniformity. 12118 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 12119 unsigned NotMaskLZ = countLeadingZeros(NotMask); 12120 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 12121 unsigned NotMaskTZ = countTrailingZeros(NotMask); 12122 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 12123 if (NotMaskLZ == 64) return Result; // All zero mask. 12124 12125 // See if we have a continuous run of bits. If so, we have 0*1+0* 12126 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 12127 return Result; 12128 12129 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 12130 if (V.getValueType() != MVT::i64 && NotMaskLZ) 12131 NotMaskLZ -= 64-V.getValueSizeInBits(); 12132 12133 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 12134 switch (MaskedBytes) { 12135 case 1: 12136 case 2: 12137 case 4: break; 12138 default: return Result; // All one mask, or 5-byte mask. 12139 } 12140 12141 // Verify that the first bit starts at a multiple of mask so that the access 12142 // is aligned the same as the access width. 12143 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 12144 12145 Result.first = MaskedBytes; 12146 Result.second = NotMaskTZ/8; 12147 return Result; 12148 } 12149 12150 12151 /// Check to see if IVal is something that provides a value as specified by 12152 /// MaskInfo. If so, replace the specified store with a narrower store of 12153 /// truncated IVal. 12154 static SDNode * 12155 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 12156 SDValue IVal, StoreSDNode *St, 12157 DAGCombiner *DC) { 12158 unsigned NumBytes = MaskInfo.first; 12159 unsigned ByteShift = MaskInfo.second; 12160 SelectionDAG &DAG = DC->getDAG(); 12161 12162 // Check to see if IVal is all zeros in the part being masked in by the 'or' 12163 // that uses this. If not, this is not a replacement. 12164 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 12165 ByteShift*8, (ByteShift+NumBytes)*8); 12166 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 12167 12168 // Check that it is legal on the target to do this. It is legal if the new 12169 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 12170 // legalization. 12171 MVT VT = MVT::getIntegerVT(NumBytes*8); 12172 if (!DC->isTypeLegal(VT)) 12173 return nullptr; 12174 12175 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 12176 // shifted by ByteShift and truncated down to NumBytes. 12177 if (ByteShift) { 12178 SDLoc DL(IVal); 12179 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 12180 DAG.getConstant(ByteShift*8, DL, 12181 DC->getShiftAmountTy(IVal.getValueType()))); 12182 } 12183 12184 // Figure out the offset for the store and the alignment of the access. 12185 unsigned StOffset; 12186 unsigned NewAlign = St->getAlignment(); 12187 12188 if (DAG.getDataLayout().isLittleEndian()) 12189 StOffset = ByteShift; 12190 else 12191 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 12192 12193 SDValue Ptr = St->getBasePtr(); 12194 if (StOffset) { 12195 SDLoc DL(IVal); 12196 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 12197 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 12198 NewAlign = MinAlign(NewAlign, StOffset); 12199 } 12200 12201 // Truncate down to the new size. 12202 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 12203 12204 ++OpsNarrowed; 12205 return DAG 12206 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 12207 St->getPointerInfo().getWithOffset(StOffset), NewAlign) 12208 .getNode(); 12209 } 12210 12211 12212 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 12213 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 12214 /// narrowing the load and store if it would end up being a win for performance 12215 /// or code size. 12216 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 12217 StoreSDNode *ST = cast<StoreSDNode>(N); 12218 if (ST->isVolatile()) 12219 return SDValue(); 12220 12221 SDValue Chain = ST->getChain(); 12222 SDValue Value = ST->getValue(); 12223 SDValue Ptr = ST->getBasePtr(); 12224 EVT VT = Value.getValueType(); 12225 12226 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 12227 return SDValue(); 12228 12229 unsigned Opc = Value.getOpcode(); 12230 12231 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 12232 // is a byte mask indicating a consecutive number of bytes, check to see if 12233 // Y is known to provide just those bytes. If so, we try to replace the 12234 // load + replace + store sequence with a single (narrower) store, which makes 12235 // the load dead. 12236 if (Opc == ISD::OR) { 12237 std::pair<unsigned, unsigned> MaskedLoad; 12238 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 12239 if (MaskedLoad.first) 12240 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 12241 Value.getOperand(1), ST,this)) 12242 return SDValue(NewST, 0); 12243 12244 // Or is commutative, so try swapping X and Y. 12245 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 12246 if (MaskedLoad.first) 12247 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 12248 Value.getOperand(0), ST,this)) 12249 return SDValue(NewST, 0); 12250 } 12251 12252 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 12253 Value.getOperand(1).getOpcode() != ISD::Constant) 12254 return SDValue(); 12255 12256 SDValue N0 = Value.getOperand(0); 12257 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 12258 Chain == SDValue(N0.getNode(), 1)) { 12259 LoadSDNode *LD = cast<LoadSDNode>(N0); 12260 if (LD->getBasePtr() != Ptr || 12261 LD->getPointerInfo().getAddrSpace() != 12262 ST->getPointerInfo().getAddrSpace()) 12263 return SDValue(); 12264 12265 // Find the type to narrow it the load / op / store to. 12266 SDValue N1 = Value.getOperand(1); 12267 unsigned BitWidth = N1.getValueSizeInBits(); 12268 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 12269 if (Opc == ISD::AND) 12270 Imm ^= APInt::getAllOnesValue(BitWidth); 12271 if (Imm == 0 || Imm.isAllOnesValue()) 12272 return SDValue(); 12273 unsigned ShAmt = Imm.countTrailingZeros(); 12274 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 12275 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 12276 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 12277 // The narrowing should be profitable, the load/store operation should be 12278 // legal (or custom) and the store size should be equal to the NewVT width. 12279 while (NewBW < BitWidth && 12280 (NewVT.getStoreSizeInBits() != NewBW || 12281 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 12282 !TLI.isNarrowingProfitable(VT, NewVT))) { 12283 NewBW = NextPowerOf2(NewBW); 12284 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 12285 } 12286 if (NewBW >= BitWidth) 12287 return SDValue(); 12288 12289 // If the lsb changed does not start at the type bitwidth boundary, 12290 // start at the previous one. 12291 if (ShAmt % NewBW) 12292 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 12293 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 12294 std::min(BitWidth, ShAmt + NewBW)); 12295 if ((Imm & Mask) == Imm) { 12296 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 12297 if (Opc == ISD::AND) 12298 NewImm ^= APInt::getAllOnesValue(NewBW); 12299 uint64_t PtrOff = ShAmt / 8; 12300 // For big endian targets, we need to adjust the offset to the pointer to 12301 // load the correct bytes. 12302 if (DAG.getDataLayout().isBigEndian()) 12303 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 12304 12305 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 12306 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 12307 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 12308 return SDValue(); 12309 12310 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 12311 Ptr.getValueType(), Ptr, 12312 DAG.getConstant(PtrOff, SDLoc(LD), 12313 Ptr.getValueType())); 12314 SDValue NewLD = 12315 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 12316 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 12317 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 12318 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 12319 DAG.getConstant(NewImm, SDLoc(Value), 12320 NewVT)); 12321 SDValue NewST = 12322 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 12323 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 12324 12325 AddToWorklist(NewPtr.getNode()); 12326 AddToWorklist(NewLD.getNode()); 12327 AddToWorklist(NewVal.getNode()); 12328 WorklistRemover DeadNodes(*this); 12329 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 12330 ++OpsNarrowed; 12331 return NewST; 12332 } 12333 } 12334 12335 return SDValue(); 12336 } 12337 12338 /// For a given floating point load / store pair, if the load value isn't used 12339 /// by any other operations, then consider transforming the pair to integer 12340 /// load / store operations if the target deems the transformation profitable. 12341 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 12342 StoreSDNode *ST = cast<StoreSDNode>(N); 12343 SDValue Chain = ST->getChain(); 12344 SDValue Value = ST->getValue(); 12345 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 12346 Value.hasOneUse() && 12347 Chain == SDValue(Value.getNode(), 1)) { 12348 LoadSDNode *LD = cast<LoadSDNode>(Value); 12349 EVT VT = LD->getMemoryVT(); 12350 if (!VT.isFloatingPoint() || 12351 VT != ST->getMemoryVT() || 12352 LD->isNonTemporal() || 12353 ST->isNonTemporal() || 12354 LD->getPointerInfo().getAddrSpace() != 0 || 12355 ST->getPointerInfo().getAddrSpace() != 0) 12356 return SDValue(); 12357 12358 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 12359 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 12360 !TLI.isOperationLegal(ISD::STORE, IntVT) || 12361 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 12362 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 12363 return SDValue(); 12364 12365 unsigned LDAlign = LD->getAlignment(); 12366 unsigned STAlign = ST->getAlignment(); 12367 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 12368 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 12369 if (LDAlign < ABIAlign || STAlign < ABIAlign) 12370 return SDValue(); 12371 12372 SDValue NewLD = 12373 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 12374 LD->getPointerInfo(), LDAlign); 12375 12376 SDValue NewST = 12377 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(), 12378 ST->getPointerInfo(), STAlign); 12379 12380 AddToWorklist(NewLD.getNode()); 12381 AddToWorklist(NewST.getNode()); 12382 WorklistRemover DeadNodes(*this); 12383 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 12384 ++LdStFP2Int; 12385 return NewST; 12386 } 12387 12388 return SDValue(); 12389 } 12390 12391 // This is a helper function for visitMUL to check the profitability 12392 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 12393 // MulNode is the original multiply, AddNode is (add x, c1), 12394 // and ConstNode is c2. 12395 // 12396 // If the (add x, c1) has multiple uses, we could increase 12397 // the number of adds if we make this transformation. 12398 // It would only be worth doing this if we can remove a 12399 // multiply in the process. Check for that here. 12400 // To illustrate: 12401 // (A + c1) * c3 12402 // (A + c2) * c3 12403 // We're checking for cases where we have common "c3 * A" expressions. 12404 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 12405 SDValue &AddNode, 12406 SDValue &ConstNode) { 12407 APInt Val; 12408 12409 // If the add only has one use, this would be OK to do. 12410 if (AddNode.getNode()->hasOneUse()) 12411 return true; 12412 12413 // Walk all the users of the constant with which we're multiplying. 12414 for (SDNode *Use : ConstNode->uses()) { 12415 12416 if (Use == MulNode) // This use is the one we're on right now. Skip it. 12417 continue; 12418 12419 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 12420 SDNode *OtherOp; 12421 SDNode *MulVar = AddNode.getOperand(0).getNode(); 12422 12423 // OtherOp is what we're multiplying against the constant. 12424 if (Use->getOperand(0) == ConstNode) 12425 OtherOp = Use->getOperand(1).getNode(); 12426 else 12427 OtherOp = Use->getOperand(0).getNode(); 12428 12429 // Check to see if multiply is with the same operand of our "add". 12430 // 12431 // ConstNode = CONST 12432 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 12433 // ... 12434 // AddNode = (A + c1) <-- MulVar is A. 12435 // = AddNode * ConstNode <-- current visiting instruction. 12436 // 12437 // If we make this transformation, we will have a common 12438 // multiply (ConstNode * A) that we can save. 12439 if (OtherOp == MulVar) 12440 return true; 12441 12442 // Now check to see if a future expansion will give us a common 12443 // multiply. 12444 // 12445 // ConstNode = CONST 12446 // AddNode = (A + c1) 12447 // ... = AddNode * ConstNode <-- current visiting instruction. 12448 // ... 12449 // OtherOp = (A + c2) 12450 // Use = OtherOp * ConstNode <-- visiting Use. 12451 // 12452 // If we make this transformation, we will have a common 12453 // multiply (CONST * A) after we also do the same transformation 12454 // to the "t2" instruction. 12455 if (OtherOp->getOpcode() == ISD::ADD && 12456 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 12457 OtherOp->getOperand(0).getNode() == MulVar) 12458 return true; 12459 } 12460 } 12461 12462 // Didn't find a case where this would be profitable. 12463 return false; 12464 } 12465 12466 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 12467 unsigned NumStores) { 12468 SmallVector<SDValue, 8> Chains; 12469 SmallPtrSet<const SDNode *, 8> Visited; 12470 SDLoc StoreDL(StoreNodes[0].MemNode); 12471 12472 for (unsigned i = 0; i < NumStores; ++i) { 12473 Visited.insert(StoreNodes[i].MemNode); 12474 } 12475 12476 // don't include nodes that are children 12477 for (unsigned i = 0; i < NumStores; ++i) { 12478 if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0) 12479 Chains.push_back(StoreNodes[i].MemNode->getChain()); 12480 } 12481 12482 assert(Chains.size() > 0 && "Chain should have generated a chain"); 12483 return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains); 12484 } 12485 12486 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 12487 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores, 12488 bool IsConstantSrc, bool UseVector, bool UseTrunc) { 12489 // Make sure we have something to merge. 12490 if (NumStores < 2) 12491 return false; 12492 12493 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 12494 12495 // The latest Node in the DAG. 12496 SDLoc DL(StoreNodes[0].MemNode); 12497 12498 SDValue StoredVal; 12499 if (UseVector) { 12500 bool IsVec = MemVT.isVector(); 12501 unsigned Elts = NumStores; 12502 if (IsVec) { 12503 // When merging vector stores, get the total number of elements. 12504 Elts *= MemVT.getVectorNumElements(); 12505 } 12506 // Get the type for the merged vector store. 12507 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 12508 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 12509 12510 if (IsConstantSrc) { 12511 SmallVector<SDValue, 8> BuildVector; 12512 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) { 12513 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode); 12514 SDValue Val = St->getValue(); 12515 if (MemVT.getScalarType().isInteger()) 12516 if (auto *CFP = dyn_cast<ConstantFPSDNode>(St->getValue())) 12517 Val = DAG.getConstant( 12518 (uint32_t)CFP->getValueAPF().bitcastToAPInt().getZExtValue(), 12519 SDLoc(CFP), MemVT); 12520 BuildVector.push_back(Val); 12521 } 12522 StoredVal = DAG.getBuildVector(Ty, DL, BuildVector); 12523 } else { 12524 SmallVector<SDValue, 8> Ops; 12525 for (unsigned i = 0; i < NumStores; ++i) { 12526 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12527 SDValue Val = St->getValue(); 12528 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 12529 if (Val.getValueType() != MemVT) 12530 return false; 12531 Ops.push_back(Val); 12532 } 12533 12534 // Build the extracted vector elements back into a vector. 12535 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 12536 DL, Ty, Ops); } 12537 } else { 12538 // We should always use a vector store when merging extracted vector 12539 // elements, so this path implies a store of constants. 12540 assert(IsConstantSrc && "Merged vector elements should use vector store"); 12541 12542 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 12543 APInt StoreInt(SizeInBits, 0); 12544 12545 // Construct a single integer constant which is made of the smaller 12546 // constant inputs. 12547 bool IsLE = DAG.getDataLayout().isLittleEndian(); 12548 for (unsigned i = 0; i < NumStores; ++i) { 12549 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 12550 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 12551 12552 SDValue Val = St->getValue(); 12553 StoreInt <<= ElementSizeBytes * 8; 12554 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 12555 StoreInt |= C->getAPIntValue().zextOrTrunc(SizeInBits); 12556 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 12557 StoreInt |= C->getValueAPF().bitcastToAPInt().zextOrTrunc(SizeInBits); 12558 } else { 12559 llvm_unreachable("Invalid constant element type"); 12560 } 12561 } 12562 12563 // Create the new Load and Store operations. 12564 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 12565 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 12566 } 12567 12568 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12569 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores); 12570 12571 // make sure we use trunc store if it's necessary to be legal. 12572 SDValue NewStore; 12573 if (UseVector || !UseTrunc) { 12574 NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(), 12575 FirstInChain->getPointerInfo(), 12576 FirstInChain->getAlignment()); 12577 } else { // Must be realized as a trunc store 12578 EVT LegalizedStoredValueTy = 12579 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 12580 unsigned LegalizedStoreSize = LegalizedStoredValueTy.getSizeInBits(); 12581 ConstantSDNode *C = cast<ConstantSDNode>(StoredVal); 12582 SDValue ExtendedStoreVal = 12583 DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL, 12584 LegalizedStoredValueTy); 12585 NewStore = DAG.getTruncStore( 12586 NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(), 12587 FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/, 12588 FirstInChain->getAlignment(), 12589 FirstInChain->getMemOperand()->getFlags()); 12590 } 12591 12592 // Replace all merged stores with the new store. 12593 for (unsigned i = 0; i < NumStores; ++i) 12594 CombineTo(StoreNodes[i].MemNode, NewStore); 12595 12596 AddToWorklist(NewChain.getNode()); 12597 return true; 12598 } 12599 12600 void DAGCombiner::getStoreMergeCandidates( 12601 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) { 12602 // This holds the base pointer, index, and the offset in bytes from the base 12603 // pointer. 12604 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 12605 EVT MemVT = St->getMemoryVT(); 12606 12607 // We must have a base and an offset. 12608 if (!BasePtr.getBase().getNode()) 12609 return; 12610 12611 // Do not handle stores to undef base pointers. 12612 if (BasePtr.getBase().isUndef()) 12613 return; 12614 12615 bool IsConstantSrc = isa<ConstantSDNode>(St->getValue()) || 12616 isa<ConstantFPSDNode>(St->getValue()); 12617 bool IsExtractVecSrc = 12618 (St->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12619 St->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR); 12620 bool IsLoadSrc = isa<LoadSDNode>(St->getValue()); 12621 BaseIndexOffset LBasePtr; 12622 // Match on loadbaseptr if relevant. 12623 if (IsLoadSrc) 12624 LBasePtr = BaseIndexOffset::match( 12625 cast<LoadSDNode>(St->getValue())->getBasePtr(), DAG); 12626 12627 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr, 12628 int64_t &Offset) -> bool { 12629 if (Other->isVolatile() || Other->isIndexed()) 12630 return false; 12631 // We can merge constant floats to equivalent integers 12632 if (Other->getMemoryVT() != MemVT) 12633 if (!(MemVT.isInteger() && MemVT.bitsEq(Other->getMemoryVT()) && 12634 isa<ConstantFPSDNode>(Other->getValue()))) 12635 return false; 12636 if (IsLoadSrc) { 12637 // The Load's Base Ptr must also match 12638 if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Other->getValue())) { 12639 auto LPtr = BaseIndexOffset::match(OtherLd->getBasePtr(), DAG); 12640 if (!(LBasePtr.equalBaseIndex(LPtr, DAG))) 12641 return false; 12642 } else 12643 return false; 12644 } 12645 if (IsConstantSrc) 12646 if (!(isa<ConstantSDNode>(Other->getValue()) || 12647 isa<ConstantFPSDNode>(Other->getValue()))) 12648 return false; 12649 if (IsExtractVecSrc) 12650 if (!(Other->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12651 Other->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR)) 12652 return false; 12653 Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG); 12654 return (BasePtr.equalBaseIndex(Ptr, DAG, Offset)); 12655 }; 12656 // We looking for a root node which is an ancestor to all mergable 12657 // stores. We search up through a load, to our root and then down 12658 // through all children. For instance we will find Store{1,2,3} if 12659 // St is Store1, Store2. or Store3 where the root is not a load 12660 // which always true for nonvolatile ops. TODO: Expand 12661 // the search to find all valid candidates through multiple layers of loads. 12662 // 12663 // Root 12664 // |-------|-------| 12665 // Load Load Store3 12666 // | | 12667 // Store1 Store2 12668 // 12669 // FIXME: We should be able to climb and 12670 // descend TokenFactors to find candidates as well. 12671 12672 SDNode *RootNode = (St->getChain()).getNode(); 12673 12674 if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) { 12675 RootNode = Ldn->getChain().getNode(); 12676 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 12677 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain 12678 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2) 12679 if (I2.getOperandNo() == 0) 12680 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) { 12681 BaseIndexOffset Ptr; 12682 int64_t PtrDiff; 12683 if (CandidateMatch(OtherST, Ptr, PtrDiff)) 12684 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff)); 12685 } 12686 } else 12687 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 12688 if (I.getOperandNo() == 0) 12689 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 12690 BaseIndexOffset Ptr; 12691 int64_t PtrDiff; 12692 if (CandidateMatch(OtherST, Ptr, PtrDiff)) 12693 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff)); 12694 } 12695 } 12696 12697 // We need to check that merging these stores does not cause a loop 12698 // in the DAG. Any store candidate may depend on another candidate 12699 // indirectly through its operand (we already consider dependencies 12700 // through the chain). Check in parallel by searching up from 12701 // non-chain operands of candidates. 12702 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 12703 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) { 12704 SmallPtrSet<const SDNode *, 16> Visited; 12705 SmallVector<const SDNode *, 8> Worklist; 12706 // search ops of store candidates 12707 for (unsigned i = 0; i < NumStores; ++i) { 12708 SDNode *n = StoreNodes[i].MemNode; 12709 // Potential loops may happen only through non-chain operands 12710 for (unsigned j = 1; j < n->getNumOperands(); ++j) 12711 Worklist.push_back(n->getOperand(j).getNode()); 12712 } 12713 // search through DAG. We can stop early if we find a storenode 12714 for (unsigned i = 0; i < NumStores; ++i) { 12715 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist)) 12716 return false; 12717 } 12718 return true; 12719 } 12720 12721 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) { 12722 if (OptLevel == CodeGenOpt::None) 12723 return false; 12724 12725 EVT MemVT = St->getMemoryVT(); 12726 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 12727 12728 if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits) 12729 return false; 12730 12731 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 12732 Attribute::NoImplicitFloat); 12733 12734 // This function cannot currently deal with non-byte-sized memory sizes. 12735 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 12736 return false; 12737 12738 if (!MemVT.isSimple()) 12739 return false; 12740 12741 // Perform an early exit check. Do not bother looking at stored values that 12742 // are not constants, loads, or extracted vector elements. 12743 SDValue StoredVal = St->getValue(); 12744 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 12745 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 12746 isa<ConstantFPSDNode>(StoredVal); 12747 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12748 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 12749 12750 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 12751 return false; 12752 12753 // Don't merge vectors into wider vectors if the source data comes from loads. 12754 // TODO: This restriction can be lifted by using logic similar to the 12755 // ExtractVecSrc case. 12756 if (MemVT.isVector() && IsLoadSrc) 12757 return false; 12758 12759 SmallVector<MemOpLink, 8> StoreNodes; 12760 // Find potential store merge candidates by searching through chain sub-DAG 12761 getStoreMergeCandidates(St, StoreNodes); 12762 12763 // Check if there is anything to merge. 12764 if (StoreNodes.size() < 2) 12765 return false; 12766 12767 // Sort the memory operands according to their distance from the 12768 // base pointer. 12769 std::sort(StoreNodes.begin(), StoreNodes.end(), 12770 [](MemOpLink LHS, MemOpLink RHS) { 12771 return LHS.OffsetFromBase < RHS.OffsetFromBase; 12772 }); 12773 12774 // Store Merge attempts to merge the lowest stores. This generally 12775 // works out as if successful, as the remaining stores are checked 12776 // after the first collection of stores is merged. However, in the 12777 // case that a non-mergeable store is found first, e.g., {p[-2], 12778 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent 12779 // mergeable cases. To prevent this, we prune such stores from the 12780 // front of StoreNodes here. 12781 12782 bool RV = false; 12783 while (StoreNodes.size() > 1) { 12784 unsigned StartIdx = 0; 12785 while ((StartIdx + 1 < StoreNodes.size()) && 12786 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes != 12787 StoreNodes[StartIdx + 1].OffsetFromBase) 12788 ++StartIdx; 12789 12790 // Bail if we don't have enough candidates to merge. 12791 if (StartIdx + 1 >= StoreNodes.size()) 12792 return RV; 12793 12794 if (StartIdx) 12795 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx); 12796 12797 // Scan the memory operations on the chain and find the first 12798 // non-consecutive store memory address. 12799 unsigned NumConsecutiveStores = 1; 12800 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 12801 // Check that the addresses are consecutive starting from the second 12802 // element in the list of stores. 12803 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) { 12804 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 12805 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 12806 break; 12807 NumConsecutiveStores = i + 1; 12808 } 12809 12810 if (NumConsecutiveStores < 2) { 12811 StoreNodes.erase(StoreNodes.begin(), 12812 StoreNodes.begin() + NumConsecutiveStores); 12813 continue; 12814 } 12815 12816 // Check that we can merge these candidates without causing a cycle 12817 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, 12818 NumConsecutiveStores)) { 12819 StoreNodes.erase(StoreNodes.begin(), 12820 StoreNodes.begin() + NumConsecutiveStores); 12821 continue; 12822 } 12823 12824 // The node with the lowest store address. 12825 LLVMContext &Context = *DAG.getContext(); 12826 const DataLayout &DL = DAG.getDataLayout(); 12827 12828 // Store the constants into memory as one consecutive store. 12829 if (IsConstantSrc) { 12830 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12831 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 12832 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 12833 unsigned LastLegalType = 1; 12834 unsigned LastLegalVectorType = 1; 12835 bool LastIntegerTrunc = false; 12836 bool NonZero = false; 12837 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 12838 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode); 12839 SDValue StoredVal = ST->getValue(); 12840 12841 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 12842 NonZero |= !C->isNullValue(); 12843 } else if (ConstantFPSDNode *C = 12844 dyn_cast<ConstantFPSDNode>(StoredVal)) { 12845 NonZero |= !C->getConstantFPValue()->isNullValue(); 12846 } else { 12847 // Non-constant. 12848 break; 12849 } 12850 12851 // Find a legal type for the constant store. 12852 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 12853 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 12854 bool IsFast = false; 12855 if (TLI.isTypeLegal(StoreTy) && 12856 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 12857 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 12858 FirstStoreAlign, &IsFast) && 12859 IsFast) { 12860 LastIntegerTrunc = false; 12861 LastLegalType = i + 1; 12862 // Or check whether a truncstore is legal. 12863 } else if (TLI.getTypeAction(Context, StoreTy) == 12864 TargetLowering::TypePromoteInteger) { 12865 EVT LegalizedStoredValueTy = 12866 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 12867 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 12868 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) && 12869 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 12870 FirstStoreAlign, &IsFast) && 12871 IsFast) { 12872 LastIntegerTrunc = true; 12873 LastLegalType = i + 1; 12874 } 12875 } 12876 12877 // We only use vectors if the constant is known to be zero or the target 12878 // allows it and the function is not marked with the noimplicitfloat 12879 // attribute. 12880 if ((!NonZero || 12881 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) && 12882 !NoVectors) { 12883 // Find a legal type for the vector store. 12884 unsigned Elts = i + 1; 12885 if (MemVT.isVector()) { 12886 // When merging vector stores, get the total number of elements. 12887 Elts *= MemVT.getVectorNumElements(); 12888 } 12889 EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 12890 if (TLI.isTypeLegal(Ty) && 12891 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && 12892 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 12893 FirstStoreAlign, &IsFast) && 12894 IsFast) 12895 LastLegalVectorType = i + 1; 12896 } 12897 } 12898 12899 // Check if we found a legal integer type that creates a meaningful merge. 12900 if (LastLegalType < 2 && LastLegalVectorType < 2) { 12901 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1); 12902 continue; 12903 } 12904 12905 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 12906 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType; 12907 12908 bool Merged = MergeStoresOfConstantsOrVecElts( 12909 StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc); 12910 if (!Merged) { 12911 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 12912 continue; 12913 } 12914 // Remove merged stores for next iteration. 12915 RV = true; 12916 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 12917 continue; 12918 } 12919 12920 // When extracting multiple vector elements, try to store them 12921 // in one vector store rather than a sequence of scalar stores. 12922 if (IsExtractVecSrc) { 12923 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12924 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 12925 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 12926 unsigned NumStoresToMerge = 1; 12927 bool IsVec = MemVT.isVector(); 12928 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 12929 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12930 unsigned StoreValOpcode = St->getValue().getOpcode(); 12931 // This restriction could be loosened. 12932 // Bail out if any stored values are not elements extracted from a 12933 // vector. It should be possible to handle mixed sources, but load 12934 // sources need more careful handling (see the block of code below that 12935 // handles consecutive loads). 12936 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT && 12937 StoreValOpcode != ISD::EXTRACT_SUBVECTOR) 12938 return RV; 12939 12940 // Find a legal type for the vector store. 12941 unsigned Elts = i + 1; 12942 if (IsVec) { 12943 // When merging vector stores, get the total number of elements. 12944 Elts *= MemVT.getVectorNumElements(); 12945 } 12946 EVT Ty = 12947 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 12948 bool IsFast; 12949 if (TLI.isTypeLegal(Ty) && 12950 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && 12951 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 12952 FirstStoreAlign, &IsFast) && 12953 IsFast) 12954 NumStoresToMerge = i + 1; 12955 } 12956 12957 bool Merged = MergeStoresOfConstantsOrVecElts( 12958 StoreNodes, MemVT, NumStoresToMerge, false, true, false); 12959 if (!Merged) { 12960 StoreNodes.erase(StoreNodes.begin(), 12961 StoreNodes.begin() + NumStoresToMerge); 12962 continue; 12963 } 12964 // Remove merged stores for next iteration. 12965 StoreNodes.erase(StoreNodes.begin(), 12966 StoreNodes.begin() + NumStoresToMerge); 12967 RV = true; 12968 continue; 12969 } 12970 12971 // Below we handle the case of multiple consecutive stores that 12972 // come from multiple consecutive loads. We merge them into a single 12973 // wide load and a single wide store. 12974 12975 // Look for load nodes which are used by the stored values. 12976 SmallVector<MemOpLink, 8> LoadNodes; 12977 12978 // Find acceptable loads. Loads need to have the same chain (token factor), 12979 // must not be zext, volatile, indexed, and they must be consecutive. 12980 BaseIndexOffset LdBasePtr; 12981 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 12982 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12983 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 12984 if (!Ld) 12985 break; 12986 12987 // Loads must only have one use. 12988 if (!Ld->hasNUsesOfValue(1, 0)) 12989 break; 12990 12991 // The memory operands must not be volatile. 12992 if (Ld->isVolatile() || Ld->isIndexed()) 12993 break; 12994 12995 // We do not accept ext loads. 12996 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 12997 break; 12998 12999 // The stored memory type must be the same. 13000 if (Ld->getMemoryVT() != MemVT) 13001 break; 13002 13003 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 13004 // If this is not the first ptr that we check. 13005 int64_t LdOffset = 0; 13006 if (LdBasePtr.getBase().getNode()) { 13007 // The base ptr must be the same. 13008 if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset)) 13009 break; 13010 } else { 13011 // Check that all other base pointers are the same as this one. 13012 LdBasePtr = LdPtr; 13013 } 13014 13015 // We found a potential memory operand to merge. 13016 LoadNodes.push_back(MemOpLink(Ld, LdOffset)); 13017 } 13018 13019 if (LoadNodes.size() < 2) { 13020 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1); 13021 continue; 13022 } 13023 13024 // If we have load/store pair instructions and we only have two values, 13025 // don't bother merging. 13026 unsigned RequiredAlignment; 13027 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 13028 StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) { 13029 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2); 13030 continue; 13031 } 13032 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 13033 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 13034 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 13035 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 13036 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 13037 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 13038 13039 // Scan the memory operations on the chain and find the first 13040 // non-consecutive load memory address. These variables hold the index in 13041 // the store node array. 13042 unsigned LastConsecutiveLoad = 1; 13043 // This variable refers to the size and not index in the array. 13044 unsigned LastLegalVectorType = 1; 13045 unsigned LastLegalIntegerType = 1; 13046 bool isDereferenceable = true; 13047 bool DoIntegerTruncate = false; 13048 StartAddress = LoadNodes[0].OffsetFromBase; 13049 SDValue FirstChain = FirstLoad->getChain(); 13050 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 13051 // All loads must share the same chain. 13052 if (LoadNodes[i].MemNode->getChain() != FirstChain) 13053 break; 13054 13055 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 13056 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 13057 break; 13058 LastConsecutiveLoad = i; 13059 13060 if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable()) 13061 isDereferenceable = false; 13062 13063 // Find a legal type for the vector store. 13064 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i + 1); 13065 bool IsFastSt, IsFastLd; 13066 if (TLI.isTypeLegal(StoreTy) && 13067 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 13068 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13069 FirstStoreAlign, &IsFastSt) && 13070 IsFastSt && 13071 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 13072 FirstLoadAlign, &IsFastLd) && 13073 IsFastLd) { 13074 LastLegalVectorType = i + 1; 13075 } 13076 13077 // Find a legal type for the integer store. 13078 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 13079 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 13080 if (TLI.isTypeLegal(StoreTy) && 13081 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 13082 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13083 FirstStoreAlign, &IsFastSt) && 13084 IsFastSt && 13085 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 13086 FirstLoadAlign, &IsFastLd) && 13087 IsFastLd) { 13088 LastLegalIntegerType = i + 1; 13089 DoIntegerTruncate = false; 13090 // Or check whether a truncstore and extload is legal. 13091 } else if (TLI.getTypeAction(Context, StoreTy) == 13092 TargetLowering::TypePromoteInteger) { 13093 EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy); 13094 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 13095 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) && 13096 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, 13097 StoreTy) && 13098 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, 13099 StoreTy) && 13100 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 13101 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13102 FirstStoreAlign, &IsFastSt) && 13103 IsFastSt && 13104 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 13105 FirstLoadAlign, &IsFastLd) && 13106 IsFastLd) { 13107 LastLegalIntegerType = i + 1; 13108 DoIntegerTruncate = true; 13109 } 13110 } 13111 } 13112 13113 // Only use vector types if the vector type is larger than the integer type. 13114 // If they are the same, use integers. 13115 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 13116 unsigned LastLegalType = 13117 std::max(LastLegalVectorType, LastLegalIntegerType); 13118 13119 // We add +1 here because the LastXXX variables refer to location while 13120 // the NumElem refers to array/index size. 13121 unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1); 13122 NumElem = std::min(LastLegalType, NumElem); 13123 13124 if (NumElem < 2) { 13125 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1); 13126 continue; 13127 } 13128 13129 // Find if it is better to use vectors or integers to load and store 13130 // to memory. 13131 EVT JointMemOpVT; 13132 if (UseVectorTy) { 13133 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 13134 } else { 13135 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 13136 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 13137 } 13138 13139 SDLoc LoadDL(LoadNodes[0].MemNode); 13140 SDLoc StoreDL(StoreNodes[0].MemNode); 13141 13142 // The merged loads are required to have the same incoming chain, so 13143 // using the first's chain is acceptable. 13144 13145 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem); 13146 AddToWorklist(NewStoreChain.getNode()); 13147 13148 MachineMemOperand::Flags MMOFlags = isDereferenceable ? 13149 MachineMemOperand::MODereferenceable: 13150 MachineMemOperand::MONone; 13151 13152 SDValue NewLoad, NewStore; 13153 if (UseVectorTy || !DoIntegerTruncate) { 13154 NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(), 13155 FirstLoad->getBasePtr(), 13156 FirstLoad->getPointerInfo(), FirstLoadAlign, 13157 MMOFlags); 13158 NewStore = DAG.getStore(NewStoreChain, StoreDL, NewLoad, 13159 FirstInChain->getBasePtr(), 13160 FirstInChain->getPointerInfo(), FirstStoreAlign); 13161 } else { // This must be the truncstore/extload case 13162 EVT ExtendedTy = 13163 TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT); 13164 NewLoad = 13165 DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, FirstLoad->getChain(), 13166 FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(), 13167 JointMemOpVT, FirstLoadAlign, MMOFlags); 13168 NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad, 13169 FirstInChain->getBasePtr(), 13170 FirstInChain->getPointerInfo(), JointMemOpVT, 13171 FirstInChain->getAlignment(), 13172 FirstInChain->getMemOperand()->getFlags()); 13173 } 13174 13175 // Transfer chain users from old loads to the new load. 13176 for (unsigned i = 0; i < NumElem; ++i) { 13177 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 13178 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 13179 SDValue(NewLoad.getNode(), 1)); 13180 } 13181 13182 // Replace the all stores with the new store. 13183 for (unsigned i = 0; i < NumElem; ++i) 13184 CombineTo(StoreNodes[i].MemNode, NewStore); 13185 RV = true; 13186 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 13187 continue; 13188 } 13189 return RV; 13190 } 13191 13192 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 13193 SDLoc SL(ST); 13194 SDValue ReplStore; 13195 13196 // Replace the chain to avoid dependency. 13197 if (ST->isTruncatingStore()) { 13198 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 13199 ST->getBasePtr(), ST->getMemoryVT(), 13200 ST->getMemOperand()); 13201 } else { 13202 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 13203 ST->getMemOperand()); 13204 } 13205 13206 // Create token to keep both nodes around. 13207 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 13208 MVT::Other, ST->getChain(), ReplStore); 13209 13210 // Make sure the new and old chains are cleaned up. 13211 AddToWorklist(Token.getNode()); 13212 13213 // Don't add users to work list. 13214 return CombineTo(ST, Token, false); 13215 } 13216 13217 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 13218 SDValue Value = ST->getValue(); 13219 if (Value.getOpcode() == ISD::TargetConstantFP) 13220 return SDValue(); 13221 13222 SDLoc DL(ST); 13223 13224 SDValue Chain = ST->getChain(); 13225 SDValue Ptr = ST->getBasePtr(); 13226 13227 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 13228 13229 // NOTE: If the original store is volatile, this transform must not increase 13230 // the number of stores. For example, on x86-32 an f64 can be stored in one 13231 // processor operation but an i64 (which is not legal) requires two. So the 13232 // transform should not be done in this case. 13233 13234 SDValue Tmp; 13235 switch (CFP->getSimpleValueType(0).SimpleTy) { 13236 default: 13237 llvm_unreachable("Unknown FP type"); 13238 case MVT::f16: // We don't do this for these yet. 13239 case MVT::f80: 13240 case MVT::f128: 13241 case MVT::ppcf128: 13242 return SDValue(); 13243 case MVT::f32: 13244 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 13245 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 13246 ; 13247 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 13248 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 13249 MVT::i32); 13250 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 13251 } 13252 13253 return SDValue(); 13254 case MVT::f64: 13255 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 13256 !ST->isVolatile()) || 13257 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 13258 ; 13259 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 13260 getZExtValue(), SDLoc(CFP), MVT::i64); 13261 return DAG.getStore(Chain, DL, Tmp, 13262 Ptr, ST->getMemOperand()); 13263 } 13264 13265 if (!ST->isVolatile() && 13266 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 13267 // Many FP stores are not made apparent until after legalize, e.g. for 13268 // argument passing. Since this is so common, custom legalize the 13269 // 64-bit integer store into two 32-bit stores. 13270 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 13271 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 13272 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 13273 if (DAG.getDataLayout().isBigEndian()) 13274 std::swap(Lo, Hi); 13275 13276 unsigned Alignment = ST->getAlignment(); 13277 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 13278 AAMDNodes AAInfo = ST->getAAInfo(); 13279 13280 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 13281 ST->getAlignment(), MMOFlags, AAInfo); 13282 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 13283 DAG.getConstant(4, DL, Ptr.getValueType())); 13284 Alignment = MinAlign(Alignment, 4U); 13285 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 13286 ST->getPointerInfo().getWithOffset(4), 13287 Alignment, MMOFlags, AAInfo); 13288 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 13289 St0, St1); 13290 } 13291 13292 return SDValue(); 13293 } 13294 } 13295 13296 SDValue DAGCombiner::visitSTORE(SDNode *N) { 13297 StoreSDNode *ST = cast<StoreSDNode>(N); 13298 SDValue Chain = ST->getChain(); 13299 SDValue Value = ST->getValue(); 13300 SDValue Ptr = ST->getBasePtr(); 13301 13302 // If this is a store of a bit convert, store the input value if the 13303 // resultant store does not need a higher alignment than the original. 13304 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 13305 ST->isUnindexed()) { 13306 EVT SVT = Value.getOperand(0).getValueType(); 13307 if (((!LegalOperations && !ST->isVolatile()) || 13308 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) && 13309 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 13310 unsigned OrigAlign = ST->getAlignment(); 13311 bool Fast = false; 13312 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 13313 ST->getAddressSpace(), OrigAlign, &Fast) && 13314 Fast) { 13315 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 13316 ST->getPointerInfo(), OrigAlign, 13317 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 13318 } 13319 } 13320 } 13321 13322 // Turn 'store undef, Ptr' -> nothing. 13323 if (Value.isUndef() && ST->isUnindexed()) 13324 return Chain; 13325 13326 // Try to infer better alignment information than the store already has. 13327 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 13328 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 13329 if (Align > ST->getAlignment()) { 13330 SDValue NewStore = 13331 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 13332 ST->getMemoryVT(), Align, 13333 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 13334 if (NewStore.getNode() != N) 13335 return CombineTo(ST, NewStore, true); 13336 } 13337 } 13338 } 13339 13340 // Try transforming a pair floating point load / store ops to integer 13341 // load / store ops. 13342 if (SDValue NewST = TransformFPLoadStorePair(N)) 13343 return NewST; 13344 13345 if (ST->isUnindexed()) { 13346 // Walk up chain skipping non-aliasing memory nodes, on this store and any 13347 // adjacent stores. 13348 if (findBetterNeighborChains(ST)) { 13349 // replaceStoreChain uses CombineTo, which handled all of the worklist 13350 // manipulation. Return the original node to not do anything else. 13351 return SDValue(ST, 0); 13352 } 13353 Chain = ST->getChain(); 13354 } 13355 13356 // FIXME: is there such a thing as a truncating indexed store? 13357 if (ST->isTruncatingStore() && ST->isUnindexed() && 13358 Value.getValueType().isInteger()) { 13359 // See if we can simplify the input to this truncstore with knowledge that 13360 // only the low bits are being used. For example: 13361 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 13362 SDValue Shorter = GetDemandedBits( 13363 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 13364 ST->getMemoryVT().getScalarSizeInBits())); 13365 AddToWorklist(Value.getNode()); 13366 if (Shorter.getNode()) 13367 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 13368 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 13369 13370 // Otherwise, see if we can simplify the operation with 13371 // SimplifyDemandedBits, which only works if the value has a single use. 13372 if (SimplifyDemandedBits( 13373 Value, 13374 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 13375 ST->getMemoryVT().getScalarSizeInBits()))) { 13376 // Re-visit the store if anything changed and the store hasn't been merged 13377 // with another node (N is deleted) SimplifyDemandedBits will add Value's 13378 // node back to the worklist if necessary, but we also need to re-visit 13379 // the Store node itself. 13380 if (N->getOpcode() != ISD::DELETED_NODE) 13381 AddToWorklist(N); 13382 return SDValue(N, 0); 13383 } 13384 } 13385 13386 // If this is a load followed by a store to the same location, then the store 13387 // is dead/noop. 13388 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 13389 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 13390 ST->isUnindexed() && !ST->isVolatile() && 13391 // There can't be any side effects between the load and store, such as 13392 // a call or store. 13393 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 13394 // The store is dead, remove it. 13395 return Chain; 13396 } 13397 } 13398 13399 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 13400 if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() && 13401 !ST1->isVolatile() && ST1->getBasePtr() == Ptr && 13402 ST->getMemoryVT() == ST1->getMemoryVT()) { 13403 // If this is a store followed by a store with the same value to the same 13404 // location, then the store is dead/noop. 13405 if (ST1->getValue() == Value) { 13406 // The store is dead, remove it. 13407 return Chain; 13408 } 13409 13410 // If this is a store who's preceeding store to the same location 13411 // and no one other node is chained to that store we can effectively 13412 // drop the store. Do not remove stores to undef as they may be used as 13413 // data sinks. 13414 if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() && 13415 !ST1->getBasePtr().isUndef()) { 13416 // ST1 is fully overwritten and can be elided. Combine with it's chain 13417 // value. 13418 CombineTo(ST1, ST1->getChain()); 13419 return SDValue(); 13420 } 13421 } 13422 } 13423 13424 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 13425 // truncating store. We can do this even if this is already a truncstore. 13426 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 13427 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 13428 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 13429 ST->getMemoryVT())) { 13430 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 13431 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 13432 } 13433 13434 // Only perform this optimization before the types are legal, because we 13435 // don't want to perform this optimization on every DAGCombine invocation. 13436 if ((TLI.mergeStoresAfterLegalization()) ? Level == AfterLegalizeDAG 13437 : !LegalTypes) { 13438 for (;;) { 13439 // There can be multiple store sequences on the same chain. 13440 // Keep trying to merge store sequences until we are unable to do so 13441 // or until we merge the last store on the chain. 13442 bool Changed = MergeConsecutiveStores(ST); 13443 if (!Changed) break; 13444 // Return N as merge only uses CombineTo and no worklist clean 13445 // up is necessary. 13446 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N)) 13447 return SDValue(N, 0); 13448 } 13449 } 13450 13451 // Try transforming N to an indexed store. 13452 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 13453 return SDValue(N, 0); 13454 13455 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 13456 // 13457 // Make sure to do this only after attempting to merge stores in order to 13458 // avoid changing the types of some subset of stores due to visit order, 13459 // preventing their merging. 13460 if (isa<ConstantFPSDNode>(ST->getValue())) { 13461 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 13462 return NewSt; 13463 } 13464 13465 if (SDValue NewSt = splitMergedValStore(ST)) 13466 return NewSt; 13467 13468 return ReduceLoadOpStoreWidth(N); 13469 } 13470 13471 /// For the instruction sequence of store below, F and I values 13472 /// are bundled together as an i64 value before being stored into memory. 13473 /// Sometimes it is more efficent to generate separate stores for F and I, 13474 /// which can remove the bitwise instructions or sink them to colder places. 13475 /// 13476 /// (store (or (zext (bitcast F to i32) to i64), 13477 /// (shl (zext I to i64), 32)), addr) --> 13478 /// (store F, addr) and (store I, addr+4) 13479 /// 13480 /// Similarly, splitting for other merged store can also be beneficial, like: 13481 /// For pair of {i32, i32}, i64 store --> two i32 stores. 13482 /// For pair of {i32, i16}, i64 store --> two i32 stores. 13483 /// For pair of {i16, i16}, i32 store --> two i16 stores. 13484 /// For pair of {i16, i8}, i32 store --> two i16 stores. 13485 /// For pair of {i8, i8}, i16 store --> two i8 stores. 13486 /// 13487 /// We allow each target to determine specifically which kind of splitting is 13488 /// supported. 13489 /// 13490 /// The store patterns are commonly seen from the simple code snippet below 13491 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 13492 /// void goo(const std::pair<int, float> &); 13493 /// hoo() { 13494 /// ... 13495 /// goo(std::make_pair(tmp, ftmp)); 13496 /// ... 13497 /// } 13498 /// 13499 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) { 13500 if (OptLevel == CodeGenOpt::None) 13501 return SDValue(); 13502 13503 SDValue Val = ST->getValue(); 13504 SDLoc DL(ST); 13505 13506 // Match OR operand. 13507 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR) 13508 return SDValue(); 13509 13510 // Match SHL operand and get Lower and Higher parts of Val. 13511 SDValue Op1 = Val.getOperand(0); 13512 SDValue Op2 = Val.getOperand(1); 13513 SDValue Lo, Hi; 13514 if (Op1.getOpcode() != ISD::SHL) { 13515 std::swap(Op1, Op2); 13516 if (Op1.getOpcode() != ISD::SHL) 13517 return SDValue(); 13518 } 13519 Lo = Op2; 13520 Hi = Op1.getOperand(0); 13521 if (!Op1.hasOneUse()) 13522 return SDValue(); 13523 13524 // Match shift amount to HalfValBitSize. 13525 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2; 13526 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1)); 13527 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize) 13528 return SDValue(); 13529 13530 // Lo and Hi are zero-extended from int with size less equal than 32 13531 // to i64. 13532 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() || 13533 !Lo.getOperand(0).getValueType().isScalarInteger() || 13534 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize || 13535 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() || 13536 !Hi.getOperand(0).getValueType().isScalarInteger() || 13537 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize) 13538 return SDValue(); 13539 13540 // Use the EVT of low and high parts before bitcast as the input 13541 // of target query. 13542 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST) 13543 ? Lo.getOperand(0).getValueType() 13544 : Lo.getValueType(); 13545 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST) 13546 ? Hi.getOperand(0).getValueType() 13547 : Hi.getValueType(); 13548 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) 13549 return SDValue(); 13550 13551 // Start to split store. 13552 unsigned Alignment = ST->getAlignment(); 13553 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 13554 AAMDNodes AAInfo = ST->getAAInfo(); 13555 13556 // Change the sizes of Lo and Hi's value types to HalfValBitSize. 13557 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize); 13558 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0)); 13559 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0)); 13560 13561 SDValue Chain = ST->getChain(); 13562 SDValue Ptr = ST->getBasePtr(); 13563 // Lower value store. 13564 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 13565 ST->getAlignment(), MMOFlags, AAInfo); 13566 Ptr = 13567 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 13568 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType())); 13569 // Higher value store. 13570 SDValue St1 = 13571 DAG.getStore(St0, DL, Hi, Ptr, 13572 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8), 13573 Alignment / 2, MMOFlags, AAInfo); 13574 return St1; 13575 } 13576 13577 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 13578 SDValue InVec = N->getOperand(0); 13579 SDValue InVal = N->getOperand(1); 13580 SDValue EltNo = N->getOperand(2); 13581 SDLoc DL(N); 13582 13583 // If the inserted element is an UNDEF, just use the input vector. 13584 if (InVal.isUndef()) 13585 return InVec; 13586 13587 EVT VT = InVec.getValueType(); 13588 13589 // Remove redundant insertions: 13590 // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x 13591 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 13592 InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1)) 13593 return InVec; 13594 13595 // Check that we know which element is being inserted 13596 if (!isa<ConstantSDNode>(EltNo)) 13597 return SDValue(); 13598 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 13599 13600 // Canonicalize insert_vector_elt dag nodes. 13601 // Example: 13602 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 13603 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 13604 // 13605 // Do this only if the child insert_vector node has one use; also 13606 // do this only if indices are both constants and Idx1 < Idx0. 13607 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 13608 && isa<ConstantSDNode>(InVec.getOperand(2))) { 13609 unsigned OtherElt = InVec.getConstantOperandVal(2); 13610 if (Elt < OtherElt) { 13611 // Swap nodes. 13612 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, 13613 InVec.getOperand(0), InVal, EltNo); 13614 AddToWorklist(NewOp.getNode()); 13615 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 13616 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 13617 } 13618 } 13619 13620 // If we can't generate a legal BUILD_VECTOR, exit 13621 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 13622 return SDValue(); 13623 13624 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 13625 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 13626 // vector elements. 13627 SmallVector<SDValue, 8> Ops; 13628 // Do not combine these two vectors if the output vector will not replace 13629 // the input vector. 13630 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 13631 Ops.append(InVec.getNode()->op_begin(), 13632 InVec.getNode()->op_end()); 13633 } else if (InVec.isUndef()) { 13634 unsigned NElts = VT.getVectorNumElements(); 13635 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 13636 } else { 13637 return SDValue(); 13638 } 13639 13640 // Insert the element 13641 if (Elt < Ops.size()) { 13642 // All the operands of BUILD_VECTOR must have the same type; 13643 // we enforce that here. 13644 EVT OpVT = Ops[0].getValueType(); 13645 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal; 13646 } 13647 13648 // Return the new vector 13649 return DAG.getBuildVector(VT, DL, Ops); 13650 } 13651 13652 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 13653 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 13654 assert(!OriginalLoad->isVolatile()); 13655 13656 EVT ResultVT = EVE->getValueType(0); 13657 EVT VecEltVT = InVecVT.getVectorElementType(); 13658 unsigned Align = OriginalLoad->getAlignment(); 13659 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 13660 VecEltVT.getTypeForEVT(*DAG.getContext())); 13661 13662 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 13663 return SDValue(); 13664 13665 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ? 13666 ISD::NON_EXTLOAD : ISD::EXTLOAD; 13667 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT)) 13668 return SDValue(); 13669 13670 Align = NewAlign; 13671 13672 SDValue NewPtr = OriginalLoad->getBasePtr(); 13673 SDValue Offset; 13674 EVT PtrType = NewPtr.getValueType(); 13675 MachinePointerInfo MPI; 13676 SDLoc DL(EVE); 13677 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 13678 int Elt = ConstEltNo->getZExtValue(); 13679 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 13680 Offset = DAG.getConstant(PtrOff, DL, PtrType); 13681 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 13682 } else { 13683 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 13684 Offset = DAG.getNode( 13685 ISD::MUL, DL, PtrType, Offset, 13686 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 13687 MPI = OriginalLoad->getPointerInfo(); 13688 } 13689 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 13690 13691 // The replacement we need to do here is a little tricky: we need to 13692 // replace an extractelement of a load with a load. 13693 // Use ReplaceAllUsesOfValuesWith to do the replacement. 13694 // Note that this replacement assumes that the extractvalue is the only 13695 // use of the load; that's okay because we don't want to perform this 13696 // transformation in other cases anyway. 13697 SDValue Load; 13698 SDValue Chain; 13699 if (ResultVT.bitsGT(VecEltVT)) { 13700 // If the result type of vextract is wider than the load, then issue an 13701 // extending load instead. 13702 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 13703 VecEltVT) 13704 ? ISD::ZEXTLOAD 13705 : ISD::EXTLOAD; 13706 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 13707 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 13708 Align, OriginalLoad->getMemOperand()->getFlags(), 13709 OriginalLoad->getAAInfo()); 13710 Chain = Load.getValue(1); 13711 } else { 13712 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, 13713 MPI, Align, OriginalLoad->getMemOperand()->getFlags(), 13714 OriginalLoad->getAAInfo()); 13715 Chain = Load.getValue(1); 13716 if (ResultVT.bitsLT(VecEltVT)) 13717 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 13718 else 13719 Load = DAG.getBitcast(ResultVT, Load); 13720 } 13721 WorklistRemover DeadNodes(*this); 13722 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 13723 SDValue To[] = { Load, Chain }; 13724 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 13725 // Since we're explicitly calling ReplaceAllUses, add the new node to the 13726 // worklist explicitly as well. 13727 AddToWorklist(Load.getNode()); 13728 AddUsersToWorklist(Load.getNode()); // Add users too 13729 // Make sure to revisit this node to clean it up; it will usually be dead. 13730 AddToWorklist(EVE); 13731 ++OpsNarrowed; 13732 return SDValue(EVE, 0); 13733 } 13734 13735 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 13736 // (vextract (scalar_to_vector val, 0) -> val 13737 SDValue InVec = N->getOperand(0); 13738 EVT VT = InVec.getValueType(); 13739 EVT NVT = N->getValueType(0); 13740 13741 if (InVec.isUndef()) 13742 return DAG.getUNDEF(NVT); 13743 13744 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 13745 // Check if the result type doesn't match the inserted element type. A 13746 // SCALAR_TO_VECTOR may truncate the inserted element and the 13747 // EXTRACT_VECTOR_ELT may widen the extracted vector. 13748 SDValue InOp = InVec.getOperand(0); 13749 if (InOp.getValueType() != NVT) { 13750 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 13751 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 13752 } 13753 return InOp; 13754 } 13755 13756 SDValue EltNo = N->getOperand(1); 13757 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 13758 13759 // extract_vector_elt (build_vector x, y), 1 -> y 13760 if (ConstEltNo && 13761 InVec.getOpcode() == ISD::BUILD_VECTOR && 13762 TLI.isTypeLegal(VT) && 13763 (InVec.hasOneUse() || 13764 TLI.aggressivelyPreferBuildVectorSources(VT))) { 13765 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 13766 EVT InEltVT = Elt.getValueType(); 13767 13768 // Sometimes build_vector's scalar input types do not match result type. 13769 if (NVT == InEltVT) 13770 return Elt; 13771 13772 // TODO: It may be useful to truncate if free if the build_vector implicitly 13773 // converts. 13774 } 13775 13776 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x) 13777 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 13778 ConstEltNo->isNullValue() && VT.isInteger()) { 13779 SDValue BCSrc = InVec.getOperand(0); 13780 if (BCSrc.getValueType().isScalarInteger()) 13781 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 13782 } 13783 13784 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 13785 // 13786 // This only really matters if the index is non-constant since other combines 13787 // on the constant elements already work. 13788 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && 13789 EltNo == InVec.getOperand(2)) { 13790 SDValue Elt = InVec.getOperand(1); 13791 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt; 13792 } 13793 13794 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 13795 // We only perform this optimization before the op legalization phase because 13796 // we may introduce new vector instructions which are not backed by TD 13797 // patterns. For example on AVX, extracting elements from a wide vector 13798 // without using extract_subvector. However, if we can find an underlying 13799 // scalar value, then we can always use that. 13800 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 13801 int NumElem = VT.getVectorNumElements(); 13802 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 13803 // Find the new index to extract from. 13804 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 13805 13806 // Extracting an undef index is undef. 13807 if (OrigElt == -1) 13808 return DAG.getUNDEF(NVT); 13809 13810 // Select the right vector half to extract from. 13811 SDValue SVInVec; 13812 if (OrigElt < NumElem) { 13813 SVInVec = InVec->getOperand(0); 13814 } else { 13815 SVInVec = InVec->getOperand(1); 13816 OrigElt -= NumElem; 13817 } 13818 13819 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 13820 SDValue InOp = SVInVec.getOperand(OrigElt); 13821 if (InOp.getValueType() != NVT) { 13822 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 13823 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 13824 } 13825 13826 return InOp; 13827 } 13828 13829 // FIXME: We should handle recursing on other vector shuffles and 13830 // scalar_to_vector here as well. 13831 13832 if (!LegalOperations) { 13833 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 13834 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 13835 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 13836 } 13837 } 13838 13839 bool BCNumEltsChanged = false; 13840 EVT ExtVT = VT.getVectorElementType(); 13841 EVT LVT = ExtVT; 13842 13843 // If the result of load has to be truncated, then it's not necessarily 13844 // profitable. 13845 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 13846 return SDValue(); 13847 13848 if (InVec.getOpcode() == ISD::BITCAST) { 13849 // Don't duplicate a load with other uses. 13850 if (!InVec.hasOneUse()) 13851 return SDValue(); 13852 13853 EVT BCVT = InVec.getOperand(0).getValueType(); 13854 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 13855 return SDValue(); 13856 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 13857 BCNumEltsChanged = true; 13858 InVec = InVec.getOperand(0); 13859 ExtVT = BCVT.getVectorElementType(); 13860 } 13861 13862 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 13863 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 13864 ISD::isNormalLoad(InVec.getNode()) && 13865 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 13866 SDValue Index = N->getOperand(1); 13867 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) { 13868 if (!OrigLoad->isVolatile()) { 13869 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 13870 OrigLoad); 13871 } 13872 } 13873 } 13874 13875 // Perform only after legalization to ensure build_vector / vector_shuffle 13876 // optimizations have already been done. 13877 if (!LegalOperations) return SDValue(); 13878 13879 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 13880 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 13881 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 13882 13883 if (ConstEltNo) { 13884 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 13885 13886 LoadSDNode *LN0 = nullptr; 13887 const ShuffleVectorSDNode *SVN = nullptr; 13888 if (ISD::isNormalLoad(InVec.getNode())) { 13889 LN0 = cast<LoadSDNode>(InVec); 13890 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 13891 InVec.getOperand(0).getValueType() == ExtVT && 13892 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 13893 // Don't duplicate a load with other uses. 13894 if (!InVec.hasOneUse()) 13895 return SDValue(); 13896 13897 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 13898 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 13899 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 13900 // => 13901 // (load $addr+1*size) 13902 13903 // Don't duplicate a load with other uses. 13904 if (!InVec.hasOneUse()) 13905 return SDValue(); 13906 13907 // If the bit convert changed the number of elements, it is unsafe 13908 // to examine the mask. 13909 if (BCNumEltsChanged) 13910 return SDValue(); 13911 13912 // Select the input vector, guarding against out of range extract vector. 13913 unsigned NumElems = VT.getVectorNumElements(); 13914 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 13915 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 13916 13917 if (InVec.getOpcode() == ISD::BITCAST) { 13918 // Don't duplicate a load with other uses. 13919 if (!InVec.hasOneUse()) 13920 return SDValue(); 13921 13922 InVec = InVec.getOperand(0); 13923 } 13924 if (ISD::isNormalLoad(InVec.getNode())) { 13925 LN0 = cast<LoadSDNode>(InVec); 13926 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 13927 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 13928 } 13929 } 13930 13931 // Make sure we found a non-volatile load and the extractelement is 13932 // the only use. 13933 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 13934 return SDValue(); 13935 13936 // If Idx was -1 above, Elt is going to be -1, so just return undef. 13937 if (Elt == -1) 13938 return DAG.getUNDEF(LVT); 13939 13940 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 13941 } 13942 13943 return SDValue(); 13944 } 13945 13946 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 13947 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 13948 // We perform this optimization post type-legalization because 13949 // the type-legalizer often scalarizes integer-promoted vectors. 13950 // Performing this optimization before may create bit-casts which 13951 // will be type-legalized to complex code sequences. 13952 // We perform this optimization only before the operation legalizer because we 13953 // may introduce illegal operations. 13954 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 13955 return SDValue(); 13956 13957 unsigned NumInScalars = N->getNumOperands(); 13958 SDLoc DL(N); 13959 EVT VT = N->getValueType(0); 13960 13961 // Check to see if this is a BUILD_VECTOR of a bunch of values 13962 // which come from any_extend or zero_extend nodes. If so, we can create 13963 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 13964 // optimizations. We do not handle sign-extend because we can't fill the sign 13965 // using shuffles. 13966 EVT SourceType = MVT::Other; 13967 bool AllAnyExt = true; 13968 13969 for (unsigned i = 0; i != NumInScalars; ++i) { 13970 SDValue In = N->getOperand(i); 13971 // Ignore undef inputs. 13972 if (In.isUndef()) continue; 13973 13974 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 13975 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 13976 13977 // Abort if the element is not an extension. 13978 if (!ZeroExt && !AnyExt) { 13979 SourceType = MVT::Other; 13980 break; 13981 } 13982 13983 // The input is a ZeroExt or AnyExt. Check the original type. 13984 EVT InTy = In.getOperand(0).getValueType(); 13985 13986 // Check that all of the widened source types are the same. 13987 if (SourceType == MVT::Other) 13988 // First time. 13989 SourceType = InTy; 13990 else if (InTy != SourceType) { 13991 // Multiple income types. Abort. 13992 SourceType = MVT::Other; 13993 break; 13994 } 13995 13996 // Check if all of the extends are ANY_EXTENDs. 13997 AllAnyExt &= AnyExt; 13998 } 13999 14000 // In order to have valid types, all of the inputs must be extended from the 14001 // same source type and all of the inputs must be any or zero extend. 14002 // Scalar sizes must be a power of two. 14003 EVT OutScalarTy = VT.getScalarType(); 14004 bool ValidTypes = SourceType != MVT::Other && 14005 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 14006 isPowerOf2_32(SourceType.getSizeInBits()); 14007 14008 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 14009 // turn into a single shuffle instruction. 14010 if (!ValidTypes) 14011 return SDValue(); 14012 14013 bool isLE = DAG.getDataLayout().isLittleEndian(); 14014 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 14015 assert(ElemRatio > 1 && "Invalid element size ratio"); 14016 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 14017 DAG.getConstant(0, DL, SourceType); 14018 14019 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 14020 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 14021 14022 // Populate the new build_vector 14023 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 14024 SDValue Cast = N->getOperand(i); 14025 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 14026 Cast.getOpcode() == ISD::ZERO_EXTEND || 14027 Cast.isUndef()) && "Invalid cast opcode"); 14028 SDValue In; 14029 if (Cast.isUndef()) 14030 In = DAG.getUNDEF(SourceType); 14031 else 14032 In = Cast->getOperand(0); 14033 unsigned Index = isLE ? (i * ElemRatio) : 14034 (i * ElemRatio + (ElemRatio - 1)); 14035 14036 assert(Index < Ops.size() && "Invalid index"); 14037 Ops[Index] = In; 14038 } 14039 14040 // The type of the new BUILD_VECTOR node. 14041 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 14042 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 14043 "Invalid vector size"); 14044 // Check if the new vector type is legal. 14045 if (!isTypeLegal(VecVT)) return SDValue(); 14046 14047 // Make the new BUILD_VECTOR. 14048 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops); 14049 14050 // The new BUILD_VECTOR node has the potential to be further optimized. 14051 AddToWorklist(BV.getNode()); 14052 // Bitcast to the desired type. 14053 return DAG.getBitcast(VT, BV); 14054 } 14055 14056 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 14057 EVT VT = N->getValueType(0); 14058 14059 unsigned NumInScalars = N->getNumOperands(); 14060 SDLoc DL(N); 14061 14062 EVT SrcVT = MVT::Other; 14063 unsigned Opcode = ISD::DELETED_NODE; 14064 unsigned NumDefs = 0; 14065 14066 for (unsigned i = 0; i != NumInScalars; ++i) { 14067 SDValue In = N->getOperand(i); 14068 unsigned Opc = In.getOpcode(); 14069 14070 if (Opc == ISD::UNDEF) 14071 continue; 14072 14073 // If all scalar values are floats and converted from integers. 14074 if (Opcode == ISD::DELETED_NODE && 14075 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 14076 Opcode = Opc; 14077 } 14078 14079 if (Opc != Opcode) 14080 return SDValue(); 14081 14082 EVT InVT = In.getOperand(0).getValueType(); 14083 14084 // If all scalar values are typed differently, bail out. It's chosen to 14085 // simplify BUILD_VECTOR of integer types. 14086 if (SrcVT == MVT::Other) 14087 SrcVT = InVT; 14088 if (SrcVT != InVT) 14089 return SDValue(); 14090 NumDefs++; 14091 } 14092 14093 // If the vector has just one element defined, it's not worth to fold it into 14094 // a vectorized one. 14095 if (NumDefs < 2) 14096 return SDValue(); 14097 14098 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 14099 && "Should only handle conversion from integer to float."); 14100 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 14101 14102 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 14103 14104 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 14105 return SDValue(); 14106 14107 // Just because the floating-point vector type is legal does not necessarily 14108 // mean that the corresponding integer vector type is. 14109 if (!isTypeLegal(NVT)) 14110 return SDValue(); 14111 14112 SmallVector<SDValue, 8> Opnds; 14113 for (unsigned i = 0; i != NumInScalars; ++i) { 14114 SDValue In = N->getOperand(i); 14115 14116 if (In.isUndef()) 14117 Opnds.push_back(DAG.getUNDEF(SrcVT)); 14118 else 14119 Opnds.push_back(In.getOperand(0)); 14120 } 14121 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds); 14122 AddToWorklist(BV.getNode()); 14123 14124 return DAG.getNode(Opcode, DL, VT, BV); 14125 } 14126 14127 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N, 14128 ArrayRef<int> VectorMask, 14129 SDValue VecIn1, SDValue VecIn2, 14130 unsigned LeftIdx) { 14131 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 14132 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy); 14133 14134 EVT VT = N->getValueType(0); 14135 EVT InVT1 = VecIn1.getValueType(); 14136 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1; 14137 14138 unsigned Vec2Offset = InVT1.getVectorNumElements(); 14139 unsigned NumElems = VT.getVectorNumElements(); 14140 unsigned ShuffleNumElems = NumElems; 14141 14142 // We can't generate a shuffle node with mismatched input and output types. 14143 // Try to make the types match the type of the output. 14144 if (InVT1 != VT || InVT2 != VT) { 14145 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) { 14146 // If the output vector length is a multiple of both input lengths, 14147 // we can concatenate them and pad the rest with undefs. 14148 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits(); 14149 assert(NumConcats >= 2 && "Concat needs at least two inputs!"); 14150 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1)); 14151 ConcatOps[0] = VecIn1; 14152 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1); 14153 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 14154 VecIn2 = SDValue(); 14155 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) { 14156 if (!TLI.isExtractSubvectorCheap(VT, NumElems)) 14157 return SDValue(); 14158 14159 if (!VecIn2.getNode()) { 14160 // If we only have one input vector, and it's twice the size of the 14161 // output, split it in two. 14162 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, 14163 DAG.getConstant(NumElems, DL, IdxTy)); 14164 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx); 14165 // Since we now have shorter input vectors, adjust the offset of the 14166 // second vector's start. 14167 Vec2Offset = NumElems; 14168 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) { 14169 // VecIn1 is wider than the output, and we have another, possibly 14170 // smaller input. Pad the smaller input with undefs, shuffle at the 14171 // input vector width, and extract the output. 14172 // The shuffle type is different than VT, so check legality again. 14173 if (LegalOperations && 14174 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1)) 14175 return SDValue(); 14176 14177 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to 14178 // lower it back into a BUILD_VECTOR. So if the inserted type is 14179 // illegal, don't even try. 14180 if (InVT1 != InVT2) { 14181 if (!TLI.isTypeLegal(InVT2)) 14182 return SDValue(); 14183 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1, 14184 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx); 14185 } 14186 ShuffleNumElems = NumElems * 2; 14187 } else { 14188 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider 14189 // than VecIn1. We can't handle this for now - this case will disappear 14190 // when we start sorting the vectors by type. 14191 return SDValue(); 14192 } 14193 } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() && 14194 InVT1.getSizeInBits() == VT.getSizeInBits()) { 14195 SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2)); 14196 ConcatOps[0] = VecIn2; 14197 VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 14198 } else { 14199 // TODO: Support cases where the length mismatch isn't exactly by a 14200 // factor of 2. 14201 // TODO: Move this check upwards, so that if we have bad type 14202 // mismatches, we don't create any DAG nodes. 14203 return SDValue(); 14204 } 14205 } 14206 14207 // Initialize mask to undef. 14208 SmallVector<int, 8> Mask(ShuffleNumElems, -1); 14209 14210 // Only need to run up to the number of elements actually used, not the 14211 // total number of elements in the shuffle - if we are shuffling a wider 14212 // vector, the high lanes should be set to undef. 14213 for (unsigned i = 0; i != NumElems; ++i) { 14214 if (VectorMask[i] <= 0) 14215 continue; 14216 14217 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1); 14218 if (VectorMask[i] == (int)LeftIdx) { 14219 Mask[i] = ExtIndex; 14220 } else if (VectorMask[i] == (int)LeftIdx + 1) { 14221 Mask[i] = Vec2Offset + ExtIndex; 14222 } 14223 } 14224 14225 // The type the input vectors may have changed above. 14226 InVT1 = VecIn1.getValueType(); 14227 14228 // If we already have a VecIn2, it should have the same type as VecIn1. 14229 // If we don't, get an undef/zero vector of the appropriate type. 14230 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1); 14231 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type."); 14232 14233 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask); 14234 if (ShuffleNumElems > NumElems) 14235 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx); 14236 14237 return Shuffle; 14238 } 14239 14240 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 14241 // operations. If the types of the vectors we're extracting from allow it, 14242 // turn this into a vector_shuffle node. 14243 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) { 14244 SDLoc DL(N); 14245 EVT VT = N->getValueType(0); 14246 14247 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 14248 if (!isTypeLegal(VT)) 14249 return SDValue(); 14250 14251 // May only combine to shuffle after legalize if shuffle is legal. 14252 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 14253 return SDValue(); 14254 14255 bool UsesZeroVector = false; 14256 unsigned NumElems = N->getNumOperands(); 14257 14258 // Record, for each element of the newly built vector, which input vector 14259 // that element comes from. -1 stands for undef, 0 for the zero vector, 14260 // and positive values for the input vectors. 14261 // VectorMask maps each element to its vector number, and VecIn maps vector 14262 // numbers to their initial SDValues. 14263 14264 SmallVector<int, 8> VectorMask(NumElems, -1); 14265 SmallVector<SDValue, 8> VecIn; 14266 VecIn.push_back(SDValue()); 14267 14268 for (unsigned i = 0; i != NumElems; ++i) { 14269 SDValue Op = N->getOperand(i); 14270 14271 if (Op.isUndef()) 14272 continue; 14273 14274 // See if we can use a blend with a zero vector. 14275 // TODO: Should we generalize this to a blend with an arbitrary constant 14276 // vector? 14277 if (isNullConstant(Op) || isNullFPConstant(Op)) { 14278 UsesZeroVector = true; 14279 VectorMask[i] = 0; 14280 continue; 14281 } 14282 14283 // Not an undef or zero. If the input is something other than an 14284 // EXTRACT_VECTOR_ELT with a constant index, bail out. 14285 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14286 !isa<ConstantSDNode>(Op.getOperand(1))) 14287 return SDValue(); 14288 14289 SDValue ExtractedFromVec = Op.getOperand(0); 14290 14291 // All inputs must have the same element type as the output. 14292 if (VT.getVectorElementType() != 14293 ExtractedFromVec.getValueType().getVectorElementType()) 14294 return SDValue(); 14295 14296 // Have we seen this input vector before? 14297 // The vectors are expected to be tiny (usually 1 or 2 elements), so using 14298 // a map back from SDValues to numbers isn't worth it. 14299 unsigned Idx = std::distance( 14300 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec)); 14301 if (Idx == VecIn.size()) 14302 VecIn.push_back(ExtractedFromVec); 14303 14304 VectorMask[i] = Idx; 14305 } 14306 14307 // If we didn't find at least one input vector, bail out. 14308 if (VecIn.size() < 2) 14309 return SDValue(); 14310 14311 // TODO: We want to sort the vectors by descending length, so that adjacent 14312 // pairs have similar length, and the longer vector is always first in the 14313 // pair. 14314 14315 // TODO: Should this fire if some of the input vectors has illegal type (like 14316 // it does now), or should we let legalization run its course first? 14317 14318 // Shuffle phase: 14319 // Take pairs of vectors, and shuffle them so that the result has elements 14320 // from these vectors in the correct places. 14321 // For example, given: 14322 // t10: i32 = extract_vector_elt t1, Constant:i64<0> 14323 // t11: i32 = extract_vector_elt t2, Constant:i64<0> 14324 // t12: i32 = extract_vector_elt t3, Constant:i64<0> 14325 // t13: i32 = extract_vector_elt t1, Constant:i64<1> 14326 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13 14327 // We will generate: 14328 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2 14329 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef 14330 SmallVector<SDValue, 4> Shuffles; 14331 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) { 14332 unsigned LeftIdx = 2 * In + 1; 14333 SDValue VecLeft = VecIn[LeftIdx]; 14334 SDValue VecRight = 14335 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue(); 14336 14337 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft, 14338 VecRight, LeftIdx)) 14339 Shuffles.push_back(Shuffle); 14340 else 14341 return SDValue(); 14342 } 14343 14344 // If we need the zero vector as an "ingredient" in the blend tree, add it 14345 // to the list of shuffles. 14346 if (UsesZeroVector) 14347 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT) 14348 : DAG.getConstantFP(0.0, DL, VT)); 14349 14350 // If we only have one shuffle, we're done. 14351 if (Shuffles.size() == 1) 14352 return Shuffles[0]; 14353 14354 // Update the vector mask to point to the post-shuffle vectors. 14355 for (int &Vec : VectorMask) 14356 if (Vec == 0) 14357 Vec = Shuffles.size() - 1; 14358 else 14359 Vec = (Vec - 1) / 2; 14360 14361 // More than one shuffle. Generate a binary tree of blends, e.g. if from 14362 // the previous step we got the set of shuffles t10, t11, t12, t13, we will 14363 // generate: 14364 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2 14365 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4 14366 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6 14367 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8 14368 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11 14369 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13 14370 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21 14371 14372 // Make sure the initial size of the shuffle list is even. 14373 if (Shuffles.size() % 2) 14374 Shuffles.push_back(DAG.getUNDEF(VT)); 14375 14376 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) { 14377 if (CurSize % 2) { 14378 Shuffles[CurSize] = DAG.getUNDEF(VT); 14379 CurSize++; 14380 } 14381 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) { 14382 int Left = 2 * In; 14383 int Right = 2 * In + 1; 14384 SmallVector<int, 8> Mask(NumElems, -1); 14385 for (unsigned i = 0; i != NumElems; ++i) { 14386 if (VectorMask[i] == Left) { 14387 Mask[i] = i; 14388 VectorMask[i] = In; 14389 } else if (VectorMask[i] == Right) { 14390 Mask[i] = i + NumElems; 14391 VectorMask[i] = In; 14392 } 14393 } 14394 14395 Shuffles[In] = 14396 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask); 14397 } 14398 } 14399 14400 return Shuffles[0]; 14401 } 14402 14403 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 14404 // operations which can be matched to a truncate. 14405 SDValue DAGCombiner::reduceBuildVecToTrunc(SDNode *N) { 14406 // TODO: Add support for big-endian. 14407 if (DAG.getDataLayout().isBigEndian()) 14408 return SDValue(); 14409 if (N->getNumOperands() < 2) 14410 return SDValue(); 14411 SDLoc DL(N); 14412 EVT VT = N->getValueType(0); 14413 unsigned NumElems = N->getNumOperands(); 14414 14415 if (!isTypeLegal(VT)) 14416 return SDValue(); 14417 14418 // If the input is something other than an EXTRACT_VECTOR_ELT with a constant 14419 // index, bail out. 14420 // TODO: Allow undef elements in some cases? 14421 if (any_of(N->ops(), [VT](SDValue Op) { 14422 return Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14423 !isa<ConstantSDNode>(Op.getOperand(1)) || 14424 Op.getValueType() != VT.getVectorElementType(); 14425 })) 14426 return SDValue(); 14427 14428 // Helper for obtaining an EXTRACT_VECTOR_ELT's constant index 14429 auto GetExtractIdx = [](SDValue Extract) { 14430 return cast<ConstantSDNode>(Extract.getOperand(1))->getSExtValue(); 14431 }; 14432 14433 // The first BUILD_VECTOR operand must be an an extract from index zero 14434 // (assuming no undef and little-endian). 14435 if (GetExtractIdx(N->getOperand(0)) != 0) 14436 return SDValue(); 14437 14438 // Compute the stride from the first index. 14439 int Stride = GetExtractIdx(N->getOperand(1)); 14440 SDValue ExtractedFromVec = N->getOperand(0).getOperand(0); 14441 14442 // Proceed only if the stride and the types can be matched to a truncate. 14443 if ((Stride == 1 || !isPowerOf2_32(Stride)) || 14444 (ExtractedFromVec.getValueType().getVectorNumElements() != 14445 Stride * NumElems) || 14446 (VT.getScalarSizeInBits() * Stride > 64)) 14447 return SDValue(); 14448 14449 // Check remaining operands are consistent with the computed stride. 14450 for (unsigned i = 1; i != NumElems; ++i) { 14451 SDValue Op = N->getOperand(i); 14452 14453 if ((Op.getOperand(0) != ExtractedFromVec) || 14454 (GetExtractIdx(Op) != Stride * i)) 14455 return SDValue(); 14456 } 14457 14458 // All checks were ok, construct the truncate. 14459 LLVMContext &Ctx = *DAG.getContext(); 14460 EVT NewVT = VT.getVectorVT( 14461 Ctx, EVT::getIntegerVT(Ctx, VT.getScalarSizeInBits() * Stride), NumElems); 14462 EVT TruncVT = 14463 VT.isFloatingPoint() ? VT.changeVectorElementTypeToInteger() : VT; 14464 14465 SDValue Res = DAG.getBitcast(NewVT, ExtractedFromVec); 14466 Res = DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, Res); 14467 return DAG.getBitcast(VT, Res); 14468 } 14469 14470 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 14471 EVT VT = N->getValueType(0); 14472 14473 // A vector built entirely of undefs is undef. 14474 if (ISD::allOperandsUndef(N)) 14475 return DAG.getUNDEF(VT); 14476 14477 // Check if we can express BUILD VECTOR via subvector extract. 14478 if (!LegalTypes && (N->getNumOperands() > 1)) { 14479 SDValue Op0 = N->getOperand(0); 14480 auto checkElem = [&](SDValue Op) -> uint64_t { 14481 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) && 14482 (Op0.getOperand(0) == Op.getOperand(0))) 14483 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 14484 return CNode->getZExtValue(); 14485 return -1; 14486 }; 14487 14488 int Offset = checkElem(Op0); 14489 for (unsigned i = 0; i < N->getNumOperands(); ++i) { 14490 if (Offset + i != checkElem(N->getOperand(i))) { 14491 Offset = -1; 14492 break; 14493 } 14494 } 14495 14496 if ((Offset == 0) && 14497 (Op0.getOperand(0).getValueType() == N->getValueType(0))) 14498 return Op0.getOperand(0); 14499 if ((Offset != -1) && 14500 ((Offset % N->getValueType(0).getVectorNumElements()) == 14501 0)) // IDX must be multiple of output size. 14502 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0), 14503 Op0.getOperand(0), Op0.getOperand(1)); 14504 } 14505 14506 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 14507 return V; 14508 14509 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 14510 return V; 14511 14512 if (TLI.isDesirableToCombineBuildVectorToTruncate()) 14513 if (SDValue V = reduceBuildVecToTrunc(N)) 14514 return V; 14515 14516 if (SDValue V = reduceBuildVecToShuffle(N)) 14517 return V; 14518 14519 return SDValue(); 14520 } 14521 14522 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 14523 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14524 EVT OpVT = N->getOperand(0).getValueType(); 14525 14526 // If the operands are legal vectors, leave them alone. 14527 if (TLI.isTypeLegal(OpVT)) 14528 return SDValue(); 14529 14530 SDLoc DL(N); 14531 EVT VT = N->getValueType(0); 14532 SmallVector<SDValue, 8> Ops; 14533 14534 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 14535 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 14536 14537 // Keep track of what we encounter. 14538 bool AnyInteger = false; 14539 bool AnyFP = false; 14540 for (const SDValue &Op : N->ops()) { 14541 if (ISD::BITCAST == Op.getOpcode() && 14542 !Op.getOperand(0).getValueType().isVector()) 14543 Ops.push_back(Op.getOperand(0)); 14544 else if (ISD::UNDEF == Op.getOpcode()) 14545 Ops.push_back(ScalarUndef); 14546 else 14547 return SDValue(); 14548 14549 // Note whether we encounter an integer or floating point scalar. 14550 // If it's neither, bail out, it could be something weird like x86mmx. 14551 EVT LastOpVT = Ops.back().getValueType(); 14552 if (LastOpVT.isFloatingPoint()) 14553 AnyFP = true; 14554 else if (LastOpVT.isInteger()) 14555 AnyInteger = true; 14556 else 14557 return SDValue(); 14558 } 14559 14560 // If any of the operands is a floating point scalar bitcast to a vector, 14561 // use floating point types throughout, and bitcast everything. 14562 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 14563 if (AnyFP) { 14564 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 14565 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 14566 if (AnyInteger) { 14567 for (SDValue &Op : Ops) { 14568 if (Op.getValueType() == SVT) 14569 continue; 14570 if (Op.isUndef()) 14571 Op = ScalarUndef; 14572 else 14573 Op = DAG.getBitcast(SVT, Op); 14574 } 14575 } 14576 } 14577 14578 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 14579 VT.getSizeInBits() / SVT.getSizeInBits()); 14580 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 14581 } 14582 14583 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 14584 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 14585 // most two distinct vectors the same size as the result, attempt to turn this 14586 // into a legal shuffle. 14587 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 14588 EVT VT = N->getValueType(0); 14589 EVT OpVT = N->getOperand(0).getValueType(); 14590 int NumElts = VT.getVectorNumElements(); 14591 int NumOpElts = OpVT.getVectorNumElements(); 14592 14593 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 14594 SmallVector<int, 8> Mask; 14595 14596 for (SDValue Op : N->ops()) { 14597 // Peek through any bitcast. 14598 while (Op.getOpcode() == ISD::BITCAST) 14599 Op = Op.getOperand(0); 14600 14601 // UNDEF nodes convert to UNDEF shuffle mask values. 14602 if (Op.isUndef()) { 14603 Mask.append((unsigned)NumOpElts, -1); 14604 continue; 14605 } 14606 14607 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 14608 return SDValue(); 14609 14610 // What vector are we extracting the subvector from and at what index? 14611 SDValue ExtVec = Op.getOperand(0); 14612 14613 // We want the EVT of the original extraction to correctly scale the 14614 // extraction index. 14615 EVT ExtVT = ExtVec.getValueType(); 14616 14617 // Peek through any bitcast. 14618 while (ExtVec.getOpcode() == ISD::BITCAST) 14619 ExtVec = ExtVec.getOperand(0); 14620 14621 // UNDEF nodes convert to UNDEF shuffle mask values. 14622 if (ExtVec.isUndef()) { 14623 Mask.append((unsigned)NumOpElts, -1); 14624 continue; 14625 } 14626 14627 if (!isa<ConstantSDNode>(Op.getOperand(1))) 14628 return SDValue(); 14629 int ExtIdx = Op.getConstantOperandVal(1); 14630 14631 // Ensure that we are extracting a subvector from a vector the same 14632 // size as the result. 14633 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 14634 return SDValue(); 14635 14636 // Scale the subvector index to account for any bitcast. 14637 int NumExtElts = ExtVT.getVectorNumElements(); 14638 if (0 == (NumExtElts % NumElts)) 14639 ExtIdx /= (NumExtElts / NumElts); 14640 else if (0 == (NumElts % NumExtElts)) 14641 ExtIdx *= (NumElts / NumExtElts); 14642 else 14643 return SDValue(); 14644 14645 // At most we can reference 2 inputs in the final shuffle. 14646 if (SV0.isUndef() || SV0 == ExtVec) { 14647 SV0 = ExtVec; 14648 for (int i = 0; i != NumOpElts; ++i) 14649 Mask.push_back(i + ExtIdx); 14650 } else if (SV1.isUndef() || SV1 == ExtVec) { 14651 SV1 = ExtVec; 14652 for (int i = 0; i != NumOpElts; ++i) 14653 Mask.push_back(i + ExtIdx + NumElts); 14654 } else { 14655 return SDValue(); 14656 } 14657 } 14658 14659 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 14660 return SDValue(); 14661 14662 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 14663 DAG.getBitcast(VT, SV1), Mask); 14664 } 14665 14666 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 14667 // If we only have one input vector, we don't need to do any concatenation. 14668 if (N->getNumOperands() == 1) 14669 return N->getOperand(0); 14670 14671 // Check if all of the operands are undefs. 14672 EVT VT = N->getValueType(0); 14673 if (ISD::allOperandsUndef(N)) 14674 return DAG.getUNDEF(VT); 14675 14676 // Optimize concat_vectors where all but the first of the vectors are undef. 14677 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 14678 return Op.isUndef(); 14679 })) { 14680 SDValue In = N->getOperand(0); 14681 assert(In.getValueType().isVector() && "Must concat vectors"); 14682 14683 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 14684 if (In->getOpcode() == ISD::BITCAST && 14685 !In->getOperand(0)->getValueType(0).isVector()) { 14686 SDValue Scalar = In->getOperand(0); 14687 14688 // If the bitcast type isn't legal, it might be a trunc of a legal type; 14689 // look through the trunc so we can still do the transform: 14690 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 14691 if (Scalar->getOpcode() == ISD::TRUNCATE && 14692 !TLI.isTypeLegal(Scalar.getValueType()) && 14693 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 14694 Scalar = Scalar->getOperand(0); 14695 14696 EVT SclTy = Scalar->getValueType(0); 14697 14698 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 14699 return SDValue(); 14700 14701 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits(); 14702 if (VNTNumElms < 2) 14703 return SDValue(); 14704 14705 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms); 14706 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 14707 return SDValue(); 14708 14709 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar); 14710 return DAG.getBitcast(VT, Res); 14711 } 14712 } 14713 14714 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 14715 // We have already tested above for an UNDEF only concatenation. 14716 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 14717 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 14718 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 14719 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 14720 }; 14721 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 14722 SmallVector<SDValue, 8> Opnds; 14723 EVT SVT = VT.getScalarType(); 14724 14725 EVT MinVT = SVT; 14726 if (!SVT.isFloatingPoint()) { 14727 // If BUILD_VECTOR are from built from integer, they may have different 14728 // operand types. Get the smallest type and truncate all operands to it. 14729 bool FoundMinVT = false; 14730 for (const SDValue &Op : N->ops()) 14731 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 14732 EVT OpSVT = Op.getOperand(0)->getValueType(0); 14733 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 14734 FoundMinVT = true; 14735 } 14736 assert(FoundMinVT && "Concat vector type mismatch"); 14737 } 14738 14739 for (const SDValue &Op : N->ops()) { 14740 EVT OpVT = Op.getValueType(); 14741 unsigned NumElts = OpVT.getVectorNumElements(); 14742 14743 if (ISD::UNDEF == Op.getOpcode()) 14744 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 14745 14746 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 14747 if (SVT.isFloatingPoint()) { 14748 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 14749 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 14750 } else { 14751 for (unsigned i = 0; i != NumElts; ++i) 14752 Opnds.push_back( 14753 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 14754 } 14755 } 14756 } 14757 14758 assert(VT.getVectorNumElements() == Opnds.size() && 14759 "Concat vector type mismatch"); 14760 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 14761 } 14762 14763 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 14764 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 14765 return V; 14766 14767 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 14768 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 14769 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 14770 return V; 14771 14772 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 14773 // nodes often generate nop CONCAT_VECTOR nodes. 14774 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 14775 // place the incoming vectors at the exact same location. 14776 SDValue SingleSource = SDValue(); 14777 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 14778 14779 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 14780 SDValue Op = N->getOperand(i); 14781 14782 if (Op.isUndef()) 14783 continue; 14784 14785 // Check if this is the identity extract: 14786 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 14787 return SDValue(); 14788 14789 // Find the single incoming vector for the extract_subvector. 14790 if (SingleSource.getNode()) { 14791 if (Op.getOperand(0) != SingleSource) 14792 return SDValue(); 14793 } else { 14794 SingleSource = Op.getOperand(0); 14795 14796 // Check the source type is the same as the type of the result. 14797 // If not, this concat may extend the vector, so we can not 14798 // optimize it away. 14799 if (SingleSource.getValueType() != N->getValueType(0)) 14800 return SDValue(); 14801 } 14802 14803 unsigned IdentityIndex = i * PartNumElem; 14804 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 14805 // The extract index must be constant. 14806 if (!CS) 14807 return SDValue(); 14808 14809 // Check that we are reading from the identity index. 14810 if (CS->getZExtValue() != IdentityIndex) 14811 return SDValue(); 14812 } 14813 14814 if (SingleSource.getNode()) 14815 return SingleSource; 14816 14817 return SDValue(); 14818 } 14819 14820 /// If we are extracting a subvector produced by a wide binary operator with at 14821 /// at least one operand that was the result of a vector concatenation, then try 14822 /// to use the narrow vector operands directly to avoid the concatenation and 14823 /// extraction. 14824 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) { 14825 // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share 14826 // some of these bailouts with other transforms. 14827 14828 // The extract index must be a constant, so we can map it to a concat operand. 14829 auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 14830 if (!ExtractIndex) 14831 return SDValue(); 14832 14833 // Only handle the case where we are doubling and then halving. A larger ratio 14834 // may require more than two narrow binops to replace the wide binop. 14835 EVT VT = Extract->getValueType(0); 14836 unsigned NumElems = VT.getVectorNumElements(); 14837 assert((ExtractIndex->getZExtValue() % NumElems) == 0 && 14838 "Extract index is not a multiple of the vector length."); 14839 if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2) 14840 return SDValue(); 14841 14842 // We are looking for an optionally bitcasted wide vector binary operator 14843 // feeding an extract subvector. 14844 SDValue BinOp = Extract->getOperand(0); 14845 if (BinOp.getOpcode() == ISD::BITCAST) 14846 BinOp = BinOp.getOperand(0); 14847 14848 // TODO: The motivating case for this transform is an x86 AVX1 target. That 14849 // target has temptingly almost legal versions of bitwise logic ops in 256-bit 14850 // flavors, but no other 256-bit integer support. This could be extended to 14851 // handle any binop, but that may require fixing/adding other folds to avoid 14852 // codegen regressions. 14853 unsigned BOpcode = BinOp.getOpcode(); 14854 if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR) 14855 return SDValue(); 14856 14857 // The binop must be a vector type, so we can chop it in half. 14858 EVT WideBVT = BinOp.getValueType(); 14859 if (!WideBVT.isVector()) 14860 return SDValue(); 14861 14862 // Bail out if the target does not support a narrower version of the binop. 14863 EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(), 14864 WideBVT.getVectorNumElements() / 2); 14865 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14866 if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT)) 14867 return SDValue(); 14868 14869 // Peek through bitcasts of the binary operator operands if needed. 14870 SDValue LHS = BinOp.getOperand(0); 14871 if (LHS.getOpcode() == ISD::BITCAST) 14872 LHS = LHS.getOperand(0); 14873 14874 SDValue RHS = BinOp.getOperand(1); 14875 if (RHS.getOpcode() == ISD::BITCAST) 14876 RHS = RHS.getOperand(0); 14877 14878 // We need at least one concatenation operation of a binop operand to make 14879 // this transform worthwhile. The concat must double the input vector sizes. 14880 // TODO: Should we also handle INSERT_SUBVECTOR patterns? 14881 bool ConcatL = 14882 LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2; 14883 bool ConcatR = 14884 RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2; 14885 if (!ConcatL && !ConcatR) 14886 return SDValue(); 14887 14888 // If one of the binop operands was not the result of a concat, we must 14889 // extract a half-sized operand for our new narrow binop. We can't just reuse 14890 // the original extract index operand because we may have bitcasted. 14891 unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems; 14892 unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements(); 14893 EVT ExtBOIdxVT = Extract->getOperand(1).getValueType(); 14894 SDLoc DL(Extract); 14895 14896 // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN 14897 // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N) 14898 // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN 14899 SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum)) 14900 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 14901 BinOp.getOperand(0), 14902 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT)); 14903 14904 SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum)) 14905 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 14906 BinOp.getOperand(1), 14907 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT)); 14908 14909 SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y); 14910 return DAG.getBitcast(VT, NarrowBinOp); 14911 } 14912 14913 /// If we are extracting a subvector from a wide vector load, convert to a 14914 /// narrow load to eliminate the extraction: 14915 /// (extract_subvector (load wide vector)) --> (load narrow vector) 14916 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) { 14917 // TODO: Add support for big-endian. The offset calculation must be adjusted. 14918 if (DAG.getDataLayout().isBigEndian()) 14919 return SDValue(); 14920 14921 // TODO: The one-use check is overly conservative. Check the cost of the 14922 // extract instead or remove that condition entirely. 14923 auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0)); 14924 auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 14925 if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() || 14926 !ExtIdx) 14927 return SDValue(); 14928 14929 // The narrow load will be offset from the base address of the old load if 14930 // we are extracting from something besides index 0 (little-endian). 14931 EVT VT = Extract->getValueType(0); 14932 SDLoc DL(Extract); 14933 SDValue BaseAddr = Ld->getOperand(1); 14934 unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize(); 14935 14936 // TODO: Use "BaseIndexOffset" to make this more effective. 14937 SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL); 14938 MachineFunction &MF = DAG.getMachineFunction(); 14939 MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset, 14940 VT.getStoreSize()); 14941 SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO); 14942 DAG.makeEquivalentMemoryOrdering(Ld, NewLd); 14943 return NewLd; 14944 } 14945 14946 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 14947 EVT NVT = N->getValueType(0); 14948 SDValue V = N->getOperand(0); 14949 14950 // Extract from UNDEF is UNDEF. 14951 if (V.isUndef()) 14952 return DAG.getUNDEF(NVT); 14953 14954 if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT)) 14955 if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG)) 14956 return NarrowLoad; 14957 14958 // Combine: 14959 // (extract_subvec (concat V1, V2, ...), i) 14960 // Into: 14961 // Vi if possible 14962 // Only operand 0 is checked as 'concat' assumes all inputs of the same 14963 // type. 14964 if (V->getOpcode() == ISD::CONCAT_VECTORS && 14965 isa<ConstantSDNode>(N->getOperand(1)) && 14966 V->getOperand(0).getValueType() == NVT) { 14967 unsigned Idx = N->getConstantOperandVal(1); 14968 unsigned NumElems = NVT.getVectorNumElements(); 14969 assert((Idx % NumElems) == 0 && 14970 "IDX in concat is not a multiple of the result vector length."); 14971 return V->getOperand(Idx / NumElems); 14972 } 14973 14974 // Skip bitcasting 14975 if (V->getOpcode() == ISD::BITCAST) 14976 V = V.getOperand(0); 14977 14978 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 14979 // Handle only simple case where vector being inserted and vector 14980 // being extracted are of same size. 14981 EVT SmallVT = V->getOperand(1).getValueType(); 14982 if (!NVT.bitsEq(SmallVT)) 14983 return SDValue(); 14984 14985 // Only handle cases where both indexes are constants. 14986 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 14987 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 14988 14989 if (InsIdx && ExtIdx) { 14990 // Combine: 14991 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 14992 // Into: 14993 // indices are equal or bit offsets are equal => V1 14994 // otherwise => (extract_subvec V1, ExtIdx) 14995 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() == 14996 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits()) 14997 return DAG.getBitcast(NVT, V->getOperand(1)); 14998 return DAG.getNode( 14999 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, 15000 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)), 15001 N->getOperand(1)); 15002 } 15003 } 15004 15005 if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG)) 15006 return NarrowBOp; 15007 15008 return SDValue(); 15009 } 15010 15011 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 15012 SDValue V, SelectionDAG &DAG) { 15013 SDLoc DL(V); 15014 EVT VT = V.getValueType(); 15015 15016 switch (V.getOpcode()) { 15017 default: 15018 return V; 15019 15020 case ISD::CONCAT_VECTORS: { 15021 EVT OpVT = V->getOperand(0).getValueType(); 15022 int OpSize = OpVT.getVectorNumElements(); 15023 SmallBitVector OpUsedElements(OpSize, false); 15024 bool FoundSimplification = false; 15025 SmallVector<SDValue, 4> NewOps; 15026 NewOps.reserve(V->getNumOperands()); 15027 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 15028 SDValue Op = V->getOperand(i); 15029 bool OpUsed = false; 15030 for (int j = 0; j < OpSize; ++j) 15031 if (UsedElements[i * OpSize + j]) { 15032 OpUsedElements[j] = true; 15033 OpUsed = true; 15034 } 15035 NewOps.push_back( 15036 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 15037 : DAG.getUNDEF(OpVT)); 15038 FoundSimplification |= Op == NewOps.back(); 15039 OpUsedElements.reset(); 15040 } 15041 if (FoundSimplification) 15042 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 15043 return V; 15044 } 15045 15046 case ISD::INSERT_SUBVECTOR: { 15047 SDValue BaseV = V->getOperand(0); 15048 SDValue SubV = V->getOperand(1); 15049 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 15050 if (!IdxN) 15051 return V; 15052 15053 int SubSize = SubV.getValueType().getVectorNumElements(); 15054 int Idx = IdxN->getZExtValue(); 15055 bool SubVectorUsed = false; 15056 SmallBitVector SubUsedElements(SubSize, false); 15057 for (int i = 0; i < SubSize; ++i) 15058 if (UsedElements[i + Idx]) { 15059 SubVectorUsed = true; 15060 SubUsedElements[i] = true; 15061 UsedElements[i + Idx] = false; 15062 } 15063 15064 // Now recurse on both the base and sub vectors. 15065 SDValue SimplifiedSubV = 15066 SubVectorUsed 15067 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 15068 : DAG.getUNDEF(SubV.getValueType()); 15069 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 15070 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 15071 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 15072 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 15073 return V; 15074 } 15075 } 15076 } 15077 15078 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 15079 SDValue N1, SelectionDAG &DAG) { 15080 EVT VT = SVN->getValueType(0); 15081 int NumElts = VT.getVectorNumElements(); 15082 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 15083 for (int M : SVN->getMask()) 15084 if (M >= 0 && M < NumElts) 15085 N0UsedElements[M] = true; 15086 else if (M >= NumElts) 15087 N1UsedElements[M - NumElts] = true; 15088 15089 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 15090 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 15091 if (S0 == N0 && S1 == N1) 15092 return SDValue(); 15093 15094 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 15095 } 15096 15097 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 15098 // or turn a shuffle of a single concat into simpler shuffle then concat. 15099 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 15100 EVT VT = N->getValueType(0); 15101 unsigned NumElts = VT.getVectorNumElements(); 15102 15103 SDValue N0 = N->getOperand(0); 15104 SDValue N1 = N->getOperand(1); 15105 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 15106 15107 SmallVector<SDValue, 4> Ops; 15108 EVT ConcatVT = N0.getOperand(0).getValueType(); 15109 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 15110 unsigned NumConcats = NumElts / NumElemsPerConcat; 15111 15112 // Special case: shuffle(concat(A,B)) can be more efficiently represented 15113 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 15114 // half vector elements. 15115 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 15116 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 15117 SVN->getMask().end(), [](int i) { return i == -1; })) { 15118 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 15119 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 15120 N1 = DAG.getUNDEF(ConcatVT); 15121 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 15122 } 15123 15124 // Look at every vector that's inserted. We're looking for exact 15125 // subvector-sized copies from a concatenated vector 15126 for (unsigned I = 0; I != NumConcats; ++I) { 15127 // Make sure we're dealing with a copy. 15128 unsigned Begin = I * NumElemsPerConcat; 15129 bool AllUndef = true, NoUndef = true; 15130 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 15131 if (SVN->getMaskElt(J) >= 0) 15132 AllUndef = false; 15133 else 15134 NoUndef = false; 15135 } 15136 15137 if (NoUndef) { 15138 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 15139 return SDValue(); 15140 15141 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 15142 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 15143 return SDValue(); 15144 15145 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 15146 if (FirstElt < N0.getNumOperands()) 15147 Ops.push_back(N0.getOperand(FirstElt)); 15148 else 15149 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 15150 15151 } else if (AllUndef) { 15152 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 15153 } else { // Mixed with general masks and undefs, can't do optimization. 15154 return SDValue(); 15155 } 15156 } 15157 15158 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 15159 } 15160 15161 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 15162 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 15163 // 15164 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always 15165 // a simplification in some sense, but it isn't appropriate in general: some 15166 // BUILD_VECTORs are substantially cheaper than others. The general case 15167 // of a BUILD_VECTOR requires inserting each element individually (or 15168 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of 15169 // all constants is a single constant pool load. A BUILD_VECTOR where each 15170 // element is identical is a splat. A BUILD_VECTOR where most of the operands 15171 // are undef lowers to a small number of element insertions. 15172 // 15173 // To deal with this, we currently use a bunch of mostly arbitrary heuristics. 15174 // We don't fold shuffles where one side is a non-zero constant, and we don't 15175 // fold shuffles if the resulting BUILD_VECTOR would have duplicate 15176 // non-constant operands. This seems to work out reasonably well in practice. 15177 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN, 15178 SelectionDAG &DAG, 15179 const TargetLowering &TLI) { 15180 EVT VT = SVN->getValueType(0); 15181 unsigned NumElts = VT.getVectorNumElements(); 15182 SDValue N0 = SVN->getOperand(0); 15183 SDValue N1 = SVN->getOperand(1); 15184 15185 if (!N0->hasOneUse() || !N1->hasOneUse()) 15186 return SDValue(); 15187 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as 15188 // discussed above. 15189 if (!N1.isUndef()) { 15190 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode()); 15191 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode()); 15192 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode())) 15193 return SDValue(); 15194 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode())) 15195 return SDValue(); 15196 } 15197 15198 SmallVector<SDValue, 8> Ops; 15199 SmallSet<SDValue, 16> DuplicateOps; 15200 for (int M : SVN->getMask()) { 15201 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 15202 if (M >= 0) { 15203 int Idx = M < (int)NumElts ? M : M - NumElts; 15204 SDValue &S = (M < (int)NumElts ? N0 : N1); 15205 if (S.getOpcode() == ISD::BUILD_VECTOR) { 15206 Op = S.getOperand(Idx); 15207 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) { 15208 if (Idx == 0) 15209 Op = S.getOperand(0); 15210 } else { 15211 // Operand can't be combined - bail out. 15212 return SDValue(); 15213 } 15214 } 15215 15216 // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is 15217 // fine, but it's likely to generate low-quality code if the target can't 15218 // reconstruct an appropriate shuffle. 15219 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op)) 15220 if (!DuplicateOps.insert(Op).second) 15221 return SDValue(); 15222 15223 Ops.push_back(Op); 15224 } 15225 // BUILD_VECTOR requires all inputs to be of the same type, find the 15226 // maximum type and extend them all. 15227 EVT SVT = VT.getScalarType(); 15228 if (SVT.isInteger()) 15229 for (SDValue &Op : Ops) 15230 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 15231 if (SVT != VT.getScalarType()) 15232 for (SDValue &Op : Ops) 15233 Op = TLI.isZExtFree(Op.getValueType(), SVT) 15234 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT) 15235 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT); 15236 return DAG.getBuildVector(VT, SDLoc(SVN), Ops); 15237 } 15238 15239 // Match shuffles that can be converted to any_vector_extend_in_reg. 15240 // This is often generated during legalization. 15241 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src)) 15242 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case. 15243 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN, 15244 SelectionDAG &DAG, 15245 const TargetLowering &TLI, 15246 bool LegalOperations) { 15247 EVT VT = SVN->getValueType(0); 15248 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 15249 15250 // TODO Add support for big-endian when we have a test case. 15251 if (!VT.isInteger() || IsBigEndian) 15252 return SDValue(); 15253 15254 unsigned NumElts = VT.getVectorNumElements(); 15255 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 15256 ArrayRef<int> Mask = SVN->getMask(); 15257 SDValue N0 = SVN->getOperand(0); 15258 15259 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32)) 15260 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) { 15261 for (unsigned i = 0; i != NumElts; ++i) { 15262 if (Mask[i] < 0) 15263 continue; 15264 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale)) 15265 continue; 15266 return false; 15267 } 15268 return true; 15269 }; 15270 15271 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for 15272 // power-of-2 extensions as they are the most likely. 15273 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) { 15274 if (!isAnyExtend(Scale)) 15275 continue; 15276 15277 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale); 15278 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale); 15279 if (!LegalOperations || 15280 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT)) 15281 return DAG.getBitcast(VT, 15282 DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT)); 15283 } 15284 15285 return SDValue(); 15286 } 15287 15288 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of 15289 // each source element of a large type into the lowest elements of a smaller 15290 // destination type. This is often generated during legalization. 15291 // If the source node itself was a '*_extend_vector_inreg' node then we should 15292 // then be able to remove it. 15293 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, 15294 SelectionDAG &DAG) { 15295 EVT VT = SVN->getValueType(0); 15296 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 15297 15298 // TODO Add support for big-endian when we have a test case. 15299 if (!VT.isInteger() || IsBigEndian) 15300 return SDValue(); 15301 15302 SDValue N0 = SVN->getOperand(0); 15303 while (N0.getOpcode() == ISD::BITCAST) 15304 N0 = N0.getOperand(0); 15305 15306 unsigned Opcode = N0.getOpcode(); 15307 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG && 15308 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG && 15309 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG) 15310 return SDValue(); 15311 15312 SDValue N00 = N0.getOperand(0); 15313 ArrayRef<int> Mask = SVN->getMask(); 15314 unsigned NumElts = VT.getVectorNumElements(); 15315 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 15316 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits(); 15317 unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits(); 15318 15319 if (ExtDstSizeInBits % ExtSrcSizeInBits != 0) 15320 return SDValue(); 15321 unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits; 15322 15323 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1> 15324 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1> 15325 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1> 15326 auto isTruncate = [&Mask, &NumElts](unsigned Scale) { 15327 for (unsigned i = 0; i != NumElts; ++i) { 15328 if (Mask[i] < 0) 15329 continue; 15330 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale)) 15331 continue; 15332 return false; 15333 } 15334 return true; 15335 }; 15336 15337 // At the moment we just handle the case where we've truncated back to the 15338 // same size as before the extension. 15339 // TODO: handle more extension/truncation cases as cases arise. 15340 if (EltSizeInBits != ExtSrcSizeInBits) 15341 return SDValue(); 15342 15343 // We can remove *extend_vector_inreg only if the truncation happens at 15344 // the same scale as the extension. 15345 if (isTruncate(ExtScale)) 15346 return DAG.getBitcast(VT, N00); 15347 15348 return SDValue(); 15349 } 15350 15351 // Combine shuffles of splat-shuffles of the form: 15352 // shuffle (shuffle V, undef, splat-mask), undef, M 15353 // If splat-mask contains undef elements, we need to be careful about 15354 // introducing undef's in the folded mask which are not the result of composing 15355 // the masks of the shuffles. 15356 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask, 15357 ShuffleVectorSDNode *Splat, 15358 SelectionDAG &DAG) { 15359 ArrayRef<int> SplatMask = Splat->getMask(); 15360 assert(UserMask.size() == SplatMask.size() && "Mask length mismatch"); 15361 15362 // Prefer simplifying to the splat-shuffle, if possible. This is legal if 15363 // every undef mask element in the splat-shuffle has a corresponding undef 15364 // element in the user-shuffle's mask or if the composition of mask elements 15365 // would result in undef. 15366 // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask): 15367 // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u] 15368 // In this case it is not legal to simplify to the splat-shuffle because we 15369 // may be exposing the users of the shuffle an undef element at index 1 15370 // which was not there before the combine. 15371 // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u] 15372 // In this case the composition of masks yields SplatMask, so it's ok to 15373 // simplify to the splat-shuffle. 15374 // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u] 15375 // In this case the composed mask includes all undef elements of SplatMask 15376 // and in addition sets element zero to undef. It is safe to simplify to 15377 // the splat-shuffle. 15378 auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask, 15379 ArrayRef<int> SplatMask) { 15380 for (unsigned i = 0, e = UserMask.size(); i != e; ++i) 15381 if (UserMask[i] != -1 && SplatMask[i] == -1 && 15382 SplatMask[UserMask[i]] != -1) 15383 return false; 15384 return true; 15385 }; 15386 if (CanSimplifyToExistingSplat(UserMask, SplatMask)) 15387 return SDValue(Splat, 0); 15388 15389 // Create a new shuffle with a mask that is composed of the two shuffles' 15390 // masks. 15391 SmallVector<int, 32> NewMask; 15392 for (int Idx : UserMask) 15393 NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]); 15394 15395 return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat), 15396 Splat->getOperand(0), Splat->getOperand(1), 15397 NewMask); 15398 } 15399 15400 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 15401 EVT VT = N->getValueType(0); 15402 unsigned NumElts = VT.getVectorNumElements(); 15403 15404 SDValue N0 = N->getOperand(0); 15405 SDValue N1 = N->getOperand(1); 15406 15407 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 15408 15409 // Canonicalize shuffle undef, undef -> undef 15410 if (N0.isUndef() && N1.isUndef()) 15411 return DAG.getUNDEF(VT); 15412 15413 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 15414 15415 // Canonicalize shuffle v, v -> v, undef 15416 if (N0 == N1) { 15417 SmallVector<int, 8> NewMask; 15418 for (unsigned i = 0; i != NumElts; ++i) { 15419 int Idx = SVN->getMaskElt(i); 15420 if (Idx >= (int)NumElts) Idx -= NumElts; 15421 NewMask.push_back(Idx); 15422 } 15423 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 15424 } 15425 15426 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 15427 if (N0.isUndef()) 15428 return DAG.getCommutedVectorShuffle(*SVN); 15429 15430 // Remove references to rhs if it is undef 15431 if (N1.isUndef()) { 15432 bool Changed = false; 15433 SmallVector<int, 8> NewMask; 15434 for (unsigned i = 0; i != NumElts; ++i) { 15435 int Idx = SVN->getMaskElt(i); 15436 if (Idx >= (int)NumElts) { 15437 Idx = -1; 15438 Changed = true; 15439 } 15440 NewMask.push_back(Idx); 15441 } 15442 if (Changed) 15443 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 15444 } 15445 15446 // A shuffle of a single vector that is a splat can always be folded. 15447 if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0)) 15448 if (N1->isUndef() && N0Shuf->isSplat()) 15449 return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG); 15450 15451 // If it is a splat, check if the argument vector is another splat or a 15452 // build_vector. 15453 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 15454 SDNode *V = N0.getNode(); 15455 15456 // If this is a bit convert that changes the element type of the vector but 15457 // not the number of vector elements, look through it. Be careful not to 15458 // look though conversions that change things like v4f32 to v2f64. 15459 if (V->getOpcode() == ISD::BITCAST) { 15460 SDValue ConvInput = V->getOperand(0); 15461 if (ConvInput.getValueType().isVector() && 15462 ConvInput.getValueType().getVectorNumElements() == NumElts) 15463 V = ConvInput.getNode(); 15464 } 15465 15466 if (V->getOpcode() == ISD::BUILD_VECTOR) { 15467 assert(V->getNumOperands() == NumElts && 15468 "BUILD_VECTOR has wrong number of operands"); 15469 SDValue Base; 15470 bool AllSame = true; 15471 for (unsigned i = 0; i != NumElts; ++i) { 15472 if (!V->getOperand(i).isUndef()) { 15473 Base = V->getOperand(i); 15474 break; 15475 } 15476 } 15477 // Splat of <u, u, u, u>, return <u, u, u, u> 15478 if (!Base.getNode()) 15479 return N0; 15480 for (unsigned i = 0; i != NumElts; ++i) { 15481 if (V->getOperand(i) != Base) { 15482 AllSame = false; 15483 break; 15484 } 15485 } 15486 // Splat of <x, x, x, x>, return <x, x, x, x> 15487 if (AllSame) 15488 return N0; 15489 15490 // Canonicalize any other splat as a build_vector. 15491 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 15492 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 15493 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 15494 15495 // We may have jumped through bitcasts, so the type of the 15496 // BUILD_VECTOR may not match the type of the shuffle. 15497 if (V->getValueType(0) != VT) 15498 NewBV = DAG.getBitcast(VT, NewBV); 15499 return NewBV; 15500 } 15501 } 15502 15503 // There are various patterns used to build up a vector from smaller vectors, 15504 // subvectors, or elements. Scan chains of these and replace unused insertions 15505 // or components with undef. 15506 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 15507 return S; 15508 15509 // Match shuffles that can be converted to any_vector_extend_in_reg. 15510 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations)) 15511 return V; 15512 15513 // Combine "truncate_vector_in_reg" style shuffles. 15514 if (SDValue V = combineTruncationShuffle(SVN, DAG)) 15515 return V; 15516 15517 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 15518 Level < AfterLegalizeVectorOps && 15519 (N1.isUndef() || 15520 (N1.getOpcode() == ISD::CONCAT_VECTORS && 15521 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 15522 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 15523 return V; 15524 } 15525 15526 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 15527 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 15528 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 15529 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI)) 15530 return Res; 15531 15532 // If this shuffle only has a single input that is a bitcasted shuffle, 15533 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 15534 // back to their original types. 15535 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 15536 N1.isUndef() && Level < AfterLegalizeVectorOps && 15537 TLI.isTypeLegal(VT)) { 15538 15539 // Peek through the bitcast only if there is one user. 15540 SDValue BC0 = N0; 15541 while (BC0.getOpcode() == ISD::BITCAST) { 15542 if (!BC0.hasOneUse()) 15543 break; 15544 BC0 = BC0.getOperand(0); 15545 } 15546 15547 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 15548 if (Scale == 1) 15549 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 15550 15551 SmallVector<int, 8> NewMask; 15552 for (int M : Mask) 15553 for (int s = 0; s != Scale; ++s) 15554 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 15555 return NewMask; 15556 }; 15557 15558 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 15559 EVT SVT = VT.getScalarType(); 15560 EVT InnerVT = BC0->getValueType(0); 15561 EVT InnerSVT = InnerVT.getScalarType(); 15562 15563 // Determine which shuffle works with the smaller scalar type. 15564 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 15565 EVT ScaleSVT = ScaleVT.getScalarType(); 15566 15567 if (TLI.isTypeLegal(ScaleVT) && 15568 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 15569 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 15570 15571 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 15572 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 15573 15574 // Scale the shuffle masks to the smaller scalar type. 15575 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 15576 SmallVector<int, 8> InnerMask = 15577 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 15578 SmallVector<int, 8> OuterMask = 15579 ScaleShuffleMask(SVN->getMask(), OuterScale); 15580 15581 // Merge the shuffle masks. 15582 SmallVector<int, 8> NewMask; 15583 for (int M : OuterMask) 15584 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 15585 15586 // Test for shuffle mask legality over both commutations. 15587 SDValue SV0 = BC0->getOperand(0); 15588 SDValue SV1 = BC0->getOperand(1); 15589 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 15590 if (!LegalMask) { 15591 std::swap(SV0, SV1); 15592 ShuffleVectorSDNode::commuteMask(NewMask); 15593 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 15594 } 15595 15596 if (LegalMask) { 15597 SV0 = DAG.getBitcast(ScaleVT, SV0); 15598 SV1 = DAG.getBitcast(ScaleVT, SV1); 15599 return DAG.getBitcast( 15600 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 15601 } 15602 } 15603 } 15604 } 15605 15606 // Canonicalize shuffles according to rules: 15607 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 15608 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 15609 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 15610 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 15611 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 15612 TLI.isTypeLegal(VT)) { 15613 // The incoming shuffle must be of the same type as the result of the 15614 // current shuffle. 15615 assert(N1->getOperand(0).getValueType() == VT && 15616 "Shuffle types don't match"); 15617 15618 SDValue SV0 = N1->getOperand(0); 15619 SDValue SV1 = N1->getOperand(1); 15620 bool HasSameOp0 = N0 == SV0; 15621 bool IsSV1Undef = SV1.isUndef(); 15622 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 15623 // Commute the operands of this shuffle so that next rule 15624 // will trigger. 15625 return DAG.getCommutedVectorShuffle(*SVN); 15626 } 15627 15628 // Try to fold according to rules: 15629 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 15630 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 15631 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 15632 // Don't try to fold shuffles with illegal type. 15633 // Only fold if this shuffle is the only user of the other shuffle. 15634 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 15635 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 15636 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 15637 15638 // Don't try to fold splats; they're likely to simplify somehow, or they 15639 // might be free. 15640 if (OtherSV->isSplat()) 15641 return SDValue(); 15642 15643 // The incoming shuffle must be of the same type as the result of the 15644 // current shuffle. 15645 assert(OtherSV->getOperand(0).getValueType() == VT && 15646 "Shuffle types don't match"); 15647 15648 SDValue SV0, SV1; 15649 SmallVector<int, 4> Mask; 15650 // Compute the combined shuffle mask for a shuffle with SV0 as the first 15651 // operand, and SV1 as the second operand. 15652 for (unsigned i = 0; i != NumElts; ++i) { 15653 int Idx = SVN->getMaskElt(i); 15654 if (Idx < 0) { 15655 // Propagate Undef. 15656 Mask.push_back(Idx); 15657 continue; 15658 } 15659 15660 SDValue CurrentVec; 15661 if (Idx < (int)NumElts) { 15662 // This shuffle index refers to the inner shuffle N0. Lookup the inner 15663 // shuffle mask to identify which vector is actually referenced. 15664 Idx = OtherSV->getMaskElt(Idx); 15665 if (Idx < 0) { 15666 // Propagate Undef. 15667 Mask.push_back(Idx); 15668 continue; 15669 } 15670 15671 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 15672 : OtherSV->getOperand(1); 15673 } else { 15674 // This shuffle index references an element within N1. 15675 CurrentVec = N1; 15676 } 15677 15678 // Simple case where 'CurrentVec' is UNDEF. 15679 if (CurrentVec.isUndef()) { 15680 Mask.push_back(-1); 15681 continue; 15682 } 15683 15684 // Canonicalize the shuffle index. We don't know yet if CurrentVec 15685 // will be the first or second operand of the combined shuffle. 15686 Idx = Idx % NumElts; 15687 if (!SV0.getNode() || SV0 == CurrentVec) { 15688 // Ok. CurrentVec is the left hand side. 15689 // Update the mask accordingly. 15690 SV0 = CurrentVec; 15691 Mask.push_back(Idx); 15692 continue; 15693 } 15694 15695 // Bail out if we cannot convert the shuffle pair into a single shuffle. 15696 if (SV1.getNode() && SV1 != CurrentVec) 15697 return SDValue(); 15698 15699 // Ok. CurrentVec is the right hand side. 15700 // Update the mask accordingly. 15701 SV1 = CurrentVec; 15702 Mask.push_back(Idx + NumElts); 15703 } 15704 15705 // Check if all indices in Mask are Undef. In case, propagate Undef. 15706 bool isUndefMask = true; 15707 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 15708 isUndefMask &= Mask[i] < 0; 15709 15710 if (isUndefMask) 15711 return DAG.getUNDEF(VT); 15712 15713 if (!SV0.getNode()) 15714 SV0 = DAG.getUNDEF(VT); 15715 if (!SV1.getNode()) 15716 SV1 = DAG.getUNDEF(VT); 15717 15718 // Avoid introducing shuffles with illegal mask. 15719 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 15720 ShuffleVectorSDNode::commuteMask(Mask); 15721 15722 if (!TLI.isShuffleMaskLegal(Mask, VT)) 15723 return SDValue(); 15724 15725 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 15726 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 15727 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 15728 std::swap(SV0, SV1); 15729 } 15730 15731 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 15732 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 15733 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 15734 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask); 15735 } 15736 15737 return SDValue(); 15738 } 15739 15740 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 15741 SDValue InVal = N->getOperand(0); 15742 EVT VT = N->getValueType(0); 15743 15744 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 15745 // with a VECTOR_SHUFFLE. 15746 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 15747 SDValue InVec = InVal->getOperand(0); 15748 SDValue EltNo = InVal->getOperand(1); 15749 15750 // FIXME: We could support implicit truncation if the shuffle can be 15751 // scaled to a smaller vector scalar type. 15752 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 15753 if (C0 && VT == InVec.getValueType() && 15754 VT.getScalarType() == InVal.getValueType()) { 15755 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 15756 int Elt = C0->getZExtValue(); 15757 NewMask[0] = Elt; 15758 15759 if (TLI.isShuffleMaskLegal(NewMask, VT)) 15760 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 15761 NewMask); 15762 } 15763 } 15764 15765 return SDValue(); 15766 } 15767 15768 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 15769 EVT VT = N->getValueType(0); 15770 SDValue N0 = N->getOperand(0); 15771 SDValue N1 = N->getOperand(1); 15772 SDValue N2 = N->getOperand(2); 15773 15774 // If inserting an UNDEF, just return the original vector. 15775 if (N1.isUndef()) 15776 return N0; 15777 15778 // If this is an insert of an extracted vector into an undef vector, we can 15779 // just use the input to the extract. 15780 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 15781 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT) 15782 return N1.getOperand(0); 15783 15784 // Combine INSERT_SUBVECTORs where we are inserting to the same index. 15785 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) 15786 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) 15787 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && 15788 N0.getOperand(1).getValueType() == N1.getValueType() && 15789 N0.getOperand(2) == N2) 15790 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), 15791 N1, N2); 15792 15793 if (!isa<ConstantSDNode>(N2)) 15794 return SDValue(); 15795 15796 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue(); 15797 15798 // Canonicalize insert_subvector dag nodes. 15799 // Example: 15800 // (insert_subvector (insert_subvector A, Idx0), Idx1) 15801 // -> (insert_subvector (insert_subvector A, Idx1), Idx0) 15802 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() && 15803 N1.getValueType() == N0.getOperand(1).getValueType() && 15804 isa<ConstantSDNode>(N0.getOperand(2))) { 15805 unsigned OtherIdx = N0.getConstantOperandVal(2); 15806 if (InsIdx < OtherIdx) { 15807 // Swap nodes. 15808 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, 15809 N0.getOperand(0), N1, N2); 15810 AddToWorklist(NewOp.getNode()); 15811 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()), 15812 VT, NewOp, N0.getOperand(1), N0.getOperand(2)); 15813 } 15814 } 15815 15816 // If the input vector is a concatenation, and the insert replaces 15817 // one of the pieces, we can optimize into a single concat_vectors. 15818 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() && 15819 N0.getOperand(0).getValueType() == N1.getValueType()) { 15820 unsigned Factor = N1.getValueType().getVectorNumElements(); 15821 15822 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end()); 15823 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1; 15824 15825 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 15826 } 15827 15828 return SDValue(); 15829 } 15830 15831 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 15832 SDValue N0 = N->getOperand(0); 15833 15834 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 15835 if (N0->getOpcode() == ISD::FP16_TO_FP) 15836 return N0->getOperand(0); 15837 15838 return SDValue(); 15839 } 15840 15841 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 15842 SDValue N0 = N->getOperand(0); 15843 15844 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 15845 if (N0->getOpcode() == ISD::AND) { 15846 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 15847 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 15848 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 15849 N0.getOperand(0)); 15850 } 15851 } 15852 15853 return SDValue(); 15854 } 15855 15856 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 15857 /// with the destination vector and a zero vector. 15858 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 15859 /// vector_shuffle V, Zero, <0, 4, 2, 4> 15860 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 15861 EVT VT = N->getValueType(0); 15862 SDValue LHS = N->getOperand(0); 15863 SDValue RHS = N->getOperand(1); 15864 SDLoc DL(N); 15865 15866 // Make sure we're not running after operation legalization where it 15867 // may have custom lowered the vector shuffles. 15868 if (LegalOperations) 15869 return SDValue(); 15870 15871 if (N->getOpcode() != ISD::AND) 15872 return SDValue(); 15873 15874 if (RHS.getOpcode() == ISD::BITCAST) 15875 RHS = RHS.getOperand(0); 15876 15877 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 15878 return SDValue(); 15879 15880 EVT RVT = RHS.getValueType(); 15881 unsigned NumElts = RHS.getNumOperands(); 15882 15883 // Attempt to create a valid clear mask, splitting the mask into 15884 // sub elements and checking to see if each is 15885 // all zeros or all ones - suitable for shuffle masking. 15886 auto BuildClearMask = [&](int Split) { 15887 int NumSubElts = NumElts * Split; 15888 int NumSubBits = RVT.getScalarSizeInBits() / Split; 15889 15890 SmallVector<int, 8> Indices; 15891 for (int i = 0; i != NumSubElts; ++i) { 15892 int EltIdx = i / Split; 15893 int SubIdx = i % Split; 15894 SDValue Elt = RHS.getOperand(EltIdx); 15895 if (Elt.isUndef()) { 15896 Indices.push_back(-1); 15897 continue; 15898 } 15899 15900 APInt Bits; 15901 if (isa<ConstantSDNode>(Elt)) 15902 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 15903 else if (isa<ConstantFPSDNode>(Elt)) 15904 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 15905 else 15906 return SDValue(); 15907 15908 // Extract the sub element from the constant bit mask. 15909 if (DAG.getDataLayout().isBigEndian()) { 15910 Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits); 15911 } else { 15912 Bits.lshrInPlace(SubIdx * NumSubBits); 15913 } 15914 15915 if (Split > 1) 15916 Bits = Bits.trunc(NumSubBits); 15917 15918 if (Bits.isAllOnesValue()) 15919 Indices.push_back(i); 15920 else if (Bits == 0) 15921 Indices.push_back(i + NumSubElts); 15922 else 15923 return SDValue(); 15924 } 15925 15926 // Let's see if the target supports this vector_shuffle. 15927 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 15928 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 15929 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 15930 return SDValue(); 15931 15932 SDValue Zero = DAG.getConstant(0, DL, ClearVT); 15933 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL, 15934 DAG.getBitcast(ClearVT, LHS), 15935 Zero, Indices)); 15936 }; 15937 15938 // Determine maximum split level (byte level masking). 15939 int MaxSplit = 1; 15940 if (RVT.getScalarSizeInBits() % 8 == 0) 15941 MaxSplit = RVT.getScalarSizeInBits() / 8; 15942 15943 for (int Split = 1; Split <= MaxSplit; ++Split) 15944 if (RVT.getScalarSizeInBits() % Split == 0) 15945 if (SDValue S = BuildClearMask(Split)) 15946 return S; 15947 15948 return SDValue(); 15949 } 15950 15951 /// Visit a binary vector operation, like ADD. 15952 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 15953 assert(N->getValueType(0).isVector() && 15954 "SimplifyVBinOp only works on vectors!"); 15955 15956 SDValue LHS = N->getOperand(0); 15957 SDValue RHS = N->getOperand(1); 15958 SDValue Ops[] = {LHS, RHS}; 15959 15960 // See if we can constant fold the vector operation. 15961 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 15962 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 15963 return Fold; 15964 15965 // Try to convert a constant mask AND into a shuffle clear mask. 15966 if (SDValue Shuffle = XformToShuffleWithZero(N)) 15967 return Shuffle; 15968 15969 // Type legalization might introduce new shuffles in the DAG. 15970 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 15971 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 15972 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 15973 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 15974 LHS.getOperand(1).isUndef() && 15975 RHS.getOperand(1).isUndef()) { 15976 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 15977 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 15978 15979 if (SVN0->getMask().equals(SVN1->getMask())) { 15980 EVT VT = N->getValueType(0); 15981 SDValue UndefVector = LHS.getOperand(1); 15982 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 15983 LHS.getOperand(0), RHS.getOperand(0), 15984 N->getFlags()); 15985 AddUsersToWorklist(N); 15986 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 15987 SVN0->getMask()); 15988 } 15989 } 15990 15991 return SDValue(); 15992 } 15993 15994 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 15995 SDValue N2) { 15996 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 15997 15998 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 15999 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 16000 16001 // If we got a simplified select_cc node back from SimplifySelectCC, then 16002 // break it down into a new SETCC node, and a new SELECT node, and then return 16003 // the SELECT node, since we were called with a SELECT node. 16004 if (SCC.getNode()) { 16005 // Check to see if we got a select_cc back (to turn into setcc/select). 16006 // Otherwise, just return whatever node we got back, like fabs. 16007 if (SCC.getOpcode() == ISD::SELECT_CC) { 16008 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 16009 N0.getValueType(), 16010 SCC.getOperand(0), SCC.getOperand(1), 16011 SCC.getOperand(4)); 16012 AddToWorklist(SETCC.getNode()); 16013 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 16014 SCC.getOperand(2), SCC.getOperand(3)); 16015 } 16016 16017 return SCC; 16018 } 16019 return SDValue(); 16020 } 16021 16022 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 16023 /// being selected between, see if we can simplify the select. Callers of this 16024 /// should assume that TheSelect is deleted if this returns true. As such, they 16025 /// should return the appropriate thing (e.g. the node) back to the top-level of 16026 /// the DAG combiner loop to avoid it being looked at. 16027 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 16028 SDValue RHS) { 16029 16030 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 16031 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 16032 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 16033 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 16034 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 16035 SDValue Sqrt = RHS; 16036 ISD::CondCode CC; 16037 SDValue CmpLHS; 16038 const ConstantFPSDNode *Zero = nullptr; 16039 16040 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 16041 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 16042 CmpLHS = TheSelect->getOperand(0); 16043 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 16044 } else { 16045 // SELECT or VSELECT 16046 SDValue Cmp = TheSelect->getOperand(0); 16047 if (Cmp.getOpcode() == ISD::SETCC) { 16048 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 16049 CmpLHS = Cmp.getOperand(0); 16050 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 16051 } 16052 } 16053 if (Zero && Zero->isZero() && 16054 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 16055 CC == ISD::SETULT || CC == ISD::SETLT)) { 16056 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 16057 CombineTo(TheSelect, Sqrt); 16058 return true; 16059 } 16060 } 16061 } 16062 // Cannot simplify select with vector condition 16063 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 16064 16065 // If this is a select from two identical things, try to pull the operation 16066 // through the select. 16067 if (LHS.getOpcode() != RHS.getOpcode() || 16068 !LHS.hasOneUse() || !RHS.hasOneUse()) 16069 return false; 16070 16071 // If this is a load and the token chain is identical, replace the select 16072 // of two loads with a load through a select of the address to load from. 16073 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 16074 // constants have been dropped into the constant pool. 16075 if (LHS.getOpcode() == ISD::LOAD) { 16076 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 16077 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 16078 16079 // Token chains must be identical. 16080 if (LHS.getOperand(0) != RHS.getOperand(0) || 16081 // Do not let this transformation reduce the number of volatile loads. 16082 LLD->isVolatile() || RLD->isVolatile() || 16083 // FIXME: If either is a pre/post inc/dec load, 16084 // we'd need to split out the address adjustment. 16085 LLD->isIndexed() || RLD->isIndexed() || 16086 // If this is an EXTLOAD, the VT's must match. 16087 LLD->getMemoryVT() != RLD->getMemoryVT() || 16088 // If this is an EXTLOAD, the kind of extension must match. 16089 (LLD->getExtensionType() != RLD->getExtensionType() && 16090 // The only exception is if one of the extensions is anyext. 16091 LLD->getExtensionType() != ISD::EXTLOAD && 16092 RLD->getExtensionType() != ISD::EXTLOAD) || 16093 // FIXME: this discards src value information. This is 16094 // over-conservative. It would be beneficial to be able to remember 16095 // both potential memory locations. Since we are discarding 16096 // src value info, don't do the transformation if the memory 16097 // locations are not in the default address space. 16098 LLD->getPointerInfo().getAddrSpace() != 0 || 16099 RLD->getPointerInfo().getAddrSpace() != 0 || 16100 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 16101 LLD->getBasePtr().getValueType())) 16102 return false; 16103 16104 // Check that the select condition doesn't reach either load. If so, 16105 // folding this will induce a cycle into the DAG. If not, this is safe to 16106 // xform, so create a select of the addresses. 16107 SDValue Addr; 16108 if (TheSelect->getOpcode() == ISD::SELECT) { 16109 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 16110 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 16111 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 16112 return false; 16113 // The loads must not depend on one another. 16114 if (LLD->isPredecessorOf(RLD) || 16115 RLD->isPredecessorOf(LLD)) 16116 return false; 16117 Addr = DAG.getSelect(SDLoc(TheSelect), 16118 LLD->getBasePtr().getValueType(), 16119 TheSelect->getOperand(0), LLD->getBasePtr(), 16120 RLD->getBasePtr()); 16121 } else { // Otherwise SELECT_CC 16122 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 16123 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 16124 16125 if ((LLD->hasAnyUseOfValue(1) && 16126 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 16127 (RLD->hasAnyUseOfValue(1) && 16128 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 16129 return false; 16130 16131 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 16132 LLD->getBasePtr().getValueType(), 16133 TheSelect->getOperand(0), 16134 TheSelect->getOperand(1), 16135 LLD->getBasePtr(), RLD->getBasePtr(), 16136 TheSelect->getOperand(4)); 16137 } 16138 16139 SDValue Load; 16140 // It is safe to replace the two loads if they have different alignments, 16141 // but the new load must be the minimum (most restrictive) alignment of the 16142 // inputs. 16143 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 16144 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 16145 if (!RLD->isInvariant()) 16146 MMOFlags &= ~MachineMemOperand::MOInvariant; 16147 if (!RLD->isDereferenceable()) 16148 MMOFlags &= ~MachineMemOperand::MODereferenceable; 16149 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 16150 // FIXME: Discards pointer and AA info. 16151 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 16152 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 16153 MMOFlags); 16154 } else { 16155 // FIXME: Discards pointer and AA info. 16156 Load = DAG.getExtLoad( 16157 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 16158 : LLD->getExtensionType(), 16159 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 16160 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 16161 } 16162 16163 // Users of the select now use the result of the load. 16164 CombineTo(TheSelect, Load); 16165 16166 // Users of the old loads now use the new load's chain. We know the 16167 // old-load value is dead now. 16168 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 16169 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 16170 return true; 16171 } 16172 16173 return false; 16174 } 16175 16176 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and 16177 /// bitwise 'and'. 16178 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, 16179 SDValue N1, SDValue N2, SDValue N3, 16180 ISD::CondCode CC) { 16181 // If this is a select where the false operand is zero and the compare is a 16182 // check of the sign bit, see if we can perform the "gzip trick": 16183 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A 16184 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A 16185 EVT XType = N0.getValueType(); 16186 EVT AType = N2.getValueType(); 16187 if (!isNullConstant(N3) || !XType.bitsGE(AType)) 16188 return SDValue(); 16189 16190 // If the comparison is testing for a positive value, we have to invert 16191 // the sign bit mask, so only do that transform if the target has a bitwise 16192 // 'and not' instruction (the invert is free). 16193 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) { 16194 // (X > -1) ? A : 0 16195 // (X > 0) ? X : 0 <-- This is canonical signed max. 16196 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2))) 16197 return SDValue(); 16198 } else if (CC == ISD::SETLT) { 16199 // (X < 0) ? A : 0 16200 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min. 16201 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2))) 16202 return SDValue(); 16203 } else { 16204 return SDValue(); 16205 } 16206 16207 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit 16208 // constant. 16209 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 16210 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 16211 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 16212 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1; 16213 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); 16214 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt); 16215 AddToWorklist(Shift.getNode()); 16216 16217 if (XType.bitsGT(AType)) { 16218 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 16219 AddToWorklist(Shift.getNode()); 16220 } 16221 16222 if (CC == ISD::SETGT) 16223 Shift = DAG.getNOT(DL, Shift, AType); 16224 16225 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 16226 } 16227 16228 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy); 16229 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt); 16230 AddToWorklist(Shift.getNode()); 16231 16232 if (XType.bitsGT(AType)) { 16233 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 16234 AddToWorklist(Shift.getNode()); 16235 } 16236 16237 if (CC == ISD::SETGT) 16238 Shift = DAG.getNOT(DL, Shift, AType); 16239 16240 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 16241 } 16242 16243 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 16244 /// where 'cond' is the comparison specified by CC. 16245 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 16246 SDValue N2, SDValue N3, ISD::CondCode CC, 16247 bool NotExtCompare) { 16248 // (x ? y : y) -> y. 16249 if (N2 == N3) return N2; 16250 16251 EVT VT = N2.getValueType(); 16252 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 16253 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 16254 16255 // Determine if the condition we're dealing with is constant 16256 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 16257 N0, N1, CC, DL, false); 16258 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 16259 16260 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 16261 // fold select_cc true, x, y -> x 16262 // fold select_cc false, x, y -> y 16263 return !SCCC->isNullValue() ? N2 : N3; 16264 } 16265 16266 // Check to see if we can simplify the select into an fabs node 16267 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 16268 // Allow either -0.0 or 0.0 16269 if (CFP->isZero()) { 16270 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 16271 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 16272 N0 == N2 && N3.getOpcode() == ISD::FNEG && 16273 N2 == N3.getOperand(0)) 16274 return DAG.getNode(ISD::FABS, DL, VT, N0); 16275 16276 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 16277 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 16278 N0 == N3 && N2.getOpcode() == ISD::FNEG && 16279 N2.getOperand(0) == N3) 16280 return DAG.getNode(ISD::FABS, DL, VT, N3); 16281 } 16282 } 16283 16284 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 16285 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 16286 // in it. This is a win when the constant is not otherwise available because 16287 // it replaces two constant pool loads with one. We only do this if the FP 16288 // type is known to be legal, because if it isn't, then we are before legalize 16289 // types an we want the other legalization to happen first (e.g. to avoid 16290 // messing with soft float) and if the ConstantFP is not legal, because if 16291 // it is legal, we may not need to store the FP constant in a constant pool. 16292 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 16293 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 16294 if (TLI.isTypeLegal(N2.getValueType()) && 16295 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 16296 TargetLowering::Legal && 16297 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 16298 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 16299 // If both constants have multiple uses, then we won't need to do an 16300 // extra load, they are likely around in registers for other users. 16301 (TV->hasOneUse() || FV->hasOneUse())) { 16302 Constant *Elts[] = { 16303 const_cast<ConstantFP*>(FV->getConstantFPValue()), 16304 const_cast<ConstantFP*>(TV->getConstantFPValue()) 16305 }; 16306 Type *FPTy = Elts[0]->getType(); 16307 const DataLayout &TD = DAG.getDataLayout(); 16308 16309 // Create a ConstantArray of the two constants. 16310 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 16311 SDValue CPIdx = 16312 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 16313 TD.getPrefTypeAlignment(FPTy)); 16314 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 16315 16316 // Get the offsets to the 0 and 1 element of the array so that we can 16317 // select between them. 16318 SDValue Zero = DAG.getIntPtrConstant(0, DL); 16319 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 16320 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 16321 16322 SDValue Cond = DAG.getSetCC(DL, 16323 getSetCCResultType(N0.getValueType()), 16324 N0, N1, CC); 16325 AddToWorklist(Cond.getNode()); 16326 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 16327 Cond, One, Zero); 16328 AddToWorklist(CstOffset.getNode()); 16329 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 16330 CstOffset); 16331 AddToWorklist(CPIdx.getNode()); 16332 return DAG.getLoad( 16333 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 16334 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 16335 Alignment); 16336 } 16337 } 16338 16339 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC)) 16340 return V; 16341 16342 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 16343 // where y is has a single bit set. 16344 // A plaintext description would be, we can turn the SELECT_CC into an AND 16345 // when the condition can be materialized as an all-ones register. Any 16346 // single bit-test can be materialized as an all-ones register with 16347 // shift-left and shift-right-arith. 16348 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 16349 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 16350 SDValue AndLHS = N0->getOperand(0); 16351 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 16352 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 16353 // Shift the tested bit over the sign bit. 16354 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 16355 SDValue ShlAmt = 16356 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 16357 getShiftAmountTy(AndLHS.getValueType())); 16358 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 16359 16360 // Now arithmetic right shift it all the way over, so the result is either 16361 // all-ones, or zero. 16362 SDValue ShrAmt = 16363 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 16364 getShiftAmountTy(Shl.getValueType())); 16365 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 16366 16367 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 16368 } 16369 } 16370 16371 // fold select C, 16, 0 -> shl C, 4 16372 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 16373 TLI.getBooleanContents(N0.getValueType()) == 16374 TargetLowering::ZeroOrOneBooleanContent) { 16375 16376 // If the caller doesn't want us to simplify this into a zext of a compare, 16377 // don't do it. 16378 if (NotExtCompare && N2C->isOne()) 16379 return SDValue(); 16380 16381 // Get a SetCC of the condition 16382 // NOTE: Don't create a SETCC if it's not legal on this target. 16383 if (!LegalOperations || 16384 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 16385 SDValue Temp, SCC; 16386 // cast from setcc result type to select result type 16387 if (LegalTypes) { 16388 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 16389 N0, N1, CC); 16390 if (N2.getValueType().bitsLT(SCC.getValueType())) 16391 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 16392 N2.getValueType()); 16393 else 16394 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 16395 N2.getValueType(), SCC); 16396 } else { 16397 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 16398 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 16399 N2.getValueType(), SCC); 16400 } 16401 16402 AddToWorklist(SCC.getNode()); 16403 AddToWorklist(Temp.getNode()); 16404 16405 if (N2C->isOne()) 16406 return Temp; 16407 16408 // shl setcc result by log2 n2c 16409 return DAG.getNode( 16410 ISD::SHL, DL, N2.getValueType(), Temp, 16411 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 16412 getShiftAmountTy(Temp.getValueType()))); 16413 } 16414 } 16415 16416 // Check to see if this is an integer abs. 16417 // select_cc setg[te] X, 0, X, -X -> 16418 // select_cc setgt X, -1, X, -X -> 16419 // select_cc setl[te] X, 0, -X, X -> 16420 // select_cc setlt X, 1, -X, X -> 16421 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 16422 if (N1C) { 16423 ConstantSDNode *SubC = nullptr; 16424 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 16425 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 16426 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 16427 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 16428 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 16429 (N1C->isOne() && CC == ISD::SETLT)) && 16430 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 16431 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 16432 16433 EVT XType = N0.getValueType(); 16434 if (SubC && SubC->isNullValue() && XType.isInteger()) { 16435 SDLoc DL(N0); 16436 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 16437 N0, 16438 DAG.getConstant(XType.getSizeInBits() - 1, DL, 16439 getShiftAmountTy(N0.getValueType()))); 16440 SDValue Add = DAG.getNode(ISD::ADD, DL, 16441 XType, N0, Shift); 16442 AddToWorklist(Shift.getNode()); 16443 AddToWorklist(Add.getNode()); 16444 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 16445 } 16446 } 16447 16448 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 16449 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 16450 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 16451 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 16452 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 16453 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 16454 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 16455 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 16456 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 16457 SDValue ValueOnZero = N2; 16458 SDValue Count = N3; 16459 // If the condition is NE instead of E, swap the operands. 16460 if (CC == ISD::SETNE) 16461 std::swap(ValueOnZero, Count); 16462 // Check if the value on zero is a constant equal to the bits in the type. 16463 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 16464 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 16465 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 16466 // legal, combine to just cttz. 16467 if ((Count.getOpcode() == ISD::CTTZ || 16468 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 16469 N0 == Count.getOperand(0) && 16470 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 16471 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 16472 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 16473 // legal, combine to just ctlz. 16474 if ((Count.getOpcode() == ISD::CTLZ || 16475 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 16476 N0 == Count.getOperand(0) && 16477 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 16478 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 16479 } 16480 } 16481 } 16482 16483 return SDValue(); 16484 } 16485 16486 /// This is a stub for TargetLowering::SimplifySetCC. 16487 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 16488 ISD::CondCode Cond, const SDLoc &DL, 16489 bool foldBooleans) { 16490 TargetLowering::DAGCombinerInfo 16491 DagCombineInfo(DAG, Level, false, this); 16492 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 16493 } 16494 16495 /// Given an ISD::SDIV node expressing a divide by constant, return 16496 /// a DAG expression to select that will generate the same value by multiplying 16497 /// by a magic number. 16498 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 16499 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 16500 // when optimising for minimum size, we don't want to expand a div to a mul 16501 // and a shift. 16502 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 16503 return SDValue(); 16504 16505 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 16506 if (!C) 16507 return SDValue(); 16508 16509 // Avoid division by zero. 16510 if (C->isNullValue()) 16511 return SDValue(); 16512 16513 std::vector<SDNode*> Built; 16514 SDValue S = 16515 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 16516 16517 for (SDNode *N : Built) 16518 AddToWorklist(N); 16519 return S; 16520 } 16521 16522 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 16523 /// DAG expression that will generate the same value by right shifting. 16524 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 16525 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 16526 if (!C) 16527 return SDValue(); 16528 16529 // Avoid division by zero. 16530 if (C->isNullValue()) 16531 return SDValue(); 16532 16533 std::vector<SDNode *> Built; 16534 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 16535 16536 for (SDNode *N : Built) 16537 AddToWorklist(N); 16538 return S; 16539 } 16540 16541 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 16542 /// expression that will generate the same value by multiplying by a magic 16543 /// number. 16544 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 16545 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 16546 // when optimising for minimum size, we don't want to expand a div to a mul 16547 // and a shift. 16548 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 16549 return SDValue(); 16550 16551 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 16552 if (!C) 16553 return SDValue(); 16554 16555 // Avoid division by zero. 16556 if (C->isNullValue()) 16557 return SDValue(); 16558 16559 std::vector<SDNode*> Built; 16560 SDValue S = 16561 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 16562 16563 for (SDNode *N : Built) 16564 AddToWorklist(N); 16565 return S; 16566 } 16567 16568 /// Determines the LogBase2 value for a non-null input value using the 16569 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V). 16570 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) { 16571 EVT VT = V.getValueType(); 16572 unsigned EltBits = VT.getScalarSizeInBits(); 16573 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V); 16574 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT); 16575 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz); 16576 return LogBase2; 16577 } 16578 16579 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 16580 /// For the reciprocal, we need to find the zero of the function: 16581 /// F(X) = A X - 1 [which has a zero at X = 1/A] 16582 /// => 16583 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 16584 /// does not require additional intermediate precision] 16585 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) { 16586 if (Level >= AfterLegalizeDAG) 16587 return SDValue(); 16588 16589 // TODO: Handle half and/or extended types? 16590 EVT VT = Op.getValueType(); 16591 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 16592 return SDValue(); 16593 16594 // If estimates are explicitly disabled for this function, we're done. 16595 MachineFunction &MF = DAG.getMachineFunction(); 16596 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF); 16597 if (Enabled == TLI.ReciprocalEstimate::Disabled) 16598 return SDValue(); 16599 16600 // Estimates may be explicitly enabled for this type with a custom number of 16601 // refinement steps. 16602 int Iterations = TLI.getDivRefinementSteps(VT, MF); 16603 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) { 16604 AddToWorklist(Est.getNode()); 16605 16606 if (Iterations) { 16607 EVT VT = Op.getValueType(); 16608 SDLoc DL(Op); 16609 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 16610 16611 // Newton iterations: Est = Est + Est (1 - Arg * Est) 16612 for (int i = 0; i < Iterations; ++i) { 16613 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 16614 AddToWorklist(NewEst.getNode()); 16615 16616 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 16617 AddToWorklist(NewEst.getNode()); 16618 16619 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 16620 AddToWorklist(NewEst.getNode()); 16621 16622 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 16623 AddToWorklist(Est.getNode()); 16624 } 16625 } 16626 return Est; 16627 } 16628 16629 return SDValue(); 16630 } 16631 16632 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 16633 /// For the reciprocal sqrt, we need to find the zero of the function: 16634 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 16635 /// => 16636 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 16637 /// As a result, we precompute A/2 prior to the iteration loop. 16638 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 16639 unsigned Iterations, 16640 SDNodeFlags Flags, bool Reciprocal) { 16641 EVT VT = Arg.getValueType(); 16642 SDLoc DL(Arg); 16643 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 16644 16645 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 16646 // this entire sequence requires only one FP constant. 16647 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 16648 AddToWorklist(HalfArg.getNode()); 16649 16650 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 16651 AddToWorklist(HalfArg.getNode()); 16652 16653 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 16654 for (unsigned i = 0; i < Iterations; ++i) { 16655 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 16656 AddToWorklist(NewEst.getNode()); 16657 16658 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 16659 AddToWorklist(NewEst.getNode()); 16660 16661 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 16662 AddToWorklist(NewEst.getNode()); 16663 16664 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 16665 AddToWorklist(Est.getNode()); 16666 } 16667 16668 // If non-reciprocal square root is requested, multiply the result by Arg. 16669 if (!Reciprocal) { 16670 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 16671 AddToWorklist(Est.getNode()); 16672 } 16673 16674 return Est; 16675 } 16676 16677 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 16678 /// For the reciprocal sqrt, we need to find the zero of the function: 16679 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 16680 /// => 16681 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 16682 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 16683 unsigned Iterations, 16684 SDNodeFlags Flags, bool Reciprocal) { 16685 EVT VT = Arg.getValueType(); 16686 SDLoc DL(Arg); 16687 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 16688 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 16689 16690 // This routine must enter the loop below to work correctly 16691 // when (Reciprocal == false). 16692 assert(Iterations > 0); 16693 16694 // Newton iterations for reciprocal square root: 16695 // E = (E * -0.5) * ((A * E) * E + -3.0) 16696 for (unsigned i = 0; i < Iterations; ++i) { 16697 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 16698 AddToWorklist(AE.getNode()); 16699 16700 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 16701 AddToWorklist(AEE.getNode()); 16702 16703 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 16704 AddToWorklist(RHS.getNode()); 16705 16706 // When calculating a square root at the last iteration build: 16707 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 16708 // (notice a common subexpression) 16709 SDValue LHS; 16710 if (Reciprocal || (i + 1) < Iterations) { 16711 // RSQRT: LHS = (E * -0.5) 16712 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 16713 } else { 16714 // SQRT: LHS = (A * E) * -0.5 16715 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 16716 } 16717 AddToWorklist(LHS.getNode()); 16718 16719 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 16720 AddToWorklist(Est.getNode()); 16721 } 16722 16723 return Est; 16724 } 16725 16726 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 16727 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 16728 /// Op can be zero. 16729 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, 16730 bool Reciprocal) { 16731 if (Level >= AfterLegalizeDAG) 16732 return SDValue(); 16733 16734 // TODO: Handle half and/or extended types? 16735 EVT VT = Op.getValueType(); 16736 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 16737 return SDValue(); 16738 16739 // If estimates are explicitly disabled for this function, we're done. 16740 MachineFunction &MF = DAG.getMachineFunction(); 16741 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF); 16742 if (Enabled == TLI.ReciprocalEstimate::Disabled) 16743 return SDValue(); 16744 16745 // Estimates may be explicitly enabled for this type with a custom number of 16746 // refinement steps. 16747 int Iterations = TLI.getSqrtRefinementSteps(VT, MF); 16748 16749 bool UseOneConstNR = false; 16750 if (SDValue Est = 16751 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR, 16752 Reciprocal)) { 16753 AddToWorklist(Est.getNode()); 16754 16755 if (Iterations) { 16756 Est = UseOneConstNR 16757 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 16758 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 16759 16760 if (!Reciprocal) { 16761 // Unfortunately, Est is now NaN if the input was exactly 0.0. 16762 // Select out this case and force the answer to 0.0. 16763 EVT VT = Op.getValueType(); 16764 SDLoc DL(Op); 16765 16766 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 16767 EVT CCVT = getSetCCResultType(VT); 16768 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 16769 AddToWorklist(ZeroCmp.getNode()); 16770 16771 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 16772 ZeroCmp, FPZero, Est); 16773 AddToWorklist(Est.getNode()); 16774 } 16775 } 16776 return Est; 16777 } 16778 16779 return SDValue(); 16780 } 16781 16782 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) { 16783 return buildSqrtEstimateImpl(Op, Flags, true); 16784 } 16785 16786 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) { 16787 return buildSqrtEstimateImpl(Op, Flags, false); 16788 } 16789 16790 /// Return true if base is a frame index, which is known not to alias with 16791 /// anything but itself. Provides base object and offset as results. 16792 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 16793 const GlobalValue *&GV, const void *&CV) { 16794 // Assume it is a primitive operation. 16795 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 16796 16797 // If it's an adding a simple constant then integrate the offset. 16798 if (Base.getOpcode() == ISD::ADD) { 16799 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 16800 Base = Base.getOperand(0); 16801 Offset += C->getSExtValue(); 16802 } 16803 } 16804 16805 // Return the underlying GlobalValue, and update the Offset. Return false 16806 // for GlobalAddressSDNode since the same GlobalAddress may be represented 16807 // by multiple nodes with different offsets. 16808 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 16809 GV = G->getGlobal(); 16810 Offset += G->getOffset(); 16811 return false; 16812 } 16813 16814 // Return the underlying Constant value, and update the Offset. Return false 16815 // for ConstantSDNodes since the same constant pool entry may be represented 16816 // by multiple nodes with different offsets. 16817 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 16818 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 16819 : (const void *)C->getConstVal(); 16820 Offset += C->getOffset(); 16821 return false; 16822 } 16823 // If it's any of the following then it can't alias with anything but itself. 16824 return isa<FrameIndexSDNode>(Base); 16825 } 16826 16827 /// Return true if there is any possibility that the two addresses overlap. 16828 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 16829 // If they are the same then they must be aliases. 16830 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 16831 16832 // If they are both volatile then they cannot be reordered. 16833 if (Op0->isVolatile() && Op1->isVolatile()) return true; 16834 16835 // If one operation reads from invariant memory, and the other may store, they 16836 // cannot alias. These should really be checking the equivalent of mayWrite, 16837 // but it only matters for memory nodes other than load /store. 16838 if (Op0->isInvariant() && Op1->writeMem()) 16839 return false; 16840 16841 if (Op1->isInvariant() && Op0->writeMem()) 16842 return false; 16843 16844 unsigned NumBytes0 = Op0->getMemoryVT().getSizeInBits() >> 3; 16845 unsigned NumBytes1 = Op1->getMemoryVT().getSizeInBits() >> 3; 16846 16847 // Check for BaseIndexOffset matching. 16848 BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG); 16849 BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG); 16850 int64_t PtrDiff; 16851 if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff)) 16852 return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0)); 16853 16854 // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be 16855 // able to calculate their relative offset if at least one arises 16856 // from an alloca. However, these allocas cannot overlap and we 16857 // can infer there is no alias. 16858 if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase())) 16859 if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) { 16860 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 16861 // If the base are the same frame index but the we couldn't find a 16862 // constant offset, (indices are different) be conservative. 16863 if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) || 16864 !MFI.isFixedObjectIndex(B->getIndex()))) 16865 return false; 16866 } 16867 16868 // FIXME: findBaseOffset and ConstantValue/GlobalValue/FrameIndex analysis 16869 // modified to use BaseIndexOffset. 16870 16871 // Gather base node and offset information. 16872 SDValue Base0, Base1; 16873 int64_t Offset0, Offset1; 16874 const GlobalValue *GV0, *GV1; 16875 const void *CV0, *CV1; 16876 bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(), 16877 Base0, Offset0, GV0, CV0); 16878 bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(), 16879 Base1, Offset1, GV1, CV1); 16880 16881 // If they have the same base address, then check to see if they overlap. 16882 if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1))) 16883 return !((Offset0 + NumBytes0) <= Offset1 || 16884 (Offset1 + NumBytes1) <= Offset0); 16885 16886 // It is possible for different frame indices to alias each other, mostly 16887 // when tail call optimization reuses return address slots for arguments. 16888 // To catch this case, look up the actual index of frame indices to compute 16889 // the real alias relationship. 16890 if (IsFrameIndex0 && IsFrameIndex1) { 16891 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 16892 Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex()); 16893 Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 16894 return !((Offset0 + NumBytes0) <= Offset1 || 16895 (Offset1 + NumBytes1) <= Offset0); 16896 } 16897 16898 // Otherwise, if we know what the bases are, and they aren't identical, then 16899 // we know they cannot alias. 16900 if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1)) 16901 return false; 16902 16903 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 16904 // compared to the size and offset of the access, we may be able to prove they 16905 // do not alias. This check is conservative for now to catch cases created by 16906 // splitting vector types. 16907 int64_t SrcValOffset0 = Op0->getSrcValueOffset(); 16908 int64_t SrcValOffset1 = Op1->getSrcValueOffset(); 16909 unsigned OrigAlignment0 = Op0->getOriginalAlignment(); 16910 unsigned OrigAlignment1 = Op1->getOriginalAlignment(); 16911 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 && 16912 NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) { 16913 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0; 16914 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1; 16915 16916 // There is no overlap between these relatively aligned accesses of similar 16917 // size. Return no alias. 16918 if ((OffAlign0 + NumBytes0) <= OffAlign1 || 16919 (OffAlign1 + NumBytes1) <= OffAlign0) 16920 return false; 16921 } 16922 16923 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 16924 ? CombinerGlobalAA 16925 : DAG.getSubtarget().useAA(); 16926 #ifndef NDEBUG 16927 if (CombinerAAOnlyFunc.getNumOccurrences() && 16928 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 16929 UseAA = false; 16930 #endif 16931 16932 if (UseAA && AA && 16933 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 16934 // Use alias analysis information. 16935 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1); 16936 int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset; 16937 int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset; 16938 AliasResult AAResult = 16939 AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0, 16940 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 16941 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1, 16942 UseTBAA ? Op1->getAAInfo() : AAMDNodes()) ); 16943 if (AAResult == NoAlias) 16944 return false; 16945 } 16946 16947 // Otherwise we have to assume they alias. 16948 return true; 16949 } 16950 16951 /// Walk up chain skipping non-aliasing memory nodes, 16952 /// looking for aliasing nodes and adding them to the Aliases vector. 16953 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 16954 SmallVectorImpl<SDValue> &Aliases) { 16955 SmallVector<SDValue, 8> Chains; // List of chains to visit. 16956 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 16957 16958 // Get alias information for node. 16959 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 16960 16961 // Starting off. 16962 Chains.push_back(OriginalChain); 16963 unsigned Depth = 0; 16964 16965 // Look at each chain and determine if it is an alias. If so, add it to the 16966 // aliases list. If not, then continue up the chain looking for the next 16967 // candidate. 16968 while (!Chains.empty()) { 16969 SDValue Chain = Chains.pop_back_val(); 16970 16971 // For TokenFactor nodes, look at each operand and only continue up the 16972 // chain until we reach the depth limit. 16973 // 16974 // FIXME: The depth check could be made to return the last non-aliasing 16975 // chain we found before we hit a tokenfactor rather than the original 16976 // chain. 16977 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 16978 Aliases.clear(); 16979 Aliases.push_back(OriginalChain); 16980 return; 16981 } 16982 16983 // Don't bother if we've been before. 16984 if (!Visited.insert(Chain.getNode()).second) 16985 continue; 16986 16987 switch (Chain.getOpcode()) { 16988 case ISD::EntryToken: 16989 // Entry token is ideal chain operand, but handled in FindBetterChain. 16990 break; 16991 16992 case ISD::LOAD: 16993 case ISD::STORE: { 16994 // Get alias information for Chain. 16995 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 16996 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 16997 16998 // If chain is alias then stop here. 16999 if (!(IsLoad && IsOpLoad) && 17000 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 17001 Aliases.push_back(Chain); 17002 } else { 17003 // Look further up the chain. 17004 Chains.push_back(Chain.getOperand(0)); 17005 ++Depth; 17006 } 17007 break; 17008 } 17009 17010 case ISD::TokenFactor: 17011 // We have to check each of the operands of the token factor for "small" 17012 // token factors, so we queue them up. Adding the operands to the queue 17013 // (stack) in reverse order maintains the original order and increases the 17014 // likelihood that getNode will find a matching token factor (CSE.) 17015 if (Chain.getNumOperands() > 16) { 17016 Aliases.push_back(Chain); 17017 break; 17018 } 17019 for (unsigned n = Chain.getNumOperands(); n;) 17020 Chains.push_back(Chain.getOperand(--n)); 17021 ++Depth; 17022 break; 17023 17024 case ISD::CopyFromReg: 17025 // Forward past CopyFromReg. 17026 Chains.push_back(Chain.getOperand(0)); 17027 ++Depth; 17028 break; 17029 17030 default: 17031 // For all other instructions we will just have to take what we can get. 17032 Aliases.push_back(Chain); 17033 break; 17034 } 17035 } 17036 } 17037 17038 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 17039 /// (aliasing node.) 17040 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 17041 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 17042 17043 // Accumulate all the aliases to this node. 17044 GatherAllAliases(N, OldChain, Aliases); 17045 17046 // If no operands then chain to entry token. 17047 if (Aliases.size() == 0) 17048 return DAG.getEntryNode(); 17049 17050 // If a single operand then chain to it. We don't need to revisit it. 17051 if (Aliases.size() == 1) 17052 return Aliases[0]; 17053 17054 // Construct a custom tailored token factor. 17055 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 17056 } 17057 17058 // This function tries to collect a bunch of potentially interesting 17059 // nodes to improve the chains of, all at once. This might seem 17060 // redundant, as this function gets called when visiting every store 17061 // node, so why not let the work be done on each store as it's visited? 17062 // 17063 // I believe this is mainly important because MergeConsecutiveStores 17064 // is unable to deal with merging stores of different sizes, so unless 17065 // we improve the chains of all the potential candidates up-front 17066 // before running MergeConsecutiveStores, it might only see some of 17067 // the nodes that will eventually be candidates, and then not be able 17068 // to go from a partially-merged state to the desired final 17069 // fully-merged state. 17070 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 17071 // This holds the base pointer, index, and the offset in bytes from the base 17072 // pointer. 17073 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 17074 17075 // We must have a base and an offset. 17076 if (!BasePtr.getBase().getNode()) 17077 return false; 17078 17079 // Do not handle stores to undef base pointers. 17080 if (BasePtr.getBase().isUndef()) 17081 return false; 17082 17083 SmallVector<StoreSDNode *, 8> ChainedStores; 17084 ChainedStores.push_back(St); 17085 17086 // Walk up the chain and look for nodes with offsets from the same 17087 // base pointer. Stop when reaching an instruction with a different kind 17088 // or instruction which has a different base pointer. 17089 StoreSDNode *Index = St; 17090 while (Index) { 17091 // If the chain has more than one use, then we can't reorder the mem ops. 17092 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 17093 break; 17094 17095 if (Index->isVolatile() || Index->isIndexed()) 17096 break; 17097 17098 // Find the base pointer and offset for this memory node. 17099 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 17100 17101 // Check that the base pointer is the same as the original one. 17102 if (!BasePtr.equalBaseIndex(Ptr, DAG)) 17103 break; 17104 17105 // Walk up the chain to find the next store node, ignoring any 17106 // intermediate loads. Any other kind of node will halt the loop. 17107 SDNode *NextInChain = Index->getChain().getNode(); 17108 while (true) { 17109 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 17110 // We found a store node. Use it for the next iteration. 17111 if (STn->isVolatile() || STn->isIndexed()) { 17112 Index = nullptr; 17113 break; 17114 } 17115 ChainedStores.push_back(STn); 17116 Index = STn; 17117 break; 17118 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 17119 NextInChain = Ldn->getChain().getNode(); 17120 continue; 17121 } else { 17122 Index = nullptr; 17123 break; 17124 } 17125 } // end while 17126 } 17127 17128 // At this point, ChainedStores lists all of the Store nodes 17129 // reachable by iterating up through chain nodes matching the above 17130 // conditions. For each such store identified, try to find an 17131 // earlier chain to attach the store to which won't violate the 17132 // required ordering. 17133 bool MadeChangeToSt = false; 17134 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 17135 17136 for (StoreSDNode *ChainedStore : ChainedStores) { 17137 SDValue Chain = ChainedStore->getChain(); 17138 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 17139 17140 if (Chain != BetterChain) { 17141 if (ChainedStore == St) 17142 MadeChangeToSt = true; 17143 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 17144 } 17145 } 17146 17147 // Do all replacements after finding the replacements to make to avoid making 17148 // the chains more complicated by introducing new TokenFactors. 17149 for (auto Replacement : BetterChains) 17150 replaceStoreChain(Replacement.first, Replacement.second); 17151 17152 return MadeChangeToSt; 17153 } 17154 17155 /// This is the entry point for the file. 17156 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA, 17157 CodeGenOpt::Level OptLevel) { 17158 /// This is the main entry point to this class. 17159 DAGCombiner(*this, AA, OptLevel).Run(Level); 17160 } 17161