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/SelectionDAGTargetInfo.h" 29 #include "llvm/IR/DataLayout.h" 30 #include "llvm/IR/DerivedTypes.h" 31 #include "llvm/IR/Function.h" 32 #include "llvm/IR/LLVMContext.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/ErrorHandling.h" 36 #include "llvm/Support/MathExtras.h" 37 #include "llvm/Support/raw_ostream.h" 38 #include "llvm/Target/TargetLowering.h" 39 #include "llvm/Target/TargetOptions.h" 40 #include "llvm/Target/TargetRegisterInfo.h" 41 #include "llvm/Target/TargetSubtargetInfo.h" 42 #include <algorithm> 43 using namespace llvm; 44 45 #define DEBUG_TYPE "dagcombine" 46 47 STATISTIC(NodesCombined , "Number of dag nodes combined"); 48 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 49 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 50 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 51 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 52 STATISTIC(SlicedLoads, "Number of load sliced"); 53 54 namespace { 55 static cl::opt<bool> 56 CombinerAA("combiner-alias-analysis", cl::Hidden, 57 cl::desc("Enable DAG combiner alias-analysis heuristics")); 58 59 static cl::opt<bool> 60 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 61 cl::desc("Enable DAG combiner's use of IR alias analysis")); 62 63 static cl::opt<bool> 64 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 65 cl::desc("Enable DAG combiner's use of TBAA")); 66 67 #ifndef NDEBUG 68 static cl::opt<std::string> 69 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 70 cl::desc("Only use DAG-combiner alias analysis in this" 71 " function")); 72 #endif 73 74 /// Hidden option to stress test load slicing, i.e., when this option 75 /// is enabled, load slicing bypasses most of its profitability guards. 76 static cl::opt<bool> 77 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 78 cl::desc("Bypass the profitability model of load " 79 "slicing"), 80 cl::init(false)); 81 82 static cl::opt<bool> 83 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 84 cl::desc("DAG combiner may split indexing from loads")); 85 86 //------------------------------ DAGCombiner ---------------------------------// 87 88 class DAGCombiner { 89 SelectionDAG &DAG; 90 const TargetLowering &TLI; 91 CombineLevel Level; 92 CodeGenOpt::Level OptLevel; 93 bool LegalOperations; 94 bool LegalTypes; 95 bool ForCodeSize; 96 97 /// \brief Worklist of all of the nodes that need to be simplified. 98 /// 99 /// This must behave as a stack -- new nodes to process are pushed onto the 100 /// back and when processing we pop off of the back. 101 /// 102 /// The worklist will not contain duplicates but may contain null entries 103 /// due to nodes being deleted from the underlying DAG. 104 SmallVector<SDNode *, 64> Worklist; 105 106 /// \brief Mapping from an SDNode to its position on the worklist. 107 /// 108 /// This is used to find and remove nodes from the worklist (by nulling 109 /// them) when they are deleted from the underlying DAG. It relies on 110 /// stable indices of nodes within the worklist. 111 DenseMap<SDNode *, unsigned> WorklistMap; 112 113 /// \brief Set of nodes which have been combined (at least once). 114 /// 115 /// This is used to allow us to reliably add any operands of a DAG node 116 /// which have not yet been combined to the worklist. 117 SmallPtrSet<SDNode *, 32> CombinedNodes; 118 119 // AA - Used for DAG load/store alias analysis. 120 AliasAnalysis &AA; 121 122 /// When an instruction is simplified, add all users of the instruction to 123 /// the work lists because they might get more simplified now. 124 void AddUsersToWorklist(SDNode *N) { 125 for (SDNode *Node : N->uses()) 126 AddToWorklist(Node); 127 } 128 129 /// Call the node-specific routine that folds each particular type of node. 130 SDValue visit(SDNode *N); 131 132 public: 133 /// Add to the worklist making sure its instance is at the back (next to be 134 /// processed.) 135 void AddToWorklist(SDNode *N) { 136 // Skip handle nodes as they can't usefully be combined and confuse the 137 // zero-use deletion strategy. 138 if (N->getOpcode() == ISD::HANDLENODE) 139 return; 140 141 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 142 Worklist.push_back(N); 143 } 144 145 /// Remove all instances of N from the worklist. 146 void removeFromWorklist(SDNode *N) { 147 CombinedNodes.erase(N); 148 149 auto It = WorklistMap.find(N); 150 if (It == WorklistMap.end()) 151 return; // Not in the worklist. 152 153 // Null out the entry rather than erasing it to avoid a linear operation. 154 Worklist[It->second] = nullptr; 155 WorklistMap.erase(It); 156 } 157 158 void deleteAndRecombine(SDNode *N); 159 bool recursivelyDeleteUnusedNodes(SDNode *N); 160 161 /// Replaces all uses of the results of one DAG node with new values. 162 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 163 bool AddTo = true); 164 165 /// Replaces all uses of the results of one DAG node with new values. 166 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 167 return CombineTo(N, &Res, 1, AddTo); 168 } 169 170 /// Replaces all uses of the results of one DAG node with new values. 171 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 172 bool AddTo = true) { 173 SDValue To[] = { Res0, Res1 }; 174 return CombineTo(N, To, 2, AddTo); 175 } 176 177 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 178 179 private: 180 181 /// Check the specified integer node value to see if it can be simplified or 182 /// if things it uses can be simplified by bit propagation. 183 /// If so, return true. 184 bool SimplifyDemandedBits(SDValue Op) { 185 unsigned BitWidth = Op.getScalarValueSizeInBits(); 186 APInt Demanded = APInt::getAllOnesValue(BitWidth); 187 return SimplifyDemandedBits(Op, Demanded); 188 } 189 190 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 191 192 bool CombineToPreIndexedLoadStore(SDNode *N); 193 bool CombineToPostIndexedLoadStore(SDNode *N); 194 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 195 bool SliceUpLoad(SDNode *N); 196 197 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 198 /// load. 199 /// 200 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 201 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 202 /// \param EltNo index of the vector element to load. 203 /// \param OriginalLoad load that EVE came from to be replaced. 204 /// \returns EVE on success SDValue() on failure. 205 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 206 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 207 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 208 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 209 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 210 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 211 SDValue PromoteIntBinOp(SDValue Op); 212 SDValue PromoteIntShiftOp(SDValue Op); 213 SDValue PromoteExtend(SDValue Op); 214 bool PromoteLoad(SDValue Op); 215 216 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc, 217 SDValue ExtLoad, const SDLoc &DL, 218 ISD::NodeType ExtType); 219 220 /// Call the node-specific routine that knows how to fold each 221 /// particular type of node. If that doesn't do anything, try the 222 /// target-specific DAG combines. 223 SDValue combine(SDNode *N); 224 225 // Visitation implementation - Implement dag node combining for different 226 // node types. The semantics are as follows: 227 // Return Value: 228 // SDValue.getNode() == 0 - No change was made 229 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 230 // otherwise - N should be replaced by the returned Operand. 231 // 232 SDValue visitTokenFactor(SDNode *N); 233 SDValue visitMERGE_VALUES(SDNode *N); 234 SDValue visitADD(SDNode *N); 235 SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference); 236 SDValue visitSUB(SDNode *N); 237 SDValue visitADDC(SDNode *N); 238 SDValue visitSUBC(SDNode *N); 239 SDValue visitADDE(SDNode *N); 240 SDValue visitSUBE(SDNode *N); 241 SDValue visitMUL(SDNode *N); 242 SDValue useDivRem(SDNode *N); 243 SDValue visitSDIV(SDNode *N); 244 SDValue visitUDIV(SDNode *N); 245 SDValue visitREM(SDNode *N); 246 SDValue visitMULHU(SDNode *N); 247 SDValue visitMULHS(SDNode *N); 248 SDValue visitSMUL_LOHI(SDNode *N); 249 SDValue visitUMUL_LOHI(SDNode *N); 250 SDValue visitSMULO(SDNode *N); 251 SDValue visitUMULO(SDNode *N); 252 SDValue visitIMINMAX(SDNode *N); 253 SDValue visitAND(SDNode *N); 254 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference); 255 SDValue visitOR(SDNode *N); 256 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference); 257 SDValue visitXOR(SDNode *N); 258 SDValue SimplifyVBinOp(SDNode *N); 259 SDValue visitSHL(SDNode *N); 260 SDValue visitSRA(SDNode *N); 261 SDValue visitSRL(SDNode *N); 262 SDValue visitRotate(SDNode *N); 263 SDValue visitBSWAP(SDNode *N); 264 SDValue visitBITREVERSE(SDNode *N); 265 SDValue visitCTLZ(SDNode *N); 266 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 267 SDValue visitCTTZ(SDNode *N); 268 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 269 SDValue visitCTPOP(SDNode *N); 270 SDValue visitSELECT(SDNode *N); 271 SDValue visitVSELECT(SDNode *N); 272 SDValue visitSELECT_CC(SDNode *N); 273 SDValue visitSETCC(SDNode *N); 274 SDValue visitSETCCE(SDNode *N); 275 SDValue visitSIGN_EXTEND(SDNode *N); 276 SDValue visitZERO_EXTEND(SDNode *N); 277 SDValue visitANY_EXTEND(SDNode *N); 278 SDValue visitAssertZext(SDNode *N); 279 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 280 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 281 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N); 282 SDValue visitTRUNCATE(SDNode *N); 283 SDValue visitBITCAST(SDNode *N); 284 SDValue visitBUILD_PAIR(SDNode *N); 285 SDValue visitFADD(SDNode *N); 286 SDValue visitFSUB(SDNode *N); 287 SDValue visitFMUL(SDNode *N); 288 SDValue visitFMA(SDNode *N); 289 SDValue visitFDIV(SDNode *N); 290 SDValue visitFREM(SDNode *N); 291 SDValue visitFSQRT(SDNode *N); 292 SDValue visitFCOPYSIGN(SDNode *N); 293 SDValue visitSINT_TO_FP(SDNode *N); 294 SDValue visitUINT_TO_FP(SDNode *N); 295 SDValue visitFP_TO_SINT(SDNode *N); 296 SDValue visitFP_TO_UINT(SDNode *N); 297 SDValue visitFP_ROUND(SDNode *N); 298 SDValue visitFP_ROUND_INREG(SDNode *N); 299 SDValue visitFP_EXTEND(SDNode *N); 300 SDValue visitFNEG(SDNode *N); 301 SDValue visitFABS(SDNode *N); 302 SDValue visitFCEIL(SDNode *N); 303 SDValue visitFTRUNC(SDNode *N); 304 SDValue visitFFLOOR(SDNode *N); 305 SDValue visitFMINNUM(SDNode *N); 306 SDValue visitFMAXNUM(SDNode *N); 307 SDValue visitBRCOND(SDNode *N); 308 SDValue visitBR_CC(SDNode *N); 309 SDValue visitLOAD(SDNode *N); 310 311 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 312 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 313 314 SDValue visitSTORE(SDNode *N); 315 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 316 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 317 SDValue visitBUILD_VECTOR(SDNode *N); 318 SDValue visitCONCAT_VECTORS(SDNode *N); 319 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 320 SDValue visitVECTOR_SHUFFLE(SDNode *N); 321 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 322 SDValue visitINSERT_SUBVECTOR(SDNode *N); 323 SDValue visitMLOAD(SDNode *N); 324 SDValue visitMSTORE(SDNode *N); 325 SDValue visitMGATHER(SDNode *N); 326 SDValue visitMSCATTER(SDNode *N); 327 SDValue visitFP_TO_FP16(SDNode *N); 328 SDValue visitFP16_TO_FP(SDNode *N); 329 330 SDValue visitFADDForFMACombine(SDNode *N); 331 SDValue visitFSUBForFMACombine(SDNode *N); 332 SDValue visitFMULForFMADistributiveCombine(SDNode *N); 333 334 SDValue XformToShuffleWithZero(SDNode *N); 335 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS, 336 SDValue RHS); 337 338 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 339 340 SDValue foldSelectOfConstants(SDNode *N); 341 SDValue foldBinOpIntoSelect(SDNode *BO); 342 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 343 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 344 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2); 345 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 346 SDValue N2, SDValue N3, ISD::CondCode CC, 347 bool NotExtCompare = false); 348 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1, 349 SDValue N2, SDValue N3, ISD::CondCode CC); 350 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 351 const SDLoc &DL, bool foldBooleans = true); 352 353 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 354 SDValue &CC) const; 355 bool isOneUseSetCC(SDValue N) const; 356 357 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 358 unsigned HiOp); 359 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 360 SDValue CombineExtLoad(SDNode *N); 361 SDValue combineRepeatedFPDivisors(SDNode *N); 362 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 363 SDValue BuildSDIV(SDNode *N); 364 SDValue BuildSDIVPow2(SDNode *N); 365 SDValue BuildUDIV(SDNode *N); 366 SDValue BuildLogBase2(SDValue Op, const SDLoc &DL); 367 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags); 368 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags); 369 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags); 370 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, bool Recip); 371 SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations, 372 SDNodeFlags *Flags, bool Reciprocal); 373 SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations, 374 SDNodeFlags *Flags, bool Reciprocal); 375 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 376 bool DemandHighBits = true); 377 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 378 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 379 SDValue InnerPos, SDValue InnerNeg, 380 unsigned PosOpcode, unsigned NegOpcode, 381 const SDLoc &DL); 382 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL); 383 SDValue MatchLoadCombine(SDNode *N); 384 SDValue ReduceLoadWidth(SDNode *N); 385 SDValue ReduceLoadOpStoreWidth(SDNode *N); 386 SDValue splitMergedValStore(StoreSDNode *ST); 387 SDValue TransformFPLoadStorePair(SDNode *N); 388 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 389 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 390 SDValue reduceBuildVecToShuffle(SDNode *N); 391 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N, 392 ArrayRef<int> VectorMask, SDValue VecIn1, 393 SDValue VecIn2, unsigned LeftIdx); 394 395 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 396 397 /// Walk up chain skipping non-aliasing memory nodes, 398 /// looking for aliasing nodes and adding them to the Aliases vector. 399 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 400 SmallVectorImpl<SDValue> &Aliases); 401 402 /// Return true if there is any possibility that the two addresses overlap. 403 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 404 405 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 406 /// chain (aliasing node.) 407 SDValue FindBetterChain(SDNode *N, SDValue Chain); 408 409 /// Try to replace a store and any possibly adjacent stores on 410 /// consecutive chains with better chains. Return true only if St is 411 /// replaced. 412 /// 413 /// Notice that other chains may still be replaced even if the function 414 /// returns false. 415 bool findBetterNeighborChains(StoreSDNode *St); 416 417 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 418 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask); 419 420 /// Holds a pointer to an LSBaseSDNode as well as information on where it 421 /// is located in a sequence of memory operations connected by a chain. 422 struct MemOpLink { 423 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 424 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 425 // Ptr to the mem node. 426 LSBaseSDNode *MemNode; 427 // Offset from the base ptr. 428 int64_t OffsetFromBase; 429 // What is the sequence number of this mem node. 430 // Lowest mem operand in the DAG starts at zero. 431 unsigned SequenceNum; 432 }; 433 434 /// This is a helper function for visitMUL to check the profitability 435 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 436 /// MulNode is the original multiply, AddNode is (add x, c1), 437 /// and ConstNode is c2. 438 bool isMulAddWithConstProfitable(SDNode *MulNode, 439 SDValue &AddNode, 440 SDValue &ConstNode); 441 442 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a 443 /// constant build_vector of the stored constant values in Stores. 444 SDValue getMergedConstantVectorStore(SelectionDAG &DAG, const SDLoc &SL, 445 ArrayRef<MemOpLink> Stores, 446 SmallVectorImpl<SDValue> &Chains, 447 EVT Ty) const; 448 449 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 450 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 451 /// the type of the loaded value to be extended. LoadedVT returns the type 452 /// of the original loaded value. NarrowLoad returns whether the load would 453 /// need to be narrowed in order to match. 454 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 455 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 456 bool &NarrowLoad); 457 458 /// This is a helper function for MergeConsecutiveStores. When the source 459 /// elements of the consecutive stores are all constants or all extracted 460 /// vector elements, try to merge them into one larger store. 461 /// \return number of stores that were merged into a merged store (always 462 /// a prefix of \p StoreNode). 463 bool MergeStoresOfConstantsOrVecElts( 464 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores, 465 bool IsConstantSrc, bool UseVector); 466 467 /// This is a helper function for MergeConsecutiveStores. 468 /// Stores that may be merged are placed in StoreNodes. 469 /// Loads that may alias with those stores are placed in AliasLoadNodes. 470 void getStoreMergeAndAliasCandidates( 471 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 472 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes); 473 474 /// Helper function for MergeConsecutiveStores. Checks if 475 /// Candidate stores have indirect dependency through their 476 /// operands. \return True if safe to merge 477 bool checkMergeStoreCandidatesForDependencies( 478 SmallVectorImpl<MemOpLink> &StoreNodes); 479 480 /// Merge consecutive store operations into a wide store. 481 /// This optimization uses wide integers or vectors when possible. 482 /// \return number of stores that were merged into a merged store (the 483 /// affected nodes are stored as a prefix in \p StoreNodes). 484 bool MergeConsecutiveStores(StoreSDNode *N, 485 SmallVectorImpl<MemOpLink> &StoreNodes); 486 487 /// \brief Try to transform a truncation where C is a constant: 488 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 489 /// 490 /// \p N needs to be a truncation and its first operand an AND. Other 491 /// requirements are checked by the function (e.g. that trunc is 492 /// single-use) and if missed an empty SDValue is returned. 493 SDValue distributeTruncateThroughAnd(SDNode *N); 494 495 public: 496 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 497 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 498 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 499 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize(); 500 } 501 502 /// Runs the dag combiner on all nodes in the work list 503 void Run(CombineLevel AtLevel); 504 505 SelectionDAG &getDAG() const { return DAG; } 506 507 /// Returns a type large enough to hold any valid shift amount - before type 508 /// legalization these can be huge. 509 EVT getShiftAmountTy(EVT LHSTy) { 510 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 511 if (LHSTy.isVector()) 512 return LHSTy; 513 auto &DL = DAG.getDataLayout(); 514 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 515 : TLI.getPointerTy(DL); 516 } 517 518 /// This method returns true if we are running before type legalization or 519 /// if the specified VT is legal. 520 bool isTypeLegal(const EVT &VT) { 521 if (!LegalTypes) return true; 522 return TLI.isTypeLegal(VT); 523 } 524 525 /// Convenience wrapper around TargetLowering::getSetCCResultType 526 EVT getSetCCResultType(EVT VT) const { 527 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 528 } 529 }; 530 } 531 532 533 namespace { 534 /// This class is a DAGUpdateListener that removes any deleted 535 /// nodes from the worklist. 536 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 537 DAGCombiner &DC; 538 public: 539 explicit WorklistRemover(DAGCombiner &dc) 540 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 541 542 void NodeDeleted(SDNode *N, SDNode *E) override { 543 DC.removeFromWorklist(N); 544 } 545 }; 546 } 547 548 //===----------------------------------------------------------------------===// 549 // TargetLowering::DAGCombinerInfo implementation 550 //===----------------------------------------------------------------------===// 551 552 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 553 ((DAGCombiner*)DC)->AddToWorklist(N); 554 } 555 556 SDValue TargetLowering::DAGCombinerInfo:: 557 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 558 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 559 } 560 561 SDValue TargetLowering::DAGCombinerInfo:: 562 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 563 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 564 } 565 566 567 SDValue TargetLowering::DAGCombinerInfo:: 568 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 569 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 570 } 571 572 void TargetLowering::DAGCombinerInfo:: 573 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 574 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 575 } 576 577 //===----------------------------------------------------------------------===// 578 // Helper Functions 579 //===----------------------------------------------------------------------===// 580 581 void DAGCombiner::deleteAndRecombine(SDNode *N) { 582 removeFromWorklist(N); 583 584 // If the operands of this node are only used by the node, they will now be 585 // dead. Make sure to re-visit them and recursively delete dead nodes. 586 for (const SDValue &Op : N->ops()) 587 // For an operand generating multiple values, one of the values may 588 // become dead allowing further simplification (e.g. split index 589 // arithmetic from an indexed load). 590 if (Op->hasOneUse() || Op->getNumValues() > 1) 591 AddToWorklist(Op.getNode()); 592 593 DAG.DeleteNode(N); 594 } 595 596 /// Return 1 if we can compute the negated form of the specified expression for 597 /// the same cost as the expression itself, or 2 if we can compute the negated 598 /// form more cheaply than the expression itself. 599 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 600 const TargetLowering &TLI, 601 const TargetOptions *Options, 602 unsigned Depth = 0) { 603 // fneg is removable even if it has multiple uses. 604 if (Op.getOpcode() == ISD::FNEG) return 2; 605 606 // Don't allow anything with multiple uses. 607 if (!Op.hasOneUse()) return 0; 608 609 // Don't recurse exponentially. 610 if (Depth > 6) return 0; 611 612 switch (Op.getOpcode()) { 613 default: return false; 614 case ISD::ConstantFP: { 615 if (!LegalOperations) 616 return 1; 617 618 // Don't invert constant FP values after legalization unless the target says 619 // the negated constant is legal. 620 EVT VT = Op.getValueType(); 621 return TLI.isOperationLegal(ISD::ConstantFP, VT) || 622 TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT); 623 } 624 case ISD::FADD: 625 // FIXME: determine better conditions for this xform. 626 if (!Options->UnsafeFPMath) return 0; 627 628 // After operation legalization, it might not be legal to create new FSUBs. 629 if (LegalOperations && 630 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 631 return 0; 632 633 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 634 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 635 Options, Depth + 1)) 636 return V; 637 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 638 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 639 Depth + 1); 640 case ISD::FSUB: 641 // We can't turn -(A-B) into B-A when we honor signed zeros. 642 if (!Options->NoSignedZerosFPMath && 643 !Op.getNode()->getFlags()->hasNoSignedZeros()) 644 return 0; 645 646 // fold (fneg (fsub A, B)) -> (fsub B, A) 647 return 1; 648 649 case ISD::FMUL: 650 case ISD::FDIV: 651 if (Options->HonorSignDependentRoundingFPMath()) return 0; 652 653 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 654 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 655 Options, Depth + 1)) 656 return V; 657 658 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 659 Depth + 1); 660 661 case ISD::FP_EXTEND: 662 case ISD::FP_ROUND: 663 case ISD::FSIN: 664 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 665 Depth + 1); 666 } 667 } 668 669 /// If isNegatibleForFree returns true, return the newly negated expression. 670 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 671 bool LegalOperations, unsigned Depth = 0) { 672 const TargetOptions &Options = DAG.getTarget().Options; 673 // fneg is removable even if it has multiple uses. 674 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 675 676 // Don't allow anything with multiple uses. 677 assert(Op.hasOneUse() && "Unknown reuse!"); 678 679 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 680 681 const SDNodeFlags *Flags = Op.getNode()->getFlags(); 682 683 switch (Op.getOpcode()) { 684 default: llvm_unreachable("Unknown code"); 685 case ISD::ConstantFP: { 686 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 687 V.changeSign(); 688 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 689 } 690 case ISD::FADD: 691 // FIXME: determine better conditions for this xform. 692 assert(Options.UnsafeFPMath); 693 694 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 695 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 696 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 697 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 698 GetNegatedExpression(Op.getOperand(0), DAG, 699 LegalOperations, Depth+1), 700 Op.getOperand(1), Flags); 701 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 702 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 703 GetNegatedExpression(Op.getOperand(1), DAG, 704 LegalOperations, Depth+1), 705 Op.getOperand(0), Flags); 706 case ISD::FSUB: 707 // fold (fneg (fsub 0, B)) -> B 708 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 709 if (N0CFP->isZero()) 710 return Op.getOperand(1); 711 712 // fold (fneg (fsub A, B)) -> (fsub B, A) 713 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 714 Op.getOperand(1), Op.getOperand(0), Flags); 715 716 case ISD::FMUL: 717 case ISD::FDIV: 718 assert(!Options.HonorSignDependentRoundingFPMath()); 719 720 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 721 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 722 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 723 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 724 GetNegatedExpression(Op.getOperand(0), DAG, 725 LegalOperations, Depth+1), 726 Op.getOperand(1), Flags); 727 728 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 729 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 730 Op.getOperand(0), 731 GetNegatedExpression(Op.getOperand(1), DAG, 732 LegalOperations, Depth+1), Flags); 733 734 case ISD::FP_EXTEND: 735 case ISD::FSIN: 736 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 737 GetNegatedExpression(Op.getOperand(0), DAG, 738 LegalOperations, Depth+1)); 739 case ISD::FP_ROUND: 740 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 741 GetNegatedExpression(Op.getOperand(0), DAG, 742 LegalOperations, Depth+1), 743 Op.getOperand(1)); 744 } 745 } 746 747 // APInts must be the same size for most operations, this helper 748 // function zero extends the shorter of the pair so that they match. 749 // We provide an Offset so that we can create bitwidths that won't overflow. 750 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) { 751 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth()); 752 LHS = LHS.zextOrSelf(Bits); 753 RHS = RHS.zextOrSelf(Bits); 754 } 755 756 // Return true if this node is a setcc, or is a select_cc 757 // that selects between the target values used for true and false, making it 758 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 759 // the appropriate nodes based on the type of node we are checking. This 760 // simplifies life a bit for the callers. 761 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 762 SDValue &CC) const { 763 if (N.getOpcode() == ISD::SETCC) { 764 LHS = N.getOperand(0); 765 RHS = N.getOperand(1); 766 CC = N.getOperand(2); 767 return true; 768 } 769 770 if (N.getOpcode() != ISD::SELECT_CC || 771 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 772 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 773 return false; 774 775 if (TLI.getBooleanContents(N.getValueType()) == 776 TargetLowering::UndefinedBooleanContent) 777 return false; 778 779 LHS = N.getOperand(0); 780 RHS = N.getOperand(1); 781 CC = N.getOperand(4); 782 return true; 783 } 784 785 /// Return true if this is a SetCC-equivalent operation with only one use. 786 /// If this is true, it allows the users to invert the operation for free when 787 /// it is profitable to do so. 788 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 789 SDValue N0, N1, N2; 790 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 791 return true; 792 return false; 793 } 794 795 // \brief Returns the SDNode if it is a constant float BuildVector 796 // or constant float. 797 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 798 if (isa<ConstantFPSDNode>(N)) 799 return N.getNode(); 800 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 801 return N.getNode(); 802 return nullptr; 803 } 804 805 // Determines if it is a constant integer or a build vector of constant 806 // integers (and undefs). 807 // Do not permit build vector implicit truncation. 808 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) { 809 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N)) 810 return !(Const->isOpaque() && NoOpaques); 811 if (N.getOpcode() != ISD::BUILD_VECTOR) 812 return false; 813 unsigned BitWidth = N.getScalarValueSizeInBits(); 814 for (const SDValue &Op : N->op_values()) { 815 if (Op.isUndef()) 816 continue; 817 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op); 818 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth || 819 (Const->isOpaque() && NoOpaques)) 820 return false; 821 } 822 return true; 823 } 824 825 // Determines if it is a constant null integer or a splatted vector of a 826 // constant null integer (with no undefs). 827 // Build vector implicit truncation is not an issue for null values. 828 static bool isNullConstantOrNullSplatConstant(SDValue N) { 829 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 830 return Splat->isNullValue(); 831 return false; 832 } 833 834 // Determines if it is a constant integer of one or a splatted vector of a 835 // constant integer of one (with no undefs). 836 // Do not permit build vector implicit truncation. 837 static bool isOneConstantOrOneSplatConstant(SDValue N) { 838 unsigned BitWidth = N.getScalarValueSizeInBits(); 839 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 840 return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth; 841 return false; 842 } 843 844 // Determines if it is a constant integer of all ones or a splatted vector of a 845 // constant integer of all ones (with no undefs). 846 // Do not permit build vector implicit truncation. 847 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) { 848 unsigned BitWidth = N.getScalarValueSizeInBits(); 849 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 850 return Splat->isAllOnesValue() && 851 Splat->getAPIntValue().getBitWidth() == BitWidth; 852 return false; 853 } 854 855 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with 856 // undef's. 857 static bool isAnyConstantBuildVector(const SDNode *N) { 858 return ISD::isBuildVectorOfConstantSDNodes(N) || 859 ISD::isBuildVectorOfConstantFPSDNodes(N); 860 } 861 862 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 863 SDValue N1) { 864 EVT VT = N0.getValueType(); 865 if (N0.getOpcode() == Opc) { 866 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 867 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 868 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 869 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 870 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 871 return SDValue(); 872 } 873 if (N0.hasOneUse()) { 874 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 875 // use 876 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 877 if (!OpNode.getNode()) 878 return SDValue(); 879 AddToWorklist(OpNode.getNode()); 880 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 881 } 882 } 883 } 884 885 if (N1.getOpcode() == Opc) { 886 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 887 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 888 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 889 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 890 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 891 return SDValue(); 892 } 893 if (N1.hasOneUse()) { 894 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 895 // use 896 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 897 if (!OpNode.getNode()) 898 return SDValue(); 899 AddToWorklist(OpNode.getNode()); 900 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 901 } 902 } 903 } 904 905 return SDValue(); 906 } 907 908 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 909 bool AddTo) { 910 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 911 ++NodesCombined; 912 DEBUG(dbgs() << "\nReplacing.1 "; 913 N->dump(&DAG); 914 dbgs() << "\nWith: "; 915 To[0].getNode()->dump(&DAG); 916 dbgs() << " and " << NumTo-1 << " other values\n"); 917 for (unsigned i = 0, e = NumTo; i != e; ++i) 918 assert((!To[i].getNode() || 919 N->getValueType(i) == To[i].getValueType()) && 920 "Cannot combine value to value of different type!"); 921 922 WorklistRemover DeadNodes(*this); 923 DAG.ReplaceAllUsesWith(N, To); 924 if (AddTo) { 925 // Push the new nodes and any users onto the worklist 926 for (unsigned i = 0, e = NumTo; i != e; ++i) { 927 if (To[i].getNode()) { 928 AddToWorklist(To[i].getNode()); 929 AddUsersToWorklist(To[i].getNode()); 930 } 931 } 932 } 933 934 // Finally, if the node is now dead, remove it from the graph. The node 935 // may not be dead if the replacement process recursively simplified to 936 // something else needing this node. 937 if (N->use_empty()) 938 deleteAndRecombine(N); 939 return SDValue(N, 0); 940 } 941 942 void DAGCombiner:: 943 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 944 // Replace all uses. If any nodes become isomorphic to other nodes and 945 // are deleted, make sure to remove them from our worklist. 946 WorklistRemover DeadNodes(*this); 947 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 948 949 // Push the new node and any (possibly new) users onto the worklist. 950 AddToWorklist(TLO.New.getNode()); 951 AddUsersToWorklist(TLO.New.getNode()); 952 953 // Finally, if the node is now dead, remove it from the graph. The node 954 // may not be dead if the replacement process recursively simplified to 955 // something else needing this node. 956 if (TLO.Old.getNode()->use_empty()) 957 deleteAndRecombine(TLO.Old.getNode()); 958 } 959 960 /// Check the specified integer node value to see if it can be simplified or if 961 /// things it uses can be simplified by bit propagation. If so, return true. 962 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 963 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 964 APInt KnownZero, KnownOne; 965 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 966 return false; 967 968 // Revisit the node. 969 AddToWorklist(Op.getNode()); 970 971 // Replace the old value with the new one. 972 ++NodesCombined; 973 DEBUG(dbgs() << "\nReplacing.2 "; 974 TLO.Old.getNode()->dump(&DAG); 975 dbgs() << "\nWith: "; 976 TLO.New.getNode()->dump(&DAG); 977 dbgs() << '\n'); 978 979 CommitTargetLoweringOpt(TLO); 980 return true; 981 } 982 983 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 984 SDLoc DL(Load); 985 EVT VT = Load->getValueType(0); 986 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0)); 987 988 DEBUG(dbgs() << "\nReplacing.9 "; 989 Load->dump(&DAG); 990 dbgs() << "\nWith: "; 991 Trunc.getNode()->dump(&DAG); 992 dbgs() << '\n'); 993 WorklistRemover DeadNodes(*this); 994 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 995 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 996 deleteAndRecombine(Load); 997 AddToWorklist(Trunc.getNode()); 998 } 999 1000 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 1001 Replace = false; 1002 SDLoc DL(Op); 1003 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 1004 LoadSDNode *LD = cast<LoadSDNode>(Op); 1005 EVT MemVT = LD->getMemoryVT(); 1006 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1007 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1008 : ISD::EXTLOAD) 1009 : LD->getExtensionType(); 1010 Replace = true; 1011 return DAG.getExtLoad(ExtType, DL, PVT, 1012 LD->getChain(), LD->getBasePtr(), 1013 MemVT, LD->getMemOperand()); 1014 } 1015 1016 unsigned Opc = Op.getOpcode(); 1017 switch (Opc) { 1018 default: break; 1019 case ISD::AssertSext: 1020 return DAG.getNode(ISD::AssertSext, DL, PVT, 1021 SExtPromoteOperand(Op.getOperand(0), PVT), 1022 Op.getOperand(1)); 1023 case ISD::AssertZext: 1024 return DAG.getNode(ISD::AssertZext, DL, PVT, 1025 ZExtPromoteOperand(Op.getOperand(0), PVT), 1026 Op.getOperand(1)); 1027 case ISD::Constant: { 1028 unsigned ExtOpc = 1029 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1030 return DAG.getNode(ExtOpc, DL, PVT, Op); 1031 } 1032 } 1033 1034 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 1035 return SDValue(); 1036 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op); 1037 } 1038 1039 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1040 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1041 return SDValue(); 1042 EVT OldVT = Op.getValueType(); 1043 SDLoc DL(Op); 1044 bool Replace = false; 1045 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1046 if (!NewOp.getNode()) 1047 return SDValue(); 1048 AddToWorklist(NewOp.getNode()); 1049 1050 if (Replace) 1051 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1052 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp, 1053 DAG.getValueType(OldVT)); 1054 } 1055 1056 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1057 EVT OldVT = Op.getValueType(); 1058 SDLoc DL(Op); 1059 bool Replace = false; 1060 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1061 if (!NewOp.getNode()) 1062 return SDValue(); 1063 AddToWorklist(NewOp.getNode()); 1064 1065 if (Replace) 1066 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1067 return DAG.getZeroExtendInReg(NewOp, DL, OldVT); 1068 } 1069 1070 /// Promote the specified integer binary operation if the target indicates it is 1071 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1072 /// i32 since i16 instructions are longer. 1073 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1074 if (!LegalOperations) 1075 return SDValue(); 1076 1077 EVT VT = Op.getValueType(); 1078 if (VT.isVector() || !VT.isInteger()) 1079 return SDValue(); 1080 1081 // If operation type is 'undesirable', e.g. i16 on x86, consider 1082 // promoting it. 1083 unsigned Opc = Op.getOpcode(); 1084 if (TLI.isTypeDesirableForOp(Opc, VT)) 1085 return SDValue(); 1086 1087 EVT PVT = VT; 1088 // Consult target whether it is a good idea to promote this operation and 1089 // what's the right type to promote it to. 1090 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1091 assert(PVT != VT && "Don't know what type to promote to!"); 1092 1093 bool Replace0 = false; 1094 SDValue N0 = Op.getOperand(0); 1095 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1096 if (!NN0.getNode()) 1097 return SDValue(); 1098 1099 bool Replace1 = false; 1100 SDValue N1 = Op.getOperand(1); 1101 SDValue NN1; 1102 if (N0 == N1) 1103 NN1 = NN0; 1104 else { 1105 NN1 = PromoteOperand(N1, PVT, Replace1); 1106 if (!NN1.getNode()) 1107 return SDValue(); 1108 } 1109 1110 AddToWorklist(NN0.getNode()); 1111 if (NN1.getNode()) 1112 AddToWorklist(NN1.getNode()); 1113 1114 if (Replace0) 1115 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1116 if (Replace1) 1117 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1118 1119 DEBUG(dbgs() << "\nPromoting "; 1120 Op.getNode()->dump(&DAG)); 1121 SDLoc DL(Op); 1122 return DAG.getNode(ISD::TRUNCATE, DL, VT, 1123 DAG.getNode(Opc, DL, PVT, NN0, NN1)); 1124 } 1125 return SDValue(); 1126 } 1127 1128 /// Promote the specified integer shift operation if the target indicates it is 1129 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1130 /// i32 since i16 instructions are longer. 1131 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1132 if (!LegalOperations) 1133 return SDValue(); 1134 1135 EVT VT = Op.getValueType(); 1136 if (VT.isVector() || !VT.isInteger()) 1137 return SDValue(); 1138 1139 // If operation type is 'undesirable', e.g. i16 on x86, consider 1140 // promoting it. 1141 unsigned Opc = Op.getOpcode(); 1142 if (TLI.isTypeDesirableForOp(Opc, VT)) 1143 return SDValue(); 1144 1145 EVT PVT = VT; 1146 // Consult target whether it is a good idea to promote this operation and 1147 // what's the right type to promote it to. 1148 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1149 assert(PVT != VT && "Don't know what type to promote to!"); 1150 1151 bool Replace = false; 1152 SDValue N0 = Op.getOperand(0); 1153 if (Opc == ISD::SRA) 1154 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1155 else if (Opc == ISD::SRL) 1156 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1157 else 1158 N0 = PromoteOperand(N0, PVT, Replace); 1159 if (!N0.getNode()) 1160 return SDValue(); 1161 1162 AddToWorklist(N0.getNode()); 1163 if (Replace) 1164 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1165 1166 DEBUG(dbgs() << "\nPromoting "; 1167 Op.getNode()->dump(&DAG)); 1168 SDLoc DL(Op); 1169 return DAG.getNode(ISD::TRUNCATE, DL, VT, 1170 DAG.getNode(Opc, DL, PVT, N0, Op.getOperand(1))); 1171 } 1172 return SDValue(); 1173 } 1174 1175 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1176 if (!LegalOperations) 1177 return SDValue(); 1178 1179 EVT VT = Op.getValueType(); 1180 if (VT.isVector() || !VT.isInteger()) 1181 return SDValue(); 1182 1183 // If operation type is 'undesirable', e.g. i16 on x86, consider 1184 // promoting it. 1185 unsigned Opc = Op.getOpcode(); 1186 if (TLI.isTypeDesirableForOp(Opc, VT)) 1187 return SDValue(); 1188 1189 EVT PVT = VT; 1190 // Consult target whether it is a good idea to promote this operation and 1191 // what's the right type to promote it to. 1192 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1193 assert(PVT != VT && "Don't know what type to promote to!"); 1194 // fold (aext (aext x)) -> (aext x) 1195 // fold (aext (zext x)) -> (zext x) 1196 // fold (aext (sext x)) -> (sext x) 1197 DEBUG(dbgs() << "\nPromoting "; 1198 Op.getNode()->dump(&DAG)); 1199 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1200 } 1201 return SDValue(); 1202 } 1203 1204 bool DAGCombiner::PromoteLoad(SDValue Op) { 1205 if (!LegalOperations) 1206 return false; 1207 1208 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1209 return false; 1210 1211 EVT VT = Op.getValueType(); 1212 if (VT.isVector() || !VT.isInteger()) 1213 return false; 1214 1215 // If operation type is 'undesirable', e.g. i16 on x86, consider 1216 // promoting it. 1217 unsigned Opc = Op.getOpcode(); 1218 if (TLI.isTypeDesirableForOp(Opc, VT)) 1219 return false; 1220 1221 EVT PVT = VT; 1222 // Consult target whether it is a good idea to promote this operation and 1223 // what's the right type to promote it to. 1224 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1225 assert(PVT != VT && "Don't know what type to promote to!"); 1226 1227 SDLoc DL(Op); 1228 SDNode *N = Op.getNode(); 1229 LoadSDNode *LD = cast<LoadSDNode>(N); 1230 EVT MemVT = LD->getMemoryVT(); 1231 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1232 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1233 : ISD::EXTLOAD) 1234 : LD->getExtensionType(); 1235 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT, 1236 LD->getChain(), LD->getBasePtr(), 1237 MemVT, LD->getMemOperand()); 1238 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD); 1239 1240 DEBUG(dbgs() << "\nPromoting "; 1241 N->dump(&DAG); 1242 dbgs() << "\nTo: "; 1243 Result.getNode()->dump(&DAG); 1244 dbgs() << '\n'); 1245 WorklistRemover DeadNodes(*this); 1246 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1247 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1248 deleteAndRecombine(N); 1249 AddToWorklist(Result.getNode()); 1250 return true; 1251 } 1252 return false; 1253 } 1254 1255 /// \brief Recursively delete a node which has no uses and any operands for 1256 /// which it is the only use. 1257 /// 1258 /// Note that this both deletes the nodes and removes them from the worklist. 1259 /// It also adds any nodes who have had a user deleted to the worklist as they 1260 /// may now have only one use and subject to other combines. 1261 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1262 if (!N->use_empty()) 1263 return false; 1264 1265 SmallSetVector<SDNode *, 16> Nodes; 1266 Nodes.insert(N); 1267 do { 1268 N = Nodes.pop_back_val(); 1269 if (!N) 1270 continue; 1271 1272 if (N->use_empty()) { 1273 for (const SDValue &ChildN : N->op_values()) 1274 Nodes.insert(ChildN.getNode()); 1275 1276 removeFromWorklist(N); 1277 DAG.DeleteNode(N); 1278 } else { 1279 AddToWorklist(N); 1280 } 1281 } while (!Nodes.empty()); 1282 return true; 1283 } 1284 1285 //===----------------------------------------------------------------------===// 1286 // Main DAG Combiner implementation 1287 //===----------------------------------------------------------------------===// 1288 1289 void DAGCombiner::Run(CombineLevel AtLevel) { 1290 // set the instance variables, so that the various visit routines may use it. 1291 Level = AtLevel; 1292 LegalOperations = Level >= AfterLegalizeVectorOps; 1293 LegalTypes = Level >= AfterLegalizeTypes; 1294 1295 // Add all the dag nodes to the worklist. 1296 for (SDNode &Node : DAG.allnodes()) 1297 AddToWorklist(&Node); 1298 1299 // Create a dummy node (which is not added to allnodes), that adds a reference 1300 // to the root node, preventing it from being deleted, and tracking any 1301 // changes of the root. 1302 HandleSDNode Dummy(DAG.getRoot()); 1303 1304 // While the worklist isn't empty, find a node and try to combine it. 1305 while (!WorklistMap.empty()) { 1306 SDNode *N; 1307 // The Worklist holds the SDNodes in order, but it may contain null entries. 1308 do { 1309 N = Worklist.pop_back_val(); 1310 } while (!N); 1311 1312 bool GoodWorklistEntry = WorklistMap.erase(N); 1313 (void)GoodWorklistEntry; 1314 assert(GoodWorklistEntry && 1315 "Found a worklist entry without a corresponding map entry!"); 1316 1317 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1318 // N is deleted from the DAG, since they too may now be dead or may have a 1319 // reduced number of uses, allowing other xforms. 1320 if (recursivelyDeleteUnusedNodes(N)) 1321 continue; 1322 1323 WorklistRemover DeadNodes(*this); 1324 1325 // If this combine is running after legalizing the DAG, re-legalize any 1326 // nodes pulled off the worklist. 1327 if (Level == AfterLegalizeDAG) { 1328 SmallSetVector<SDNode *, 16> UpdatedNodes; 1329 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1330 1331 for (SDNode *LN : UpdatedNodes) { 1332 AddToWorklist(LN); 1333 AddUsersToWorklist(LN); 1334 } 1335 if (!NIsValid) 1336 continue; 1337 } 1338 1339 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1340 1341 // Add any operands of the new node which have not yet been combined to the 1342 // worklist as well. Because the worklist uniques things already, this 1343 // won't repeatedly process the same operand. 1344 CombinedNodes.insert(N); 1345 for (const SDValue &ChildN : N->op_values()) 1346 if (!CombinedNodes.count(ChildN.getNode())) 1347 AddToWorklist(ChildN.getNode()); 1348 1349 SDValue RV = combine(N); 1350 1351 if (!RV.getNode()) 1352 continue; 1353 1354 ++NodesCombined; 1355 1356 // If we get back the same node we passed in, rather than a new node or 1357 // zero, we know that the node must have defined multiple values and 1358 // CombineTo was used. Since CombineTo takes care of the worklist 1359 // mechanics for us, we have no work to do in this case. 1360 if (RV.getNode() == N) 1361 continue; 1362 1363 assert(N->getOpcode() != ISD::DELETED_NODE && 1364 RV.getOpcode() != ISD::DELETED_NODE && 1365 "Node was deleted but visit returned new node!"); 1366 1367 DEBUG(dbgs() << " ... into: "; 1368 RV.getNode()->dump(&DAG)); 1369 1370 if (N->getNumValues() == RV.getNode()->getNumValues()) 1371 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1372 else { 1373 assert(N->getValueType(0) == RV.getValueType() && 1374 N->getNumValues() == 1 && "Type mismatch"); 1375 DAG.ReplaceAllUsesWith(N, &RV); 1376 } 1377 1378 // Push the new node and any users onto the worklist 1379 AddToWorklist(RV.getNode()); 1380 AddUsersToWorklist(RV.getNode()); 1381 1382 // Finally, if the node is now dead, remove it from the graph. The node 1383 // may not be dead if the replacement process recursively simplified to 1384 // something else needing this node. This will also take care of adding any 1385 // operands which have lost a user to the worklist. 1386 recursivelyDeleteUnusedNodes(N); 1387 } 1388 1389 // If the root changed (e.g. it was a dead load, update the root). 1390 DAG.setRoot(Dummy.getValue()); 1391 DAG.RemoveDeadNodes(); 1392 } 1393 1394 SDValue DAGCombiner::visit(SDNode *N) { 1395 switch (N->getOpcode()) { 1396 default: break; 1397 case ISD::TokenFactor: return visitTokenFactor(N); 1398 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1399 case ISD::ADD: return visitADD(N); 1400 case ISD::SUB: return visitSUB(N); 1401 case ISD::ADDC: return visitADDC(N); 1402 case ISD::SUBC: return visitSUBC(N); 1403 case ISD::ADDE: return visitADDE(N); 1404 case ISD::SUBE: return visitSUBE(N); 1405 case ISD::MUL: return visitMUL(N); 1406 case ISD::SDIV: return visitSDIV(N); 1407 case ISD::UDIV: return visitUDIV(N); 1408 case ISD::SREM: 1409 case ISD::UREM: return visitREM(N); 1410 case ISD::MULHU: return visitMULHU(N); 1411 case ISD::MULHS: return visitMULHS(N); 1412 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1413 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1414 case ISD::SMULO: return visitSMULO(N); 1415 case ISD::UMULO: return visitUMULO(N); 1416 case ISD::SMIN: 1417 case ISD::SMAX: 1418 case ISD::UMIN: 1419 case ISD::UMAX: return visitIMINMAX(N); 1420 case ISD::AND: return visitAND(N); 1421 case ISD::OR: return visitOR(N); 1422 case ISD::XOR: return visitXOR(N); 1423 case ISD::SHL: return visitSHL(N); 1424 case ISD::SRA: return visitSRA(N); 1425 case ISD::SRL: return visitSRL(N); 1426 case ISD::ROTR: 1427 case ISD::ROTL: return visitRotate(N); 1428 case ISD::BSWAP: return visitBSWAP(N); 1429 case ISD::BITREVERSE: return visitBITREVERSE(N); 1430 case ISD::CTLZ: return visitCTLZ(N); 1431 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1432 case ISD::CTTZ: return visitCTTZ(N); 1433 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1434 case ISD::CTPOP: return visitCTPOP(N); 1435 case ISD::SELECT: return visitSELECT(N); 1436 case ISD::VSELECT: return visitVSELECT(N); 1437 case ISD::SELECT_CC: return visitSELECT_CC(N); 1438 case ISD::SETCC: return visitSETCC(N); 1439 case ISD::SETCCE: return visitSETCCE(N); 1440 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1441 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1442 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1443 case ISD::AssertZext: return visitAssertZext(N); 1444 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1445 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1446 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1447 case ISD::TRUNCATE: return visitTRUNCATE(N); 1448 case ISD::BITCAST: return visitBITCAST(N); 1449 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1450 case ISD::FADD: return visitFADD(N); 1451 case ISD::FSUB: return visitFSUB(N); 1452 case ISD::FMUL: return visitFMUL(N); 1453 case ISD::FMA: return visitFMA(N); 1454 case ISD::FDIV: return visitFDIV(N); 1455 case ISD::FREM: return visitFREM(N); 1456 case ISD::FSQRT: return visitFSQRT(N); 1457 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1458 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1459 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1460 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1461 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1462 case ISD::FP_ROUND: return visitFP_ROUND(N); 1463 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1464 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1465 case ISD::FNEG: return visitFNEG(N); 1466 case ISD::FABS: return visitFABS(N); 1467 case ISD::FFLOOR: return visitFFLOOR(N); 1468 case ISD::FMINNUM: return visitFMINNUM(N); 1469 case ISD::FMAXNUM: return visitFMAXNUM(N); 1470 case ISD::FCEIL: return visitFCEIL(N); 1471 case ISD::FTRUNC: return visitFTRUNC(N); 1472 case ISD::BRCOND: return visitBRCOND(N); 1473 case ISD::BR_CC: return visitBR_CC(N); 1474 case ISD::LOAD: return visitLOAD(N); 1475 case ISD::STORE: return visitSTORE(N); 1476 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1477 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1478 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1479 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1480 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1481 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1482 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1483 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1484 case ISD::MGATHER: return visitMGATHER(N); 1485 case ISD::MLOAD: return visitMLOAD(N); 1486 case ISD::MSCATTER: return visitMSCATTER(N); 1487 case ISD::MSTORE: return visitMSTORE(N); 1488 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1489 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1490 } 1491 return SDValue(); 1492 } 1493 1494 SDValue DAGCombiner::combine(SDNode *N) { 1495 SDValue RV = visit(N); 1496 1497 // If nothing happened, try a target-specific DAG combine. 1498 if (!RV.getNode()) { 1499 assert(N->getOpcode() != ISD::DELETED_NODE && 1500 "Node was deleted but visit returned NULL!"); 1501 1502 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1503 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1504 1505 // Expose the DAG combiner to the target combiner impls. 1506 TargetLowering::DAGCombinerInfo 1507 DagCombineInfo(DAG, Level, false, this); 1508 1509 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1510 } 1511 } 1512 1513 // If nothing happened still, try promoting the operation. 1514 if (!RV.getNode()) { 1515 switch (N->getOpcode()) { 1516 default: break; 1517 case ISD::ADD: 1518 case ISD::SUB: 1519 case ISD::MUL: 1520 case ISD::AND: 1521 case ISD::OR: 1522 case ISD::XOR: 1523 RV = PromoteIntBinOp(SDValue(N, 0)); 1524 break; 1525 case ISD::SHL: 1526 case ISD::SRA: 1527 case ISD::SRL: 1528 RV = PromoteIntShiftOp(SDValue(N, 0)); 1529 break; 1530 case ISD::SIGN_EXTEND: 1531 case ISD::ZERO_EXTEND: 1532 case ISD::ANY_EXTEND: 1533 RV = PromoteExtend(SDValue(N, 0)); 1534 break; 1535 case ISD::LOAD: 1536 if (PromoteLoad(SDValue(N, 0))) 1537 RV = SDValue(N, 0); 1538 break; 1539 } 1540 } 1541 1542 // If N is a commutative binary node, try commuting it to enable more 1543 // sdisel CSE. 1544 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1545 N->getNumValues() == 1) { 1546 SDValue N0 = N->getOperand(0); 1547 SDValue N1 = N->getOperand(1); 1548 1549 // Constant operands are canonicalized to RHS. 1550 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1551 SDValue Ops[] = {N1, N0}; 1552 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1553 N->getFlags()); 1554 if (CSENode) 1555 return SDValue(CSENode, 0); 1556 } 1557 } 1558 1559 return RV; 1560 } 1561 1562 /// Given a node, return its input chain if it has one, otherwise return a null 1563 /// sd operand. 1564 static SDValue getInputChainForNode(SDNode *N) { 1565 if (unsigned NumOps = N->getNumOperands()) { 1566 if (N->getOperand(0).getValueType() == MVT::Other) 1567 return N->getOperand(0); 1568 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1569 return N->getOperand(NumOps-1); 1570 for (unsigned i = 1; i < NumOps-1; ++i) 1571 if (N->getOperand(i).getValueType() == MVT::Other) 1572 return N->getOperand(i); 1573 } 1574 return SDValue(); 1575 } 1576 1577 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1578 // If N has two operands, where one has an input chain equal to the other, 1579 // the 'other' chain is redundant. 1580 if (N->getNumOperands() == 2) { 1581 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1582 return N->getOperand(0); 1583 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1584 return N->getOperand(1); 1585 } 1586 1587 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1588 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1589 SmallPtrSet<SDNode*, 16> SeenOps; 1590 bool Changed = false; // If we should replace this token factor. 1591 1592 // Start out with this token factor. 1593 TFs.push_back(N); 1594 1595 // Iterate through token factors. The TFs grows when new token factors are 1596 // encountered. 1597 for (unsigned i = 0; i < TFs.size(); ++i) { 1598 SDNode *TF = TFs[i]; 1599 1600 // Check each of the operands. 1601 for (const SDValue &Op : TF->op_values()) { 1602 1603 switch (Op.getOpcode()) { 1604 case ISD::EntryToken: 1605 // Entry tokens don't need to be added to the list. They are 1606 // redundant. 1607 Changed = true; 1608 break; 1609 1610 case ISD::TokenFactor: 1611 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) { 1612 // Queue up for processing. 1613 TFs.push_back(Op.getNode()); 1614 // Clean up in case the token factor is removed. 1615 AddToWorklist(Op.getNode()); 1616 Changed = true; 1617 break; 1618 } 1619 LLVM_FALLTHROUGH; 1620 1621 default: 1622 // Only add if it isn't already in the list. 1623 if (SeenOps.insert(Op.getNode()).second) 1624 Ops.push_back(Op); 1625 else 1626 Changed = true; 1627 break; 1628 } 1629 } 1630 } 1631 1632 SDValue Result; 1633 1634 // If we've changed things around then replace token factor. 1635 if (Changed) { 1636 if (Ops.empty()) { 1637 // The entry token is the only possible outcome. 1638 Result = DAG.getEntryNode(); 1639 } else { 1640 // New and improved token factor. 1641 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1642 } 1643 1644 // Add users to worklist if AA is enabled, since it may introduce 1645 // a lot of new chained token factors while removing memory deps. 1646 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1647 : DAG.getSubtarget().useAA(); 1648 return CombineTo(N, Result, UseAA /*add to worklist*/); 1649 } 1650 1651 return Result; 1652 } 1653 1654 /// MERGE_VALUES can always be eliminated. 1655 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1656 WorklistRemover DeadNodes(*this); 1657 // Replacing results may cause a different MERGE_VALUES to suddenly 1658 // be CSE'd with N, and carry its uses with it. Iterate until no 1659 // uses remain, to ensure that the node can be safely deleted. 1660 // First add the users of this node to the work list so that they 1661 // can be tried again once they have new operands. 1662 AddUsersToWorklist(N); 1663 do { 1664 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1665 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1666 } while (!N->use_empty()); 1667 deleteAndRecombine(N); 1668 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1669 } 1670 1671 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1672 /// ConstantSDNode pointer else nullptr. 1673 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1674 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1675 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1676 } 1677 1678 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) { 1679 auto BinOpcode = BO->getOpcode(); 1680 assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB || 1681 BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV || 1682 BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || 1683 BinOpcode == ISD::UREM || BinOpcode == ISD::AND || 1684 BinOpcode == ISD::OR || BinOpcode == ISD::XOR || 1685 BinOpcode == ISD::SHL || BinOpcode == ISD::SRL || 1686 BinOpcode == ISD::SRA || BinOpcode == ISD::FADD || 1687 BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || 1688 BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) && 1689 "Unexpected binary operator"); 1690 1691 // Bail out if any constants are opaque because we can't constant fold those. 1692 SDValue C1 = BO->getOperand(1); 1693 if (!isConstantOrConstantVector(C1, true) && 1694 !isConstantFPBuildVectorOrConstantFP(C1)) 1695 return SDValue(); 1696 1697 // Don't do this unless the old select is going away. We want to eliminate the 1698 // binary operator, not replace a binop with a select. 1699 // TODO: Handle ISD::SELECT_CC. 1700 SDValue Sel = BO->getOperand(0); 1701 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) 1702 return SDValue(); 1703 1704 SDValue CT = Sel.getOperand(1); 1705 if (!isConstantOrConstantVector(CT, true) && 1706 !isConstantFPBuildVectorOrConstantFP(CT)) 1707 return SDValue(); 1708 1709 SDValue CF = Sel.getOperand(2); 1710 if (!isConstantOrConstantVector(CF, true) && 1711 !isConstantFPBuildVectorOrConstantFP(CF)) 1712 return SDValue(); 1713 1714 // We have a select-of-constants followed by a binary operator with a 1715 // constant. Eliminate the binop by pulling the constant math into the select. 1716 // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1 1717 EVT VT = Sel.getValueType(); 1718 SDLoc DL(Sel); 1719 SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1); 1720 assert((isConstantOrConstantVector(NewCT) || 1721 isConstantFPBuildVectorOrConstantFP(NewCT)) && 1722 "Failed to constant fold a binop with constant operands"); 1723 1724 SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1); 1725 assert((isConstantOrConstantVector(NewCF) || 1726 isConstantFPBuildVectorOrConstantFP(NewCF)) && 1727 "Failed to constant fold a binop with constant operands"); 1728 1729 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF); 1730 } 1731 1732 SDValue DAGCombiner::visitADD(SDNode *N) { 1733 SDValue N0 = N->getOperand(0); 1734 SDValue N1 = N->getOperand(1); 1735 EVT VT = N0.getValueType(); 1736 SDLoc DL(N); 1737 1738 // fold vector ops 1739 if (VT.isVector()) { 1740 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1741 return FoldedVOp; 1742 1743 // fold (add x, 0) -> x, vector edition 1744 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1745 return N0; 1746 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1747 return N1; 1748 } 1749 1750 // fold (add x, undef) -> undef 1751 if (N0.isUndef()) 1752 return N0; 1753 1754 if (N1.isUndef()) 1755 return N1; 1756 1757 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 1758 // canonicalize constant to RHS 1759 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 1760 return DAG.getNode(ISD::ADD, DL, VT, N1, N0); 1761 // fold (add c1, c2) -> c1+c2 1762 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(), 1763 N1.getNode()); 1764 } 1765 1766 // fold (add x, 0) -> x 1767 if (isNullConstant(N1)) 1768 return N0; 1769 1770 // fold ((c1-A)+c2) -> (c1+c2)-A 1771 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) { 1772 if (N0.getOpcode() == ISD::SUB) 1773 if (isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) { 1774 return DAG.getNode(ISD::SUB, DL, VT, 1775 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)), 1776 N0.getOperand(1)); 1777 } 1778 } 1779 1780 if (SDValue NewSel = foldBinOpIntoSelect(N)) 1781 return NewSel; 1782 1783 // reassociate add 1784 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1)) 1785 return RADD; 1786 1787 // fold ((0-A) + B) -> B-A 1788 if (N0.getOpcode() == ISD::SUB && 1789 isNullConstantOrNullSplatConstant(N0.getOperand(0))) 1790 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); 1791 1792 // fold (A + (0-B)) -> A-B 1793 if (N1.getOpcode() == ISD::SUB && 1794 isNullConstantOrNullSplatConstant(N1.getOperand(0))) 1795 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1)); 1796 1797 // fold (A+(B-A)) -> B 1798 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1799 return N1.getOperand(0); 1800 1801 // fold ((B-A)+A) -> B 1802 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1803 return N0.getOperand(0); 1804 1805 // fold (A+(B-(A+C))) to (B-C) 1806 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1807 N0 == N1.getOperand(1).getOperand(0)) 1808 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 1809 N1.getOperand(1).getOperand(1)); 1810 1811 // fold (A+(B-(C+A))) to (B-C) 1812 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1813 N0 == N1.getOperand(1).getOperand(1)) 1814 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 1815 N1.getOperand(1).getOperand(0)); 1816 1817 // fold (A+((B-A)+or-C)) to (B+or-C) 1818 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1819 N1.getOperand(0).getOpcode() == ISD::SUB && 1820 N0 == N1.getOperand(0).getOperand(1)) 1821 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0), 1822 N1.getOperand(1)); 1823 1824 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1825 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1826 SDValue N00 = N0.getOperand(0); 1827 SDValue N01 = N0.getOperand(1); 1828 SDValue N10 = N1.getOperand(0); 1829 SDValue N11 = N1.getOperand(1); 1830 1831 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10)) 1832 return DAG.getNode(ISD::SUB, DL, VT, 1833 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1834 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1835 } 1836 1837 if (SimplifyDemandedBits(SDValue(N, 0))) 1838 return SDValue(N, 0); 1839 1840 // fold (a+b) -> (a|b) iff a and b share no bits. 1841 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 1842 VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1)) 1843 return DAG.getNode(ISD::OR, DL, VT, N0, N1); 1844 1845 if (SDValue Combined = visitADDLike(N0, N1, N)) 1846 return Combined; 1847 1848 if (SDValue Combined = visitADDLike(N1, N0, N)) 1849 return Combined; 1850 1851 return SDValue(); 1852 } 1853 1854 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) { 1855 EVT VT = N0.getValueType(); 1856 SDLoc DL(LocReference); 1857 1858 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1859 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 1860 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0))) 1861 return DAG.getNode(ISD::SUB, DL, VT, N0, 1862 DAG.getNode(ISD::SHL, DL, VT, 1863 N1.getOperand(0).getOperand(1), 1864 N1.getOperand(1))); 1865 1866 if (N1.getOpcode() == ISD::AND) { 1867 SDValue AndOp0 = N1.getOperand(0); 1868 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1869 unsigned DestBits = VT.getScalarSizeInBits(); 1870 1871 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1872 // and similar xforms where the inner op is either ~0 or 0. 1873 if (NumSignBits == DestBits && 1874 isOneConstantOrOneSplatConstant(N1->getOperand(1))) 1875 return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0); 1876 } 1877 1878 // add (sext i1), X -> sub X, (zext i1) 1879 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1880 N0.getOperand(0).getValueType() == MVT::i1 && 1881 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1882 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1883 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1884 } 1885 1886 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1887 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1888 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1889 if (TN->getVT() == MVT::i1) { 1890 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1891 DAG.getConstant(1, DL, VT)); 1892 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1893 } 1894 } 1895 1896 return SDValue(); 1897 } 1898 1899 SDValue DAGCombiner::visitADDC(SDNode *N) { 1900 SDValue N0 = N->getOperand(0); 1901 SDValue N1 = N->getOperand(1); 1902 EVT VT = N0.getValueType(); 1903 SDLoc DL(N); 1904 1905 // If the flag result is dead, turn this into an ADD. 1906 if (!N->hasAnyUseOfValue(1)) 1907 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 1908 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1909 1910 // canonicalize constant to RHS. 1911 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1912 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1913 if (N0C && !N1C) 1914 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0); 1915 1916 // fold (addc x, 0) -> x + no carry out 1917 if (isNullConstant(N1)) 1918 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1919 DL, MVT::Glue)); 1920 1921 // If it cannot overflow, transform into an add. 1922 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 1923 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 1924 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1925 1926 return SDValue(); 1927 } 1928 1929 SDValue DAGCombiner::visitADDE(SDNode *N) { 1930 SDValue N0 = N->getOperand(0); 1931 SDValue N1 = N->getOperand(1); 1932 SDValue CarryIn = N->getOperand(2); 1933 1934 // canonicalize constant to RHS 1935 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1936 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1937 if (N0C && !N1C) 1938 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1939 N1, N0, CarryIn); 1940 1941 // fold (adde x, y, false) -> (addc x, y) 1942 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1943 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1944 1945 return SDValue(); 1946 } 1947 1948 // Since it may not be valid to emit a fold to zero for vector initializers 1949 // check if we can before folding. 1950 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 1951 SelectionDAG &DAG, bool LegalOperations, 1952 bool LegalTypes) { 1953 if (!VT.isVector()) 1954 return DAG.getConstant(0, DL, VT); 1955 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1956 return DAG.getConstant(0, DL, VT); 1957 return SDValue(); 1958 } 1959 1960 SDValue DAGCombiner::visitSUB(SDNode *N) { 1961 SDValue N0 = N->getOperand(0); 1962 SDValue N1 = N->getOperand(1); 1963 EVT VT = N0.getValueType(); 1964 SDLoc DL(N); 1965 1966 // fold vector ops 1967 if (VT.isVector()) { 1968 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1969 return FoldedVOp; 1970 1971 // fold (sub x, 0) -> x, vector edition 1972 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1973 return N0; 1974 } 1975 1976 // fold (sub x, x) -> 0 1977 // FIXME: Refactor this and xor and other similar operations together. 1978 if (N0 == N1) 1979 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes); 1980 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 1981 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 1982 // fold (sub c1, c2) -> c1-c2 1983 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(), 1984 N1.getNode()); 1985 } 1986 1987 if (SDValue NewSel = foldBinOpIntoSelect(N)) 1988 return NewSel; 1989 1990 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1991 1992 // fold (sub x, c) -> (add x, -c) 1993 if (N1C) { 1994 return DAG.getNode(ISD::ADD, DL, VT, N0, 1995 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 1996 } 1997 1998 if (isNullConstantOrNullSplatConstant(N0)) { 1999 unsigned BitWidth = VT.getScalarSizeInBits(); 2000 // Right-shifting everything out but the sign bit followed by negation is 2001 // the same as flipping arithmetic/logical shift type without the negation: 2002 // -(X >>u 31) -> (X >>s 31) 2003 // -(X >>s 31) -> (X >>u 31) 2004 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) { 2005 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1)); 2006 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) { 2007 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA; 2008 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT)) 2009 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1)); 2010 } 2011 } 2012 2013 // 0 - X --> 0 if the sub is NUW. 2014 if (N->getFlags()->hasNoUnsignedWrap()) 2015 return N0; 2016 2017 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignBit(BitWidth))) { 2018 // N1 is either 0 or the minimum signed value. If the sub is NSW, then 2019 // N1 must be 0 because negating the minimum signed value is undefined. 2020 if (N->getFlags()->hasNoSignedWrap()) 2021 return N0; 2022 2023 // 0 - X --> X if X is 0 or the minimum signed value. 2024 return N1; 2025 } 2026 } 2027 2028 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 2029 if (isAllOnesConstantOrAllOnesSplatConstant(N0)) 2030 return DAG.getNode(ISD::XOR, DL, VT, N1, N0); 2031 2032 // fold A-(A-B) -> B 2033 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 2034 return N1.getOperand(1); 2035 2036 // fold (A+B)-A -> B 2037 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 2038 return N0.getOperand(1); 2039 2040 // fold (A+B)-B -> A 2041 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 2042 return N0.getOperand(0); 2043 2044 // fold C2-(A+C1) -> (C2-C1)-A 2045 if (N1.getOpcode() == ISD::ADD) { 2046 SDValue N11 = N1.getOperand(1); 2047 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) && 2048 isConstantOrConstantVector(N11, /* NoOpaques */ true)) { 2049 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11); 2050 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0)); 2051 } 2052 } 2053 2054 // fold ((A+(B+or-C))-B) -> A+or-C 2055 if (N0.getOpcode() == ISD::ADD && 2056 (N0.getOperand(1).getOpcode() == ISD::SUB || 2057 N0.getOperand(1).getOpcode() == ISD::ADD) && 2058 N0.getOperand(1).getOperand(0) == N1) 2059 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0), 2060 N0.getOperand(1).getOperand(1)); 2061 2062 // fold ((A+(C+B))-B) -> A+C 2063 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD && 2064 N0.getOperand(1).getOperand(1) == N1) 2065 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), 2066 N0.getOperand(1).getOperand(0)); 2067 2068 // fold ((A-(B-C))-C) -> A-B 2069 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB && 2070 N0.getOperand(1).getOperand(1) == N1) 2071 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), 2072 N0.getOperand(1).getOperand(0)); 2073 2074 // If either operand of a sub is undef, the result is undef 2075 if (N0.isUndef()) 2076 return N0; 2077 if (N1.isUndef()) 2078 return N1; 2079 2080 // If the relocation model supports it, consider symbol offsets. 2081 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 2082 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 2083 // fold (sub Sym, c) -> Sym-c 2084 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 2085 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 2086 GA->getOffset() - 2087 (uint64_t)N1C->getSExtValue()); 2088 // fold (sub Sym+c1, Sym+c2) -> c1-c2 2089 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 2090 if (GA->getGlobal() == GB->getGlobal()) 2091 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 2092 DL, VT); 2093 } 2094 2095 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 2096 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2097 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2098 if (TN->getVT() == MVT::i1) { 2099 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2100 DAG.getConstant(1, DL, VT)); 2101 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 2102 } 2103 } 2104 2105 return SDValue(); 2106 } 2107 2108 SDValue DAGCombiner::visitSUBC(SDNode *N) { 2109 SDValue N0 = N->getOperand(0); 2110 SDValue N1 = N->getOperand(1); 2111 EVT VT = N0.getValueType(); 2112 SDLoc DL(N); 2113 2114 // If the flag result is dead, turn this into an SUB. 2115 if (!N->hasAnyUseOfValue(1)) 2116 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2117 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2118 2119 // fold (subc x, x) -> 0 + no borrow 2120 if (N0 == N1) 2121 return CombineTo(N, DAG.getConstant(0, DL, VT), 2122 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2123 2124 // fold (subc x, 0) -> x + no borrow 2125 if (isNullConstant(N1)) 2126 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2127 2128 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2129 if (isAllOnesConstant(N0)) 2130 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2131 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2132 2133 return SDValue(); 2134 } 2135 2136 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2137 SDValue N0 = N->getOperand(0); 2138 SDValue N1 = N->getOperand(1); 2139 SDValue CarryIn = N->getOperand(2); 2140 2141 // fold (sube x, y, false) -> (subc x, y) 2142 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2143 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2144 2145 return SDValue(); 2146 } 2147 2148 SDValue DAGCombiner::visitMUL(SDNode *N) { 2149 SDValue N0 = N->getOperand(0); 2150 SDValue N1 = N->getOperand(1); 2151 EVT VT = N0.getValueType(); 2152 2153 // fold (mul x, undef) -> 0 2154 if (N0.isUndef() || N1.isUndef()) 2155 return DAG.getConstant(0, SDLoc(N), VT); 2156 2157 bool N0IsConst = false; 2158 bool N1IsConst = false; 2159 bool N1IsOpaqueConst = false; 2160 bool N0IsOpaqueConst = false; 2161 APInt ConstValue0, ConstValue1; 2162 // fold vector ops 2163 if (VT.isVector()) { 2164 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2165 return FoldedVOp; 2166 2167 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0); 2168 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 2169 } else { 2170 N0IsConst = isa<ConstantSDNode>(N0); 2171 if (N0IsConst) { 2172 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2173 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2174 } 2175 N1IsConst = isa<ConstantSDNode>(N1); 2176 if (N1IsConst) { 2177 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2178 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2179 } 2180 } 2181 2182 // fold (mul c1, c2) -> c1*c2 2183 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2184 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2185 N0.getNode(), N1.getNode()); 2186 2187 // canonicalize constant to RHS (vector doesn't have to splat) 2188 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2189 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2190 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2191 // fold (mul x, 0) -> 0 2192 if (N1IsConst && ConstValue1 == 0) 2193 return N1; 2194 // We require a splat of the entire scalar bit width for non-contiguous 2195 // bit patterns. 2196 bool IsFullSplat = 2197 ConstValue1.getBitWidth() == VT.getScalarSizeInBits(); 2198 // fold (mul x, 1) -> x 2199 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2200 return N0; 2201 2202 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2203 return NewSel; 2204 2205 // fold (mul x, -1) -> 0-x 2206 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2207 SDLoc DL(N); 2208 return DAG.getNode(ISD::SUB, DL, VT, 2209 DAG.getConstant(0, DL, VT), N0); 2210 } 2211 // fold (mul x, (1 << c)) -> x << c 2212 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2213 IsFullSplat) { 2214 SDLoc DL(N); 2215 return DAG.getNode(ISD::SHL, DL, VT, N0, 2216 DAG.getConstant(ConstValue1.logBase2(), DL, 2217 getShiftAmountTy(N0.getValueType()))); 2218 } 2219 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2220 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2221 IsFullSplat) { 2222 unsigned Log2Val = (-ConstValue1).logBase2(); 2223 SDLoc DL(N); 2224 // FIXME: If the input is something that is easily negated (e.g. a 2225 // single-use add), we should put the negate there. 2226 return DAG.getNode(ISD::SUB, DL, VT, 2227 DAG.getConstant(0, DL, VT), 2228 DAG.getNode(ISD::SHL, DL, VT, N0, 2229 DAG.getConstant(Log2Val, DL, 2230 getShiftAmountTy(N0.getValueType())))); 2231 } 2232 2233 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2234 if (N0.getOpcode() == ISD::SHL && 2235 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 2236 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 2237 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 2238 if (isConstantOrConstantVector(C3)) 2239 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 2240 } 2241 2242 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2243 // use. 2244 { 2245 SDValue Sh(nullptr, 0), Y(nullptr, 0); 2246 2247 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2248 if (N0.getOpcode() == ISD::SHL && 2249 isConstantOrConstantVector(N0.getOperand(1)) && 2250 N0.getNode()->hasOneUse()) { 2251 Sh = N0; Y = N1; 2252 } else if (N1.getOpcode() == ISD::SHL && 2253 isConstantOrConstantVector(N1.getOperand(1)) && 2254 N1.getNode()->hasOneUse()) { 2255 Sh = N1; Y = N0; 2256 } 2257 2258 if (Sh.getNode()) { 2259 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 2260 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 2261 } 2262 } 2263 2264 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2265 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2266 N0.getOpcode() == ISD::ADD && 2267 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2268 isMulAddWithConstProfitable(N, N0, N1)) 2269 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2270 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2271 N0.getOperand(0), N1), 2272 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2273 N0.getOperand(1), N1)); 2274 2275 // reassociate mul 2276 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2277 return RMUL; 2278 2279 return SDValue(); 2280 } 2281 2282 /// Return true if divmod libcall is available. 2283 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2284 const TargetLowering &TLI) { 2285 RTLIB::Libcall LC; 2286 EVT NodeType = Node->getValueType(0); 2287 if (!NodeType.isSimple()) 2288 return false; 2289 switch (NodeType.getSimpleVT().SimpleTy) { 2290 default: return false; // No libcall for vector types. 2291 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2292 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2293 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2294 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2295 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2296 } 2297 2298 return TLI.getLibcallName(LC) != nullptr; 2299 } 2300 2301 /// Issue divrem if both quotient and remainder are needed. 2302 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2303 if (Node->use_empty()) 2304 return SDValue(); // This is a dead node, leave it alone. 2305 2306 unsigned Opcode = Node->getOpcode(); 2307 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2308 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2309 2310 // DivMod lib calls can still work on non-legal types if using lib-calls. 2311 EVT VT = Node->getValueType(0); 2312 if (VT.isVector() || !VT.isInteger()) 2313 return SDValue(); 2314 2315 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 2316 return SDValue(); 2317 2318 // If DIVREM is going to get expanded into a libcall, 2319 // but there is no libcall available, then don't combine. 2320 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2321 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2322 return SDValue(); 2323 2324 // If div is legal, it's better to do the normal expansion 2325 unsigned OtherOpcode = 0; 2326 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2327 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2328 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2329 return SDValue(); 2330 } else { 2331 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2332 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2333 return SDValue(); 2334 } 2335 2336 SDValue Op0 = Node->getOperand(0); 2337 SDValue Op1 = Node->getOperand(1); 2338 SDValue combined; 2339 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2340 UE = Op0.getNode()->use_end(); UI != UE;) { 2341 SDNode *User = *UI++; 2342 if (User == Node || User->use_empty()) 2343 continue; 2344 // Convert the other matching node(s), too; 2345 // otherwise, the DIVREM may get target-legalized into something 2346 // target-specific that we won't be able to recognize. 2347 unsigned UserOpc = User->getOpcode(); 2348 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2349 User->getOperand(0) == Op0 && 2350 User->getOperand(1) == Op1) { 2351 if (!combined) { 2352 if (UserOpc == OtherOpcode) { 2353 SDVTList VTs = DAG.getVTList(VT, VT); 2354 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2355 } else if (UserOpc == DivRemOpc) { 2356 combined = SDValue(User, 0); 2357 } else { 2358 assert(UserOpc == Opcode); 2359 continue; 2360 } 2361 } 2362 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2363 CombineTo(User, combined); 2364 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2365 CombineTo(User, combined.getValue(1)); 2366 } 2367 } 2368 return combined; 2369 } 2370 2371 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2372 SDValue N0 = N->getOperand(0); 2373 SDValue N1 = N->getOperand(1); 2374 EVT VT = N->getValueType(0); 2375 2376 // fold vector ops 2377 if (VT.isVector()) 2378 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2379 return FoldedVOp; 2380 2381 SDLoc DL(N); 2382 2383 // fold (sdiv c1, c2) -> c1/c2 2384 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2385 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2386 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2387 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2388 // fold (sdiv X, 1) -> X 2389 if (N1C && N1C->isOne()) 2390 return N0; 2391 // fold (sdiv X, -1) -> 0-X 2392 if (N1C && N1C->isAllOnesValue()) 2393 return DAG.getNode(ISD::SUB, DL, VT, 2394 DAG.getConstant(0, DL, VT), N0); 2395 2396 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2397 return NewSel; 2398 2399 // If we know the sign bits of both operands are zero, strength reduce to a 2400 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2401 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2402 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2403 2404 // fold (sdiv X, pow2) -> simple ops after legalize 2405 // FIXME: We check for the exact bit here because the generic lowering gives 2406 // better results in that case. The target-specific lowering should learn how 2407 // to handle exact sdivs efficiently. 2408 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2409 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() && 2410 (N1C->getAPIntValue().isPowerOf2() || 2411 (-N1C->getAPIntValue()).isPowerOf2())) { 2412 // Target-specific implementation of sdiv x, pow2. 2413 if (SDValue Res = BuildSDIVPow2(N)) 2414 return Res; 2415 2416 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2417 2418 // Splat the sign bit into the register 2419 SDValue SGN = 2420 DAG.getNode(ISD::SRA, DL, VT, N0, 2421 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2422 getShiftAmountTy(N0.getValueType()))); 2423 AddToWorklist(SGN.getNode()); 2424 2425 // Add (N0 < 0) ? abs2 - 1 : 0; 2426 SDValue SRL = 2427 DAG.getNode(ISD::SRL, DL, VT, SGN, 2428 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2429 getShiftAmountTy(SGN.getValueType()))); 2430 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2431 AddToWorklist(SRL.getNode()); 2432 AddToWorklist(ADD.getNode()); // Divide by pow2 2433 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2434 DAG.getConstant(lg2, DL, 2435 getShiftAmountTy(ADD.getValueType()))); 2436 2437 // If we're dividing by a positive value, we're done. Otherwise, we must 2438 // negate the result. 2439 if (N1C->getAPIntValue().isNonNegative()) 2440 return SRA; 2441 2442 AddToWorklist(SRA.getNode()); 2443 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2444 } 2445 2446 // If integer divide is expensive and we satisfy the requirements, emit an 2447 // alternate sequence. Targets may check function attributes for size/speed 2448 // trade-offs. 2449 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2450 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2451 if (SDValue Op = BuildSDIV(N)) 2452 return Op; 2453 2454 // sdiv, srem -> sdivrem 2455 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 2456 // true. Otherwise, we break the simplification logic in visitREM(). 2457 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2458 if (SDValue DivRem = useDivRem(N)) 2459 return DivRem; 2460 2461 // undef / X -> 0 2462 if (N0.isUndef()) 2463 return DAG.getConstant(0, DL, VT); 2464 // X / undef -> undef 2465 if (N1.isUndef()) 2466 return N1; 2467 2468 return SDValue(); 2469 } 2470 2471 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2472 SDValue N0 = N->getOperand(0); 2473 SDValue N1 = N->getOperand(1); 2474 EVT VT = N->getValueType(0); 2475 2476 // fold vector ops 2477 if (VT.isVector()) 2478 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2479 return FoldedVOp; 2480 2481 SDLoc DL(N); 2482 2483 // fold (udiv c1, c2) -> c1/c2 2484 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2485 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2486 if (N0C && N1C) 2487 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2488 N0C, N1C)) 2489 return Folded; 2490 2491 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2492 return NewSel; 2493 2494 // fold (udiv x, (1 << c)) -> x >>u c 2495 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 2496 DAG.isKnownToBeAPowerOfTwo(N1)) { 2497 SDValue LogBase2 = BuildLogBase2(N1, DL); 2498 AddToWorklist(LogBase2.getNode()); 2499 2500 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 2501 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 2502 AddToWorklist(Trunc.getNode()); 2503 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 2504 } 2505 2506 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2507 if (N1.getOpcode() == ISD::SHL) { 2508 SDValue N10 = N1.getOperand(0); 2509 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) && 2510 DAG.isKnownToBeAPowerOfTwo(N10)) { 2511 SDValue LogBase2 = BuildLogBase2(N10, DL); 2512 AddToWorklist(LogBase2.getNode()); 2513 2514 EVT ADDVT = N1.getOperand(1).getValueType(); 2515 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT); 2516 AddToWorklist(Trunc.getNode()); 2517 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc); 2518 AddToWorklist(Add.getNode()); 2519 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2520 } 2521 } 2522 2523 // fold (udiv x, c) -> alternate 2524 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2525 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2526 if (SDValue Op = BuildUDIV(N)) 2527 return Op; 2528 2529 // sdiv, srem -> sdivrem 2530 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 2531 // true. Otherwise, we break the simplification logic in visitREM(). 2532 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2533 if (SDValue DivRem = useDivRem(N)) 2534 return DivRem; 2535 2536 // undef / X -> 0 2537 if (N0.isUndef()) 2538 return DAG.getConstant(0, DL, VT); 2539 // X / undef -> undef 2540 if (N1.isUndef()) 2541 return N1; 2542 2543 return SDValue(); 2544 } 2545 2546 // handles ISD::SREM and ISD::UREM 2547 SDValue DAGCombiner::visitREM(SDNode *N) { 2548 unsigned Opcode = N->getOpcode(); 2549 SDValue N0 = N->getOperand(0); 2550 SDValue N1 = N->getOperand(1); 2551 EVT VT = N->getValueType(0); 2552 bool isSigned = (Opcode == ISD::SREM); 2553 SDLoc DL(N); 2554 2555 // fold (rem c1, c2) -> c1%c2 2556 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2557 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2558 if (N0C && N1C) 2559 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 2560 return Folded; 2561 2562 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2563 return NewSel; 2564 2565 if (isSigned) { 2566 // If we know the sign bits of both operands are zero, strength reduce to a 2567 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2568 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2569 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 2570 } else { 2571 SDValue NegOne = DAG.getAllOnesConstant(DL, VT); 2572 if (DAG.isKnownToBeAPowerOfTwo(N1)) { 2573 // fold (urem x, pow2) -> (and x, pow2-1) 2574 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 2575 AddToWorklist(Add.getNode()); 2576 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2577 } 2578 if (N1.getOpcode() == ISD::SHL && 2579 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) { 2580 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2581 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 2582 AddToWorklist(Add.getNode()); 2583 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2584 } 2585 } 2586 2587 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2588 2589 // If X/C can be simplified by the division-by-constant logic, lower 2590 // X%C to the equivalent of X-X/C*C. 2591 // To avoid mangling nodes, this simplification requires that the combine() 2592 // call for the speculative DIV must not cause a DIVREM conversion. We guard 2593 // against this by skipping the simplification if isIntDivCheap(). When 2594 // div is not cheap, combine will not return a DIVREM. Regardless, 2595 // checking cheapness here makes sense since the simplification results in 2596 // fatter code. 2597 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 2598 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2599 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 2600 AddToWorklist(Div.getNode()); 2601 SDValue OptimizedDiv = combine(Div.getNode()); 2602 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2603 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 2604 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 2605 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 2606 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 2607 AddToWorklist(Mul.getNode()); 2608 return Sub; 2609 } 2610 } 2611 2612 // sdiv, srem -> sdivrem 2613 if (SDValue DivRem = useDivRem(N)) 2614 return DivRem.getValue(1); 2615 2616 // undef % X -> 0 2617 if (N0.isUndef()) 2618 return DAG.getConstant(0, DL, VT); 2619 // X % undef -> undef 2620 if (N1.isUndef()) 2621 return N1; 2622 2623 return SDValue(); 2624 } 2625 2626 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2627 SDValue N0 = N->getOperand(0); 2628 SDValue N1 = N->getOperand(1); 2629 EVT VT = N->getValueType(0); 2630 SDLoc DL(N); 2631 2632 // fold (mulhs x, 0) -> 0 2633 if (isNullConstant(N1)) 2634 return N1; 2635 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2636 if (isOneConstant(N1)) { 2637 SDLoc DL(N); 2638 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2639 DAG.getConstant(N0.getValueSizeInBits() - 1, DL, 2640 getShiftAmountTy(N0.getValueType()))); 2641 } 2642 // fold (mulhs x, undef) -> 0 2643 if (N0.isUndef() || N1.isUndef()) 2644 return DAG.getConstant(0, SDLoc(N), VT); 2645 2646 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2647 // plus a shift. 2648 if (VT.isSimple() && !VT.isVector()) { 2649 MVT Simple = VT.getSimpleVT(); 2650 unsigned SimpleSize = Simple.getSizeInBits(); 2651 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2652 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2653 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2654 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2655 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2656 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2657 DAG.getConstant(SimpleSize, DL, 2658 getShiftAmountTy(N1.getValueType()))); 2659 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2660 } 2661 } 2662 2663 return SDValue(); 2664 } 2665 2666 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2667 SDValue N0 = N->getOperand(0); 2668 SDValue N1 = N->getOperand(1); 2669 EVT VT = N->getValueType(0); 2670 SDLoc DL(N); 2671 2672 // fold (mulhu x, 0) -> 0 2673 if (isNullConstant(N1)) 2674 return N1; 2675 // fold (mulhu x, 1) -> 0 2676 if (isOneConstant(N1)) 2677 return DAG.getConstant(0, DL, N0.getValueType()); 2678 // fold (mulhu x, undef) -> 0 2679 if (N0.isUndef() || N1.isUndef()) 2680 return DAG.getConstant(0, DL, VT); 2681 2682 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2683 // plus a shift. 2684 if (VT.isSimple() && !VT.isVector()) { 2685 MVT Simple = VT.getSimpleVT(); 2686 unsigned SimpleSize = Simple.getSizeInBits(); 2687 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2688 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2689 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2690 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2691 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2692 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2693 DAG.getConstant(SimpleSize, DL, 2694 getShiftAmountTy(N1.getValueType()))); 2695 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2696 } 2697 } 2698 2699 return SDValue(); 2700 } 2701 2702 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2703 /// give the opcodes for the two computations that are being performed. Return 2704 /// true if a simplification was made. 2705 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2706 unsigned HiOp) { 2707 // If the high half is not needed, just compute the low half. 2708 bool HiExists = N->hasAnyUseOfValue(1); 2709 if (!HiExists && 2710 (!LegalOperations || 2711 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2712 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2713 return CombineTo(N, Res, Res); 2714 } 2715 2716 // If the low half is not needed, just compute the high half. 2717 bool LoExists = N->hasAnyUseOfValue(0); 2718 if (!LoExists && 2719 (!LegalOperations || 2720 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2721 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2722 return CombineTo(N, Res, Res); 2723 } 2724 2725 // If both halves are used, return as it is. 2726 if (LoExists && HiExists) 2727 return SDValue(); 2728 2729 // If the two computed results can be simplified separately, separate them. 2730 if (LoExists) { 2731 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2732 AddToWorklist(Lo.getNode()); 2733 SDValue LoOpt = combine(Lo.getNode()); 2734 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2735 (!LegalOperations || 2736 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2737 return CombineTo(N, LoOpt, LoOpt); 2738 } 2739 2740 if (HiExists) { 2741 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2742 AddToWorklist(Hi.getNode()); 2743 SDValue HiOpt = combine(Hi.getNode()); 2744 if (HiOpt.getNode() && HiOpt != Hi && 2745 (!LegalOperations || 2746 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2747 return CombineTo(N, HiOpt, HiOpt); 2748 } 2749 2750 return SDValue(); 2751 } 2752 2753 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2754 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 2755 return Res; 2756 2757 EVT VT = N->getValueType(0); 2758 SDLoc DL(N); 2759 2760 // If the type is twice as wide is legal, transform the mulhu to a wider 2761 // multiply plus a shift. 2762 if (VT.isSimple() && !VT.isVector()) { 2763 MVT Simple = VT.getSimpleVT(); 2764 unsigned SimpleSize = Simple.getSizeInBits(); 2765 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2766 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2767 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2768 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2769 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2770 // Compute the high part as N1. 2771 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2772 DAG.getConstant(SimpleSize, DL, 2773 getShiftAmountTy(Lo.getValueType()))); 2774 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2775 // Compute the low part as N0. 2776 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2777 return CombineTo(N, Lo, Hi); 2778 } 2779 } 2780 2781 return SDValue(); 2782 } 2783 2784 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2785 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 2786 return Res; 2787 2788 EVT VT = N->getValueType(0); 2789 SDLoc DL(N); 2790 2791 // If the type is twice as wide is legal, transform the mulhu to a wider 2792 // multiply plus a shift. 2793 if (VT.isSimple() && !VT.isVector()) { 2794 MVT Simple = VT.getSimpleVT(); 2795 unsigned SimpleSize = Simple.getSizeInBits(); 2796 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2797 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2798 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2799 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2800 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2801 // Compute the high part as N1. 2802 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2803 DAG.getConstant(SimpleSize, DL, 2804 getShiftAmountTy(Lo.getValueType()))); 2805 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2806 // Compute the low part as N0. 2807 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2808 return CombineTo(N, Lo, Hi); 2809 } 2810 } 2811 2812 return SDValue(); 2813 } 2814 2815 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2816 // (smulo x, 2) -> (saddo x, x) 2817 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2818 if (C2->getAPIntValue() == 2) 2819 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2820 N->getOperand(0), N->getOperand(0)); 2821 2822 return SDValue(); 2823 } 2824 2825 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2826 // (umulo x, 2) -> (uaddo x, x) 2827 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2828 if (C2->getAPIntValue() == 2) 2829 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2830 N->getOperand(0), N->getOperand(0)); 2831 2832 return SDValue(); 2833 } 2834 2835 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 2836 SDValue N0 = N->getOperand(0); 2837 SDValue N1 = N->getOperand(1); 2838 EVT VT = N0.getValueType(); 2839 2840 // fold vector ops 2841 if (VT.isVector()) 2842 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2843 return FoldedVOp; 2844 2845 // fold (add c1, c2) -> c1+c2 2846 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 2847 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2848 if (N0C && N1C) 2849 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 2850 2851 // canonicalize constant to RHS 2852 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2853 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2854 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 2855 2856 return SDValue(); 2857 } 2858 2859 /// If this is a binary operator with two operands of the same opcode, try to 2860 /// simplify it. 2861 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2862 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2863 EVT VT = N0.getValueType(); 2864 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2865 2866 // Bail early if none of these transforms apply. 2867 if (N0.getNumOperands() == 0) return SDValue(); 2868 2869 // For each of OP in AND/OR/XOR: 2870 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2871 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2872 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2873 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2874 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2875 // 2876 // do not sink logical op inside of a vector extend, since it may combine 2877 // into a vsetcc. 2878 EVT Op0VT = N0.getOperand(0).getValueType(); 2879 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2880 N0.getOpcode() == ISD::SIGN_EXTEND || 2881 N0.getOpcode() == ISD::BSWAP || 2882 // Avoid infinite looping with PromoteIntBinOp. 2883 (N0.getOpcode() == ISD::ANY_EXTEND && 2884 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2885 (N0.getOpcode() == ISD::TRUNCATE && 2886 (!TLI.isZExtFree(VT, Op0VT) || 2887 !TLI.isTruncateFree(Op0VT, VT)) && 2888 TLI.isTypeLegal(Op0VT))) && 2889 !VT.isVector() && 2890 Op0VT == N1.getOperand(0).getValueType() && 2891 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2892 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2893 N0.getOperand(0).getValueType(), 2894 N0.getOperand(0), N1.getOperand(0)); 2895 AddToWorklist(ORNode.getNode()); 2896 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2897 } 2898 2899 // For each of OP in SHL/SRL/SRA/AND... 2900 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2901 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2902 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2903 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2904 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2905 N0.getOperand(1) == N1.getOperand(1)) { 2906 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2907 N0.getOperand(0).getValueType(), 2908 N0.getOperand(0), N1.getOperand(0)); 2909 AddToWorklist(ORNode.getNode()); 2910 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2911 ORNode, N0.getOperand(1)); 2912 } 2913 2914 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2915 // Only perform this optimization up until type legalization, before 2916 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2917 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2918 // we don't want to undo this promotion. 2919 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2920 // on scalars. 2921 if ((N0.getOpcode() == ISD::BITCAST || 2922 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2923 Level <= AfterLegalizeTypes) { 2924 SDValue In0 = N0.getOperand(0); 2925 SDValue In1 = N1.getOperand(0); 2926 EVT In0Ty = In0.getValueType(); 2927 EVT In1Ty = In1.getValueType(); 2928 SDLoc DL(N); 2929 // If both incoming values are integers, and the original types are the 2930 // same. 2931 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2932 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2933 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2934 AddToWorklist(Op.getNode()); 2935 return BC; 2936 } 2937 } 2938 2939 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2940 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2941 // If both shuffles use the same mask, and both shuffle within a single 2942 // vector, then it is worthwhile to move the swizzle after the operation. 2943 // The type-legalizer generates this pattern when loading illegal 2944 // vector types from memory. In many cases this allows additional shuffle 2945 // optimizations. 2946 // There are other cases where moving the shuffle after the xor/and/or 2947 // is profitable even if shuffles don't perform a swizzle. 2948 // If both shuffles use the same mask, and both shuffles have the same first 2949 // or second operand, then it might still be profitable to move the shuffle 2950 // after the xor/and/or operation. 2951 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2952 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2953 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2954 2955 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2956 "Inputs to shuffles are not the same type"); 2957 2958 // Check that both shuffles use the same mask. The masks are known to be of 2959 // the same length because the result vector type is the same. 2960 // Check also that shuffles have only one use to avoid introducing extra 2961 // instructions. 2962 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2963 SVN0->getMask().equals(SVN1->getMask())) { 2964 SDValue ShOp = N0->getOperand(1); 2965 2966 // Don't try to fold this node if it requires introducing a 2967 // build vector of all zeros that might be illegal at this stage. 2968 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 2969 if (!LegalTypes) 2970 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2971 else 2972 ShOp = SDValue(); 2973 } 2974 2975 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2976 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2977 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2978 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2979 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2980 N0->getOperand(0), N1->getOperand(0)); 2981 AddToWorklist(NewNode.getNode()); 2982 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2983 SVN0->getMask()); 2984 } 2985 2986 // Don't try to fold this node if it requires introducing a 2987 // build vector of all zeros that might be illegal at this stage. 2988 ShOp = N0->getOperand(0); 2989 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 2990 if (!LegalTypes) 2991 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2992 else 2993 ShOp = SDValue(); 2994 } 2995 2996 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2997 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2998 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2999 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 3000 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3001 N0->getOperand(1), N1->getOperand(1)); 3002 AddToWorklist(NewNode.getNode()); 3003 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 3004 SVN0->getMask()); 3005 } 3006 } 3007 } 3008 3009 return SDValue(); 3010 } 3011 3012 /// This contains all DAGCombine rules which reduce two values combined by 3013 /// an And operation to a single value. This makes them reusable in the context 3014 /// of visitSELECT(). Rules involving constants are not included as 3015 /// visitSELECT() already handles those cases. 3016 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 3017 SDNode *LocReference) { 3018 EVT VT = N1.getValueType(); 3019 3020 // fold (and x, undef) -> 0 3021 if (N0.isUndef() || N1.isUndef()) 3022 return DAG.getConstant(0, SDLoc(LocReference), VT); 3023 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 3024 SDValue LL, LR, RL, RR, CC0, CC1; 3025 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3026 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3027 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3028 3029 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 3030 LL.getValueType().isInteger()) { 3031 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 3032 if (isNullConstant(LR) && Op1 == ISD::SETEQ) { 3033 EVT CCVT = getSetCCResultType(LR.getValueType()); 3034 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 3035 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 3036 LR.getValueType(), LL, RL); 3037 AddToWorklist(ORNode.getNode()); 3038 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3039 } 3040 } 3041 if (isAllOnesConstant(LR)) { 3042 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 3043 if (Op1 == ISD::SETEQ) { 3044 EVT CCVT = getSetCCResultType(LR.getValueType()); 3045 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 3046 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 3047 LR.getValueType(), LL, RL); 3048 AddToWorklist(ANDNode.getNode()); 3049 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3050 } 3051 } 3052 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 3053 if (Op1 == ISD::SETGT) { 3054 EVT CCVT = getSetCCResultType(LR.getValueType()); 3055 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 3056 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 3057 LR.getValueType(), LL, RL); 3058 AddToWorklist(ORNode.getNode()); 3059 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3060 } 3061 } 3062 } 3063 } 3064 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 3065 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 3066 Op0 == Op1 && LL.getValueType().isInteger() && 3067 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) || 3068 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 3069 EVT CCVT = getSetCCResultType(LL.getValueType()); 3070 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 3071 SDLoc DL(N0); 3072 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(), 3073 LL, DAG.getConstant(1, DL, 3074 LL.getValueType())); 3075 AddToWorklist(ADDNode.getNode()); 3076 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 3077 DAG.getConstant(2, DL, LL.getValueType()), 3078 ISD::SETUGE); 3079 } 3080 } 3081 // canonicalize equivalent to ll == rl 3082 if (LL == RR && LR == RL) { 3083 Op1 = ISD::getSetCCSwappedOperands(Op1); 3084 std::swap(RL, RR); 3085 } 3086 if (LL == RL && LR == RR) { 3087 bool isInteger = LL.getValueType().isInteger(); 3088 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 3089 if (Result != ISD::SETCC_INVALID && 3090 (!LegalOperations || 3091 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3092 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 3093 EVT CCVT = getSetCCResultType(LL.getValueType()); 3094 if (N0.getValueType() == CCVT || 3095 (!LegalOperations && N0.getValueType() == MVT::i1)) 3096 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3097 LL, LR, Result); 3098 } 3099 } 3100 } 3101 3102 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 3103 VT.getSizeInBits() <= 64) { 3104 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3105 APInt ADDC = ADDI->getAPIntValue(); 3106 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3107 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 3108 // immediate for an add, but it is legal if its top c2 bits are set, 3109 // transform the ADD so the immediate doesn't need to be materialized 3110 // in a register. 3111 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 3112 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3113 SRLI->getZExtValue()); 3114 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 3115 ADDC |= Mask; 3116 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3117 SDLoc DL(N0); 3118 SDValue NewAdd = 3119 DAG.getNode(ISD::ADD, DL, VT, 3120 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 3121 CombineTo(N0.getNode(), NewAdd); 3122 // Return N so it doesn't get rechecked! 3123 return SDValue(LocReference, 0); 3124 } 3125 } 3126 } 3127 } 3128 } 3129 } 3130 3131 // Reduce bit extract of low half of an integer to the narrower type. 3132 // (and (srl i64:x, K), KMask) -> 3133 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 3134 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 3135 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 3136 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3137 unsigned Size = VT.getSizeInBits(); 3138 const APInt &AndMask = CAnd->getAPIntValue(); 3139 unsigned ShiftBits = CShift->getZExtValue(); 3140 3141 // Bail out, this node will probably disappear anyway. 3142 if (ShiftBits == 0) 3143 return SDValue(); 3144 3145 unsigned MaskBits = AndMask.countTrailingOnes(); 3146 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 3147 3148 if (APIntOps::isMask(AndMask) && 3149 // Required bits must not span the two halves of the integer and 3150 // must fit in the half size type. 3151 (ShiftBits + MaskBits <= Size / 2) && 3152 TLI.isNarrowingProfitable(VT, HalfVT) && 3153 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 3154 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 3155 TLI.isTruncateFree(VT, HalfVT) && 3156 TLI.isZExtFree(HalfVT, VT)) { 3157 // The isNarrowingProfitable is to avoid regressions on PPC and 3158 // AArch64 which match a few 64-bit bit insert / bit extract patterns 3159 // on downstream users of this. Those patterns could probably be 3160 // extended to handle extensions mixed in. 3161 3162 SDValue SL(N0); 3163 assert(MaskBits <= Size); 3164 3165 // Extracting the highest bit of the low half. 3166 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 3167 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 3168 N0.getOperand(0)); 3169 3170 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 3171 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 3172 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 3173 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 3174 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 3175 } 3176 } 3177 } 3178 } 3179 3180 return SDValue(); 3181 } 3182 3183 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 3184 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 3185 bool &NarrowLoad) { 3186 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits(); 3187 3188 if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue())) 3189 return false; 3190 3191 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3192 LoadedVT = LoadN->getMemoryVT(); 3193 3194 if (ExtVT == LoadedVT && 3195 (!LegalOperations || 3196 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 3197 // ZEXTLOAD will match without needing to change the size of the value being 3198 // loaded. 3199 NarrowLoad = false; 3200 return true; 3201 } 3202 3203 // Do not change the width of a volatile load. 3204 if (LoadN->isVolatile()) 3205 return false; 3206 3207 // Do not generate loads of non-round integer types since these can 3208 // be expensive (and would be wrong if the type is not byte sized). 3209 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 3210 return false; 3211 3212 if (LegalOperations && 3213 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 3214 return false; 3215 3216 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 3217 return false; 3218 3219 NarrowLoad = true; 3220 return true; 3221 } 3222 3223 SDValue DAGCombiner::visitAND(SDNode *N) { 3224 SDValue N0 = N->getOperand(0); 3225 SDValue N1 = N->getOperand(1); 3226 EVT VT = N1.getValueType(); 3227 3228 // x & x --> x 3229 if (N0 == N1) 3230 return N0; 3231 3232 // fold vector ops 3233 if (VT.isVector()) { 3234 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3235 return FoldedVOp; 3236 3237 // fold (and x, 0) -> 0, vector edition 3238 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3239 // do not return N0, because undef node may exist in N0 3240 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()), 3241 SDLoc(N), N0.getValueType()); 3242 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3243 // do not return N1, because undef node may exist in N1 3244 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()), 3245 SDLoc(N), N1.getValueType()); 3246 3247 // fold (and x, -1) -> x, vector edition 3248 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3249 return N1; 3250 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3251 return N0; 3252 } 3253 3254 // fold (and c1, c2) -> c1&c2 3255 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3256 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3257 if (N0C && N1C && !N1C->isOpaque()) 3258 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3259 // canonicalize constant to RHS 3260 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3261 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3262 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3263 // fold (and x, -1) -> x 3264 if (isAllOnesConstant(N1)) 3265 return N0; 3266 // if (and x, c) is known to be zero, return 0 3267 unsigned BitWidth = VT.getScalarSizeInBits(); 3268 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3269 APInt::getAllOnesValue(BitWidth))) 3270 return DAG.getConstant(0, SDLoc(N), VT); 3271 3272 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3273 return NewSel; 3274 3275 // reassociate and 3276 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3277 return RAND; 3278 // fold (and (or x, C), D) -> D if (C & D) == D 3279 if (N1C && N0.getOpcode() == ISD::OR) 3280 if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1))) 3281 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 3282 return N1; 3283 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 3284 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3285 SDValue N0Op0 = N0.getOperand(0); 3286 APInt Mask = ~N1C->getAPIntValue(); 3287 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits()); 3288 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 3289 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 3290 N0.getValueType(), N0Op0); 3291 3292 // Replace uses of the AND with uses of the Zero extend node. 3293 CombineTo(N, Zext); 3294 3295 // We actually want to replace all uses of the any_extend with the 3296 // zero_extend, to avoid duplicating things. This will later cause this 3297 // AND to be folded. 3298 CombineTo(N0.getNode(), Zext); 3299 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3300 } 3301 } 3302 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3303 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3304 // already be zero by virtue of the width of the base type of the load. 3305 // 3306 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3307 // more cases. 3308 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3309 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 3310 N0.getOperand(0).getOpcode() == ISD::LOAD && 3311 N0.getOperand(0).getResNo() == 0) || 3312 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 3313 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3314 N0 : N0.getOperand(0) ); 3315 3316 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3317 // This can be a pure constant or a vector splat, in which case we treat the 3318 // vector as a scalar and use the splat value. 3319 APInt Constant = APInt::getNullValue(1); 3320 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3321 Constant = C->getAPIntValue(); 3322 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3323 APInt SplatValue, SplatUndef; 3324 unsigned SplatBitSize; 3325 bool HasAnyUndefs; 3326 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3327 SplatBitSize, HasAnyUndefs); 3328 if (IsSplat) { 3329 // Undef bits can contribute to a possible optimisation if set, so 3330 // set them. 3331 SplatValue |= SplatUndef; 3332 3333 // The splat value may be something like "0x00FFFFFF", which means 0 for 3334 // the first vector value and FF for the rest, repeating. We need a mask 3335 // that will apply equally to all members of the vector, so AND all the 3336 // lanes of the constant together. 3337 EVT VT = Vector->getValueType(0); 3338 unsigned BitWidth = VT.getScalarSizeInBits(); 3339 3340 // If the splat value has been compressed to a bitlength lower 3341 // than the size of the vector lane, we need to re-expand it to 3342 // the lane size. 3343 if (BitWidth > SplatBitSize) 3344 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3345 SplatBitSize < BitWidth; 3346 SplatBitSize = SplatBitSize * 2) 3347 SplatValue |= SplatValue.shl(SplatBitSize); 3348 3349 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3350 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3351 if (SplatBitSize % BitWidth == 0) { 3352 Constant = APInt::getAllOnesValue(BitWidth); 3353 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3354 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3355 } 3356 } 3357 } 3358 3359 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3360 // actually legal and isn't going to get expanded, else this is a false 3361 // optimisation. 3362 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3363 Load->getValueType(0), 3364 Load->getMemoryVT()); 3365 3366 // Resize the constant to the same size as the original memory access before 3367 // extension. If it is still the AllOnesValue then this AND is completely 3368 // unneeded. 3369 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits()); 3370 3371 bool B; 3372 switch (Load->getExtensionType()) { 3373 default: B = false; break; 3374 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3375 case ISD::ZEXTLOAD: 3376 case ISD::NON_EXTLOAD: B = true; break; 3377 } 3378 3379 if (B && Constant.isAllOnesValue()) { 3380 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3381 // preserve semantics once we get rid of the AND. 3382 SDValue NewLoad(Load, 0); 3383 if (Load->getExtensionType() == ISD::EXTLOAD) { 3384 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3385 Load->getValueType(0), SDLoc(Load), 3386 Load->getChain(), Load->getBasePtr(), 3387 Load->getOffset(), Load->getMemoryVT(), 3388 Load->getMemOperand()); 3389 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3390 if (Load->getNumValues() == 3) { 3391 // PRE/POST_INC loads have 3 values. 3392 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3393 NewLoad.getValue(2) }; 3394 CombineTo(Load, To, 3, true); 3395 } else { 3396 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3397 } 3398 } 3399 3400 // Fold the AND away, taking care not to fold to the old load node if we 3401 // replaced it. 3402 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3403 3404 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3405 } 3406 } 3407 3408 // fold (and (load x), 255) -> (zextload x, i8) 3409 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3410 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3411 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD || 3412 (N0.getOpcode() == ISD::ANY_EXTEND && 3413 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3414 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3415 LoadSDNode *LN0 = HasAnyExt 3416 ? cast<LoadSDNode>(N0.getOperand(0)) 3417 : cast<LoadSDNode>(N0); 3418 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3419 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3420 auto NarrowLoad = false; 3421 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3422 EVT ExtVT, LoadedVT; 3423 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT, 3424 NarrowLoad)) { 3425 if (!NarrowLoad) { 3426 SDValue NewLoad = 3427 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3428 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3429 LN0->getMemOperand()); 3430 AddToWorklist(N); 3431 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3432 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3433 } else { 3434 EVT PtrType = LN0->getOperand(1).getValueType(); 3435 3436 unsigned Alignment = LN0->getAlignment(); 3437 SDValue NewPtr = LN0->getBasePtr(); 3438 3439 // For big endian targets, we need to add an offset to the pointer 3440 // to load the correct bytes. For little endian systems, we merely 3441 // need to read fewer bytes from the same pointer. 3442 if (DAG.getDataLayout().isBigEndian()) { 3443 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3444 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3445 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3446 SDLoc DL(LN0); 3447 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3448 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3449 Alignment = MinAlign(Alignment, PtrOff); 3450 } 3451 3452 AddToWorklist(NewPtr.getNode()); 3453 3454 SDValue Load = DAG.getExtLoad( 3455 ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr, 3456 LN0->getPointerInfo(), ExtVT, Alignment, 3457 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 3458 AddToWorklist(N); 3459 CombineTo(LN0, Load, Load.getValue(1)); 3460 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3461 } 3462 } 3463 } 3464 } 3465 3466 if (SDValue Combined = visitANDLike(N0, N1, N)) 3467 return Combined; 3468 3469 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3470 if (N0.getOpcode() == N1.getOpcode()) 3471 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3472 return Tmp; 3473 3474 // Masking the negated extension of a boolean is just the zero-extended 3475 // boolean: 3476 // and (sub 0, zext(bool X)), 1 --> zext(bool X) 3477 // and (sub 0, sext(bool X)), 1 --> zext(bool X) 3478 // 3479 // Note: the SimplifyDemandedBits fold below can make an information-losing 3480 // transform, and then we have no way to find this better fold. 3481 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) { 3482 ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0)); 3483 SDValue SubRHS = N0.getOperand(1); 3484 if (SubLHS && SubLHS->isNullValue()) { 3485 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND && 3486 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 3487 return SubRHS; 3488 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND && 3489 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 3490 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0)); 3491 } 3492 } 3493 3494 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3495 // fold (and (sra)) -> (and (srl)) when possible. 3496 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 3497 return SDValue(N, 0); 3498 3499 // fold (zext_inreg (extload x)) -> (zextload x) 3500 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3501 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3502 EVT MemVT = LN0->getMemoryVT(); 3503 // If we zero all the possible extended bits, then we can turn this into 3504 // a zextload if we are running before legalize or the operation is legal. 3505 unsigned BitWidth = N1.getScalarValueSizeInBits(); 3506 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3507 BitWidth - MemVT.getScalarSizeInBits())) && 3508 ((!LegalOperations && !LN0->isVolatile()) || 3509 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3510 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3511 LN0->getChain(), LN0->getBasePtr(), 3512 MemVT, LN0->getMemOperand()); 3513 AddToWorklist(N); 3514 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3515 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3516 } 3517 } 3518 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3519 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3520 N0.hasOneUse()) { 3521 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3522 EVT MemVT = LN0->getMemoryVT(); 3523 // If we zero all the possible extended bits, then we can turn this into 3524 // a zextload if we are running before legalize or the operation is legal. 3525 unsigned BitWidth = N1.getScalarValueSizeInBits(); 3526 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3527 BitWidth - MemVT.getScalarSizeInBits())) && 3528 ((!LegalOperations && !LN0->isVolatile()) || 3529 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3530 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3531 LN0->getChain(), LN0->getBasePtr(), 3532 MemVT, LN0->getMemOperand()); 3533 AddToWorklist(N); 3534 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3535 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3536 } 3537 } 3538 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3539 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3540 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3541 N0.getOperand(1), false)) 3542 return BSwap; 3543 } 3544 3545 return SDValue(); 3546 } 3547 3548 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3549 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3550 bool DemandHighBits) { 3551 if (!LegalOperations) 3552 return SDValue(); 3553 3554 EVT VT = N->getValueType(0); 3555 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3556 return SDValue(); 3557 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3558 return SDValue(); 3559 3560 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3561 bool LookPassAnd0 = false; 3562 bool LookPassAnd1 = false; 3563 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3564 std::swap(N0, N1); 3565 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3566 std::swap(N0, N1); 3567 if (N0.getOpcode() == ISD::AND) { 3568 if (!N0.getNode()->hasOneUse()) 3569 return SDValue(); 3570 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3571 if (!N01C || N01C->getZExtValue() != 0xFF00) 3572 return SDValue(); 3573 N0 = N0.getOperand(0); 3574 LookPassAnd0 = true; 3575 } 3576 3577 if (N1.getOpcode() == ISD::AND) { 3578 if (!N1.getNode()->hasOneUse()) 3579 return SDValue(); 3580 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3581 if (!N11C || N11C->getZExtValue() != 0xFF) 3582 return SDValue(); 3583 N1 = N1.getOperand(0); 3584 LookPassAnd1 = true; 3585 } 3586 3587 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3588 std::swap(N0, N1); 3589 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3590 return SDValue(); 3591 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse()) 3592 return SDValue(); 3593 3594 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3595 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3596 if (!N01C || !N11C) 3597 return SDValue(); 3598 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3599 return SDValue(); 3600 3601 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3602 SDValue N00 = N0->getOperand(0); 3603 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3604 if (!N00.getNode()->hasOneUse()) 3605 return SDValue(); 3606 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3607 if (!N001C || N001C->getZExtValue() != 0xFF) 3608 return SDValue(); 3609 N00 = N00.getOperand(0); 3610 LookPassAnd0 = true; 3611 } 3612 3613 SDValue N10 = N1->getOperand(0); 3614 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3615 if (!N10.getNode()->hasOneUse()) 3616 return SDValue(); 3617 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3618 if (!N101C || N101C->getZExtValue() != 0xFF00) 3619 return SDValue(); 3620 N10 = N10.getOperand(0); 3621 LookPassAnd1 = true; 3622 } 3623 3624 if (N00 != N10) 3625 return SDValue(); 3626 3627 // Make sure everything beyond the low halfword gets set to zero since the SRL 3628 // 16 will clear the top bits. 3629 unsigned OpSizeInBits = VT.getSizeInBits(); 3630 if (DemandHighBits && OpSizeInBits > 16) { 3631 // If the left-shift isn't masked out then the only way this is a bswap is 3632 // if all bits beyond the low 8 are 0. In that case the entire pattern 3633 // reduces to a left shift anyway: leave it for other parts of the combiner. 3634 if (!LookPassAnd0) 3635 return SDValue(); 3636 3637 // However, if the right shift isn't masked out then it might be because 3638 // it's not needed. See if we can spot that too. 3639 if (!LookPassAnd1 && 3640 !DAG.MaskedValueIsZero( 3641 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3642 return SDValue(); 3643 } 3644 3645 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3646 if (OpSizeInBits > 16) { 3647 SDLoc DL(N); 3648 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3649 DAG.getConstant(OpSizeInBits - 16, DL, 3650 getShiftAmountTy(VT))); 3651 } 3652 return Res; 3653 } 3654 3655 /// Return true if the specified node is an element that makes up a 32-bit 3656 /// packed halfword byteswap. 3657 /// ((x & 0x000000ff) << 8) | 3658 /// ((x & 0x0000ff00) >> 8) | 3659 /// ((x & 0x00ff0000) << 8) | 3660 /// ((x & 0xff000000) >> 8) 3661 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3662 if (!N.getNode()->hasOneUse()) 3663 return false; 3664 3665 unsigned Opc = N.getOpcode(); 3666 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3667 return false; 3668 3669 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3670 if (!N1C) 3671 return false; 3672 3673 unsigned Num; 3674 switch (N1C->getZExtValue()) { 3675 default: 3676 return false; 3677 case 0xFF: Num = 0; break; 3678 case 0xFF00: Num = 1; break; 3679 case 0xFF0000: Num = 2; break; 3680 case 0xFF000000: Num = 3; break; 3681 } 3682 3683 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3684 SDValue N0 = N.getOperand(0); 3685 if (Opc == ISD::AND) { 3686 if (Num == 0 || Num == 2) { 3687 // (x >> 8) & 0xff 3688 // (x >> 8) & 0xff0000 3689 if (N0.getOpcode() != ISD::SRL) 3690 return false; 3691 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3692 if (!C || C->getZExtValue() != 8) 3693 return false; 3694 } else { 3695 // (x << 8) & 0xff00 3696 // (x << 8) & 0xff000000 3697 if (N0.getOpcode() != ISD::SHL) 3698 return false; 3699 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3700 if (!C || C->getZExtValue() != 8) 3701 return false; 3702 } 3703 } else if (Opc == ISD::SHL) { 3704 // (x & 0xff) << 8 3705 // (x & 0xff0000) << 8 3706 if (Num != 0 && Num != 2) 3707 return false; 3708 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3709 if (!C || C->getZExtValue() != 8) 3710 return false; 3711 } else { // Opc == ISD::SRL 3712 // (x & 0xff00) >> 8 3713 // (x & 0xff000000) >> 8 3714 if (Num != 1 && Num != 3) 3715 return false; 3716 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3717 if (!C || C->getZExtValue() != 8) 3718 return false; 3719 } 3720 3721 if (Parts[Num]) 3722 return false; 3723 3724 Parts[Num] = N0.getOperand(0).getNode(); 3725 return true; 3726 } 3727 3728 /// Match a 32-bit packed halfword bswap. That is 3729 /// ((x & 0x000000ff) << 8) | 3730 /// ((x & 0x0000ff00) >> 8) | 3731 /// ((x & 0x00ff0000) << 8) | 3732 /// ((x & 0xff000000) >> 8) 3733 /// => (rotl (bswap x), 16) 3734 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3735 if (!LegalOperations) 3736 return SDValue(); 3737 3738 EVT VT = N->getValueType(0); 3739 if (VT != MVT::i32) 3740 return SDValue(); 3741 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3742 return SDValue(); 3743 3744 // Look for either 3745 // (or (or (and), (and)), (or (and), (and))) 3746 // (or (or (or (and), (and)), (and)), (and)) 3747 if (N0.getOpcode() != ISD::OR) 3748 return SDValue(); 3749 SDValue N00 = N0.getOperand(0); 3750 SDValue N01 = N0.getOperand(1); 3751 SDNode *Parts[4] = {}; 3752 3753 if (N1.getOpcode() == ISD::OR && 3754 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3755 // (or (or (and), (and)), (or (and), (and))) 3756 SDValue N000 = N00.getOperand(0); 3757 if (!isBSwapHWordElement(N000, Parts)) 3758 return SDValue(); 3759 3760 SDValue N001 = N00.getOperand(1); 3761 if (!isBSwapHWordElement(N001, Parts)) 3762 return SDValue(); 3763 SDValue N010 = N01.getOperand(0); 3764 if (!isBSwapHWordElement(N010, Parts)) 3765 return SDValue(); 3766 SDValue N011 = N01.getOperand(1); 3767 if (!isBSwapHWordElement(N011, Parts)) 3768 return SDValue(); 3769 } else { 3770 // (or (or (or (and), (and)), (and)), (and)) 3771 if (!isBSwapHWordElement(N1, Parts)) 3772 return SDValue(); 3773 if (!isBSwapHWordElement(N01, Parts)) 3774 return SDValue(); 3775 if (N00.getOpcode() != ISD::OR) 3776 return SDValue(); 3777 SDValue N000 = N00.getOperand(0); 3778 if (!isBSwapHWordElement(N000, Parts)) 3779 return SDValue(); 3780 SDValue N001 = N00.getOperand(1); 3781 if (!isBSwapHWordElement(N001, Parts)) 3782 return SDValue(); 3783 } 3784 3785 // Make sure the parts are all coming from the same node. 3786 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3787 return SDValue(); 3788 3789 SDLoc DL(N); 3790 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 3791 SDValue(Parts[0], 0)); 3792 3793 // Result of the bswap should be rotated by 16. If it's not legal, then 3794 // do (x << 16) | (x >> 16). 3795 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 3796 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3797 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 3798 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3799 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 3800 return DAG.getNode(ISD::OR, DL, VT, 3801 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 3802 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 3803 } 3804 3805 /// This contains all DAGCombine rules which reduce two values combined by 3806 /// an Or operation to a single value \see visitANDLike(). 3807 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3808 EVT VT = N1.getValueType(); 3809 // fold (or x, undef) -> -1 3810 if (!LegalOperations && (N0.isUndef() || N1.isUndef())) 3811 return DAG.getAllOnesConstant(SDLoc(LocReference), VT); 3812 3813 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3814 SDValue LL, LR, RL, RR, CC0, CC1; 3815 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3816 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3817 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3818 3819 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) { 3820 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3821 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3822 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3823 EVT CCVT = getSetCCResultType(LR.getValueType()); 3824 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 3825 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3826 LR.getValueType(), LL, RL); 3827 AddToWorklist(ORNode.getNode()); 3828 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3829 } 3830 } 3831 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3832 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3833 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3834 EVT CCVT = getSetCCResultType(LR.getValueType()); 3835 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 3836 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3837 LR.getValueType(), LL, RL); 3838 AddToWorklist(ANDNode.getNode()); 3839 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3840 } 3841 } 3842 } 3843 // canonicalize equivalent to ll == rl 3844 if (LL == RR && LR == RL) { 3845 Op1 = ISD::getSetCCSwappedOperands(Op1); 3846 std::swap(RL, RR); 3847 } 3848 if (LL == RL && LR == RR) { 3849 bool isInteger = LL.getValueType().isInteger(); 3850 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3851 if (Result != ISD::SETCC_INVALID && 3852 (!LegalOperations || 3853 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3854 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 3855 EVT CCVT = getSetCCResultType(LL.getValueType()); 3856 if (N0.getValueType() == CCVT || 3857 (!LegalOperations && N0.getValueType() == MVT::i1)) 3858 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3859 LL, LR, Result); 3860 } 3861 } 3862 } 3863 3864 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3865 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 3866 // Don't increase # computations. 3867 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3868 // We can only do this xform if we know that bits from X that are set in C2 3869 // but not in C1 are already zero. Likewise for Y. 3870 if (const ConstantSDNode *N0O1C = 3871 getAsNonOpaqueConstant(N0.getOperand(1))) { 3872 if (const ConstantSDNode *N1O1C = 3873 getAsNonOpaqueConstant(N1.getOperand(1))) { 3874 // We can only do this xform if we know that bits from X that are set in 3875 // C2 but not in C1 are already zero. Likewise for Y. 3876 const APInt &LHSMask = N0O1C->getAPIntValue(); 3877 const APInt &RHSMask = N1O1C->getAPIntValue(); 3878 3879 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3880 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3881 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3882 N0.getOperand(0), N1.getOperand(0)); 3883 SDLoc DL(LocReference); 3884 return DAG.getNode(ISD::AND, DL, VT, X, 3885 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 3886 } 3887 } 3888 } 3889 } 3890 3891 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3892 if (N0.getOpcode() == ISD::AND && 3893 N1.getOpcode() == ISD::AND && 3894 N0.getOperand(0) == N1.getOperand(0) && 3895 // Don't increase # computations. 3896 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3897 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3898 N0.getOperand(1), N1.getOperand(1)); 3899 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3900 } 3901 3902 return SDValue(); 3903 } 3904 3905 SDValue DAGCombiner::visitOR(SDNode *N) { 3906 SDValue N0 = N->getOperand(0); 3907 SDValue N1 = N->getOperand(1); 3908 EVT VT = N1.getValueType(); 3909 3910 // x | x --> x 3911 if (N0 == N1) 3912 return N0; 3913 3914 // fold vector ops 3915 if (VT.isVector()) { 3916 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3917 return FoldedVOp; 3918 3919 // fold (or x, 0) -> x, vector edition 3920 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3921 return N1; 3922 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3923 return N0; 3924 3925 // fold (or x, -1) -> -1, vector edition 3926 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3927 // do not return N0, because undef node may exist in N0 3928 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType()); 3929 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3930 // do not return N1, because undef node may exist in N1 3931 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType()); 3932 3933 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 3934 // Do this only if the resulting shuffle is legal. 3935 if (isa<ShuffleVectorSDNode>(N0) && 3936 isa<ShuffleVectorSDNode>(N1) && 3937 // Avoid folding a node with illegal type. 3938 TLI.isTypeLegal(VT)) { 3939 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 3940 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 3941 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 3942 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 3943 // Ensure both shuffles have a zero input. 3944 if ((ZeroN00 || ZeroN01) && (ZeroN10 || ZeroN11)) { 3945 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 3946 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 3947 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3948 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3949 bool CanFold = true; 3950 int NumElts = VT.getVectorNumElements(); 3951 SmallVector<int, 4> Mask(NumElts); 3952 3953 for (int i = 0; i != NumElts; ++i) { 3954 int M0 = SV0->getMaskElt(i); 3955 int M1 = SV1->getMaskElt(i); 3956 3957 // Determine if either index is pointing to a zero vector. 3958 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 3959 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 3960 3961 // If one element is zero and the otherside is undef, keep undef. 3962 // This also handles the case that both are undef. 3963 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 3964 Mask[i] = -1; 3965 continue; 3966 } 3967 3968 // Make sure only one of the elements is zero. 3969 if (M0Zero == M1Zero) { 3970 CanFold = false; 3971 break; 3972 } 3973 3974 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 3975 3976 // We have a zero and non-zero element. If the non-zero came from 3977 // SV0 make the index a LHS index. If it came from SV1, make it 3978 // a RHS index. We need to mod by NumElts because we don't care 3979 // which operand it came from in the original shuffles. 3980 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 3981 } 3982 3983 if (CanFold) { 3984 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 3985 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 3986 3987 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 3988 if (!LegalMask) { 3989 std::swap(NewLHS, NewRHS); 3990 ShuffleVectorSDNode::commuteMask(Mask); 3991 LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 3992 } 3993 3994 if (LegalMask) 3995 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask); 3996 } 3997 } 3998 } 3999 } 4000 4001 // fold (or c1, c2) -> c1|c2 4002 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4003 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4004 if (N0C && N1C && !N1C->isOpaque()) 4005 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 4006 // canonicalize constant to RHS 4007 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4008 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4009 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 4010 // fold (or x, 0) -> x 4011 if (isNullConstant(N1)) 4012 return N0; 4013 // fold (or x, -1) -> -1 4014 if (isAllOnesConstant(N1)) 4015 return N1; 4016 4017 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4018 return NewSel; 4019 4020 // fold (or x, c) -> c iff (x & ~c) == 0 4021 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 4022 return N1; 4023 4024 if (SDValue Combined = visitORLike(N0, N1, N)) 4025 return Combined; 4026 4027 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 4028 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 4029 return BSwap; 4030 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 4031 return BSwap; 4032 4033 // reassociate or 4034 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 4035 return ROR; 4036 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 4037 // iff (c1 & c2) == 0. 4038 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4039 isa<ConstantSDNode>(N0.getOperand(1))) { 4040 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 4041 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 4042 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 4043 N1C, C1)) 4044 return DAG.getNode( 4045 ISD::AND, SDLoc(N), VT, 4046 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 4047 return SDValue(); 4048 } 4049 } 4050 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 4051 if (N0.getOpcode() == N1.getOpcode()) 4052 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4053 return Tmp; 4054 4055 // See if this is some rotate idiom. 4056 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 4057 return SDValue(Rot, 0); 4058 4059 if (SDValue Load = MatchLoadCombine(N)) 4060 return Load; 4061 4062 // Simplify the operands using demanded-bits information. 4063 if (!VT.isVector() && 4064 SimplifyDemandedBits(SDValue(N, 0))) 4065 return SDValue(N, 0); 4066 4067 return SDValue(); 4068 } 4069 4070 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 4071 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 4072 if (Op.getOpcode() == ISD::AND) { 4073 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 4074 Mask = Op.getOperand(1); 4075 Op = Op.getOperand(0); 4076 } else { 4077 return false; 4078 } 4079 } 4080 4081 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 4082 Shift = Op; 4083 return true; 4084 } 4085 4086 return false; 4087 } 4088 4089 // Return true if we can prove that, whenever Neg and Pos are both in the 4090 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 4091 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 4092 // 4093 // (or (shift1 X, Neg), (shift2 X, Pos)) 4094 // 4095 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 4096 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 4097 // to consider shift amounts with defined behavior. 4098 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 4099 // If EltSize is a power of 2 then: 4100 // 4101 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 4102 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 4103 // 4104 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 4105 // for the stronger condition: 4106 // 4107 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 4108 // 4109 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 4110 // we can just replace Neg with Neg' for the rest of the function. 4111 // 4112 // In other cases we check for the even stronger condition: 4113 // 4114 // Neg == EltSize - Pos [B] 4115 // 4116 // for all Neg and Pos. Note that the (or ...) then invokes undefined 4117 // behavior if Pos == 0 (and consequently Neg == EltSize). 4118 // 4119 // We could actually use [A] whenever EltSize is a power of 2, but the 4120 // only extra cases that it would match are those uninteresting ones 4121 // where Neg and Pos are never in range at the same time. E.g. for 4122 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 4123 // as well as (sub 32, Pos), but: 4124 // 4125 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 4126 // 4127 // always invokes undefined behavior for 32-bit X. 4128 // 4129 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 4130 unsigned MaskLoBits = 0; 4131 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 4132 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 4133 if (NegC->getAPIntValue() == EltSize - 1) { 4134 Neg = Neg.getOperand(0); 4135 MaskLoBits = Log2_64(EltSize); 4136 } 4137 } 4138 } 4139 4140 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 4141 if (Neg.getOpcode() != ISD::SUB) 4142 return false; 4143 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 4144 if (!NegC) 4145 return false; 4146 SDValue NegOp1 = Neg.getOperand(1); 4147 4148 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 4149 // Pos'. The truncation is redundant for the purpose of the equality. 4150 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 4151 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4152 if (PosC->getAPIntValue() == EltSize - 1) 4153 Pos = Pos.getOperand(0); 4154 4155 // The condition we need is now: 4156 // 4157 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 4158 // 4159 // If NegOp1 == Pos then we need: 4160 // 4161 // EltSize & Mask == NegC & Mask 4162 // 4163 // (because "x & Mask" is a truncation and distributes through subtraction). 4164 APInt Width; 4165 if (Pos == NegOp1) 4166 Width = NegC->getAPIntValue(); 4167 4168 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 4169 // Then the condition we want to prove becomes: 4170 // 4171 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 4172 // 4173 // which, again because "x & Mask" is a truncation, becomes: 4174 // 4175 // NegC & Mask == (EltSize - PosC) & Mask 4176 // EltSize & Mask == (NegC + PosC) & Mask 4177 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 4178 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4179 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 4180 else 4181 return false; 4182 } else 4183 return false; 4184 4185 // Now we just need to check that EltSize & Mask == Width & Mask. 4186 if (MaskLoBits) 4187 // EltSize & Mask is 0 since Mask is EltSize - 1. 4188 return Width.getLoBits(MaskLoBits) == 0; 4189 return Width == EltSize; 4190 } 4191 4192 // A subroutine of MatchRotate used once we have found an OR of two opposite 4193 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 4194 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 4195 // former being preferred if supported. InnerPos and InnerNeg are Pos and 4196 // Neg with outer conversions stripped away. 4197 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 4198 SDValue Neg, SDValue InnerPos, 4199 SDValue InnerNeg, unsigned PosOpcode, 4200 unsigned NegOpcode, const SDLoc &DL) { 4201 // fold (or (shl x, (*ext y)), 4202 // (srl x, (*ext (sub 32, y)))) -> 4203 // (rotl x, y) or (rotr x, (sub 32, y)) 4204 // 4205 // fold (or (shl x, (*ext (sub 32, y))), 4206 // (srl x, (*ext y))) -> 4207 // (rotr x, y) or (rotl x, (sub 32, y)) 4208 EVT VT = Shifted.getValueType(); 4209 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 4210 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 4211 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 4212 HasPos ? Pos : Neg).getNode(); 4213 } 4214 4215 return nullptr; 4216 } 4217 4218 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 4219 // idioms for rotate, and if the target supports rotation instructions, generate 4220 // a rot[lr]. 4221 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 4222 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 4223 EVT VT = LHS.getValueType(); 4224 if (!TLI.isTypeLegal(VT)) return nullptr; 4225 4226 // The target must have at least one rotate flavor. 4227 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 4228 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 4229 if (!HasROTL && !HasROTR) return nullptr; 4230 4231 // Match "(X shl/srl V1) & V2" where V2 may not be present. 4232 SDValue LHSShift; // The shift. 4233 SDValue LHSMask; // AND value if any. 4234 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 4235 return nullptr; // Not part of a rotate. 4236 4237 SDValue RHSShift; // The shift. 4238 SDValue RHSMask; // AND value if any. 4239 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 4240 return nullptr; // Not part of a rotate. 4241 4242 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 4243 return nullptr; // Not shifting the same value. 4244 4245 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 4246 return nullptr; // Shifts must disagree. 4247 4248 // Canonicalize shl to left side in a shl/srl pair. 4249 if (RHSShift.getOpcode() == ISD::SHL) { 4250 std::swap(LHS, RHS); 4251 std::swap(LHSShift, RHSShift); 4252 std::swap(LHSMask, RHSMask); 4253 } 4254 4255 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4256 SDValue LHSShiftArg = LHSShift.getOperand(0); 4257 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4258 SDValue RHSShiftArg = RHSShift.getOperand(0); 4259 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4260 4261 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4262 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4263 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) { 4264 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue(); 4265 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue(); 4266 if ((LShVal + RShVal) != EltSizeInBits) 4267 return nullptr; 4268 4269 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4270 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4271 4272 // If there is an AND of either shifted operand, apply it to the result. 4273 if (LHSMask.getNode() || RHSMask.getNode()) { 4274 SDValue Mask = DAG.getAllOnesConstant(DL, VT); 4275 4276 if (LHSMask.getNode()) { 4277 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal); 4278 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4279 DAG.getNode(ISD::OR, DL, VT, LHSMask, 4280 DAG.getConstant(RHSBits, DL, VT))); 4281 } 4282 if (RHSMask.getNode()) { 4283 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal); 4284 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4285 DAG.getNode(ISD::OR, DL, VT, RHSMask, 4286 DAG.getConstant(LHSBits, DL, VT))); 4287 } 4288 4289 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4290 } 4291 4292 return Rot.getNode(); 4293 } 4294 4295 // If there is a mask here, and we have a variable shift, we can't be sure 4296 // that we're masking out the right stuff. 4297 if (LHSMask.getNode() || RHSMask.getNode()) 4298 return nullptr; 4299 4300 // If the shift amount is sign/zext/any-extended just peel it off. 4301 SDValue LExtOp0 = LHSShiftAmt; 4302 SDValue RExtOp0 = RHSShiftAmt; 4303 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4304 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4305 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4306 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4307 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4308 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4309 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4310 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4311 LExtOp0 = LHSShiftAmt.getOperand(0); 4312 RExtOp0 = RHSShiftAmt.getOperand(0); 4313 } 4314 4315 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4316 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4317 if (TryL) 4318 return TryL; 4319 4320 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4321 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4322 if (TryR) 4323 return TryR; 4324 4325 return nullptr; 4326 } 4327 4328 namespace { 4329 /// Helper struct to parse and store a memory address as base + index + offset. 4330 /// We ignore sign extensions when it is safe to do so. 4331 /// The following two expressions are not equivalent. To differentiate we need 4332 /// to store whether there was a sign extension involved in the index 4333 /// computation. 4334 /// (load (i64 add (i64 copyfromreg %c) 4335 /// (i64 signextend (add (i8 load %index) 4336 /// (i8 1)))) 4337 /// vs 4338 /// 4339 /// (load (i64 add (i64 copyfromreg %c) 4340 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 4341 /// (i32 1))))) 4342 struct BaseIndexOffset { 4343 SDValue Base; 4344 SDValue Index; 4345 int64_t Offset; 4346 bool IsIndexSignExt; 4347 4348 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 4349 4350 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 4351 bool IsIndexSignExt) : 4352 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 4353 4354 bool equalBaseIndex(const BaseIndexOffset &Other) { 4355 return Other.Base == Base && Other.Index == Index && 4356 Other.IsIndexSignExt == IsIndexSignExt; 4357 } 4358 4359 /// Parses tree in Ptr for base, index, offset addresses. 4360 static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG, 4361 int64_t PartialOffset = 0) { 4362 bool IsIndexSignExt = false; 4363 4364 // Split up a folded GlobalAddress+Offset into its component parts. 4365 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr)) 4366 if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) { 4367 return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(), 4368 SDLoc(GA), 4369 GA->getValueType(0), 4370 /*Offset=*/PartialOffset, 4371 /*isTargetGA=*/false, 4372 GA->getTargetFlags()), 4373 SDValue(), 4374 GA->getOffset(), 4375 IsIndexSignExt); 4376 } 4377 4378 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 4379 // instruction, then it could be just the BASE or everything else we don't 4380 // know how to handle. Just use Ptr as BASE and give up. 4381 if (Ptr->getOpcode() != ISD::ADD) 4382 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt); 4383 4384 // We know that we have at least an ADD instruction. Try to pattern match 4385 // the simple case of BASE + OFFSET. 4386 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 4387 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 4388 return match(Ptr->getOperand(0), DAG, Offset + PartialOffset); 4389 } 4390 4391 // Inside a loop the current BASE pointer is calculated using an ADD and a 4392 // MUL instruction. In this case Ptr is the actual BASE pointer. 4393 // (i64 add (i64 %array_ptr) 4394 // (i64 mul (i64 %induction_var) 4395 // (i64 %element_size))) 4396 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 4397 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt); 4398 4399 // Look at Base + Index + Offset cases. 4400 SDValue Base = Ptr->getOperand(0); 4401 SDValue IndexOffset = Ptr->getOperand(1); 4402 4403 // Skip signextends. 4404 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 4405 IndexOffset = IndexOffset->getOperand(0); 4406 IsIndexSignExt = true; 4407 } 4408 4409 // Either the case of Base + Index (no offset) or something else. 4410 if (IndexOffset->getOpcode() != ISD::ADD) 4411 return BaseIndexOffset(Base, IndexOffset, PartialOffset, IsIndexSignExt); 4412 4413 // Now we have the case of Base + Index + offset. 4414 SDValue Index = IndexOffset->getOperand(0); 4415 SDValue Offset = IndexOffset->getOperand(1); 4416 4417 if (!isa<ConstantSDNode>(Offset)) 4418 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt); 4419 4420 // Ignore signextends. 4421 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 4422 Index = Index->getOperand(0); 4423 IsIndexSignExt = true; 4424 } else IsIndexSignExt = false; 4425 4426 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 4427 return BaseIndexOffset(Base, Index, Off + PartialOffset, IsIndexSignExt); 4428 } 4429 }; 4430 } // namespace 4431 4432 namespace { 4433 /// Represents known origin of an individual byte in load combine pattern. The 4434 /// value of the byte is either constant zero or comes from memory. 4435 struct ByteProvider { 4436 // For constant zero providers Load is set to nullptr. For memory providers 4437 // Load represents the node which loads the byte from memory. 4438 // ByteOffset is the offset of the byte in the value produced by the load. 4439 LoadSDNode *Load; 4440 unsigned ByteOffset; 4441 4442 ByteProvider() : Load(nullptr), ByteOffset(0) {} 4443 4444 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) { 4445 return ByteProvider(Load, ByteOffset); 4446 } 4447 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); } 4448 4449 bool isConstantZero() const { return !Load; } 4450 bool isMemory() const { return Load; } 4451 4452 bool operator==(const ByteProvider &Other) const { 4453 return Other.Load == Load && Other.ByteOffset == ByteOffset; 4454 } 4455 4456 private: 4457 ByteProvider(LoadSDNode *Load, unsigned ByteOffset) 4458 : Load(Load), ByteOffset(ByteOffset) {} 4459 }; 4460 4461 /// Recursively traverses the expression calculating the origin of the requested 4462 /// byte of the given value. Returns None if the provider can't be calculated. 4463 /// 4464 /// For all the values except the root of the expression verifies that the value 4465 /// has exactly one use and if it's not true return None. This way if the origin 4466 /// of the byte is returned it's guaranteed that the values which contribute to 4467 /// the byte are not used outside of this expression. 4468 /// 4469 /// Because the parts of the expression are not allowed to have more than one 4470 /// use this function iterates over trees, not DAGs. So it never visits the same 4471 /// node more than once. 4472 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index, 4473 unsigned Depth, 4474 bool Root = false) { 4475 // Typical i64 by i8 pattern requires recursion up to 8 calls depth 4476 if (Depth == 10) 4477 return None; 4478 4479 if (!Root && !Op.hasOneUse()) 4480 return None; 4481 4482 assert(Op.getValueType().isScalarInteger() && "can't handle other types"); 4483 unsigned BitWidth = Op.getValueSizeInBits(); 4484 if (BitWidth % 8 != 0) 4485 return None; 4486 unsigned ByteWidth = BitWidth / 8; 4487 assert(Index < ByteWidth && "invalid index requested"); 4488 (void) ByteWidth; 4489 4490 switch (Op.getOpcode()) { 4491 case ISD::OR: { 4492 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1); 4493 if (!LHS) 4494 return None; 4495 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1); 4496 if (!RHS) 4497 return None; 4498 4499 if (LHS->isConstantZero()) 4500 return RHS; 4501 else if (RHS->isConstantZero()) 4502 return LHS; 4503 else 4504 return None; 4505 } 4506 case ISD::SHL: { 4507 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 4508 if (!ShiftOp) 4509 return None; 4510 4511 uint64_t BitShift = ShiftOp->getZExtValue(); 4512 if (BitShift % 8 != 0) 4513 return None; 4514 uint64_t ByteShift = BitShift / 8; 4515 4516 return Index < ByteShift 4517 ? ByteProvider::getConstantZero() 4518 : calculateByteProvider(Op->getOperand(0), Index - ByteShift, 4519 Depth + 1); 4520 } 4521 case ISD::ANY_EXTEND: 4522 case ISD::SIGN_EXTEND: 4523 case ISD::ZERO_EXTEND: { 4524 SDValue NarrowOp = Op->getOperand(0); 4525 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits(); 4526 if (NarrowBitWidth % 8 != 0) 4527 return None; 4528 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 4529 4530 if (Index >= NarrowByteWidth) 4531 return Op.getOpcode() == ISD::ZERO_EXTEND 4532 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 4533 : None; 4534 else 4535 return calculateByteProvider(NarrowOp, Index, Depth + 1); 4536 } 4537 case ISD::BSWAP: 4538 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1, 4539 Depth + 1); 4540 case ISD::LOAD: { 4541 auto L = cast<LoadSDNode>(Op.getNode()); 4542 if (L->isVolatile() || L->isIndexed()) 4543 return None; 4544 4545 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits(); 4546 if (NarrowBitWidth % 8 != 0) 4547 return None; 4548 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 4549 4550 if (Index >= NarrowByteWidth) 4551 return L->getExtensionType() == ISD::ZEXTLOAD 4552 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 4553 : None; 4554 else 4555 return ByteProvider::getMemory(L, Index); 4556 } 4557 } 4558 4559 return None; 4560 } 4561 } // namespace 4562 4563 /// Match a pattern where a wide type scalar value is loaded by several narrow 4564 /// loads and combined by shifts and ors. Fold it into a single load or a load 4565 /// and a BSWAP if the targets supports it. 4566 /// 4567 /// Assuming little endian target: 4568 /// i8 *a = ... 4569 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24) 4570 /// => 4571 /// i32 val = *((i32)a) 4572 /// 4573 /// i8 *a = ... 4574 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3] 4575 /// => 4576 /// i32 val = BSWAP(*((i32)a)) 4577 /// 4578 /// TODO: This rule matches complex patterns with OR node roots and doesn't 4579 /// interact well with the worklist mechanism. When a part of the pattern is 4580 /// updated (e.g. one of the loads) its direct users are put into the worklist, 4581 /// but the root node of the pattern which triggers the load combine is not 4582 /// necessarily a direct user of the changed node. For example, once the address 4583 /// of t28 load is reassociated load combine won't be triggered: 4584 /// t25: i32 = add t4, Constant:i32<2> 4585 /// t26: i64 = sign_extend t25 4586 /// t27: i64 = add t2, t26 4587 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64 4588 /// t29: i32 = zero_extend t28 4589 /// t32: i32 = shl t29, Constant:i8<8> 4590 /// t33: i32 = or t23, t32 4591 /// As a possible fix visitLoad can check if the load can be a part of a load 4592 /// combine pattern and add corresponding OR roots to the worklist. 4593 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) { 4594 assert(N->getOpcode() == ISD::OR && 4595 "Can only match load combining against OR nodes"); 4596 4597 // Handles simple types only 4598 EVT VT = N->getValueType(0); 4599 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 4600 return SDValue(); 4601 unsigned ByteWidth = VT.getSizeInBits() / 8; 4602 4603 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4604 // Before legalize we can introduce too wide illegal loads which will be later 4605 // split into legal sized loads. This enables us to combine i64 load by i8 4606 // patterns to a couple of i32 loads on 32 bit targets. 4607 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT)) 4608 return SDValue(); 4609 4610 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = []( 4611 unsigned BW, unsigned i) { return i; }; 4612 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = []( 4613 unsigned BW, unsigned i) { return BW - i - 1; }; 4614 4615 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian(); 4616 auto MemoryByteOffset = [&] (ByteProvider P) { 4617 assert(P.isMemory() && "Must be a memory byte provider"); 4618 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits(); 4619 assert(LoadBitWidth % 8 == 0 && 4620 "can only analyze providers for individual bytes not bit"); 4621 unsigned LoadByteWidth = LoadBitWidth / 8; 4622 return IsBigEndianTarget 4623 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset) 4624 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset); 4625 }; 4626 4627 Optional<BaseIndexOffset> Base; 4628 SDValue Chain; 4629 4630 SmallSet<LoadSDNode *, 8> Loads; 4631 Optional<ByteProvider> FirstByteProvider; 4632 int64_t FirstOffset = INT64_MAX; 4633 4634 // Check if all the bytes of the OR we are looking at are loaded from the same 4635 // base address. Collect bytes offsets from Base address in ByteOffsets. 4636 SmallVector<int64_t, 4> ByteOffsets(ByteWidth); 4637 for (unsigned i = 0; i < ByteWidth; i++) { 4638 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true); 4639 if (!P || !P->isMemory()) // All the bytes must be loaded from memory 4640 return SDValue(); 4641 4642 LoadSDNode *L = P->Load; 4643 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() && 4644 "Must be enforced by calculateByteProvider"); 4645 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset"); 4646 4647 // All loads must share the same chain 4648 SDValue LChain = L->getChain(); 4649 if (!Chain) 4650 Chain = LChain; 4651 else if (Chain != LChain) 4652 return SDValue(); 4653 4654 // Loads must share the same base address 4655 BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG); 4656 if (!Base) 4657 Base = Ptr; 4658 else if (!Base->equalBaseIndex(Ptr)) 4659 return SDValue(); 4660 4661 // Calculate the offset of the current byte from the base address 4662 int64_t ByteOffsetFromBase = Ptr.Offset + MemoryByteOffset(*P); 4663 ByteOffsets[i] = ByteOffsetFromBase; 4664 4665 // Remember the first byte load 4666 if (ByteOffsetFromBase < FirstOffset) { 4667 FirstByteProvider = P; 4668 FirstOffset = ByteOffsetFromBase; 4669 } 4670 4671 Loads.insert(L); 4672 } 4673 assert(Loads.size() > 0 && "All the bytes of the value must be loaded from " 4674 "memory, so there must be at least one load which produces the value"); 4675 assert(Base && "Base address of the accessed memory location must be set"); 4676 assert(FirstOffset != INT64_MAX && "First byte offset must be set"); 4677 4678 // Check if the bytes of the OR we are looking at match with either big or 4679 // little endian value load 4680 bool BigEndian = true, LittleEndian = true; 4681 for (unsigned i = 0; i < ByteWidth; i++) { 4682 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset; 4683 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i); 4684 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i); 4685 if (!BigEndian && !LittleEndian) 4686 return SDValue(); 4687 } 4688 assert((BigEndian != LittleEndian) && "should be either or"); 4689 assert(FirstByteProvider && "must be set"); 4690 4691 // Ensure that the first byte is loaded from zero offset of the first load. 4692 // So the combined value can be loaded from the first load address. 4693 if (MemoryByteOffset(*FirstByteProvider) != 0) 4694 return SDValue(); 4695 LoadSDNode *FirstLoad = FirstByteProvider->Load; 4696 4697 // The node we are looking at matches with the pattern, check if we can 4698 // replace it with a single load and bswap if needed. 4699 4700 // If the load needs byte swap check if the target supports it 4701 bool NeedsBswap = IsBigEndianTarget != BigEndian; 4702 4703 // Before legalize we can introduce illegal bswaps which will be later 4704 // converted to an explicit bswap sequence. This way we end up with a single 4705 // load and byte shuffling instead of several loads and byte shuffling. 4706 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT)) 4707 return SDValue(); 4708 4709 // Check that a load of the wide type is both allowed and fast on the target 4710 bool Fast = false; 4711 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), 4712 VT, FirstLoad->getAddressSpace(), 4713 FirstLoad->getAlignment(), &Fast); 4714 if (!Allowed || !Fast) 4715 return SDValue(); 4716 4717 SDValue NewLoad = 4718 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(), 4719 FirstLoad->getPointerInfo(), FirstLoad->getAlignment()); 4720 4721 // Transfer chain users from old loads to the new load. 4722 for (LoadSDNode *L : Loads) 4723 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1)); 4724 4725 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad; 4726 } 4727 4728 SDValue DAGCombiner::visitXOR(SDNode *N) { 4729 SDValue N0 = N->getOperand(0); 4730 SDValue N1 = N->getOperand(1); 4731 EVT VT = N0.getValueType(); 4732 4733 // fold vector ops 4734 if (VT.isVector()) { 4735 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4736 return FoldedVOp; 4737 4738 // fold (xor x, 0) -> x, vector edition 4739 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4740 return N1; 4741 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4742 return N0; 4743 } 4744 4745 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 4746 if (N0.isUndef() && N1.isUndef()) 4747 return DAG.getConstant(0, SDLoc(N), VT); 4748 // fold (xor x, undef) -> undef 4749 if (N0.isUndef()) 4750 return N0; 4751 if (N1.isUndef()) 4752 return N1; 4753 // fold (xor c1, c2) -> c1^c2 4754 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4755 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 4756 if (N0C && N1C) 4757 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 4758 // canonicalize constant to RHS 4759 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4760 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4761 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 4762 // fold (xor x, 0) -> x 4763 if (isNullConstant(N1)) 4764 return N0; 4765 4766 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4767 return NewSel; 4768 4769 // reassociate xor 4770 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 4771 return RXOR; 4772 4773 // fold !(x cc y) -> (x !cc y) 4774 SDValue LHS, RHS, CC; 4775 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 4776 bool isInt = LHS.getValueType().isInteger(); 4777 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 4778 isInt); 4779 4780 if (!LegalOperations || 4781 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 4782 switch (N0.getOpcode()) { 4783 default: 4784 llvm_unreachable("Unhandled SetCC Equivalent!"); 4785 case ISD::SETCC: 4786 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC); 4787 case ISD::SELECT_CC: 4788 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2), 4789 N0.getOperand(3), NotCC); 4790 } 4791 } 4792 } 4793 4794 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 4795 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 4796 N0.getNode()->hasOneUse() && 4797 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 4798 SDValue V = N0.getOperand(0); 4799 SDLoc DL(N0); 4800 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 4801 DAG.getConstant(1, DL, V.getValueType())); 4802 AddToWorklist(V.getNode()); 4803 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 4804 } 4805 4806 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 4807 if (isOneConstant(N1) && VT == MVT::i1 && 4808 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4809 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4810 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 4811 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4812 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4813 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4814 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4815 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4816 } 4817 } 4818 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 4819 if (isAllOnesConstant(N1) && 4820 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4821 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4822 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 4823 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4824 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4825 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4826 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4827 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4828 } 4829 } 4830 // fold (xor (and x, y), y) -> (and (not x), y) 4831 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4832 N0->getOperand(1) == N1) { 4833 SDValue X = N0->getOperand(0); 4834 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 4835 AddToWorklist(NotX.getNode()); 4836 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 4837 } 4838 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 4839 if (N1C && N0.getOpcode() == ISD::XOR) { 4840 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 4841 SDLoc DL(N); 4842 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 4843 DAG.getConstant(N1C->getAPIntValue() ^ 4844 N00C->getAPIntValue(), DL, VT)); 4845 } 4846 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 4847 SDLoc DL(N); 4848 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 4849 DAG.getConstant(N1C->getAPIntValue() ^ 4850 N01C->getAPIntValue(), DL, VT)); 4851 } 4852 } 4853 // fold (xor x, x) -> 0 4854 if (N0 == N1) 4855 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 4856 4857 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 4858 // Here is a concrete example of this equivalence: 4859 // i16 x == 14 4860 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 4861 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 4862 // 4863 // => 4864 // 4865 // i16 ~1 == 0b1111111111111110 4866 // i16 rol(~1, 14) == 0b1011111111111111 4867 // 4868 // Some additional tips to help conceptualize this transform: 4869 // - Try to see the operation as placing a single zero in a value of all ones. 4870 // - There exists no value for x which would allow the result to contain zero. 4871 // - Values of x larger than the bitwidth are undefined and do not require a 4872 // consistent result. 4873 // - Pushing the zero left requires shifting one bits in from the right. 4874 // A rotate left of ~1 is a nice way of achieving the desired result. 4875 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 4876 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 4877 SDLoc DL(N); 4878 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 4879 N0.getOperand(1)); 4880 } 4881 4882 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4883 if (N0.getOpcode() == N1.getOpcode()) 4884 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4885 return Tmp; 4886 4887 // Simplify the expression using non-local knowledge. 4888 if (!VT.isVector() && 4889 SimplifyDemandedBits(SDValue(N, 0))) 4890 return SDValue(N, 0); 4891 4892 return SDValue(); 4893 } 4894 4895 /// Handle transforms common to the three shifts, when the shift amount is a 4896 /// constant. 4897 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4898 SDNode *LHS = N->getOperand(0).getNode(); 4899 if (!LHS->hasOneUse()) return SDValue(); 4900 4901 // We want to pull some binops through shifts, so that we have (and (shift)) 4902 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4903 // thing happens with address calculations, so it's important to canonicalize 4904 // it. 4905 bool HighBitSet = false; // Can we transform this if the high bit is set? 4906 4907 switch (LHS->getOpcode()) { 4908 default: return SDValue(); 4909 case ISD::OR: 4910 case ISD::XOR: 4911 HighBitSet = false; // We can only transform sra if the high bit is clear. 4912 break; 4913 case ISD::AND: 4914 HighBitSet = true; // We can only transform sra if the high bit is set. 4915 break; 4916 case ISD::ADD: 4917 if (N->getOpcode() != ISD::SHL) 4918 return SDValue(); // only shl(add) not sr[al](add). 4919 HighBitSet = false; // We can only transform sra if the high bit is clear. 4920 break; 4921 } 4922 4923 // We require the RHS of the binop to be a constant and not opaque as well. 4924 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 4925 if (!BinOpCst) return SDValue(); 4926 4927 // FIXME: disable this unless the input to the binop is a shift by a constant 4928 // or is copy/select.Enable this in other cases when figure out it's exactly profitable. 4929 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4930 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL || 4931 BinOpLHSVal->getOpcode() == ISD::SRA || 4932 BinOpLHSVal->getOpcode() == ISD::SRL; 4933 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg || 4934 BinOpLHSVal->getOpcode() == ISD::SELECT; 4935 4936 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) && 4937 !isCopyOrSelect) 4938 return SDValue(); 4939 4940 if (isCopyOrSelect && N->hasOneUse()) 4941 return SDValue(); 4942 4943 EVT VT = N->getValueType(0); 4944 4945 // If this is a signed shift right, and the high bit is modified by the 4946 // logical operation, do not perform the transformation. The highBitSet 4947 // boolean indicates the value of the high bit of the constant which would 4948 // cause it to be modified for this operation. 4949 if (N->getOpcode() == ISD::SRA) { 4950 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4951 if (BinOpRHSSignSet != HighBitSet) 4952 return SDValue(); 4953 } 4954 4955 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4956 return SDValue(); 4957 4958 // Fold the constants, shifting the binop RHS by the shift amount. 4959 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4960 N->getValueType(0), 4961 LHS->getOperand(1), N->getOperand(1)); 4962 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4963 4964 // Create the new shift. 4965 SDValue NewShift = DAG.getNode(N->getOpcode(), 4966 SDLoc(LHS->getOperand(0)), 4967 VT, LHS->getOperand(0), N->getOperand(1)); 4968 4969 // Create the new binop. 4970 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4971 } 4972 4973 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4974 assert(N->getOpcode() == ISD::TRUNCATE); 4975 assert(N->getOperand(0).getOpcode() == ISD::AND); 4976 4977 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4978 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4979 SDValue N01 = N->getOperand(0).getOperand(1); 4980 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) { 4981 SDLoc DL(N); 4982 EVT TruncVT = N->getValueType(0); 4983 SDValue N00 = N->getOperand(0).getOperand(0); 4984 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00); 4985 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01); 4986 AddToWorklist(Trunc00.getNode()); 4987 AddToWorklist(Trunc01.getNode()); 4988 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01); 4989 } 4990 } 4991 4992 return SDValue(); 4993 } 4994 4995 SDValue DAGCombiner::visitRotate(SDNode *N) { 4996 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4997 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4998 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4999 if (SDValue NewOp1 = 5000 distributeTruncateThroughAnd(N->getOperand(1).getNode())) 5001 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 5002 N->getOperand(0), NewOp1); 5003 } 5004 return SDValue(); 5005 } 5006 5007 SDValue DAGCombiner::visitSHL(SDNode *N) { 5008 SDValue N0 = N->getOperand(0); 5009 SDValue N1 = N->getOperand(1); 5010 EVT VT = N0.getValueType(); 5011 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5012 5013 // fold vector ops 5014 if (VT.isVector()) { 5015 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5016 return FoldedVOp; 5017 5018 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 5019 // If setcc produces all-one true value then: 5020 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 5021 if (N1CV && N1CV->isConstant()) { 5022 if (N0.getOpcode() == ISD::AND) { 5023 SDValue N00 = N0->getOperand(0); 5024 SDValue N01 = N0->getOperand(1); 5025 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 5026 5027 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 5028 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 5029 TargetLowering::ZeroOrNegativeOneBooleanContent) { 5030 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 5031 N01CV, N1CV)) 5032 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 5033 } 5034 } 5035 } 5036 } 5037 5038 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5039 5040 // fold (shl c1, c2) -> c1<<c2 5041 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5042 if (N0C && N1C && !N1C->isOpaque()) 5043 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 5044 // fold (shl 0, x) -> 0 5045 if (isNullConstant(N0)) 5046 return N0; 5047 // fold (shl x, c >= size(x)) -> undef 5048 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 5049 return DAG.getUNDEF(VT); 5050 // fold (shl x, 0) -> x 5051 if (N1C && N1C->isNullValue()) 5052 return N0; 5053 // fold (shl undef, x) -> 0 5054 if (N0.isUndef()) 5055 return DAG.getConstant(0, SDLoc(N), VT); 5056 5057 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5058 return NewSel; 5059 5060 // if (shl x, c) is known to be zero, return 0 5061 if (DAG.MaskedValueIsZero(SDValue(N, 0), 5062 APInt::getAllOnesValue(OpSizeInBits))) 5063 return DAG.getConstant(0, SDLoc(N), VT); 5064 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 5065 if (N1.getOpcode() == ISD::TRUNCATE && 5066 N1.getOperand(0).getOpcode() == ISD::AND) { 5067 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5068 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 5069 } 5070 5071 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5072 return SDValue(N, 0); 5073 5074 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 5075 if (N1C && N0.getOpcode() == ISD::SHL) { 5076 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5077 SDLoc DL(N); 5078 APInt c1 = N0C1->getAPIntValue(); 5079 APInt c2 = N1C->getAPIntValue(); 5080 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5081 5082 APInt Sum = c1 + c2; 5083 if (Sum.uge(OpSizeInBits)) 5084 return DAG.getConstant(0, DL, VT); 5085 5086 return DAG.getNode( 5087 ISD::SHL, DL, VT, N0.getOperand(0), 5088 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5089 } 5090 } 5091 5092 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 5093 // For this to be valid, the second form must not preserve any of the bits 5094 // that are shifted out by the inner shift in the first form. This means 5095 // the outer shift size must be >= the number of bits added by the ext. 5096 // As a corollary, we don't care what kind of ext it is. 5097 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 5098 N0.getOpcode() == ISD::ANY_EXTEND || 5099 N0.getOpcode() == ISD::SIGN_EXTEND) && 5100 N0.getOperand(0).getOpcode() == ISD::SHL) { 5101 SDValue N0Op0 = N0.getOperand(0); 5102 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5103 APInt c1 = N0Op0C1->getAPIntValue(); 5104 APInt c2 = N1C->getAPIntValue(); 5105 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5106 5107 EVT InnerShiftVT = N0Op0.getValueType(); 5108 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 5109 if (c2.uge(OpSizeInBits - InnerShiftSize)) { 5110 SDLoc DL(N0); 5111 APInt Sum = c1 + c2; 5112 if (Sum.uge(OpSizeInBits)) 5113 return DAG.getConstant(0, DL, VT); 5114 5115 return DAG.getNode( 5116 ISD::SHL, DL, VT, 5117 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)), 5118 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5119 } 5120 } 5121 } 5122 5123 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 5124 // Only fold this if the inner zext has no other uses to avoid increasing 5125 // the total number of instructions. 5126 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 5127 N0.getOperand(0).getOpcode() == ISD::SRL) { 5128 SDValue N0Op0 = N0.getOperand(0); 5129 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5130 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) { 5131 uint64_t c1 = N0Op0C1->getZExtValue(); 5132 uint64_t c2 = N1C->getZExtValue(); 5133 if (c1 == c2) { 5134 SDValue NewOp0 = N0.getOperand(0); 5135 EVT CountVT = NewOp0.getOperand(1).getValueType(); 5136 SDLoc DL(N); 5137 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 5138 NewOp0, 5139 DAG.getConstant(c2, DL, CountVT)); 5140 AddToWorklist(NewSHL.getNode()); 5141 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 5142 } 5143 } 5144 } 5145 } 5146 5147 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 5148 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 5149 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 5150 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) { 5151 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5152 uint64_t C1 = N0C1->getZExtValue(); 5153 uint64_t C2 = N1C->getZExtValue(); 5154 SDLoc DL(N); 5155 if (C1 <= C2) 5156 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5157 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 5158 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 5159 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 5160 } 5161 } 5162 5163 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 5164 // (and (srl x, (sub c1, c2), MASK) 5165 // Only fold this if the inner shift has no other uses -- if it does, folding 5166 // this will increase the total number of instructions. 5167 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5168 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5169 uint64_t c1 = N0C1->getZExtValue(); 5170 if (c1 < OpSizeInBits) { 5171 uint64_t c2 = N1C->getZExtValue(); 5172 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 5173 SDValue Shift; 5174 if (c2 > c1) { 5175 Mask = Mask.shl(c2 - c1); 5176 SDLoc DL(N); 5177 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5178 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 5179 } else { 5180 Mask = Mask.lshr(c1 - c2); 5181 SDLoc DL(N); 5182 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 5183 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 5184 } 5185 SDLoc DL(N0); 5186 return DAG.getNode(ISD::AND, DL, VT, Shift, 5187 DAG.getConstant(Mask, DL, VT)); 5188 } 5189 } 5190 } 5191 5192 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 5193 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) && 5194 isConstantOrConstantVector(N1, /* No Opaques */ true)) { 5195 SDLoc DL(N); 5196 SDValue AllBits = DAG.getAllOnesConstant(DL, VT); 5197 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1); 5198 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask); 5199 } 5200 5201 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 5202 // Variant of version done on multiply, except mul by a power of 2 is turned 5203 // into a shift. 5204 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 5205 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5206 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5207 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 5208 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5209 AddToWorklist(Shl0.getNode()); 5210 AddToWorklist(Shl1.getNode()); 5211 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 5212 } 5213 5214 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 5215 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() && 5216 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5217 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5218 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5219 if (isConstantOrConstantVector(Shl)) 5220 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl); 5221 } 5222 5223 if (N1C && !N1C->isOpaque()) 5224 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 5225 return NewSHL; 5226 5227 return SDValue(); 5228 } 5229 5230 SDValue DAGCombiner::visitSRA(SDNode *N) { 5231 SDValue N0 = N->getOperand(0); 5232 SDValue N1 = N->getOperand(1); 5233 EVT VT = N0.getValueType(); 5234 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5235 5236 // Arithmetic shifting an all-sign-bit value is a no-op. 5237 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits) 5238 return N0; 5239 5240 // fold vector ops 5241 if (VT.isVector()) 5242 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5243 return FoldedVOp; 5244 5245 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5246 5247 // fold (sra c1, c2) -> (sra c1, c2) 5248 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5249 if (N0C && N1C && !N1C->isOpaque()) 5250 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 5251 // fold (sra 0, x) -> 0 5252 if (isNullConstant(N0)) 5253 return N0; 5254 // fold (sra -1, x) -> -1 5255 if (isAllOnesConstant(N0)) 5256 return N0; 5257 // fold (sra x, c >= size(x)) -> undef 5258 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 5259 return DAG.getUNDEF(VT); 5260 // fold (sra x, 0) -> x 5261 if (N1C && N1C->isNullValue()) 5262 return N0; 5263 5264 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5265 return NewSel; 5266 5267 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 5268 // sext_inreg. 5269 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 5270 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 5271 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 5272 if (VT.isVector()) 5273 ExtVT = EVT::getVectorVT(*DAG.getContext(), 5274 ExtVT, VT.getVectorNumElements()); 5275 if ((!LegalOperations || 5276 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 5277 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5278 N0.getOperand(0), DAG.getValueType(ExtVT)); 5279 } 5280 5281 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 5282 if (N1C && N0.getOpcode() == ISD::SRA) { 5283 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5284 SDLoc DL(N); 5285 APInt c1 = N0C1->getAPIntValue(); 5286 APInt c2 = N1C->getAPIntValue(); 5287 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5288 5289 APInt Sum = c1 + c2; 5290 if (Sum.uge(OpSizeInBits)) 5291 Sum = APInt(OpSizeInBits, OpSizeInBits - 1); 5292 5293 return DAG.getNode( 5294 ISD::SRA, DL, VT, N0.getOperand(0), 5295 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5296 } 5297 } 5298 5299 // fold (sra (shl X, m), (sub result_size, n)) 5300 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 5301 // result_size - n != m. 5302 // If truncate is free for the target sext(shl) is likely to result in better 5303 // code. 5304 if (N0.getOpcode() == ISD::SHL && N1C) { 5305 // Get the two constanst of the shifts, CN0 = m, CN = n. 5306 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 5307 if (N01C) { 5308 LLVMContext &Ctx = *DAG.getContext(); 5309 // Determine what the truncate's result bitsize and type would be. 5310 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 5311 5312 if (VT.isVector()) 5313 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 5314 5315 // Determine the residual right-shift amount. 5316 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 5317 5318 // If the shift is not a no-op (in which case this should be just a sign 5319 // extend already), the truncated to type is legal, sign_extend is legal 5320 // on that type, and the truncate to that type is both legal and free, 5321 // perform the transform. 5322 if ((ShiftAmt > 0) && 5323 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 5324 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 5325 TLI.isTruncateFree(VT, TruncVT)) { 5326 5327 SDLoc DL(N); 5328 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 5329 getShiftAmountTy(N0.getOperand(0).getValueType())); 5330 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 5331 N0.getOperand(0), Amt); 5332 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 5333 Shift); 5334 return DAG.getNode(ISD::SIGN_EXTEND, DL, 5335 N->getValueType(0), Trunc); 5336 } 5337 } 5338 } 5339 5340 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 5341 if (N1.getOpcode() == ISD::TRUNCATE && 5342 N1.getOperand(0).getOpcode() == ISD::AND) { 5343 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5344 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 5345 } 5346 5347 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 5348 // if c1 is equal to the number of bits the trunc removes 5349 if (N0.getOpcode() == ISD::TRUNCATE && 5350 (N0.getOperand(0).getOpcode() == ISD::SRL || 5351 N0.getOperand(0).getOpcode() == ISD::SRA) && 5352 N0.getOperand(0).hasOneUse() && 5353 N0.getOperand(0).getOperand(1).hasOneUse() && 5354 N1C) { 5355 SDValue N0Op0 = N0.getOperand(0); 5356 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 5357 unsigned LargeShiftVal = LargeShift->getZExtValue(); 5358 EVT LargeVT = N0Op0.getValueType(); 5359 5360 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 5361 SDLoc DL(N); 5362 SDValue Amt = 5363 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 5364 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 5365 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 5366 N0Op0.getOperand(0), Amt); 5367 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 5368 } 5369 } 5370 } 5371 5372 // Simplify, based on bits shifted out of the LHS. 5373 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5374 return SDValue(N, 0); 5375 5376 5377 // If the sign bit is known to be zero, switch this to a SRL. 5378 if (DAG.SignBitIsZero(N0)) 5379 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 5380 5381 if (N1C && !N1C->isOpaque()) 5382 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 5383 return NewSRA; 5384 5385 return SDValue(); 5386 } 5387 5388 SDValue DAGCombiner::visitSRL(SDNode *N) { 5389 SDValue N0 = N->getOperand(0); 5390 SDValue N1 = N->getOperand(1); 5391 EVT VT = N0.getValueType(); 5392 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5393 5394 // fold vector ops 5395 if (VT.isVector()) 5396 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5397 return FoldedVOp; 5398 5399 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5400 5401 // fold (srl c1, c2) -> c1 >>u c2 5402 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5403 if (N0C && N1C && !N1C->isOpaque()) 5404 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 5405 // fold (srl 0, x) -> 0 5406 if (isNullConstant(N0)) 5407 return N0; 5408 // fold (srl x, c >= size(x)) -> undef 5409 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 5410 return DAG.getUNDEF(VT); 5411 // fold (srl x, 0) -> x 5412 if (N1C && N1C->isNullValue()) 5413 return N0; 5414 5415 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5416 return NewSel; 5417 5418 // if (srl x, c) is known to be zero, return 0 5419 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 5420 APInt::getAllOnesValue(OpSizeInBits))) 5421 return DAG.getConstant(0, SDLoc(N), VT); 5422 5423 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 5424 if (N1C && N0.getOpcode() == ISD::SRL) { 5425 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5426 SDLoc DL(N); 5427 APInt c1 = N0C1->getAPIntValue(); 5428 APInt c2 = N1C->getAPIntValue(); 5429 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5430 5431 APInt Sum = c1 + c2; 5432 if (Sum.uge(OpSizeInBits)) 5433 return DAG.getConstant(0, DL, VT); 5434 5435 return DAG.getNode( 5436 ISD::SRL, DL, VT, N0.getOperand(0), 5437 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5438 } 5439 } 5440 5441 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 5442 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 5443 N0.getOperand(0).getOpcode() == ISD::SRL && 5444 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 5445 uint64_t c1 = 5446 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 5447 uint64_t c2 = N1C->getZExtValue(); 5448 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 5449 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 5450 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 5451 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 5452 if (c1 + OpSizeInBits == InnerShiftSize) { 5453 SDLoc DL(N0); 5454 if (c1 + c2 >= InnerShiftSize) 5455 return DAG.getConstant(0, DL, VT); 5456 return DAG.getNode(ISD::TRUNCATE, DL, VT, 5457 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 5458 N0.getOperand(0)->getOperand(0), 5459 DAG.getConstant(c1 + c2, DL, 5460 ShiftCountVT))); 5461 } 5462 } 5463 5464 // fold (srl (shl x, c), c) -> (and x, cst2) 5465 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 5466 isConstantOrConstantVector(N1, /* NoOpaques */ true)) { 5467 SDLoc DL(N); 5468 SDValue Mask = 5469 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1); 5470 AddToWorklist(Mask.getNode()); 5471 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask); 5472 } 5473 5474 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 5475 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 5476 // Shifting in all undef bits? 5477 EVT SmallVT = N0.getOperand(0).getValueType(); 5478 unsigned BitSize = SmallVT.getScalarSizeInBits(); 5479 if (N1C->getZExtValue() >= BitSize) 5480 return DAG.getUNDEF(VT); 5481 5482 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 5483 uint64_t ShiftAmt = N1C->getZExtValue(); 5484 SDLoc DL0(N0); 5485 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 5486 N0.getOperand(0), 5487 DAG.getConstant(ShiftAmt, DL0, 5488 getShiftAmountTy(SmallVT))); 5489 AddToWorklist(SmallShift.getNode()); 5490 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 5491 SDLoc DL(N); 5492 return DAG.getNode(ISD::AND, DL, VT, 5493 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 5494 DAG.getConstant(Mask, DL, VT)); 5495 } 5496 } 5497 5498 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 5499 // bit, which is unmodified by sra. 5500 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 5501 if (N0.getOpcode() == ISD::SRA) 5502 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 5503 } 5504 5505 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 5506 if (N1C && N0.getOpcode() == ISD::CTLZ && 5507 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 5508 APInt KnownZero, KnownOne; 5509 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 5510 5511 // If any of the input bits are KnownOne, then the input couldn't be all 5512 // zeros, thus the result of the srl will always be zero. 5513 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 5514 5515 // If all of the bits input the to ctlz node are known to be zero, then 5516 // the result of the ctlz is "32" and the result of the shift is one. 5517 APInt UnknownBits = ~KnownZero; 5518 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 5519 5520 // Otherwise, check to see if there is exactly one bit input to the ctlz. 5521 if ((UnknownBits & (UnknownBits - 1)) == 0) { 5522 // Okay, we know that only that the single bit specified by UnknownBits 5523 // could be set on input to the CTLZ node. If this bit is set, the SRL 5524 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 5525 // to an SRL/XOR pair, which is likely to simplify more. 5526 unsigned ShAmt = UnknownBits.countTrailingZeros(); 5527 SDValue Op = N0.getOperand(0); 5528 5529 if (ShAmt) { 5530 SDLoc DL(N0); 5531 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 5532 DAG.getConstant(ShAmt, DL, 5533 getShiftAmountTy(Op.getValueType()))); 5534 AddToWorklist(Op.getNode()); 5535 } 5536 5537 SDLoc DL(N); 5538 return DAG.getNode(ISD::XOR, DL, VT, 5539 Op, DAG.getConstant(1, DL, VT)); 5540 } 5541 } 5542 5543 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 5544 if (N1.getOpcode() == ISD::TRUNCATE && 5545 N1.getOperand(0).getOpcode() == ISD::AND) { 5546 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5547 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 5548 } 5549 5550 // fold operands of srl based on knowledge that the low bits are not 5551 // demanded. 5552 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5553 return SDValue(N, 0); 5554 5555 if (N1C && !N1C->isOpaque()) 5556 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 5557 return NewSRL; 5558 5559 // Attempt to convert a srl of a load into a narrower zero-extending load. 5560 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 5561 return NarrowLoad; 5562 5563 // Here is a common situation. We want to optimize: 5564 // 5565 // %a = ... 5566 // %b = and i32 %a, 2 5567 // %c = srl i32 %b, 1 5568 // brcond i32 %c ... 5569 // 5570 // into 5571 // 5572 // %a = ... 5573 // %b = and %a, 2 5574 // %c = setcc eq %b, 0 5575 // brcond %c ... 5576 // 5577 // However when after the source operand of SRL is optimized into AND, the SRL 5578 // itself may not be optimized further. Look for it and add the BRCOND into 5579 // the worklist. 5580 if (N->hasOneUse()) { 5581 SDNode *Use = *N->use_begin(); 5582 if (Use->getOpcode() == ISD::BRCOND) 5583 AddToWorklist(Use); 5584 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 5585 // Also look pass the truncate. 5586 Use = *Use->use_begin(); 5587 if (Use->getOpcode() == ISD::BRCOND) 5588 AddToWorklist(Use); 5589 } 5590 } 5591 5592 return SDValue(); 5593 } 5594 5595 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 5596 SDValue N0 = N->getOperand(0); 5597 EVT VT = N->getValueType(0); 5598 5599 // fold (bswap c1) -> c2 5600 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5601 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 5602 // fold (bswap (bswap x)) -> x 5603 if (N0.getOpcode() == ISD::BSWAP) 5604 return N0->getOperand(0); 5605 return SDValue(); 5606 } 5607 5608 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 5609 SDValue N0 = N->getOperand(0); 5610 EVT VT = N->getValueType(0); 5611 5612 // fold (bitreverse c1) -> c2 5613 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5614 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0); 5615 // fold (bitreverse (bitreverse x)) -> x 5616 if (N0.getOpcode() == ISD::BITREVERSE) 5617 return N0.getOperand(0); 5618 return SDValue(); 5619 } 5620 5621 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 5622 SDValue N0 = N->getOperand(0); 5623 EVT VT = N->getValueType(0); 5624 5625 // fold (ctlz c1) -> c2 5626 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5627 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 5628 return SDValue(); 5629 } 5630 5631 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 5632 SDValue N0 = N->getOperand(0); 5633 EVT VT = N->getValueType(0); 5634 5635 // fold (ctlz_zero_undef c1) -> c2 5636 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5637 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5638 return SDValue(); 5639 } 5640 5641 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 5642 SDValue N0 = N->getOperand(0); 5643 EVT VT = N->getValueType(0); 5644 5645 // fold (cttz c1) -> c2 5646 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5647 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 5648 return SDValue(); 5649 } 5650 5651 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 5652 SDValue N0 = N->getOperand(0); 5653 EVT VT = N->getValueType(0); 5654 5655 // fold (cttz_zero_undef c1) -> c2 5656 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5657 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5658 return SDValue(); 5659 } 5660 5661 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 5662 SDValue N0 = N->getOperand(0); 5663 EVT VT = N->getValueType(0); 5664 5665 // fold (ctpop c1) -> c2 5666 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5667 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 5668 return SDValue(); 5669 } 5670 5671 5672 /// \brief Generate Min/Max node 5673 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 5674 SDValue RHS, SDValue True, SDValue False, 5675 ISD::CondCode CC, const TargetLowering &TLI, 5676 SelectionDAG &DAG) { 5677 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 5678 return SDValue(); 5679 5680 switch (CC) { 5681 case ISD::SETOLT: 5682 case ISD::SETOLE: 5683 case ISD::SETLT: 5684 case ISD::SETLE: 5685 case ISD::SETULT: 5686 case ISD::SETULE: { 5687 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 5688 if (TLI.isOperationLegal(Opcode, VT)) 5689 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5690 return SDValue(); 5691 } 5692 case ISD::SETOGT: 5693 case ISD::SETOGE: 5694 case ISD::SETGT: 5695 case ISD::SETGE: 5696 case ISD::SETUGT: 5697 case ISD::SETUGE: { 5698 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 5699 if (TLI.isOperationLegal(Opcode, VT)) 5700 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5701 return SDValue(); 5702 } 5703 default: 5704 return SDValue(); 5705 } 5706 } 5707 5708 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) { 5709 SDValue Cond = N->getOperand(0); 5710 SDValue N1 = N->getOperand(1); 5711 SDValue N2 = N->getOperand(2); 5712 EVT VT = N->getValueType(0); 5713 EVT CondVT = Cond.getValueType(); 5714 SDLoc DL(N); 5715 5716 if (!VT.isInteger()) 5717 return SDValue(); 5718 5719 auto *C1 = dyn_cast<ConstantSDNode>(N1); 5720 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5721 if (!C1 || !C2) 5722 return SDValue(); 5723 5724 // Only do this before legalization to avoid conflicting with target-specific 5725 // transforms in the other direction (create a select from a zext/sext). There 5726 // is also a target-independent combine here in DAGCombiner in the other 5727 // direction for (select Cond, -1, 0) when the condition is not i1. 5728 // TODO: This could be generalized for any 2 constants that differ by 1: 5729 // add ({s/z}ext Cond), C 5730 if (CondVT == MVT::i1 && !LegalOperations) { 5731 if (C1->isNullValue() && C2->isOne()) { 5732 // select Cond, 0, 1 --> zext (!Cond) 5733 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 5734 if (VT != MVT::i1) 5735 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond); 5736 return NotCond; 5737 } 5738 if (C1->isNullValue() && C2->isAllOnesValue()) { 5739 // select Cond, 0, -1 --> sext (!Cond) 5740 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 5741 if (VT != MVT::i1) 5742 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond); 5743 return NotCond; 5744 } 5745 if (C1->isOne() && C2->isNullValue()) { 5746 // select Cond, 1, 0 --> zext (Cond) 5747 if (VT != MVT::i1) 5748 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 5749 return Cond; 5750 } 5751 if (C1->isAllOnesValue() && C2->isNullValue()) { 5752 // select Cond, -1, 0 --> sext (Cond) 5753 if (VT != MVT::i1) 5754 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 5755 return Cond; 5756 } 5757 return SDValue(); 5758 } 5759 5760 // fold (select Cond, 0, 1) -> (xor Cond, 1) 5761 // We can't do this reliably if integer based booleans have different contents 5762 // to floating point based booleans. This is because we can't tell whether we 5763 // have an integer-based boolean or a floating-point-based boolean unless we 5764 // can find the SETCC that produced it and inspect its operands. This is 5765 // fairly easy if C is the SETCC node, but it can potentially be 5766 // undiscoverable (or not reasonably discoverable). For example, it could be 5767 // in another basic block or it could require searching a complicated 5768 // expression. 5769 if (CondVT.isInteger() && 5770 TLI.getBooleanContents(false, true) == 5771 TargetLowering::ZeroOrOneBooleanContent && 5772 TLI.getBooleanContents(false, false) == 5773 TargetLowering::ZeroOrOneBooleanContent && 5774 C1->isNullValue() && C2->isOne()) { 5775 SDValue NotCond = 5776 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT)); 5777 if (VT.bitsEq(CondVT)) 5778 return NotCond; 5779 return DAG.getZExtOrTrunc(NotCond, DL, VT); 5780 } 5781 5782 return SDValue(); 5783 } 5784 5785 SDValue DAGCombiner::visitSELECT(SDNode *N) { 5786 SDValue N0 = N->getOperand(0); 5787 SDValue N1 = N->getOperand(1); 5788 SDValue N2 = N->getOperand(2); 5789 EVT VT = N->getValueType(0); 5790 EVT VT0 = N0.getValueType(); 5791 5792 // fold (select C, X, X) -> X 5793 if (N1 == N2) 5794 return N1; 5795 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 5796 // fold (select true, X, Y) -> X 5797 // fold (select false, X, Y) -> Y 5798 return !N0C->isNullValue() ? N1 : N2; 5799 } 5800 // fold (select X, X, Y) -> (or X, Y) 5801 // fold (select X, 1, Y) -> (or C, Y) 5802 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 5803 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5804 5805 if (SDValue V = foldSelectOfConstants(N)) 5806 return V; 5807 5808 // fold (select C, 0, X) -> (and (not C), X) 5809 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 5810 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5811 AddToWorklist(NOTNode.getNode()); 5812 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 5813 } 5814 // fold (select C, X, 1) -> (or (not C), X) 5815 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 5816 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5817 AddToWorklist(NOTNode.getNode()); 5818 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 5819 } 5820 // fold (select X, Y, X) -> (and X, Y) 5821 // fold (select X, Y, 0) -> (and X, Y) 5822 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 5823 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5824 5825 // If we can fold this based on the true/false value, do so. 5826 if (SimplifySelectOps(N, N1, N2)) 5827 return SDValue(N, 0); // Don't revisit N. 5828 5829 if (VT0 == MVT::i1) { 5830 // The code in this block deals with the following 2 equivalences: 5831 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 5832 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 5833 // The target can specify its preferred form with the 5834 // shouldNormalizeToSelectSequence() callback. However we always transform 5835 // to the right anyway if we find the inner select exists in the DAG anyway 5836 // and we always transform to the left side if we know that we can further 5837 // optimize the combination of the conditions. 5838 bool normalizeToSequence 5839 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 5840 // select (and Cond0, Cond1), X, Y 5841 // -> select Cond0, (select Cond1, X, Y), Y 5842 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 5843 SDValue Cond0 = N0->getOperand(0); 5844 SDValue Cond1 = N0->getOperand(1); 5845 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5846 N1.getValueType(), Cond1, N1, N2); 5847 if (normalizeToSequence || !InnerSelect.use_empty()) 5848 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 5849 InnerSelect, N2); 5850 } 5851 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 5852 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 5853 SDValue Cond0 = N0->getOperand(0); 5854 SDValue Cond1 = N0->getOperand(1); 5855 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5856 N1.getValueType(), Cond1, N1, N2); 5857 if (normalizeToSequence || !InnerSelect.use_empty()) 5858 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 5859 InnerSelect); 5860 } 5861 5862 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 5863 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 5864 SDValue N1_0 = N1->getOperand(0); 5865 SDValue N1_1 = N1->getOperand(1); 5866 SDValue N1_2 = N1->getOperand(2); 5867 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 5868 // Create the actual and node if we can generate good code for it. 5869 if (!normalizeToSequence) { 5870 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 5871 N0, N1_0); 5872 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 5873 N1_1, N2); 5874 } 5875 // Otherwise see if we can optimize the "and" to a better pattern. 5876 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 5877 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5878 N1_1, N2); 5879 } 5880 } 5881 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 5882 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 5883 SDValue N2_0 = N2->getOperand(0); 5884 SDValue N2_1 = N2->getOperand(1); 5885 SDValue N2_2 = N2->getOperand(2); 5886 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 5887 // Create the actual or node if we can generate good code for it. 5888 if (!normalizeToSequence) { 5889 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 5890 N0, N2_0); 5891 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 5892 N1, N2_2); 5893 } 5894 // Otherwise see if we can optimize to a better pattern. 5895 if (SDValue Combined = visitORLike(N0, N2_0, N)) 5896 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5897 N1, N2_2); 5898 } 5899 } 5900 } 5901 5902 // select (xor Cond, 1), X, Y -> select Cond, Y, X 5903 if (VT0 == MVT::i1) { 5904 if (N0->getOpcode() == ISD::XOR) { 5905 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) { 5906 SDValue Cond0 = N0->getOperand(0); 5907 if (C->isOne()) 5908 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), 5909 Cond0, N2, N1); 5910 } 5911 } 5912 } 5913 5914 // fold selects based on a setcc into other things, such as min/max/abs 5915 if (N0.getOpcode() == ISD::SETCC) { 5916 // select x, y (fcmp lt x, y) -> fminnum x, y 5917 // select x, y (fcmp gt x, y) -> fmaxnum x, y 5918 // 5919 // This is OK if we don't care about what happens if either operand is a 5920 // NaN. 5921 // 5922 5923 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 5924 // no signed zeros as well as no nans. 5925 const TargetOptions &Options = DAG.getTarget().Options; 5926 if (Options.UnsafeFPMath && 5927 VT.isFloatingPoint() && N0.hasOneUse() && 5928 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 5929 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5930 5931 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 5932 N0.getOperand(1), N1, N2, CC, 5933 TLI, DAG)) 5934 return FMinMax; 5935 } 5936 5937 if ((!LegalOperations && 5938 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 5939 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 5940 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 5941 N0.getOperand(0), N0.getOperand(1), 5942 N1, N2, N0.getOperand(2)); 5943 return SimplifySelect(SDLoc(N), N0, N1, N2); 5944 } 5945 5946 return SDValue(); 5947 } 5948 5949 static 5950 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 5951 SDLoc DL(N); 5952 EVT LoVT, HiVT; 5953 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 5954 5955 // Split the inputs. 5956 SDValue Lo, Hi, LL, LH, RL, RH; 5957 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 5958 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 5959 5960 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 5961 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 5962 5963 return std::make_pair(Lo, Hi); 5964 } 5965 5966 // This function assumes all the vselect's arguments are CONCAT_VECTOR 5967 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 5968 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 5969 SDLoc DL(N); 5970 SDValue Cond = N->getOperand(0); 5971 SDValue LHS = N->getOperand(1); 5972 SDValue RHS = N->getOperand(2); 5973 EVT VT = N->getValueType(0); 5974 int NumElems = VT.getVectorNumElements(); 5975 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 5976 RHS.getOpcode() == ISD::CONCAT_VECTORS && 5977 Cond.getOpcode() == ISD::BUILD_VECTOR); 5978 5979 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 5980 // binary ones here. 5981 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 5982 return SDValue(); 5983 5984 // We're sure we have an even number of elements due to the 5985 // concat_vectors we have as arguments to vselect. 5986 // Skip BV elements until we find one that's not an UNDEF 5987 // After we find an UNDEF element, keep looping until we get to half the 5988 // length of the BV and see if all the non-undef nodes are the same. 5989 ConstantSDNode *BottomHalf = nullptr; 5990 for (int i = 0; i < NumElems / 2; ++i) { 5991 if (Cond->getOperand(i)->isUndef()) 5992 continue; 5993 5994 if (BottomHalf == nullptr) 5995 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5996 else if (Cond->getOperand(i).getNode() != BottomHalf) 5997 return SDValue(); 5998 } 5999 6000 // Do the same for the second half of the BuildVector 6001 ConstantSDNode *TopHalf = nullptr; 6002 for (int i = NumElems / 2; i < NumElems; ++i) { 6003 if (Cond->getOperand(i)->isUndef()) 6004 continue; 6005 6006 if (TopHalf == nullptr) 6007 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 6008 else if (Cond->getOperand(i).getNode() != TopHalf) 6009 return SDValue(); 6010 } 6011 6012 assert(TopHalf && BottomHalf && 6013 "One half of the selector was all UNDEFs and the other was all the " 6014 "same value. This should have been addressed before this function."); 6015 return DAG.getNode( 6016 ISD::CONCAT_VECTORS, DL, VT, 6017 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 6018 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 6019 } 6020 6021 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 6022 6023 if (Level >= AfterLegalizeTypes) 6024 return SDValue(); 6025 6026 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 6027 SDValue Mask = MSC->getMask(); 6028 SDValue Data = MSC->getValue(); 6029 SDLoc DL(N); 6030 6031 // If the MSCATTER data type requires splitting and the mask is provided by a 6032 // SETCC, then split both nodes and its operands before legalization. This 6033 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6034 // and enables future optimizations (e.g. min/max pattern matching on X86). 6035 if (Mask.getOpcode() != ISD::SETCC) 6036 return SDValue(); 6037 6038 // Check if any splitting is required. 6039 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 6040 TargetLowering::TypeSplitVector) 6041 return SDValue(); 6042 SDValue MaskLo, MaskHi, Lo, Hi; 6043 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6044 6045 EVT LoVT, HiVT; 6046 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 6047 6048 SDValue Chain = MSC->getChain(); 6049 6050 EVT MemoryVT = MSC->getMemoryVT(); 6051 unsigned Alignment = MSC->getOriginalAlignment(); 6052 6053 EVT LoMemVT, HiMemVT; 6054 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6055 6056 SDValue DataLo, DataHi; 6057 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6058 6059 SDValue BasePtr = MSC->getBasePtr(); 6060 SDValue IndexLo, IndexHi; 6061 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 6062 6063 MachineMemOperand *MMO = DAG.getMachineFunction(). 6064 getMachineMemOperand(MSC->getPointerInfo(), 6065 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6066 Alignment, MSC->getAAInfo(), MSC->getRanges()); 6067 6068 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 6069 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 6070 DL, OpsLo, MMO); 6071 6072 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 6073 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 6074 DL, OpsHi, MMO); 6075 6076 AddToWorklist(Lo.getNode()); 6077 AddToWorklist(Hi.getNode()); 6078 6079 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6080 } 6081 6082 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 6083 6084 if (Level >= AfterLegalizeTypes) 6085 return SDValue(); 6086 6087 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 6088 SDValue Mask = MST->getMask(); 6089 SDValue Data = MST->getValue(); 6090 EVT VT = Data.getValueType(); 6091 SDLoc DL(N); 6092 6093 // If the MSTORE data type requires splitting and the mask is provided by a 6094 // SETCC, then split both nodes and its operands before legalization. This 6095 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6096 // and enables future optimizations (e.g. min/max pattern matching on X86). 6097 if (Mask.getOpcode() == ISD::SETCC) { 6098 6099 // Check if any splitting is required. 6100 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6101 TargetLowering::TypeSplitVector) 6102 return SDValue(); 6103 6104 SDValue MaskLo, MaskHi, Lo, Hi; 6105 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6106 6107 SDValue Chain = MST->getChain(); 6108 SDValue Ptr = MST->getBasePtr(); 6109 6110 EVT MemoryVT = MST->getMemoryVT(); 6111 unsigned Alignment = MST->getOriginalAlignment(); 6112 6113 // if Alignment is equal to the vector size, 6114 // take the half of it for the second part 6115 unsigned SecondHalfAlignment = 6116 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment; 6117 6118 EVT LoMemVT, HiMemVT; 6119 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6120 6121 SDValue DataLo, DataHi; 6122 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6123 6124 MachineMemOperand *MMO = DAG.getMachineFunction(). 6125 getMachineMemOperand(MST->getPointerInfo(), 6126 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6127 Alignment, MST->getAAInfo(), MST->getRanges()); 6128 6129 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 6130 MST->isTruncatingStore(), 6131 MST->isCompressingStore()); 6132 6133 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6134 MST->isCompressingStore()); 6135 6136 MMO = DAG.getMachineFunction(). 6137 getMachineMemOperand(MST->getPointerInfo(), 6138 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 6139 SecondHalfAlignment, MST->getAAInfo(), 6140 MST->getRanges()); 6141 6142 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 6143 MST->isTruncatingStore(), 6144 MST->isCompressingStore()); 6145 6146 AddToWorklist(Lo.getNode()); 6147 AddToWorklist(Hi.getNode()); 6148 6149 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6150 } 6151 return SDValue(); 6152 } 6153 6154 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 6155 6156 if (Level >= AfterLegalizeTypes) 6157 return SDValue(); 6158 6159 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 6160 SDValue Mask = MGT->getMask(); 6161 SDLoc DL(N); 6162 6163 // If the MGATHER result requires splitting and the mask is provided by a 6164 // SETCC, then split both nodes and its operands before legalization. This 6165 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6166 // and enables future optimizations (e.g. min/max pattern matching on X86). 6167 6168 if (Mask.getOpcode() != ISD::SETCC) 6169 return SDValue(); 6170 6171 EVT VT = N->getValueType(0); 6172 6173 // Check if any splitting is required. 6174 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6175 TargetLowering::TypeSplitVector) 6176 return SDValue(); 6177 6178 SDValue MaskLo, MaskHi, Lo, Hi; 6179 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6180 6181 SDValue Src0 = MGT->getValue(); 6182 SDValue Src0Lo, Src0Hi; 6183 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6184 6185 EVT LoVT, HiVT; 6186 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 6187 6188 SDValue Chain = MGT->getChain(); 6189 EVT MemoryVT = MGT->getMemoryVT(); 6190 unsigned Alignment = MGT->getOriginalAlignment(); 6191 6192 EVT LoMemVT, HiMemVT; 6193 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6194 6195 SDValue BasePtr = MGT->getBasePtr(); 6196 SDValue Index = MGT->getIndex(); 6197 SDValue IndexLo, IndexHi; 6198 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 6199 6200 MachineMemOperand *MMO = DAG.getMachineFunction(). 6201 getMachineMemOperand(MGT->getPointerInfo(), 6202 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6203 Alignment, MGT->getAAInfo(), MGT->getRanges()); 6204 6205 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 6206 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 6207 MMO); 6208 6209 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 6210 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 6211 MMO); 6212 6213 AddToWorklist(Lo.getNode()); 6214 AddToWorklist(Hi.getNode()); 6215 6216 // Build a factor node to remember that this load is independent of the 6217 // other one. 6218 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6219 Hi.getValue(1)); 6220 6221 // Legalized the chain result - switch anything that used the old chain to 6222 // use the new one. 6223 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 6224 6225 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6226 6227 SDValue RetOps[] = { GatherRes, Chain }; 6228 return DAG.getMergeValues(RetOps, DL); 6229 } 6230 6231 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 6232 6233 if (Level >= AfterLegalizeTypes) 6234 return SDValue(); 6235 6236 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 6237 SDValue Mask = MLD->getMask(); 6238 SDLoc DL(N); 6239 6240 // If the MLOAD result requires splitting and the mask is provided by a 6241 // SETCC, then split both nodes and its operands before legalization. This 6242 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6243 // and enables future optimizations (e.g. min/max pattern matching on X86). 6244 6245 if (Mask.getOpcode() == ISD::SETCC) { 6246 EVT VT = N->getValueType(0); 6247 6248 // Check if any splitting is required. 6249 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6250 TargetLowering::TypeSplitVector) 6251 return SDValue(); 6252 6253 SDValue MaskLo, MaskHi, Lo, Hi; 6254 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6255 6256 SDValue Src0 = MLD->getSrc0(); 6257 SDValue Src0Lo, Src0Hi; 6258 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6259 6260 EVT LoVT, HiVT; 6261 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 6262 6263 SDValue Chain = MLD->getChain(); 6264 SDValue Ptr = MLD->getBasePtr(); 6265 EVT MemoryVT = MLD->getMemoryVT(); 6266 unsigned Alignment = MLD->getOriginalAlignment(); 6267 6268 // if Alignment is equal to the vector size, 6269 // take the half of it for the second part 6270 unsigned SecondHalfAlignment = 6271 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 6272 Alignment/2 : Alignment; 6273 6274 EVT LoMemVT, HiMemVT; 6275 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6276 6277 MachineMemOperand *MMO = DAG.getMachineFunction(). 6278 getMachineMemOperand(MLD->getPointerInfo(), 6279 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6280 Alignment, MLD->getAAInfo(), MLD->getRanges()); 6281 6282 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 6283 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6284 6285 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6286 MLD->isExpandingLoad()); 6287 6288 MMO = DAG.getMachineFunction(). 6289 getMachineMemOperand(MLD->getPointerInfo(), 6290 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 6291 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 6292 6293 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 6294 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6295 6296 AddToWorklist(Lo.getNode()); 6297 AddToWorklist(Hi.getNode()); 6298 6299 // Build a factor node to remember that this load is independent of the 6300 // other one. 6301 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6302 Hi.getValue(1)); 6303 6304 // Legalized the chain result - switch anything that used the old chain to 6305 // use the new one. 6306 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 6307 6308 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6309 6310 SDValue RetOps[] = { LoadRes, Chain }; 6311 return DAG.getMergeValues(RetOps, DL); 6312 } 6313 return SDValue(); 6314 } 6315 6316 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 6317 SDValue N0 = N->getOperand(0); 6318 SDValue N1 = N->getOperand(1); 6319 SDValue N2 = N->getOperand(2); 6320 SDLoc DL(N); 6321 6322 // fold (vselect C, X, X) -> X 6323 if (N1 == N2) 6324 return N1; 6325 6326 // Canonicalize integer abs. 6327 // vselect (setg[te] X, 0), X, -X -> 6328 // vselect (setgt X, -1), X, -X -> 6329 // vselect (setl[te] X, 0), -X, X -> 6330 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 6331 if (N0.getOpcode() == ISD::SETCC) { 6332 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 6333 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6334 bool isAbs = false; 6335 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 6336 6337 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 6338 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 6339 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 6340 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 6341 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 6342 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 6343 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 6344 6345 if (isAbs) { 6346 EVT VT = LHS.getValueType(); 6347 SDValue Shift = DAG.getNode( 6348 ISD::SRA, DL, VT, LHS, 6349 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT)); 6350 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 6351 AddToWorklist(Shift.getNode()); 6352 AddToWorklist(Add.getNode()); 6353 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 6354 } 6355 } 6356 6357 if (SimplifySelectOps(N, N1, N2)) 6358 return SDValue(N, 0); // Don't revisit N. 6359 6360 // If the VSELECT result requires splitting and the mask is provided by a 6361 // SETCC, then split both nodes and its operands before legalization. This 6362 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6363 // and enables future optimizations (e.g. min/max pattern matching on X86). 6364 if (N0.getOpcode() == ISD::SETCC) { 6365 EVT VT = N->getValueType(0); 6366 6367 // Check if any splitting is required. 6368 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6369 TargetLowering::TypeSplitVector) 6370 return SDValue(); 6371 6372 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 6373 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 6374 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 6375 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 6376 6377 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 6378 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 6379 6380 // Add the new VSELECT nodes to the work list in case they need to be split 6381 // again. 6382 AddToWorklist(Lo.getNode()); 6383 AddToWorklist(Hi.getNode()); 6384 6385 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6386 } 6387 6388 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 6389 if (ISD::isBuildVectorAllOnes(N0.getNode())) 6390 return N1; 6391 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 6392 if (ISD::isBuildVectorAllZeros(N0.getNode())) 6393 return N2; 6394 6395 // The ConvertSelectToConcatVector function is assuming both the above 6396 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 6397 // and addressed. 6398 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 6399 N2.getOpcode() == ISD::CONCAT_VECTORS && 6400 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 6401 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 6402 return CV; 6403 } 6404 6405 return SDValue(); 6406 } 6407 6408 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 6409 SDValue N0 = N->getOperand(0); 6410 SDValue N1 = N->getOperand(1); 6411 SDValue N2 = N->getOperand(2); 6412 SDValue N3 = N->getOperand(3); 6413 SDValue N4 = N->getOperand(4); 6414 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 6415 6416 // fold select_cc lhs, rhs, x, x, cc -> x 6417 if (N2 == N3) 6418 return N2; 6419 6420 // Determine if the condition we're dealing with is constant 6421 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 6422 CC, SDLoc(N), false)) { 6423 AddToWorklist(SCC.getNode()); 6424 6425 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 6426 if (!SCCC->isNullValue()) 6427 return N2; // cond always true -> true val 6428 else 6429 return N3; // cond always false -> false val 6430 } else if (SCC->isUndef()) { 6431 // When the condition is UNDEF, just return the first operand. This is 6432 // coherent the DAG creation, no setcc node is created in this case 6433 return N2; 6434 } else if (SCC.getOpcode() == ISD::SETCC) { 6435 // Fold to a simpler select_cc 6436 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 6437 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 6438 SCC.getOperand(2)); 6439 } 6440 } 6441 6442 // If we can fold this based on the true/false value, do so. 6443 if (SimplifySelectOps(N, N2, N3)) 6444 return SDValue(N, 0); // Don't revisit N. 6445 6446 // fold select_cc into other things, such as min/max/abs 6447 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 6448 } 6449 6450 SDValue DAGCombiner::visitSETCC(SDNode *N) { 6451 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 6452 cast<CondCodeSDNode>(N->getOperand(2))->get(), 6453 SDLoc(N)); 6454 } 6455 6456 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 6457 SDValue LHS = N->getOperand(0); 6458 SDValue RHS = N->getOperand(1); 6459 SDValue Carry = N->getOperand(2); 6460 SDValue Cond = N->getOperand(3); 6461 6462 // If Carry is false, fold to a regular SETCC. 6463 if (Carry.getOpcode() == ISD::CARRY_FALSE) 6464 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 6465 6466 return SDValue(); 6467 } 6468 6469 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 6470 /// a build_vector of constants. 6471 /// This function is called by the DAGCombiner when visiting sext/zext/aext 6472 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 6473 /// Vector extends are not folded if operations are legal; this is to 6474 /// avoid introducing illegal build_vector dag nodes. 6475 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 6476 SelectionDAG &DAG, bool LegalTypes, 6477 bool LegalOperations) { 6478 unsigned Opcode = N->getOpcode(); 6479 SDValue N0 = N->getOperand(0); 6480 EVT VT = N->getValueType(0); 6481 6482 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 6483 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 6484 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 6485 && "Expected EXTEND dag node in input!"); 6486 6487 // fold (sext c1) -> c1 6488 // fold (zext c1) -> c1 6489 // fold (aext c1) -> c1 6490 if (isa<ConstantSDNode>(N0)) 6491 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 6492 6493 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 6494 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 6495 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 6496 EVT SVT = VT.getScalarType(); 6497 if (!(VT.isVector() && 6498 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 6499 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 6500 return nullptr; 6501 6502 // We can fold this node into a build_vector. 6503 unsigned VTBits = SVT.getSizeInBits(); 6504 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits(); 6505 SmallVector<SDValue, 8> Elts; 6506 unsigned NumElts = VT.getVectorNumElements(); 6507 SDLoc DL(N); 6508 6509 for (unsigned i=0; i != NumElts; ++i) { 6510 SDValue Op = N0->getOperand(i); 6511 if (Op->isUndef()) { 6512 Elts.push_back(DAG.getUNDEF(SVT)); 6513 continue; 6514 } 6515 6516 SDLoc DL(Op); 6517 // Get the constant value and if needed trunc it to the size of the type. 6518 // Nodes like build_vector might have constants wider than the scalar type. 6519 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 6520 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 6521 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 6522 else 6523 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 6524 } 6525 6526 return DAG.getBuildVector(VT, DL, Elts).getNode(); 6527 } 6528 6529 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 6530 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 6531 // transformation. Returns true if extension are possible and the above 6532 // mentioned transformation is profitable. 6533 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 6534 unsigned ExtOpc, 6535 SmallVectorImpl<SDNode *> &ExtendNodes, 6536 const TargetLowering &TLI) { 6537 bool HasCopyToRegUses = false; 6538 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 6539 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 6540 UE = N0.getNode()->use_end(); 6541 UI != UE; ++UI) { 6542 SDNode *User = *UI; 6543 if (User == N) 6544 continue; 6545 if (UI.getUse().getResNo() != N0.getResNo()) 6546 continue; 6547 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 6548 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 6549 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 6550 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 6551 // Sign bits will be lost after a zext. 6552 return false; 6553 bool Add = false; 6554 for (unsigned i = 0; i != 2; ++i) { 6555 SDValue UseOp = User->getOperand(i); 6556 if (UseOp == N0) 6557 continue; 6558 if (!isa<ConstantSDNode>(UseOp)) 6559 return false; 6560 Add = true; 6561 } 6562 if (Add) 6563 ExtendNodes.push_back(User); 6564 continue; 6565 } 6566 // If truncates aren't free and there are users we can't 6567 // extend, it isn't worthwhile. 6568 if (!isTruncFree) 6569 return false; 6570 // Remember if this value is live-out. 6571 if (User->getOpcode() == ISD::CopyToReg) 6572 HasCopyToRegUses = true; 6573 } 6574 6575 if (HasCopyToRegUses) { 6576 bool BothLiveOut = false; 6577 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 6578 UI != UE; ++UI) { 6579 SDUse &Use = UI.getUse(); 6580 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 6581 BothLiveOut = true; 6582 break; 6583 } 6584 } 6585 if (BothLiveOut) 6586 // Both unextended and extended values are live out. There had better be 6587 // a good reason for the transformation. 6588 return ExtendNodes.size(); 6589 } 6590 return true; 6591 } 6592 6593 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 6594 SDValue Trunc, SDValue ExtLoad, 6595 const SDLoc &DL, ISD::NodeType ExtType) { 6596 // Extend SetCC uses if necessary. 6597 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 6598 SDNode *SetCC = SetCCs[i]; 6599 SmallVector<SDValue, 4> Ops; 6600 6601 for (unsigned j = 0; j != 2; ++j) { 6602 SDValue SOp = SetCC->getOperand(j); 6603 if (SOp == Trunc) 6604 Ops.push_back(ExtLoad); 6605 else 6606 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 6607 } 6608 6609 Ops.push_back(SetCC->getOperand(2)); 6610 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 6611 } 6612 } 6613 6614 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 6615 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 6616 SDValue N0 = N->getOperand(0); 6617 EVT DstVT = N->getValueType(0); 6618 EVT SrcVT = N0.getValueType(); 6619 6620 assert((N->getOpcode() == ISD::SIGN_EXTEND || 6621 N->getOpcode() == ISD::ZERO_EXTEND) && 6622 "Unexpected node type (not an extend)!"); 6623 6624 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 6625 // For example, on a target with legal v4i32, but illegal v8i32, turn: 6626 // (v8i32 (sext (v8i16 (load x)))) 6627 // into: 6628 // (v8i32 (concat_vectors (v4i32 (sextload x)), 6629 // (v4i32 (sextload (x + 16))))) 6630 // Where uses of the original load, i.e.: 6631 // (v8i16 (load x)) 6632 // are replaced with: 6633 // (v8i16 (truncate 6634 // (v8i32 (concat_vectors (v4i32 (sextload x)), 6635 // (v4i32 (sextload (x + 16))))))) 6636 // 6637 // This combine is only applicable to illegal, but splittable, vectors. 6638 // All legal types, and illegal non-vector types, are handled elsewhere. 6639 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 6640 // 6641 if (N0->getOpcode() != ISD::LOAD) 6642 return SDValue(); 6643 6644 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6645 6646 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 6647 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 6648 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 6649 return SDValue(); 6650 6651 SmallVector<SDNode *, 4> SetCCs; 6652 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 6653 return SDValue(); 6654 6655 ISD::LoadExtType ExtType = 6656 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 6657 6658 // Try to split the vector types to get down to legal types. 6659 EVT SplitSrcVT = SrcVT; 6660 EVT SplitDstVT = DstVT; 6661 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 6662 SplitSrcVT.getVectorNumElements() > 1) { 6663 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 6664 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 6665 } 6666 6667 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 6668 return SDValue(); 6669 6670 SDLoc DL(N); 6671 const unsigned NumSplits = 6672 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 6673 const unsigned Stride = SplitSrcVT.getStoreSize(); 6674 SmallVector<SDValue, 4> Loads; 6675 SmallVector<SDValue, 4> Chains; 6676 6677 SDValue BasePtr = LN0->getBasePtr(); 6678 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 6679 const unsigned Offset = Idx * Stride; 6680 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 6681 6682 SDValue SplitLoad = DAG.getExtLoad( 6683 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 6684 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 6685 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 6686 6687 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 6688 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 6689 6690 Loads.push_back(SplitLoad.getValue(0)); 6691 Chains.push_back(SplitLoad.getValue(1)); 6692 } 6693 6694 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 6695 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 6696 6697 CombineTo(N, NewValue); 6698 6699 // Replace uses of the original load (before extension) 6700 // with a truncate of the concatenated sextloaded vectors. 6701 SDValue Trunc = 6702 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 6703 CombineTo(N0.getNode(), Trunc, NewChain); 6704 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 6705 (ISD::NodeType)N->getOpcode()); 6706 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6707 } 6708 6709 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 6710 SDValue N0 = N->getOperand(0); 6711 EVT VT = N->getValueType(0); 6712 SDLoc DL(N); 6713 6714 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6715 LegalOperations)) 6716 return SDValue(Res, 0); 6717 6718 // fold (sext (sext x)) -> (sext x) 6719 // fold (sext (aext x)) -> (sext x) 6720 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6721 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0)); 6722 6723 if (N0.getOpcode() == ISD::TRUNCATE) { 6724 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 6725 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 6726 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6727 SDNode *oye = N0.getOperand(0).getNode(); 6728 if (NarrowLoad.getNode() != N0.getNode()) { 6729 CombineTo(N0.getNode(), NarrowLoad); 6730 // CombineTo deleted the truncate, if needed, but not what's under it. 6731 AddToWorklist(oye); 6732 } 6733 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6734 } 6735 6736 // See if the value being truncated is already sign extended. If so, just 6737 // eliminate the trunc/sext pair. 6738 SDValue Op = N0.getOperand(0); 6739 unsigned OpBits = Op.getScalarValueSizeInBits(); 6740 unsigned MidBits = N0.getScalarValueSizeInBits(); 6741 unsigned DestBits = VT.getScalarSizeInBits(); 6742 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 6743 6744 if (OpBits == DestBits) { 6745 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 6746 // bits, it is already ready. 6747 if (NumSignBits > DestBits-MidBits) 6748 return Op; 6749 } else if (OpBits < DestBits) { 6750 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 6751 // bits, just sext from i32. 6752 if (NumSignBits > OpBits-MidBits) 6753 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op); 6754 } else { 6755 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 6756 // bits, just truncate to i32. 6757 if (NumSignBits > OpBits-MidBits) 6758 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 6759 } 6760 6761 // fold (sext (truncate x)) -> (sextinreg x). 6762 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 6763 N0.getValueType())) { 6764 if (OpBits < DestBits) 6765 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 6766 else if (OpBits > DestBits) 6767 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 6768 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op, 6769 DAG.getValueType(N0.getValueType())); 6770 } 6771 } 6772 6773 // fold (sext (load x)) -> (sext (truncate (sextload x))) 6774 // Only generate vector extloads when 1) they're legal, and 2) they are 6775 // deemed desirable by the target. 6776 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6777 ((!LegalOperations && !VT.isVector() && 6778 !cast<LoadSDNode>(N0)->isVolatile()) || 6779 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 6780 bool DoXform = true; 6781 SmallVector<SDNode*, 4> SetCCs; 6782 if (!N0.hasOneUse()) 6783 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 6784 if (VT.isVector()) 6785 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6786 if (DoXform) { 6787 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6788 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 6789 LN0->getBasePtr(), N0.getValueType(), 6790 LN0->getMemOperand()); 6791 CombineTo(N, ExtLoad); 6792 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6793 N0.getValueType(), ExtLoad); 6794 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6795 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND); 6796 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6797 } 6798 } 6799 6800 // fold (sext (load x)) to multiple smaller sextloads. 6801 // Only on illegal but splittable vectors. 6802 if (SDValue ExtLoad = CombineExtLoad(N)) 6803 return ExtLoad; 6804 6805 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 6806 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 6807 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6808 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6809 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6810 EVT MemVT = LN0->getMemoryVT(); 6811 if ((!LegalOperations && !LN0->isVolatile()) || 6812 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 6813 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 6814 LN0->getBasePtr(), MemVT, 6815 LN0->getMemOperand()); 6816 CombineTo(N, ExtLoad); 6817 CombineTo(N0.getNode(), 6818 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6819 N0.getValueType(), ExtLoad), 6820 ExtLoad.getValue(1)); 6821 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6822 } 6823 } 6824 6825 // fold (sext (and/or/xor (load x), cst)) -> 6826 // (and/or/xor (sextload x), (sext cst)) 6827 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6828 N0.getOpcode() == ISD::XOR) && 6829 isa<LoadSDNode>(N0.getOperand(0)) && 6830 N0.getOperand(1).getOpcode() == ISD::Constant && 6831 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 6832 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6833 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6834 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 6835 bool DoXform = true; 6836 SmallVector<SDNode*, 4> SetCCs; 6837 if (!N0.hasOneUse()) 6838 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 6839 SetCCs, TLI); 6840 if (DoXform) { 6841 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 6842 LN0->getChain(), LN0->getBasePtr(), 6843 LN0->getMemoryVT(), 6844 LN0->getMemOperand()); 6845 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6846 Mask = Mask.sext(VT.getSizeInBits()); 6847 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6848 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6849 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6850 SDLoc(N0.getOperand(0)), 6851 N0.getOperand(0).getValueType(), ExtLoad); 6852 CombineTo(N, And); 6853 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6854 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND); 6855 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6856 } 6857 } 6858 } 6859 6860 if (N0.getOpcode() == ISD::SETCC) { 6861 SDValue N00 = N0.getOperand(0); 6862 SDValue N01 = N0.getOperand(1); 6863 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6864 EVT N00VT = N0.getOperand(0).getValueType(); 6865 6866 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 6867 // Only do this before legalize for now. 6868 if (VT.isVector() && !LegalOperations && 6869 TLI.getBooleanContents(N00VT) == 6870 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6871 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 6872 // of the same size as the compared operands. Only optimize sext(setcc()) 6873 // if this is the case. 6874 EVT SVT = getSetCCResultType(N00VT); 6875 6876 // We know that the # elements of the results is the same as the 6877 // # elements of the compare (and the # elements of the compare result 6878 // for that matter). Check to see that they are the same size. If so, 6879 // we know that the element size of the sext'd result matches the 6880 // element size of the compare operands. 6881 if (VT.getSizeInBits() == SVT.getSizeInBits()) 6882 return DAG.getSetCC(DL, VT, N00, N01, CC); 6883 6884 // If the desired elements are smaller or larger than the source 6885 // elements, we can use a matching integer vector type and then 6886 // truncate/sign extend. 6887 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger(); 6888 if (SVT == MatchingVecType) { 6889 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC); 6890 return DAG.getSExtOrTrunc(VsetCC, DL, VT); 6891 } 6892 } 6893 6894 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 6895 // Here, T can be 1 or -1, depending on the type of the setcc and 6896 // getBooleanContents(). 6897 unsigned SetCCWidth = N0.getScalarValueSizeInBits(); 6898 6899 // To determine the "true" side of the select, we need to know the high bit 6900 // of the value returned by the setcc if it evaluates to true. 6901 // If the type of the setcc is i1, then the true case of the select is just 6902 // sext(i1 1), that is, -1. 6903 // If the type of the setcc is larger (say, i8) then the value of the high 6904 // bit depends on getBooleanContents(), so ask TLI for a real "true" value 6905 // of the appropriate width. 6906 SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT) 6907 : TLI.getConstTrueVal(DAG, VT, DL); 6908 SDValue Zero = DAG.getConstant(0, DL, VT); 6909 if (SDValue SCC = 6910 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true)) 6911 return SCC; 6912 6913 if (!VT.isVector()) { 6914 EVT SetCCVT = getSetCCResultType(N00VT); 6915 // Don't do this transform for i1 because there's a select transform 6916 // that would reverse it. 6917 // TODO: We should not do this transform at all without a target hook 6918 // because a sext is likely cheaper than a select? 6919 if (SetCCVT.getScalarSizeInBits() != 1 && 6920 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) { 6921 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC); 6922 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero); 6923 } 6924 } 6925 } 6926 6927 // fold (sext x) -> (zext x) if the sign bit is known zero. 6928 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 6929 DAG.SignBitIsZero(N0)) 6930 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0); 6931 6932 return SDValue(); 6933 } 6934 6935 // isTruncateOf - If N is a truncate of some other value, return true, record 6936 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 6937 // This function computes KnownZero to avoid a duplicated call to 6938 // computeKnownBits in the caller. 6939 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 6940 APInt &KnownZero) { 6941 APInt KnownOne; 6942 if (N->getOpcode() == ISD::TRUNCATE) { 6943 Op = N->getOperand(0); 6944 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6945 return true; 6946 } 6947 6948 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 6949 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 6950 return false; 6951 6952 SDValue Op0 = N->getOperand(0); 6953 SDValue Op1 = N->getOperand(1); 6954 assert(Op0.getValueType() == Op1.getValueType()); 6955 6956 if (isNullConstant(Op0)) 6957 Op = Op1; 6958 else if (isNullConstant(Op1)) 6959 Op = Op0; 6960 else 6961 return false; 6962 6963 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6964 6965 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 6966 return false; 6967 6968 return true; 6969 } 6970 6971 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 6972 SDValue N0 = N->getOperand(0); 6973 EVT VT = N->getValueType(0); 6974 6975 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6976 LegalOperations)) 6977 return SDValue(Res, 0); 6978 6979 // fold (zext (zext x)) -> (zext x) 6980 // fold (zext (aext x)) -> (zext x) 6981 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6982 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 6983 N0.getOperand(0)); 6984 6985 // fold (zext (truncate x)) -> (zext x) or 6986 // (zext (truncate x)) -> (truncate x) 6987 // This is valid when the truncated bits of x are already zero. 6988 // FIXME: We should extend this to work for vectors too. 6989 SDValue Op; 6990 APInt KnownZero; 6991 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 6992 APInt TruncatedBits = 6993 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 6994 APInt(Op.getValueSizeInBits(), 0) : 6995 APInt::getBitsSet(Op.getValueSizeInBits(), 6996 N0.getValueSizeInBits(), 6997 std::min(Op.getValueSizeInBits(), 6998 VT.getSizeInBits())); 6999 if (TruncatedBits == (KnownZero & TruncatedBits)) { 7000 if (VT.bitsGT(Op.getValueType())) 7001 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 7002 if (VT.bitsLT(Op.getValueType())) 7003 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 7004 7005 return Op; 7006 } 7007 } 7008 7009 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 7010 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 7011 if (N0.getOpcode() == ISD::TRUNCATE) { 7012 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7013 SDNode *oye = N0.getOperand(0).getNode(); 7014 if (NarrowLoad.getNode() != N0.getNode()) { 7015 CombineTo(N0.getNode(), NarrowLoad); 7016 // CombineTo deleted the truncate, if needed, but not what's under it. 7017 AddToWorklist(oye); 7018 } 7019 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7020 } 7021 } 7022 7023 // fold (zext (truncate x)) -> (and x, mask) 7024 if (N0.getOpcode() == ISD::TRUNCATE) { 7025 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 7026 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 7027 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7028 SDNode *oye = N0.getOperand(0).getNode(); 7029 if (NarrowLoad.getNode() != N0.getNode()) { 7030 CombineTo(N0.getNode(), NarrowLoad); 7031 // CombineTo deleted the truncate, if needed, but not what's under it. 7032 AddToWorklist(oye); 7033 } 7034 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7035 } 7036 7037 EVT SrcVT = N0.getOperand(0).getValueType(); 7038 EVT MinVT = N0.getValueType(); 7039 7040 // Try to mask before the extension to avoid having to generate a larger mask, 7041 // possibly over several sub-vectors. 7042 if (SrcVT.bitsLT(VT)) { 7043 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 7044 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 7045 SDValue Op = N0.getOperand(0); 7046 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 7047 AddToWorklist(Op.getNode()); 7048 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 7049 } 7050 } 7051 7052 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 7053 SDValue Op = N0.getOperand(0); 7054 if (SrcVT.bitsLT(VT)) { 7055 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 7056 AddToWorklist(Op.getNode()); 7057 } else if (SrcVT.bitsGT(VT)) { 7058 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 7059 AddToWorklist(Op.getNode()); 7060 } 7061 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 7062 } 7063 } 7064 7065 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 7066 // if either of the casts is not free. 7067 if (N0.getOpcode() == ISD::AND && 7068 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 7069 N0.getOperand(1).getOpcode() == ISD::Constant && 7070 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 7071 N0.getValueType()) || 7072 !TLI.isZExtFree(N0.getValueType(), VT))) { 7073 SDValue X = N0.getOperand(0).getOperand(0); 7074 if (X.getValueType().bitsLT(VT)) { 7075 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 7076 } else if (X.getValueType().bitsGT(VT)) { 7077 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 7078 } 7079 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7080 Mask = Mask.zext(VT.getSizeInBits()); 7081 SDLoc DL(N); 7082 return DAG.getNode(ISD::AND, DL, VT, 7083 X, DAG.getConstant(Mask, DL, VT)); 7084 } 7085 7086 // fold (zext (load x)) -> (zext (truncate (zextload x))) 7087 // Only generate vector extloads when 1) they're legal, and 2) they are 7088 // deemed desirable by the target. 7089 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7090 ((!LegalOperations && !VT.isVector() && 7091 !cast<LoadSDNode>(N0)->isVolatile()) || 7092 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 7093 bool DoXform = true; 7094 SmallVector<SDNode*, 4> SetCCs; 7095 if (!N0.hasOneUse()) 7096 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 7097 if (VT.isVector()) 7098 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 7099 if (DoXform) { 7100 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7101 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 7102 LN0->getChain(), 7103 LN0->getBasePtr(), N0.getValueType(), 7104 LN0->getMemOperand()); 7105 CombineTo(N, ExtLoad); 7106 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7107 N0.getValueType(), ExtLoad); 7108 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 7109 7110 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 7111 ISD::ZERO_EXTEND); 7112 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7113 } 7114 } 7115 7116 // fold (zext (load x)) to multiple smaller zextloads. 7117 // Only on illegal but splittable vectors. 7118 if (SDValue ExtLoad = CombineExtLoad(N)) 7119 return ExtLoad; 7120 7121 // fold (zext (and/or/xor (load x), cst)) -> 7122 // (and/or/xor (zextload x), (zext cst)) 7123 // Unless (and (load x) cst) will match as a zextload already and has 7124 // additional users. 7125 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 7126 N0.getOpcode() == ISD::XOR) && 7127 isa<LoadSDNode>(N0.getOperand(0)) && 7128 N0.getOperand(1).getOpcode() == ISD::Constant && 7129 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 7130 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 7131 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 7132 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 7133 bool DoXform = true; 7134 SmallVector<SDNode*, 4> SetCCs; 7135 if (!N0.hasOneUse()) { 7136 if (N0.getOpcode() == ISD::AND) { 7137 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 7138 auto NarrowLoad = false; 7139 EVT LoadResultTy = AndC->getValueType(0); 7140 EVT ExtVT, LoadedVT; 7141 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT, 7142 NarrowLoad)) 7143 DoXform = false; 7144 } 7145 if (DoXform) 7146 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 7147 ISD::ZERO_EXTEND, SetCCs, TLI); 7148 } 7149 if (DoXform) { 7150 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 7151 LN0->getChain(), LN0->getBasePtr(), 7152 LN0->getMemoryVT(), 7153 LN0->getMemOperand()); 7154 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7155 Mask = Mask.zext(VT.getSizeInBits()); 7156 SDLoc DL(N); 7157 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 7158 ExtLoad, DAG.getConstant(Mask, DL, VT)); 7159 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 7160 SDLoc(N0.getOperand(0)), 7161 N0.getOperand(0).getValueType(), ExtLoad); 7162 CombineTo(N, And); 7163 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 7164 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 7165 ISD::ZERO_EXTEND); 7166 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7167 } 7168 } 7169 } 7170 7171 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 7172 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 7173 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 7174 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 7175 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7176 EVT MemVT = LN0->getMemoryVT(); 7177 if ((!LegalOperations && !LN0->isVolatile()) || 7178 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 7179 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 7180 LN0->getChain(), 7181 LN0->getBasePtr(), MemVT, 7182 LN0->getMemOperand()); 7183 CombineTo(N, ExtLoad); 7184 CombineTo(N0.getNode(), 7185 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 7186 ExtLoad), 7187 ExtLoad.getValue(1)); 7188 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7189 } 7190 } 7191 7192 if (N0.getOpcode() == ISD::SETCC) { 7193 // Only do this before legalize for now. 7194 if (!LegalOperations && VT.isVector() && 7195 N0.getValueType().getVectorElementType() == MVT::i1) { 7196 EVT N00VT = N0.getOperand(0).getValueType(); 7197 if (getSetCCResultType(N00VT) == N0.getValueType()) 7198 return SDValue(); 7199 7200 // We know that the # elements of the results is the same as the # 7201 // elements of the compare (and the # elements of the compare result for 7202 // that matter). Check to see that they are the same size. If so, we know 7203 // that the element size of the sext'd result matches the element size of 7204 // the compare operands. 7205 SDLoc DL(N); 7206 SDValue VecOnes = DAG.getConstant(1, DL, VT); 7207 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 7208 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 7209 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 7210 N0.getOperand(1), N0.getOperand(2)); 7211 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes); 7212 } 7213 7214 // If the desired elements are smaller or larger than the source 7215 // elements we can use a matching integer vector type and then 7216 // truncate/sign extend. 7217 EVT MatchingElementType = EVT::getIntegerVT( 7218 *DAG.getContext(), N00VT.getScalarSizeInBits()); 7219 EVT MatchingVectorType = EVT::getVectorVT( 7220 *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements()); 7221 SDValue VsetCC = 7222 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 7223 N0.getOperand(1), N0.getOperand(2)); 7224 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT), 7225 VecOnes); 7226 } 7227 7228 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 7229 SDLoc DL(N); 7230 if (SDValue SCC = SimplifySelectCC( 7231 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 7232 DAG.getConstant(0, DL, VT), 7233 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 7234 return SCC; 7235 } 7236 7237 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 7238 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 7239 isa<ConstantSDNode>(N0.getOperand(1)) && 7240 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 7241 N0.hasOneUse()) { 7242 SDValue ShAmt = N0.getOperand(1); 7243 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 7244 if (N0.getOpcode() == ISD::SHL) { 7245 SDValue InnerZExt = N0.getOperand(0); 7246 // If the original shl may be shifting out bits, do not perform this 7247 // transformation. 7248 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() - 7249 InnerZExt.getOperand(0).getValueSizeInBits(); 7250 if (ShAmtVal > KnownZeroBits) 7251 return SDValue(); 7252 } 7253 7254 SDLoc DL(N); 7255 7256 // Ensure that the shift amount is wide enough for the shifted value. 7257 if (VT.getSizeInBits() >= 256) 7258 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 7259 7260 return DAG.getNode(N0.getOpcode(), DL, VT, 7261 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 7262 ShAmt); 7263 } 7264 7265 return SDValue(); 7266 } 7267 7268 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 7269 SDValue N0 = N->getOperand(0); 7270 EVT VT = N->getValueType(0); 7271 7272 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7273 LegalOperations)) 7274 return SDValue(Res, 0); 7275 7276 // fold (aext (aext x)) -> (aext x) 7277 // fold (aext (zext x)) -> (zext x) 7278 // fold (aext (sext x)) -> (sext x) 7279 if (N0.getOpcode() == ISD::ANY_EXTEND || 7280 N0.getOpcode() == ISD::ZERO_EXTEND || 7281 N0.getOpcode() == ISD::SIGN_EXTEND) 7282 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7283 7284 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 7285 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 7286 if (N0.getOpcode() == ISD::TRUNCATE) { 7287 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7288 SDNode *oye = N0.getOperand(0).getNode(); 7289 if (NarrowLoad.getNode() != N0.getNode()) { 7290 CombineTo(N0.getNode(), NarrowLoad); 7291 // CombineTo deleted the truncate, if needed, but not what's under it. 7292 AddToWorklist(oye); 7293 } 7294 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7295 } 7296 } 7297 7298 // fold (aext (truncate x)) 7299 if (N0.getOpcode() == ISD::TRUNCATE) { 7300 SDValue TruncOp = N0.getOperand(0); 7301 if (TruncOp.getValueType() == VT) 7302 return TruncOp; // x iff x size == zext size. 7303 if (TruncOp.getValueType().bitsGT(VT)) 7304 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 7305 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 7306 } 7307 7308 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 7309 // if the trunc is not free. 7310 if (N0.getOpcode() == ISD::AND && 7311 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 7312 N0.getOperand(1).getOpcode() == ISD::Constant && 7313 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 7314 N0.getValueType())) { 7315 SDLoc DL(N); 7316 SDValue X = N0.getOperand(0).getOperand(0); 7317 if (X.getValueType().bitsLT(VT)) { 7318 X = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X); 7319 } else if (X.getValueType().bitsGT(VT)) { 7320 X = DAG.getNode(ISD::TRUNCATE, DL, VT, X); 7321 } 7322 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7323 Mask = Mask.zext(VT.getSizeInBits()); 7324 return DAG.getNode(ISD::AND, DL, VT, 7325 X, DAG.getConstant(Mask, DL, VT)); 7326 } 7327 7328 // fold (aext (load x)) -> (aext (truncate (extload x))) 7329 // None of the supported targets knows how to perform load and any_ext 7330 // on vectors in one instruction. We only perform this transformation on 7331 // scalars. 7332 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 7333 ISD::isUNINDEXEDLoad(N0.getNode()) && 7334 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 7335 bool DoXform = true; 7336 SmallVector<SDNode*, 4> SetCCs; 7337 if (!N0.hasOneUse()) 7338 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 7339 if (DoXform) { 7340 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7341 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 7342 LN0->getChain(), 7343 LN0->getBasePtr(), N0.getValueType(), 7344 LN0->getMemOperand()); 7345 CombineTo(N, ExtLoad); 7346 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7347 N0.getValueType(), ExtLoad); 7348 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 7349 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 7350 ISD::ANY_EXTEND); 7351 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7352 } 7353 } 7354 7355 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 7356 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 7357 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 7358 if (N0.getOpcode() == ISD::LOAD && 7359 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7360 N0.hasOneUse()) { 7361 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7362 ISD::LoadExtType ExtType = LN0->getExtensionType(); 7363 EVT MemVT = LN0->getMemoryVT(); 7364 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 7365 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 7366 VT, LN0->getChain(), LN0->getBasePtr(), 7367 MemVT, LN0->getMemOperand()); 7368 CombineTo(N, ExtLoad); 7369 CombineTo(N0.getNode(), 7370 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7371 N0.getValueType(), ExtLoad), 7372 ExtLoad.getValue(1)); 7373 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7374 } 7375 } 7376 7377 if (N0.getOpcode() == ISD::SETCC) { 7378 // For vectors: 7379 // aext(setcc) -> vsetcc 7380 // aext(setcc) -> truncate(vsetcc) 7381 // aext(setcc) -> aext(vsetcc) 7382 // Only do this before legalize for now. 7383 if (VT.isVector() && !LegalOperations) { 7384 EVT N0VT = N0.getOperand(0).getValueType(); 7385 // We know that the # elements of the results is the same as the 7386 // # elements of the compare (and the # elements of the compare result 7387 // for that matter). Check to see that they are the same size. If so, 7388 // we know that the element size of the sext'd result matches the 7389 // element size of the compare operands. 7390 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 7391 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 7392 N0.getOperand(1), 7393 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 7394 // If the desired elements are smaller or larger than the source 7395 // elements we can use a matching integer vector type and then 7396 // truncate/any extend 7397 else { 7398 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 7399 SDValue VsetCC = 7400 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 7401 N0.getOperand(1), 7402 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 7403 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 7404 } 7405 } 7406 7407 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 7408 SDLoc DL(N); 7409 if (SDValue SCC = SimplifySelectCC( 7410 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 7411 DAG.getConstant(0, DL, VT), 7412 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 7413 return SCC; 7414 } 7415 7416 return SDValue(); 7417 } 7418 7419 SDValue DAGCombiner::visitAssertZext(SDNode *N) { 7420 SDValue N0 = N->getOperand(0); 7421 SDValue N1 = N->getOperand(1); 7422 EVT EVT = cast<VTSDNode>(N1)->getVT(); 7423 7424 // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt) 7425 if (N0.getOpcode() == ISD::AssertZext && 7426 EVT == cast<VTSDNode>(N0.getOperand(1))->getVT()) 7427 return N0; 7428 7429 return SDValue(); 7430 } 7431 7432 /// See if the specified operand can be simplified with the knowledge that only 7433 /// the bits specified by Mask are used. If so, return the simpler operand, 7434 /// otherwise return a null SDValue. 7435 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 7436 switch (V.getOpcode()) { 7437 default: break; 7438 case ISD::Constant: { 7439 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 7440 assert(CV && "Const value should be ConstSDNode."); 7441 const APInt &CVal = CV->getAPIntValue(); 7442 APInt NewVal = CVal & Mask; 7443 if (NewVal != CVal) 7444 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 7445 break; 7446 } 7447 case ISD::OR: 7448 case ISD::XOR: 7449 // If the LHS or RHS don't contribute bits to the or, drop them. 7450 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 7451 return V.getOperand(1); 7452 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 7453 return V.getOperand(0); 7454 break; 7455 case ISD::SRL: 7456 // Only look at single-use SRLs. 7457 if (!V.getNode()->hasOneUse()) 7458 break; 7459 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 7460 // See if we can recursively simplify the LHS. 7461 unsigned Amt = RHSC->getZExtValue(); 7462 7463 // Watch out for shift count overflow though. 7464 if (Amt >= Mask.getBitWidth()) break; 7465 APInt NewMask = Mask << Amt; 7466 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 7467 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 7468 SimplifyLHS, V.getOperand(1)); 7469 } 7470 } 7471 return SDValue(); 7472 } 7473 7474 /// If the result of a wider load is shifted to right of N bits and then 7475 /// truncated to a narrower type and where N is a multiple of number of bits of 7476 /// the narrower type, transform it to a narrower load from address + N / num of 7477 /// bits of new type. If the result is to be extended, also fold the extension 7478 /// to form a extending load. 7479 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 7480 unsigned Opc = N->getOpcode(); 7481 7482 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 7483 SDValue N0 = N->getOperand(0); 7484 EVT VT = N->getValueType(0); 7485 EVT ExtVT = VT; 7486 7487 // This transformation isn't valid for vector loads. 7488 if (VT.isVector()) 7489 return SDValue(); 7490 7491 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 7492 // extended to VT. 7493 if (Opc == ISD::SIGN_EXTEND_INREG) { 7494 ExtType = ISD::SEXTLOAD; 7495 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 7496 } else if (Opc == ISD::SRL) { 7497 // Another special-case: SRL is basically zero-extending a narrower value. 7498 ExtType = ISD::ZEXTLOAD; 7499 N0 = SDValue(N, 0); 7500 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7501 if (!N01) return SDValue(); 7502 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 7503 VT.getSizeInBits() - N01->getZExtValue()); 7504 } 7505 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 7506 return SDValue(); 7507 7508 unsigned EVTBits = ExtVT.getSizeInBits(); 7509 7510 // Do not generate loads of non-round integer types since these can 7511 // be expensive (and would be wrong if the type is not byte sized). 7512 if (!ExtVT.isRound()) 7513 return SDValue(); 7514 7515 unsigned ShAmt = 0; 7516 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 7517 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 7518 ShAmt = N01->getZExtValue(); 7519 // Is the shift amount a multiple of size of VT? 7520 if ((ShAmt & (EVTBits-1)) == 0) { 7521 N0 = N0.getOperand(0); 7522 // Is the load width a multiple of size of VT? 7523 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0) 7524 return SDValue(); 7525 } 7526 7527 // At this point, we must have a load or else we can't do the transform. 7528 if (!isa<LoadSDNode>(N0)) return SDValue(); 7529 7530 // Because a SRL must be assumed to *need* to zero-extend the high bits 7531 // (as opposed to anyext the high bits), we can't combine the zextload 7532 // lowering of SRL and an sextload. 7533 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 7534 return SDValue(); 7535 7536 // If the shift amount is larger than the input type then we're not 7537 // accessing any of the loaded bytes. If the load was a zextload/extload 7538 // then the result of the shift+trunc is zero/undef (handled elsewhere). 7539 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 7540 return SDValue(); 7541 } 7542 } 7543 7544 // If the load is shifted left (and the result isn't shifted back right), 7545 // we can fold the truncate through the shift. 7546 unsigned ShLeftAmt = 0; 7547 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 7548 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 7549 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 7550 ShLeftAmt = N01->getZExtValue(); 7551 N0 = N0.getOperand(0); 7552 } 7553 } 7554 7555 // If we haven't found a load, we can't narrow it. Don't transform one with 7556 // multiple uses, this would require adding a new load. 7557 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 7558 return SDValue(); 7559 7560 // Don't change the width of a volatile load. 7561 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7562 if (LN0->isVolatile()) 7563 return SDValue(); 7564 7565 // Verify that we are actually reducing a load width here. 7566 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 7567 return SDValue(); 7568 7569 // For the transform to be legal, the load must produce only two values 7570 // (the value loaded and the chain). Don't transform a pre-increment 7571 // load, for example, which produces an extra value. Otherwise the 7572 // transformation is not equivalent, and the downstream logic to replace 7573 // uses gets things wrong. 7574 if (LN0->getNumValues() > 2) 7575 return SDValue(); 7576 7577 // If the load that we're shrinking is an extload and we're not just 7578 // discarding the extension we can't simply shrink the load. Bail. 7579 // TODO: It would be possible to merge the extensions in some cases. 7580 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 7581 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 7582 return SDValue(); 7583 7584 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 7585 return SDValue(); 7586 7587 EVT PtrType = N0.getOperand(1).getValueType(); 7588 7589 if (PtrType == MVT::Untyped || PtrType.isExtended()) 7590 // It's not possible to generate a constant of extended or untyped type. 7591 return SDValue(); 7592 7593 // For big endian targets, we need to adjust the offset to the pointer to 7594 // load the correct bytes. 7595 if (DAG.getDataLayout().isBigEndian()) { 7596 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 7597 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 7598 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 7599 } 7600 7601 uint64_t PtrOff = ShAmt / 8; 7602 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 7603 SDLoc DL(LN0); 7604 // The original load itself didn't wrap, so an offset within it doesn't. 7605 SDNodeFlags Flags; 7606 Flags.setNoUnsignedWrap(true); 7607 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 7608 PtrType, LN0->getBasePtr(), 7609 DAG.getConstant(PtrOff, DL, PtrType), 7610 &Flags); 7611 AddToWorklist(NewPtr.getNode()); 7612 7613 SDValue Load; 7614 if (ExtType == ISD::NON_EXTLOAD) 7615 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 7616 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 7617 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 7618 else 7619 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr, 7620 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 7621 NewAlign, LN0->getMemOperand()->getFlags(), 7622 LN0->getAAInfo()); 7623 7624 // Replace the old load's chain with the new load's chain. 7625 WorklistRemover DeadNodes(*this); 7626 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7627 7628 // Shift the result left, if we've swallowed a left shift. 7629 SDValue Result = Load; 7630 if (ShLeftAmt != 0) { 7631 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 7632 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 7633 ShImmTy = VT; 7634 // If the shift amount is as large as the result size (but, presumably, 7635 // no larger than the source) then the useful bits of the result are 7636 // zero; we can't simply return the shortened shift, because the result 7637 // of that operation is undefined. 7638 SDLoc DL(N0); 7639 if (ShLeftAmt >= VT.getSizeInBits()) 7640 Result = DAG.getConstant(0, DL, VT); 7641 else 7642 Result = DAG.getNode(ISD::SHL, DL, VT, 7643 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 7644 } 7645 7646 // Return the new loaded value. 7647 return Result; 7648 } 7649 7650 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 7651 SDValue N0 = N->getOperand(0); 7652 SDValue N1 = N->getOperand(1); 7653 EVT VT = N->getValueType(0); 7654 EVT EVT = cast<VTSDNode>(N1)->getVT(); 7655 unsigned VTBits = VT.getScalarSizeInBits(); 7656 unsigned EVTBits = EVT.getScalarSizeInBits(); 7657 7658 if (N0.isUndef()) 7659 return DAG.getUNDEF(VT); 7660 7661 // fold (sext_in_reg c1) -> c1 7662 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7663 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 7664 7665 // If the input is already sign extended, just drop the extension. 7666 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 7667 return N0; 7668 7669 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 7670 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 7671 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 7672 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 7673 N0.getOperand(0), N1); 7674 7675 // fold (sext_in_reg (sext x)) -> (sext x) 7676 // fold (sext_in_reg (aext x)) -> (sext x) 7677 // if x is small enough. 7678 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 7679 SDValue N00 = N0.getOperand(0); 7680 if (N00.getScalarValueSizeInBits() <= EVTBits && 7681 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 7682 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 7683 } 7684 7685 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x) 7686 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG || 7687 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG || 7688 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) && 7689 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) { 7690 if (!LegalOperations || 7691 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT)) 7692 return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT); 7693 } 7694 7695 // fold (sext_in_reg (zext x)) -> (sext x) 7696 // iff we are extending the source sign bit. 7697 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 7698 SDValue N00 = N0.getOperand(0); 7699 if (N00.getScalarValueSizeInBits() == EVTBits && 7700 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 7701 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 7702 } 7703 7704 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 7705 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1))) 7706 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType()); 7707 7708 // fold operands of sext_in_reg based on knowledge that the top bits are not 7709 // demanded. 7710 if (SimplifyDemandedBits(SDValue(N, 0))) 7711 return SDValue(N, 0); 7712 7713 // fold (sext_in_reg (load x)) -> (smaller sextload x) 7714 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 7715 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 7716 return NarrowLoad; 7717 7718 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 7719 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 7720 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 7721 if (N0.getOpcode() == ISD::SRL) { 7722 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 7723 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 7724 // We can turn this into an SRA iff the input to the SRL is already sign 7725 // extended enough. 7726 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 7727 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 7728 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 7729 N0.getOperand(0), N0.getOperand(1)); 7730 } 7731 } 7732 7733 // fold (sext_inreg (extload x)) -> (sextload x) 7734 if (ISD::isEXTLoad(N0.getNode()) && 7735 ISD::isUNINDEXEDLoad(N0.getNode()) && 7736 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 7737 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7738 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 7739 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7740 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 7741 LN0->getChain(), 7742 LN0->getBasePtr(), EVT, 7743 LN0->getMemOperand()); 7744 CombineTo(N, ExtLoad); 7745 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 7746 AddToWorklist(ExtLoad.getNode()); 7747 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7748 } 7749 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 7750 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7751 N0.hasOneUse() && 7752 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 7753 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7754 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 7755 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7756 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 7757 LN0->getChain(), 7758 LN0->getBasePtr(), EVT, 7759 LN0->getMemOperand()); 7760 CombineTo(N, ExtLoad); 7761 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 7762 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7763 } 7764 7765 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 7766 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 7767 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 7768 N0.getOperand(1), false)) 7769 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 7770 BSwap, N1); 7771 } 7772 7773 return SDValue(); 7774 } 7775 7776 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 7777 SDValue N0 = N->getOperand(0); 7778 EVT VT = N->getValueType(0); 7779 7780 if (N0.isUndef()) 7781 return DAG.getUNDEF(VT); 7782 7783 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7784 LegalOperations)) 7785 return SDValue(Res, 0); 7786 7787 return SDValue(); 7788 } 7789 7790 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 7791 SDValue N0 = N->getOperand(0); 7792 EVT VT = N->getValueType(0); 7793 7794 if (N0.isUndef()) 7795 return DAG.getUNDEF(VT); 7796 7797 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7798 LegalOperations)) 7799 return SDValue(Res, 0); 7800 7801 return SDValue(); 7802 } 7803 7804 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 7805 SDValue N0 = N->getOperand(0); 7806 EVT VT = N->getValueType(0); 7807 bool isLE = DAG.getDataLayout().isLittleEndian(); 7808 7809 // noop truncate 7810 if (N0.getValueType() == N->getValueType(0)) 7811 return N0; 7812 // fold (truncate c1) -> c1 7813 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7814 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 7815 // fold (truncate (truncate x)) -> (truncate x) 7816 if (N0.getOpcode() == ISD::TRUNCATE) 7817 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7818 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 7819 if (N0.getOpcode() == ISD::ZERO_EXTEND || 7820 N0.getOpcode() == ISD::SIGN_EXTEND || 7821 N0.getOpcode() == ISD::ANY_EXTEND) { 7822 // if the source is smaller than the dest, we still need an extend. 7823 if (N0.getOperand(0).getValueType().bitsLT(VT)) 7824 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7825 // if the source is larger than the dest, than we just need the truncate. 7826 if (N0.getOperand(0).getValueType().bitsGT(VT)) 7827 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7828 // if the source and dest are the same type, we can drop both the extend 7829 // and the truncate. 7830 return N0.getOperand(0); 7831 } 7832 7833 // If this is anyext(trunc), don't fold it, allow ourselves to be folded. 7834 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND)) 7835 return SDValue(); 7836 7837 // Fold extract-and-trunc into a narrow extract. For example: 7838 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 7839 // i32 y = TRUNCATE(i64 x) 7840 // -- becomes -- 7841 // v16i8 b = BITCAST (v2i64 val) 7842 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 7843 // 7844 // Note: We only run this optimization after type legalization (which often 7845 // creates this pattern) and before operation legalization after which 7846 // we need to be more careful about the vector instructions that we generate. 7847 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7848 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 7849 7850 EVT VecTy = N0.getOperand(0).getValueType(); 7851 EVT ExTy = N0.getValueType(); 7852 EVT TrTy = N->getValueType(0); 7853 7854 unsigned NumElem = VecTy.getVectorNumElements(); 7855 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 7856 7857 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 7858 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 7859 7860 SDValue EltNo = N0->getOperand(1); 7861 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 7862 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7863 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7864 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 7865 7866 SDLoc DL(N); 7867 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 7868 DAG.getBitcast(NVT, N0.getOperand(0)), 7869 DAG.getConstant(Index, DL, IndexTy)); 7870 } 7871 } 7872 7873 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 7874 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) { 7875 EVT SrcVT = N0.getValueType(); 7876 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 7877 TLI.isTruncateFree(SrcVT, VT)) { 7878 SDLoc SL(N0); 7879 SDValue Cond = N0.getOperand(0); 7880 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 7881 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 7882 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 7883 } 7884 } 7885 7886 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits() 7887 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 7888 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 7889 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 7890 if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) { 7891 uint64_t Amt = CAmt->getZExtValue(); 7892 unsigned Size = VT.getScalarSizeInBits(); 7893 7894 if (Amt < Size) { 7895 SDLoc SL(N); 7896 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 7897 7898 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 7899 return DAG.getNode(ISD::SHL, SL, VT, Trunc, 7900 DAG.getConstant(Amt, SL, AmtVT)); 7901 } 7902 } 7903 } 7904 7905 // Fold a series of buildvector, bitcast, and truncate if possible. 7906 // For example fold 7907 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 7908 // (2xi32 (buildvector x, y)). 7909 if (Level == AfterLegalizeVectorOps && VT.isVector() && 7910 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 7911 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 7912 N0.getOperand(0).hasOneUse()) { 7913 7914 SDValue BuildVect = N0.getOperand(0); 7915 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 7916 EVT TruncVecEltTy = VT.getVectorElementType(); 7917 7918 // Check that the element types match. 7919 if (BuildVectEltTy == TruncVecEltTy) { 7920 // Now we only need to compute the offset of the truncated elements. 7921 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 7922 unsigned TruncVecNumElts = VT.getVectorNumElements(); 7923 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 7924 7925 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 7926 "Invalid number of elements"); 7927 7928 SmallVector<SDValue, 8> Opnds; 7929 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 7930 Opnds.push_back(BuildVect.getOperand(i)); 7931 7932 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 7933 } 7934 } 7935 7936 // See if we can simplify the input to this truncate through knowledge that 7937 // only the low bits are being used. 7938 // For example "trunc (or (shl x, 8), y)" // -> trunc y 7939 // Currently we only perform this optimization on scalars because vectors 7940 // may have different active low bits. 7941 if (!VT.isVector()) { 7942 if (SDValue Shorter = 7943 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 7944 VT.getSizeInBits()))) 7945 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 7946 } 7947 7948 // fold (truncate (load x)) -> (smaller load x) 7949 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 7950 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 7951 if (SDValue Reduced = ReduceLoadWidth(N)) 7952 return Reduced; 7953 7954 // Handle the case where the load remains an extending load even 7955 // after truncation. 7956 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 7957 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7958 if (!LN0->isVolatile() && 7959 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 7960 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 7961 VT, LN0->getChain(), LN0->getBasePtr(), 7962 LN0->getMemoryVT(), 7963 LN0->getMemOperand()); 7964 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 7965 return NewLoad; 7966 } 7967 } 7968 } 7969 7970 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 7971 // where ... are all 'undef'. 7972 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 7973 SmallVector<EVT, 8> VTs; 7974 SDValue V; 7975 unsigned Idx = 0; 7976 unsigned NumDefs = 0; 7977 7978 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 7979 SDValue X = N0.getOperand(i); 7980 if (!X.isUndef()) { 7981 V = X; 7982 Idx = i; 7983 NumDefs++; 7984 } 7985 // Stop if more than one members are non-undef. 7986 if (NumDefs > 1) 7987 break; 7988 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 7989 VT.getVectorElementType(), 7990 X.getValueType().getVectorNumElements())); 7991 } 7992 7993 if (NumDefs == 0) 7994 return DAG.getUNDEF(VT); 7995 7996 if (NumDefs == 1) { 7997 assert(V.getNode() && "The single defined operand is empty!"); 7998 SmallVector<SDValue, 8> Opnds; 7999 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 8000 if (i != Idx) { 8001 Opnds.push_back(DAG.getUNDEF(VTs[i])); 8002 continue; 8003 } 8004 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 8005 AddToWorklist(NV.getNode()); 8006 Opnds.push_back(NV); 8007 } 8008 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 8009 } 8010 } 8011 8012 // Fold truncate of a bitcast of a vector to an extract of the low vector 8013 // element. 8014 // 8015 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0 8016 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 8017 SDValue VecSrc = N0.getOperand(0); 8018 EVT SrcVT = VecSrc.getValueType(); 8019 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 8020 (!LegalOperations || 8021 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 8022 SDLoc SL(N); 8023 8024 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 8025 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 8026 VecSrc, DAG.getConstant(0, SL, IdxVT)); 8027 } 8028 } 8029 8030 // Simplify the operands using demanded-bits information. 8031 if (!VT.isVector() && 8032 SimplifyDemandedBits(SDValue(N, 0))) 8033 return SDValue(N, 0); 8034 8035 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry) 8036 // When the adde's carry is not used. 8037 if (N0.getOpcode() == ISD::ADDE && N0.hasOneUse() && 8038 !N0.getNode()->hasAnyUseOfValue(1) && 8039 (!LegalOperations || TLI.isOperationLegal(ISD::ADDE, VT))) { 8040 SDLoc SL(N); 8041 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 8042 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 8043 return DAG.getNode(ISD::ADDE, SL, DAG.getVTList(VT, MVT::Glue), 8044 X, Y, N0.getOperand(2)); 8045 } 8046 8047 return SDValue(); 8048 } 8049 8050 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 8051 SDValue Elt = N->getOperand(i); 8052 if (Elt.getOpcode() != ISD::MERGE_VALUES) 8053 return Elt.getNode(); 8054 return Elt.getOperand(Elt.getResNo()).getNode(); 8055 } 8056 8057 /// build_pair (load, load) -> load 8058 /// if load locations are consecutive. 8059 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 8060 assert(N->getOpcode() == ISD::BUILD_PAIR); 8061 8062 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 8063 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 8064 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 8065 LD1->getAddressSpace() != LD2->getAddressSpace()) 8066 return SDValue(); 8067 EVT LD1VT = LD1->getValueType(0); 8068 unsigned LD1Bytes = LD1VT.getSizeInBits() / 8; 8069 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 8070 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 8071 unsigned Align = LD1->getAlignment(); 8072 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 8073 VT.getTypeForEVT(*DAG.getContext())); 8074 8075 if (NewAlign <= Align && 8076 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 8077 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 8078 LD1->getPointerInfo(), Align); 8079 } 8080 8081 return SDValue(); 8082 } 8083 8084 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 8085 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 8086 // and Lo parts; on big-endian machines it doesn't. 8087 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 8088 } 8089 8090 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 8091 const TargetLowering &TLI) { 8092 // If this is not a bitcast to an FP type or if the target doesn't have 8093 // IEEE754-compliant FP logic, we're done. 8094 EVT VT = N->getValueType(0); 8095 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 8096 return SDValue(); 8097 8098 // TODO: Use splat values for the constant-checking below and remove this 8099 // restriction. 8100 SDValue N0 = N->getOperand(0); 8101 EVT SourceVT = N0.getValueType(); 8102 if (SourceVT.isVector()) 8103 return SDValue(); 8104 8105 unsigned FPOpcode; 8106 APInt SignMask; 8107 switch (N0.getOpcode()) { 8108 case ISD::AND: 8109 FPOpcode = ISD::FABS; 8110 SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits()); 8111 break; 8112 case ISD::XOR: 8113 FPOpcode = ISD::FNEG; 8114 SignMask = APInt::getSignBit(SourceVT.getSizeInBits()); 8115 break; 8116 // TODO: ISD::OR --> ISD::FNABS? 8117 default: 8118 return SDValue(); 8119 } 8120 8121 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 8122 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 8123 SDValue LogicOp0 = N0.getOperand(0); 8124 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8125 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 8126 LogicOp0.getOpcode() == ISD::BITCAST && 8127 LogicOp0->getOperand(0).getValueType() == VT) 8128 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0)); 8129 8130 return SDValue(); 8131 } 8132 8133 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 8134 SDValue N0 = N->getOperand(0); 8135 EVT VT = N->getValueType(0); 8136 8137 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 8138 // Only do this before legalize, since afterward the target may be depending 8139 // on the bitconvert. 8140 // First check to see if this is all constant. 8141 if (!LegalTypes && 8142 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 8143 VT.isVector()) { 8144 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 8145 8146 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 8147 assert(!DestEltVT.isVector() && 8148 "Element type of vector ValueType must not be vector!"); 8149 if (isSimple) 8150 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 8151 } 8152 8153 // If the input is a constant, let getNode fold it. 8154 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 8155 // If we can't allow illegal operations, we need to check that this is just 8156 // a fp -> int or int -> conversion and that the resulting operation will 8157 // be legal. 8158 if (!LegalOperations || 8159 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 8160 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 8161 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 8162 TLI.isOperationLegal(ISD::Constant, VT))) 8163 return DAG.getBitcast(VT, N0); 8164 } 8165 8166 // (conv (conv x, t1), t2) -> (conv x, t2) 8167 if (N0.getOpcode() == ISD::BITCAST) 8168 return DAG.getBitcast(VT, N0.getOperand(0)); 8169 8170 // fold (conv (load x)) -> (load (conv*)x) 8171 // If the resultant load doesn't need a higher alignment than the original! 8172 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8173 // Do not change the width of a volatile load. 8174 !cast<LoadSDNode>(N0)->isVolatile() && 8175 // Do not remove the cast if the types differ in endian layout. 8176 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 8177 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 8178 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 8179 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 8180 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8181 unsigned OrigAlign = LN0->getAlignment(); 8182 8183 bool Fast = false; 8184 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 8185 LN0->getAddressSpace(), OrigAlign, &Fast) && 8186 Fast) { 8187 SDValue Load = 8188 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 8189 LN0->getPointerInfo(), OrigAlign, 8190 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8191 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 8192 return Load; 8193 } 8194 } 8195 8196 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 8197 return V; 8198 8199 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8200 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8201 // 8202 // For ppc_fp128: 8203 // fold (bitcast (fneg x)) -> 8204 // flipbit = signbit 8205 // (xor (bitcast x) (build_pair flipbit, flipbit)) 8206 // 8207 // fold (bitcast (fabs x)) -> 8208 // flipbit = (and (extract_element (bitcast x), 0), signbit) 8209 // (xor (bitcast x) (build_pair flipbit, flipbit)) 8210 // This often reduces constant pool loads. 8211 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 8212 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 8213 N0.getNode()->hasOneUse() && VT.isInteger() && 8214 !VT.isVector() && !N0.getValueType().isVector()) { 8215 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 8216 AddToWorklist(NewConv.getNode()); 8217 8218 SDLoc DL(N); 8219 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 8220 assert(VT.getSizeInBits() == 128); 8221 SDValue SignBit = DAG.getConstant( 8222 APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 8223 SDValue FlipBit; 8224 if (N0.getOpcode() == ISD::FNEG) { 8225 FlipBit = SignBit; 8226 AddToWorklist(FlipBit.getNode()); 8227 } else { 8228 assert(N0.getOpcode() == ISD::FABS); 8229 SDValue Hi = 8230 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 8231 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 8232 SDLoc(NewConv))); 8233 AddToWorklist(Hi.getNode()); 8234 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 8235 AddToWorklist(FlipBit.getNode()); 8236 } 8237 SDValue FlipBits = 8238 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 8239 AddToWorklist(FlipBits.getNode()); 8240 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 8241 } 8242 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 8243 if (N0.getOpcode() == ISD::FNEG) 8244 return DAG.getNode(ISD::XOR, DL, VT, 8245 NewConv, DAG.getConstant(SignBit, DL, VT)); 8246 assert(N0.getOpcode() == ISD::FABS); 8247 return DAG.getNode(ISD::AND, DL, VT, 8248 NewConv, DAG.getConstant(~SignBit, DL, VT)); 8249 } 8250 8251 // fold (bitconvert (fcopysign cst, x)) -> 8252 // (or (and (bitconvert x), sign), (and cst, (not sign))) 8253 // Note that we don't handle (copysign x, cst) because this can always be 8254 // folded to an fneg or fabs. 8255 // 8256 // For ppc_fp128: 8257 // fold (bitcast (fcopysign cst, x)) -> 8258 // flipbit = (and (extract_element 8259 // (xor (bitcast cst), (bitcast x)), 0), 8260 // signbit) 8261 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 8262 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 8263 isa<ConstantFPSDNode>(N0.getOperand(0)) && 8264 VT.isInteger() && !VT.isVector()) { 8265 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits(); 8266 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 8267 if (isTypeLegal(IntXVT)) { 8268 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 8269 AddToWorklist(X.getNode()); 8270 8271 // If X has a different width than the result/lhs, sext it or truncate it. 8272 unsigned VTWidth = VT.getSizeInBits(); 8273 if (OrigXWidth < VTWidth) { 8274 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 8275 AddToWorklist(X.getNode()); 8276 } else if (OrigXWidth > VTWidth) { 8277 // To get the sign bit in the right place, we have to shift it right 8278 // before truncating. 8279 SDLoc DL(X); 8280 X = DAG.getNode(ISD::SRL, DL, 8281 X.getValueType(), X, 8282 DAG.getConstant(OrigXWidth-VTWidth, DL, 8283 X.getValueType())); 8284 AddToWorklist(X.getNode()); 8285 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 8286 AddToWorklist(X.getNode()); 8287 } 8288 8289 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 8290 APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2); 8291 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 8292 AddToWorklist(Cst.getNode()); 8293 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 8294 AddToWorklist(X.getNode()); 8295 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 8296 AddToWorklist(XorResult.getNode()); 8297 SDValue XorResult64 = DAG.getNode( 8298 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 8299 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 8300 SDLoc(XorResult))); 8301 AddToWorklist(XorResult64.getNode()); 8302 SDValue FlipBit = 8303 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 8304 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 8305 AddToWorklist(FlipBit.getNode()); 8306 SDValue FlipBits = 8307 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 8308 AddToWorklist(FlipBits.getNode()); 8309 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 8310 } 8311 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 8312 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 8313 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 8314 AddToWorklist(X.getNode()); 8315 8316 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 8317 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 8318 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 8319 AddToWorklist(Cst.getNode()); 8320 8321 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 8322 } 8323 } 8324 8325 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 8326 if (N0.getOpcode() == ISD::BUILD_PAIR) 8327 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 8328 return CombineLD; 8329 8330 // Remove double bitcasts from shuffles - this is often a legacy of 8331 // XformToShuffleWithZero being used to combine bitmaskings (of 8332 // float vectors bitcast to integer vectors) into shuffles. 8333 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 8334 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 8335 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 8336 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 8337 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 8338 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 8339 8340 // If operands are a bitcast, peek through if it casts the original VT. 8341 // If operands are a constant, just bitcast back to original VT. 8342 auto PeekThroughBitcast = [&](SDValue Op) { 8343 if (Op.getOpcode() == ISD::BITCAST && 8344 Op.getOperand(0).getValueType() == VT) 8345 return SDValue(Op.getOperand(0)); 8346 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 8347 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 8348 return DAG.getBitcast(VT, Op); 8349 return SDValue(); 8350 }; 8351 8352 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 8353 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 8354 if (!(SV0 && SV1)) 8355 return SDValue(); 8356 8357 int MaskScale = 8358 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 8359 SmallVector<int, 8> NewMask; 8360 for (int M : SVN->getMask()) 8361 for (int i = 0; i != MaskScale; ++i) 8362 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 8363 8364 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 8365 if (!LegalMask) { 8366 std::swap(SV0, SV1); 8367 ShuffleVectorSDNode::commuteMask(NewMask); 8368 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 8369 } 8370 8371 if (LegalMask) 8372 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 8373 } 8374 8375 return SDValue(); 8376 } 8377 8378 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 8379 EVT VT = N->getValueType(0); 8380 return CombineConsecutiveLoads(N, VT); 8381 } 8382 8383 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 8384 /// operands. DstEltVT indicates the destination element value type. 8385 SDValue DAGCombiner:: 8386 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 8387 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 8388 8389 // If this is already the right type, we're done. 8390 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 8391 8392 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 8393 unsigned DstBitSize = DstEltVT.getSizeInBits(); 8394 8395 // If this is a conversion of N elements of one type to N elements of another 8396 // type, convert each element. This handles FP<->INT cases. 8397 if (SrcBitSize == DstBitSize) { 8398 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 8399 BV->getValueType(0).getVectorNumElements()); 8400 8401 // Due to the FP element handling below calling this routine recursively, 8402 // we can end up with a scalar-to-vector node here. 8403 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 8404 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 8405 DAG.getBitcast(DstEltVT, BV->getOperand(0))); 8406 8407 SmallVector<SDValue, 8> Ops; 8408 for (SDValue Op : BV->op_values()) { 8409 // If the vector element type is not legal, the BUILD_VECTOR operands 8410 // are promoted and implicitly truncated. Make that explicit here. 8411 if (Op.getValueType() != SrcEltVT) 8412 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 8413 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 8414 AddToWorklist(Ops.back().getNode()); 8415 } 8416 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 8417 } 8418 8419 // Otherwise, we're growing or shrinking the elements. To avoid having to 8420 // handle annoying details of growing/shrinking FP values, we convert them to 8421 // int first. 8422 if (SrcEltVT.isFloatingPoint()) { 8423 // Convert the input float vector to a int vector where the elements are the 8424 // same sizes. 8425 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 8426 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 8427 SrcEltVT = IntVT; 8428 } 8429 8430 // Now we know the input is an integer vector. If the output is a FP type, 8431 // convert to integer first, then to FP of the right size. 8432 if (DstEltVT.isFloatingPoint()) { 8433 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 8434 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 8435 8436 // Next, convert to FP elements of the same size. 8437 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 8438 } 8439 8440 SDLoc DL(BV); 8441 8442 // Okay, we know the src/dst types are both integers of differing types. 8443 // Handling growing first. 8444 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 8445 if (SrcBitSize < DstBitSize) { 8446 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 8447 8448 SmallVector<SDValue, 8> Ops; 8449 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 8450 i += NumInputsPerOutput) { 8451 bool isLE = DAG.getDataLayout().isLittleEndian(); 8452 APInt NewBits = APInt(DstBitSize, 0); 8453 bool EltIsUndef = true; 8454 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 8455 // Shift the previously computed bits over. 8456 NewBits <<= SrcBitSize; 8457 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 8458 if (Op.isUndef()) continue; 8459 EltIsUndef = false; 8460 8461 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 8462 zextOrTrunc(SrcBitSize).zext(DstBitSize); 8463 } 8464 8465 if (EltIsUndef) 8466 Ops.push_back(DAG.getUNDEF(DstEltVT)); 8467 else 8468 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 8469 } 8470 8471 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 8472 return DAG.getBuildVector(VT, DL, Ops); 8473 } 8474 8475 // Finally, this must be the case where we are shrinking elements: each input 8476 // turns into multiple outputs. 8477 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 8478 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 8479 NumOutputsPerInput*BV->getNumOperands()); 8480 SmallVector<SDValue, 8> Ops; 8481 8482 for (const SDValue &Op : BV->op_values()) { 8483 if (Op.isUndef()) { 8484 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 8485 continue; 8486 } 8487 8488 APInt OpVal = cast<ConstantSDNode>(Op)-> 8489 getAPIntValue().zextOrTrunc(SrcBitSize); 8490 8491 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 8492 APInt ThisVal = OpVal.trunc(DstBitSize); 8493 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 8494 OpVal = OpVal.lshr(DstBitSize); 8495 } 8496 8497 // For big endian targets, swap the order of the pieces of each element. 8498 if (DAG.getDataLayout().isBigEndian()) 8499 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 8500 } 8501 8502 return DAG.getBuildVector(VT, DL, Ops); 8503 } 8504 8505 /// Try to perform FMA combining on a given FADD node. 8506 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 8507 SDValue N0 = N->getOperand(0); 8508 SDValue N1 = N->getOperand(1); 8509 EVT VT = N->getValueType(0); 8510 SDLoc SL(N); 8511 8512 const TargetOptions &Options = DAG.getTarget().Options; 8513 bool AllowFusion = 8514 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 8515 8516 // Floating-point multiply-add with intermediate rounding. 8517 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8518 8519 // Floating-point multiply-add without intermediate rounding. 8520 bool HasFMA = 8521 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 8522 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8523 8524 // No valid opcode, do not combine. 8525 if (!HasFMAD && !HasFMA) 8526 return SDValue(); 8527 8528 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 8529 ; 8530 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel)) 8531 return SDValue(); 8532 8533 // Always prefer FMAD to FMA for precision. 8534 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8535 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8536 bool LookThroughFPExt = TLI.isFPExtFree(VT); 8537 8538 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 8539 // prefer to fold the multiply with fewer uses. 8540 if (Aggressive && N0.getOpcode() == ISD::FMUL && 8541 N1.getOpcode() == ISD::FMUL) { 8542 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 8543 std::swap(N0, N1); 8544 } 8545 8546 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 8547 if (N0.getOpcode() == ISD::FMUL && 8548 (Aggressive || N0->hasOneUse())) { 8549 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8550 N0.getOperand(0), N0.getOperand(1), N1); 8551 } 8552 8553 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 8554 // Note: Commutes FADD operands. 8555 if (N1.getOpcode() == ISD::FMUL && 8556 (Aggressive || N1->hasOneUse())) { 8557 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8558 N1.getOperand(0), N1.getOperand(1), N0); 8559 } 8560 8561 // Look through FP_EXTEND nodes to do more combining. 8562 if (AllowFusion && LookThroughFPExt) { 8563 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 8564 if (N0.getOpcode() == ISD::FP_EXTEND) { 8565 SDValue N00 = N0.getOperand(0); 8566 if (N00.getOpcode() == ISD::FMUL) 8567 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8568 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8569 N00.getOperand(0)), 8570 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8571 N00.getOperand(1)), N1); 8572 } 8573 8574 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 8575 // Note: Commutes FADD operands. 8576 if (N1.getOpcode() == ISD::FP_EXTEND) { 8577 SDValue N10 = N1.getOperand(0); 8578 if (N10.getOpcode() == ISD::FMUL) 8579 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8580 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8581 N10.getOperand(0)), 8582 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8583 N10.getOperand(1)), N0); 8584 } 8585 } 8586 8587 // More folding opportunities when target permits. 8588 if (Aggressive) { 8589 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 8590 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 8591 // are currently only supported on binary nodes. 8592 if (Options.UnsafeFPMath && 8593 N0.getOpcode() == PreferredFusedOpcode && 8594 N0.getOperand(2).getOpcode() == ISD::FMUL && 8595 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) { 8596 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8597 N0.getOperand(0), N0.getOperand(1), 8598 DAG.getNode(PreferredFusedOpcode, SL, VT, 8599 N0.getOperand(2).getOperand(0), 8600 N0.getOperand(2).getOperand(1), 8601 N1)); 8602 } 8603 8604 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 8605 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 8606 // are currently only supported on binary nodes. 8607 if (Options.UnsafeFPMath && 8608 N1->getOpcode() == PreferredFusedOpcode && 8609 N1.getOperand(2).getOpcode() == ISD::FMUL && 8610 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) { 8611 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8612 N1.getOperand(0), N1.getOperand(1), 8613 DAG.getNode(PreferredFusedOpcode, SL, VT, 8614 N1.getOperand(2).getOperand(0), 8615 N1.getOperand(2).getOperand(1), 8616 N0)); 8617 } 8618 8619 if (AllowFusion && LookThroughFPExt) { 8620 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 8621 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 8622 auto FoldFAddFMAFPExtFMul = [&] ( 8623 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 8624 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 8625 DAG.getNode(PreferredFusedOpcode, SL, VT, 8626 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 8627 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 8628 Z)); 8629 }; 8630 if (N0.getOpcode() == PreferredFusedOpcode) { 8631 SDValue N02 = N0.getOperand(2); 8632 if (N02.getOpcode() == ISD::FP_EXTEND) { 8633 SDValue N020 = N02.getOperand(0); 8634 if (N020.getOpcode() == ISD::FMUL) 8635 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 8636 N020.getOperand(0), N020.getOperand(1), 8637 N1); 8638 } 8639 } 8640 8641 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 8642 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 8643 // FIXME: This turns two single-precision and one double-precision 8644 // operation into two double-precision operations, which might not be 8645 // interesting for all targets, especially GPUs. 8646 auto FoldFAddFPExtFMAFMul = [&] ( 8647 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 8648 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8649 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 8650 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 8651 DAG.getNode(PreferredFusedOpcode, SL, VT, 8652 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 8653 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 8654 Z)); 8655 }; 8656 if (N0.getOpcode() == ISD::FP_EXTEND) { 8657 SDValue N00 = N0.getOperand(0); 8658 if (N00.getOpcode() == PreferredFusedOpcode) { 8659 SDValue N002 = N00.getOperand(2); 8660 if (N002.getOpcode() == ISD::FMUL) 8661 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 8662 N002.getOperand(0), N002.getOperand(1), 8663 N1); 8664 } 8665 } 8666 8667 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 8668 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 8669 if (N1.getOpcode() == PreferredFusedOpcode) { 8670 SDValue N12 = N1.getOperand(2); 8671 if (N12.getOpcode() == ISD::FP_EXTEND) { 8672 SDValue N120 = N12.getOperand(0); 8673 if (N120.getOpcode() == ISD::FMUL) 8674 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 8675 N120.getOperand(0), N120.getOperand(1), 8676 N0); 8677 } 8678 } 8679 8680 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 8681 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 8682 // FIXME: This turns two single-precision and one double-precision 8683 // operation into two double-precision operations, which might not be 8684 // interesting for all targets, especially GPUs. 8685 if (N1.getOpcode() == ISD::FP_EXTEND) { 8686 SDValue N10 = N1.getOperand(0); 8687 if (N10.getOpcode() == PreferredFusedOpcode) { 8688 SDValue N102 = N10.getOperand(2); 8689 if (N102.getOpcode() == ISD::FMUL) 8690 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 8691 N102.getOperand(0), N102.getOperand(1), 8692 N0); 8693 } 8694 } 8695 } 8696 } 8697 8698 return SDValue(); 8699 } 8700 8701 /// Try to perform FMA combining on a given FSUB node. 8702 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 8703 SDValue N0 = N->getOperand(0); 8704 SDValue N1 = N->getOperand(1); 8705 EVT VT = N->getValueType(0); 8706 SDLoc SL(N); 8707 8708 const TargetOptions &Options = DAG.getTarget().Options; 8709 bool AllowFusion = 8710 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 8711 8712 // Floating-point multiply-add with intermediate rounding. 8713 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8714 8715 // Floating-point multiply-add without intermediate rounding. 8716 bool HasFMA = 8717 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 8718 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8719 8720 // No valid opcode, do not combine. 8721 if (!HasFMAD && !HasFMA) 8722 return SDValue(); 8723 8724 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 8725 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel)) 8726 return SDValue(); 8727 8728 // Always prefer FMAD to FMA for precision. 8729 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8730 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8731 bool LookThroughFPExt = TLI.isFPExtFree(VT); 8732 8733 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 8734 if (N0.getOpcode() == ISD::FMUL && 8735 (Aggressive || N0->hasOneUse())) { 8736 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8737 N0.getOperand(0), N0.getOperand(1), 8738 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8739 } 8740 8741 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 8742 // Note: Commutes FSUB operands. 8743 if (N1.getOpcode() == ISD::FMUL && 8744 (Aggressive || N1->hasOneUse())) 8745 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8746 DAG.getNode(ISD::FNEG, SL, VT, 8747 N1.getOperand(0)), 8748 N1.getOperand(1), N0); 8749 8750 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 8751 if (N0.getOpcode() == ISD::FNEG && 8752 N0.getOperand(0).getOpcode() == ISD::FMUL && 8753 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 8754 SDValue N00 = N0.getOperand(0).getOperand(0); 8755 SDValue N01 = N0.getOperand(0).getOperand(1); 8756 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8757 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 8758 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8759 } 8760 8761 // Look through FP_EXTEND nodes to do more combining. 8762 if (AllowFusion && LookThroughFPExt) { 8763 // fold (fsub (fpext (fmul x, y)), z) 8764 // -> (fma (fpext x), (fpext y), (fneg z)) 8765 if (N0.getOpcode() == ISD::FP_EXTEND) { 8766 SDValue N00 = N0.getOperand(0); 8767 if (N00.getOpcode() == ISD::FMUL) 8768 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8769 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8770 N00.getOperand(0)), 8771 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8772 N00.getOperand(1)), 8773 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8774 } 8775 8776 // fold (fsub x, (fpext (fmul y, z))) 8777 // -> (fma (fneg (fpext y)), (fpext z), x) 8778 // Note: Commutes FSUB operands. 8779 if (N1.getOpcode() == ISD::FP_EXTEND) { 8780 SDValue N10 = N1.getOperand(0); 8781 if (N10.getOpcode() == ISD::FMUL) 8782 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8783 DAG.getNode(ISD::FNEG, SL, VT, 8784 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8785 N10.getOperand(0))), 8786 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8787 N10.getOperand(1)), 8788 N0); 8789 } 8790 8791 // fold (fsub (fpext (fneg (fmul, x, y))), z) 8792 // -> (fneg (fma (fpext x), (fpext y), z)) 8793 // Note: This could be removed with appropriate canonicalization of the 8794 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 8795 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 8796 // from implementing the canonicalization in visitFSUB. 8797 if (N0.getOpcode() == ISD::FP_EXTEND) { 8798 SDValue N00 = N0.getOperand(0); 8799 if (N00.getOpcode() == ISD::FNEG) { 8800 SDValue N000 = N00.getOperand(0); 8801 if (N000.getOpcode() == ISD::FMUL) { 8802 return DAG.getNode(ISD::FNEG, SL, VT, 8803 DAG.getNode(PreferredFusedOpcode, SL, VT, 8804 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8805 N000.getOperand(0)), 8806 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8807 N000.getOperand(1)), 8808 N1)); 8809 } 8810 } 8811 } 8812 8813 // fold (fsub (fneg (fpext (fmul, x, y))), z) 8814 // -> (fneg (fma (fpext x)), (fpext y), z) 8815 // Note: This could be removed with appropriate canonicalization of the 8816 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 8817 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 8818 // from implementing the canonicalization in visitFSUB. 8819 if (N0.getOpcode() == ISD::FNEG) { 8820 SDValue N00 = N0.getOperand(0); 8821 if (N00.getOpcode() == ISD::FP_EXTEND) { 8822 SDValue N000 = N00.getOperand(0); 8823 if (N000.getOpcode() == ISD::FMUL) { 8824 return DAG.getNode(ISD::FNEG, SL, VT, 8825 DAG.getNode(PreferredFusedOpcode, SL, VT, 8826 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8827 N000.getOperand(0)), 8828 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8829 N000.getOperand(1)), 8830 N1)); 8831 } 8832 } 8833 } 8834 8835 } 8836 8837 // More folding opportunities when target permits. 8838 if (Aggressive) { 8839 // fold (fsub (fma x, y, (fmul u, v)), z) 8840 // -> (fma x, y (fma u, v, (fneg z))) 8841 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 8842 // are currently only supported on binary nodes. 8843 if (Options.UnsafeFPMath && 8844 N0.getOpcode() == PreferredFusedOpcode && 8845 N0.getOperand(2).getOpcode() == ISD::FMUL && 8846 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) { 8847 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8848 N0.getOperand(0), N0.getOperand(1), 8849 DAG.getNode(PreferredFusedOpcode, SL, VT, 8850 N0.getOperand(2).getOperand(0), 8851 N0.getOperand(2).getOperand(1), 8852 DAG.getNode(ISD::FNEG, SL, VT, 8853 N1))); 8854 } 8855 8856 // fold (fsub x, (fma y, z, (fmul u, v))) 8857 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 8858 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 8859 // are currently only supported on binary nodes. 8860 if (Options.UnsafeFPMath && 8861 N1.getOpcode() == PreferredFusedOpcode && 8862 N1.getOperand(2).getOpcode() == ISD::FMUL) { 8863 SDValue N20 = N1.getOperand(2).getOperand(0); 8864 SDValue N21 = N1.getOperand(2).getOperand(1); 8865 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8866 DAG.getNode(ISD::FNEG, SL, VT, 8867 N1.getOperand(0)), 8868 N1.getOperand(1), 8869 DAG.getNode(PreferredFusedOpcode, SL, VT, 8870 DAG.getNode(ISD::FNEG, SL, VT, N20), 8871 8872 N21, N0)); 8873 } 8874 8875 if (AllowFusion && LookThroughFPExt) { 8876 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 8877 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 8878 if (N0.getOpcode() == PreferredFusedOpcode) { 8879 SDValue N02 = N0.getOperand(2); 8880 if (N02.getOpcode() == ISD::FP_EXTEND) { 8881 SDValue N020 = N02.getOperand(0); 8882 if (N020.getOpcode() == ISD::FMUL) 8883 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8884 N0.getOperand(0), N0.getOperand(1), 8885 DAG.getNode(PreferredFusedOpcode, SL, VT, 8886 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8887 N020.getOperand(0)), 8888 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8889 N020.getOperand(1)), 8890 DAG.getNode(ISD::FNEG, SL, VT, 8891 N1))); 8892 } 8893 } 8894 8895 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 8896 // -> (fma (fpext x), (fpext y), 8897 // (fma (fpext u), (fpext v), (fneg z))) 8898 // FIXME: This turns two single-precision and one double-precision 8899 // operation into two double-precision operations, which might not be 8900 // interesting for all targets, especially GPUs. 8901 if (N0.getOpcode() == ISD::FP_EXTEND) { 8902 SDValue N00 = N0.getOperand(0); 8903 if (N00.getOpcode() == PreferredFusedOpcode) { 8904 SDValue N002 = N00.getOperand(2); 8905 if (N002.getOpcode() == ISD::FMUL) 8906 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8907 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8908 N00.getOperand(0)), 8909 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8910 N00.getOperand(1)), 8911 DAG.getNode(PreferredFusedOpcode, SL, VT, 8912 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8913 N002.getOperand(0)), 8914 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8915 N002.getOperand(1)), 8916 DAG.getNode(ISD::FNEG, SL, VT, 8917 N1))); 8918 } 8919 } 8920 8921 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 8922 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 8923 if (N1.getOpcode() == PreferredFusedOpcode && 8924 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 8925 SDValue N120 = N1.getOperand(2).getOperand(0); 8926 if (N120.getOpcode() == ISD::FMUL) { 8927 SDValue N1200 = N120.getOperand(0); 8928 SDValue N1201 = N120.getOperand(1); 8929 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8930 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 8931 N1.getOperand(1), 8932 DAG.getNode(PreferredFusedOpcode, SL, VT, 8933 DAG.getNode(ISD::FNEG, SL, VT, 8934 DAG.getNode(ISD::FP_EXTEND, SL, 8935 VT, N1200)), 8936 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8937 N1201), 8938 N0)); 8939 } 8940 } 8941 8942 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 8943 // -> (fma (fneg (fpext y)), (fpext z), 8944 // (fma (fneg (fpext u)), (fpext v), x)) 8945 // FIXME: This turns two single-precision and one double-precision 8946 // operation into two double-precision operations, which might not be 8947 // interesting for all targets, especially GPUs. 8948 if (N1.getOpcode() == ISD::FP_EXTEND && 8949 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 8950 SDValue N100 = N1.getOperand(0).getOperand(0); 8951 SDValue N101 = N1.getOperand(0).getOperand(1); 8952 SDValue N102 = N1.getOperand(0).getOperand(2); 8953 if (N102.getOpcode() == ISD::FMUL) { 8954 SDValue N1020 = N102.getOperand(0); 8955 SDValue N1021 = N102.getOperand(1); 8956 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8957 DAG.getNode(ISD::FNEG, SL, VT, 8958 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8959 N100)), 8960 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 8961 DAG.getNode(PreferredFusedOpcode, SL, VT, 8962 DAG.getNode(ISD::FNEG, SL, VT, 8963 DAG.getNode(ISD::FP_EXTEND, SL, 8964 VT, N1020)), 8965 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8966 N1021), 8967 N0)); 8968 } 8969 } 8970 } 8971 } 8972 8973 return SDValue(); 8974 } 8975 8976 /// Try to perform FMA combining on a given FMUL node based on the distributive 8977 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions, 8978 /// subtraction instead of addition). 8979 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) { 8980 SDValue N0 = N->getOperand(0); 8981 SDValue N1 = N->getOperand(1); 8982 EVT VT = N->getValueType(0); 8983 SDLoc SL(N); 8984 8985 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 8986 8987 const TargetOptions &Options = DAG.getTarget().Options; 8988 8989 // The transforms below are incorrect when x == 0 and y == inf, because the 8990 // intermediate multiplication produces a nan. 8991 if (!Options.NoInfsFPMath) 8992 return SDValue(); 8993 8994 // Floating-point multiply-add without intermediate rounding. 8995 bool HasFMA = 8996 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 8997 TLI.isFMAFasterThanFMulAndFAdd(VT) && 8998 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8999 9000 // Floating-point multiply-add with intermediate rounding. This can result 9001 // in a less precise result due to the changed rounding order. 9002 bool HasFMAD = Options.UnsafeFPMath && 9003 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9004 9005 // No valid opcode, do not combine. 9006 if (!HasFMAD && !HasFMA) 9007 return SDValue(); 9008 9009 // Always prefer FMAD to FMA for precision. 9010 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9011 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9012 9013 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 9014 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 9015 auto FuseFADD = [&](SDValue X, SDValue Y) { 9016 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 9017 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 9018 if (XC1 && XC1->isExactlyValue(+1.0)) 9019 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 9020 if (XC1 && XC1->isExactlyValue(-1.0)) 9021 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 9022 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9023 } 9024 return SDValue(); 9025 }; 9026 9027 if (SDValue FMA = FuseFADD(N0, N1)) 9028 return FMA; 9029 if (SDValue FMA = FuseFADD(N1, N0)) 9030 return FMA; 9031 9032 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 9033 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 9034 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 9035 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 9036 auto FuseFSUB = [&](SDValue X, SDValue Y) { 9037 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 9038 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 9039 if (XC0 && XC0->isExactlyValue(+1.0)) 9040 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9041 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 9042 Y); 9043 if (XC0 && XC0->isExactlyValue(-1.0)) 9044 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9045 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 9046 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9047 9048 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 9049 if (XC1 && XC1->isExactlyValue(+1.0)) 9050 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 9051 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9052 if (XC1 && XC1->isExactlyValue(-1.0)) 9053 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 9054 } 9055 return SDValue(); 9056 }; 9057 9058 if (SDValue FMA = FuseFSUB(N0, N1)) 9059 return FMA; 9060 if (SDValue FMA = FuseFSUB(N1, N0)) 9061 return FMA; 9062 9063 return SDValue(); 9064 } 9065 9066 SDValue DAGCombiner::visitFADD(SDNode *N) { 9067 SDValue N0 = N->getOperand(0); 9068 SDValue N1 = N->getOperand(1); 9069 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 9070 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 9071 EVT VT = N->getValueType(0); 9072 SDLoc DL(N); 9073 const TargetOptions &Options = DAG.getTarget().Options; 9074 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 9075 9076 // fold vector ops 9077 if (VT.isVector()) 9078 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9079 return FoldedVOp; 9080 9081 // fold (fadd c1, c2) -> c1 + c2 9082 if (N0CFP && N1CFP) 9083 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 9084 9085 // canonicalize constant to RHS 9086 if (N0CFP && !N1CFP) 9087 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 9088 9089 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9090 return NewSel; 9091 9092 // fold (fadd A, (fneg B)) -> (fsub A, B) 9093 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 9094 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 9095 return DAG.getNode(ISD::FSUB, DL, VT, N0, 9096 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 9097 9098 // fold (fadd (fneg A), B) -> (fsub B, A) 9099 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 9100 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 9101 return DAG.getNode(ISD::FSUB, DL, VT, N1, 9102 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 9103 9104 // FIXME: Auto-upgrade the target/function-level option. 9105 if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) { 9106 // fold (fadd A, 0) -> A 9107 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 9108 if (N1C->isZero()) 9109 return N0; 9110 } 9111 9112 // If 'unsafe math' is enabled, fold lots of things. 9113 if (Options.UnsafeFPMath) { 9114 // No FP constant should be created after legalization as Instruction 9115 // Selection pass has a hard time dealing with FP constants. 9116 bool AllowNewConst = (Level < AfterLegalizeDAG); 9117 9118 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 9119 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 9120 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 9121 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 9122 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 9123 Flags), 9124 Flags); 9125 9126 // If allowed, fold (fadd (fneg x), x) -> 0.0 9127 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 9128 return DAG.getConstantFP(0.0, DL, VT); 9129 9130 // If allowed, fold (fadd x, (fneg x)) -> 0.0 9131 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 9132 return DAG.getConstantFP(0.0, DL, VT); 9133 9134 // We can fold chains of FADD's of the same value into multiplications. 9135 // This transform is not safe in general because we are reducing the number 9136 // of rounding steps. 9137 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 9138 if (N0.getOpcode() == ISD::FMUL) { 9139 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 9140 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 9141 9142 // (fadd (fmul x, c), x) -> (fmul x, c+1) 9143 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 9144 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 9145 DAG.getConstantFP(1.0, DL, VT), Flags); 9146 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 9147 } 9148 9149 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 9150 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 9151 N1.getOperand(0) == N1.getOperand(1) && 9152 N0.getOperand(0) == N1.getOperand(0)) { 9153 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 9154 DAG.getConstantFP(2.0, DL, VT), Flags); 9155 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 9156 } 9157 } 9158 9159 if (N1.getOpcode() == ISD::FMUL) { 9160 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 9161 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 9162 9163 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 9164 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 9165 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 9166 DAG.getConstantFP(1.0, DL, VT), Flags); 9167 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 9168 } 9169 9170 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 9171 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 9172 N0.getOperand(0) == N0.getOperand(1) && 9173 N1.getOperand(0) == N0.getOperand(0)) { 9174 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 9175 DAG.getConstantFP(2.0, DL, VT), Flags); 9176 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 9177 } 9178 } 9179 9180 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 9181 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 9182 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 9183 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 9184 (N0.getOperand(0) == N1)) { 9185 return DAG.getNode(ISD::FMUL, DL, VT, 9186 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 9187 } 9188 } 9189 9190 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 9191 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 9192 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 9193 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 9194 N1.getOperand(0) == N0) { 9195 return DAG.getNode(ISD::FMUL, DL, VT, 9196 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 9197 } 9198 } 9199 9200 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 9201 if (AllowNewConst && 9202 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 9203 N0.getOperand(0) == N0.getOperand(1) && 9204 N1.getOperand(0) == N1.getOperand(1) && 9205 N0.getOperand(0) == N1.getOperand(0)) { 9206 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 9207 DAG.getConstantFP(4.0, DL, VT), Flags); 9208 } 9209 } 9210 } // enable-unsafe-fp-math 9211 9212 // FADD -> FMA combines: 9213 if (SDValue Fused = visitFADDForFMACombine(N)) { 9214 AddToWorklist(Fused.getNode()); 9215 return Fused; 9216 } 9217 return SDValue(); 9218 } 9219 9220 SDValue DAGCombiner::visitFSUB(SDNode *N) { 9221 SDValue N0 = N->getOperand(0); 9222 SDValue N1 = N->getOperand(1); 9223 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9224 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9225 EVT VT = N->getValueType(0); 9226 SDLoc DL(N); 9227 const TargetOptions &Options = DAG.getTarget().Options; 9228 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 9229 9230 // fold vector ops 9231 if (VT.isVector()) 9232 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9233 return FoldedVOp; 9234 9235 // fold (fsub c1, c2) -> c1-c2 9236 if (N0CFP && N1CFP) 9237 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags); 9238 9239 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9240 return NewSel; 9241 9242 // fold (fsub A, (fneg B)) -> (fadd A, B) 9243 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 9244 return DAG.getNode(ISD::FADD, DL, VT, N0, 9245 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 9246 9247 // FIXME: Auto-upgrade the target/function-level option. 9248 if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) { 9249 // (fsub 0, B) -> -B 9250 if (N0CFP && N0CFP->isZero()) { 9251 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 9252 return GetNegatedExpression(N1, DAG, LegalOperations); 9253 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9254 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags); 9255 } 9256 } 9257 9258 // If 'unsafe math' is enabled, fold lots of things. 9259 if (Options.UnsafeFPMath) { 9260 // (fsub A, 0) -> A 9261 if (N1CFP && N1CFP->isZero()) 9262 return N0; 9263 9264 // (fsub x, x) -> 0.0 9265 if (N0 == N1) 9266 return DAG.getConstantFP(0.0f, DL, VT); 9267 9268 // (fsub x, (fadd x, y)) -> (fneg y) 9269 // (fsub x, (fadd y, x)) -> (fneg y) 9270 if (N1.getOpcode() == ISD::FADD) { 9271 SDValue N10 = N1->getOperand(0); 9272 SDValue N11 = N1->getOperand(1); 9273 9274 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 9275 return GetNegatedExpression(N11, DAG, LegalOperations); 9276 9277 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 9278 return GetNegatedExpression(N10, DAG, LegalOperations); 9279 } 9280 } 9281 9282 // FSUB -> FMA combines: 9283 if (SDValue Fused = visitFSUBForFMACombine(N)) { 9284 AddToWorklist(Fused.getNode()); 9285 return Fused; 9286 } 9287 9288 return SDValue(); 9289 } 9290 9291 SDValue DAGCombiner::visitFMUL(SDNode *N) { 9292 SDValue N0 = N->getOperand(0); 9293 SDValue N1 = N->getOperand(1); 9294 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9295 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9296 EVT VT = N->getValueType(0); 9297 SDLoc DL(N); 9298 const TargetOptions &Options = DAG.getTarget().Options; 9299 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 9300 9301 // fold vector ops 9302 if (VT.isVector()) { 9303 // This just handles C1 * C2 for vectors. Other vector folds are below. 9304 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9305 return FoldedVOp; 9306 } 9307 9308 // fold (fmul c1, c2) -> c1*c2 9309 if (N0CFP && N1CFP) 9310 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 9311 9312 // canonicalize constant to RHS 9313 if (isConstantFPBuildVectorOrConstantFP(N0) && 9314 !isConstantFPBuildVectorOrConstantFP(N1)) 9315 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 9316 9317 // fold (fmul A, 1.0) -> A 9318 if (N1CFP && N1CFP->isExactlyValue(1.0)) 9319 return N0; 9320 9321 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9322 return NewSel; 9323 9324 if (Options.UnsafeFPMath) { 9325 // fold (fmul A, 0) -> 0 9326 if (N1CFP && N1CFP->isZero()) 9327 return N1; 9328 9329 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 9330 if (N0.getOpcode() == ISD::FMUL) { 9331 // Fold scalars or any vector constants (not just splats). 9332 // This fold is done in general by InstCombine, but extra fmul insts 9333 // may have been generated during lowering. 9334 SDValue N00 = N0.getOperand(0); 9335 SDValue N01 = N0.getOperand(1); 9336 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 9337 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 9338 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 9339 9340 // Check 1: Make sure that the first operand of the inner multiply is NOT 9341 // a constant. Otherwise, we may induce infinite looping. 9342 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 9343 // Check 2: Make sure that the second operand of the inner multiply and 9344 // the second operand of the outer multiply are constants. 9345 if ((N1CFP && isConstOrConstSplatFP(N01)) || 9346 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 9347 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 9348 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 9349 } 9350 } 9351 } 9352 9353 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 9354 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 9355 // during an early run of DAGCombiner can prevent folding with fmuls 9356 // inserted during lowering. 9357 if (N0.getOpcode() == ISD::FADD && 9358 (N0.getOperand(0) == N0.getOperand(1)) && 9359 N0.hasOneUse()) { 9360 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 9361 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 9362 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 9363 } 9364 } 9365 9366 // fold (fmul X, 2.0) -> (fadd X, X) 9367 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 9368 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 9369 9370 // fold (fmul X, -1.0) -> (fneg X) 9371 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 9372 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9373 return DAG.getNode(ISD::FNEG, DL, VT, N0); 9374 9375 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 9376 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 9377 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 9378 // Both can be negated for free, check to see if at least one is cheaper 9379 // negated. 9380 if (LHSNeg == 2 || RHSNeg == 2) 9381 return DAG.getNode(ISD::FMUL, DL, VT, 9382 GetNegatedExpression(N0, DAG, LegalOperations), 9383 GetNegatedExpression(N1, DAG, LegalOperations), 9384 Flags); 9385 } 9386 } 9387 9388 // FMUL -> FMA combines: 9389 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) { 9390 AddToWorklist(Fused.getNode()); 9391 return Fused; 9392 } 9393 9394 return SDValue(); 9395 } 9396 9397 SDValue DAGCombiner::visitFMA(SDNode *N) { 9398 SDValue N0 = N->getOperand(0); 9399 SDValue N1 = N->getOperand(1); 9400 SDValue N2 = N->getOperand(2); 9401 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9402 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9403 EVT VT = N->getValueType(0); 9404 SDLoc DL(N); 9405 const TargetOptions &Options = DAG.getTarget().Options; 9406 9407 // Constant fold FMA. 9408 if (isa<ConstantFPSDNode>(N0) && 9409 isa<ConstantFPSDNode>(N1) && 9410 isa<ConstantFPSDNode>(N2)) { 9411 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2); 9412 } 9413 9414 if (Options.UnsafeFPMath) { 9415 if (N0CFP && N0CFP->isZero()) 9416 return N2; 9417 if (N1CFP && N1CFP->isZero()) 9418 return N2; 9419 } 9420 // TODO: The FMA node should have flags that propagate to these nodes. 9421 if (N0CFP && N0CFP->isExactlyValue(1.0)) 9422 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 9423 if (N1CFP && N1CFP->isExactlyValue(1.0)) 9424 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 9425 9426 // Canonicalize (fma c, x, y) -> (fma x, c, y) 9427 if (isConstantFPBuildVectorOrConstantFP(N0) && 9428 !isConstantFPBuildVectorOrConstantFP(N1)) 9429 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 9430 9431 // TODO: FMA nodes should have flags that propagate to the created nodes. 9432 // For now, create a Flags object for use with all unsafe math transforms. 9433 SDNodeFlags Flags; 9434 Flags.setUnsafeAlgebra(true); 9435 9436 if (Options.UnsafeFPMath) { 9437 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 9438 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 9439 isConstantFPBuildVectorOrConstantFP(N1) && 9440 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 9441 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9442 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1), 9443 &Flags), &Flags); 9444 } 9445 9446 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 9447 if (N0.getOpcode() == ISD::FMUL && 9448 isConstantFPBuildVectorOrConstantFP(N1) && 9449 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 9450 return DAG.getNode(ISD::FMA, DL, VT, 9451 N0.getOperand(0), 9452 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1), 9453 &Flags), 9454 N2); 9455 } 9456 } 9457 9458 // (fma x, 1, y) -> (fadd x, y) 9459 // (fma x, -1, y) -> (fadd (fneg x), y) 9460 if (N1CFP) { 9461 if (N1CFP->isExactlyValue(1.0)) 9462 // TODO: The FMA node should have flags that propagate to this node. 9463 return DAG.getNode(ISD::FADD, DL, VT, N0, N2); 9464 9465 if (N1CFP->isExactlyValue(-1.0) && 9466 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 9467 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0); 9468 AddToWorklist(RHSNeg.getNode()); 9469 // TODO: The FMA node should have flags that propagate to this node. 9470 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg); 9471 } 9472 } 9473 9474 if (Options.UnsafeFPMath) { 9475 // (fma x, c, x) -> (fmul x, (c+1)) 9476 if (N1CFP && N0 == N2) { 9477 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9478 DAG.getNode(ISD::FADD, DL, VT, N1, 9479 DAG.getConstantFP(1.0, DL, VT), &Flags), 9480 &Flags); 9481 } 9482 9483 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 9484 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 9485 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9486 DAG.getNode(ISD::FADD, DL, VT, N1, 9487 DAG.getConstantFP(-1.0, DL, VT), &Flags), 9488 &Flags); 9489 } 9490 } 9491 9492 return SDValue(); 9493 } 9494 9495 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 9496 // reciprocal. 9497 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 9498 // Notice that this is not always beneficial. One reason is different targets 9499 // may have different costs for FDIV and FMUL, so sometimes the cost of two 9500 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 9501 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 9502 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 9503 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 9504 const SDNodeFlags *Flags = N->getFlags(); 9505 if (!UnsafeMath && !Flags->hasAllowReciprocal()) 9506 return SDValue(); 9507 9508 // Skip if current node is a reciprocal. 9509 SDValue N0 = N->getOperand(0); 9510 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9511 if (N0CFP && N0CFP->isExactlyValue(1.0)) 9512 return SDValue(); 9513 9514 // Exit early if the target does not want this transform or if there can't 9515 // possibly be enough uses of the divisor to make the transform worthwhile. 9516 SDValue N1 = N->getOperand(1); 9517 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 9518 if (!MinUses || N1->use_size() < MinUses) 9519 return SDValue(); 9520 9521 // Find all FDIV users of the same divisor. 9522 // Use a set because duplicates may be present in the user list. 9523 SetVector<SDNode *> Users; 9524 for (auto *U : N1->uses()) { 9525 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 9526 // This division is eligible for optimization only if global unsafe math 9527 // is enabled or if this division allows reciprocal formation. 9528 if (UnsafeMath || U->getFlags()->hasAllowReciprocal()) 9529 Users.insert(U); 9530 } 9531 } 9532 9533 // Now that we have the actual number of divisor uses, make sure it meets 9534 // the minimum threshold specified by the target. 9535 if (Users.size() < MinUses) 9536 return SDValue(); 9537 9538 EVT VT = N->getValueType(0); 9539 SDLoc DL(N); 9540 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 9541 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 9542 9543 // Dividend / Divisor -> Dividend * Reciprocal 9544 for (auto *U : Users) { 9545 SDValue Dividend = U->getOperand(0); 9546 if (Dividend != FPOne) { 9547 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 9548 Reciprocal, Flags); 9549 CombineTo(U, NewNode); 9550 } else if (U != Reciprocal.getNode()) { 9551 // In the absence of fast-math-flags, this user node is always the 9552 // same node as Reciprocal, but with FMF they may be different nodes. 9553 CombineTo(U, Reciprocal); 9554 } 9555 } 9556 return SDValue(N, 0); // N was replaced. 9557 } 9558 9559 SDValue DAGCombiner::visitFDIV(SDNode *N) { 9560 SDValue N0 = N->getOperand(0); 9561 SDValue N1 = N->getOperand(1); 9562 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9563 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9564 EVT VT = N->getValueType(0); 9565 SDLoc DL(N); 9566 const TargetOptions &Options = DAG.getTarget().Options; 9567 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 9568 9569 // fold vector ops 9570 if (VT.isVector()) 9571 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9572 return FoldedVOp; 9573 9574 // fold (fdiv c1, c2) -> c1/c2 9575 if (N0CFP && N1CFP) 9576 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 9577 9578 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9579 return NewSel; 9580 9581 if (Options.UnsafeFPMath) { 9582 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 9583 if (N1CFP) { 9584 // Compute the reciprocal 1.0 / c2. 9585 const APFloat &N1APF = N1CFP->getValueAPF(); 9586 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 9587 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 9588 // Only do the transform if the reciprocal is a legal fp immediate that 9589 // isn't too nasty (eg NaN, denormal, ...). 9590 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 9591 (!LegalOperations || 9592 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 9593 // backend)... we should handle this gracefully after Legalize. 9594 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 9595 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 9596 TLI.isFPImmLegal(Recip, VT))) 9597 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9598 DAG.getConstantFP(Recip, DL, VT), Flags); 9599 } 9600 9601 // If this FDIV is part of a reciprocal square root, it may be folded 9602 // into a target-specific square root estimate instruction. 9603 if (N1.getOpcode() == ISD::FSQRT) { 9604 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) { 9605 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9606 } 9607 } else if (N1.getOpcode() == ISD::FP_EXTEND && 9608 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 9609 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 9610 Flags)) { 9611 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 9612 AddToWorklist(RV.getNode()); 9613 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9614 } 9615 } else if (N1.getOpcode() == ISD::FP_ROUND && 9616 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 9617 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 9618 Flags)) { 9619 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 9620 AddToWorklist(RV.getNode()); 9621 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9622 } 9623 } else if (N1.getOpcode() == ISD::FMUL) { 9624 // Look through an FMUL. Even though this won't remove the FDIV directly, 9625 // it's still worthwhile to get rid of the FSQRT if possible. 9626 SDValue SqrtOp; 9627 SDValue OtherOp; 9628 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 9629 SqrtOp = N1.getOperand(0); 9630 OtherOp = N1.getOperand(1); 9631 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 9632 SqrtOp = N1.getOperand(1); 9633 OtherOp = N1.getOperand(0); 9634 } 9635 if (SqrtOp.getNode()) { 9636 // We found a FSQRT, so try to make this fold: 9637 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 9638 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 9639 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 9640 AddToWorklist(RV.getNode()); 9641 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9642 } 9643 } 9644 } 9645 9646 // Fold into a reciprocal estimate and multiply instead of a real divide. 9647 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 9648 AddToWorklist(RV.getNode()); 9649 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9650 } 9651 } 9652 9653 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 9654 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 9655 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 9656 // Both can be negated for free, check to see if at least one is cheaper 9657 // negated. 9658 if (LHSNeg == 2 || RHSNeg == 2) 9659 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 9660 GetNegatedExpression(N0, DAG, LegalOperations), 9661 GetNegatedExpression(N1, DAG, LegalOperations), 9662 Flags); 9663 } 9664 } 9665 9666 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 9667 return CombineRepeatedDivisors; 9668 9669 return SDValue(); 9670 } 9671 9672 SDValue DAGCombiner::visitFREM(SDNode *N) { 9673 SDValue N0 = N->getOperand(0); 9674 SDValue N1 = N->getOperand(1); 9675 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9676 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9677 EVT VT = N->getValueType(0); 9678 9679 // fold (frem c1, c2) -> fmod(c1,c2) 9680 if (N0CFP && N1CFP) 9681 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, 9682 &cast<BinaryWithFlagsSDNode>(N)->Flags); 9683 9684 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9685 return NewSel; 9686 9687 return SDValue(); 9688 } 9689 9690 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 9691 if (!DAG.getTarget().Options.UnsafeFPMath) 9692 return SDValue(); 9693 9694 SDValue N0 = N->getOperand(0); 9695 if (TLI.isFsqrtCheap(N0, DAG)) 9696 return SDValue(); 9697 9698 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 9699 // For now, create a Flags object for use with all unsafe math transforms. 9700 SDNodeFlags Flags; 9701 Flags.setUnsafeAlgebra(true); 9702 return buildSqrtEstimate(N0, &Flags); 9703 } 9704 9705 /// copysign(x, fp_extend(y)) -> copysign(x, y) 9706 /// copysign(x, fp_round(y)) -> copysign(x, y) 9707 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 9708 SDValue N1 = N->getOperand(1); 9709 if ((N1.getOpcode() == ISD::FP_EXTEND || 9710 N1.getOpcode() == ISD::FP_ROUND)) { 9711 // Do not optimize out type conversion of f128 type yet. 9712 // For some targets like x86_64, configuration is changed to keep one f128 9713 // value in one SSE register, but instruction selection cannot handle 9714 // FCOPYSIGN on SSE registers yet. 9715 EVT N1VT = N1->getValueType(0); 9716 EVT N1Op0VT = N1->getOperand(0)->getValueType(0); 9717 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 9718 } 9719 return false; 9720 } 9721 9722 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 9723 SDValue N0 = N->getOperand(0); 9724 SDValue N1 = N->getOperand(1); 9725 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9726 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9727 EVT VT = N->getValueType(0); 9728 9729 if (N0CFP && N1CFP) // Constant fold 9730 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 9731 9732 if (N1CFP) { 9733 const APFloat &V = N1CFP->getValueAPF(); 9734 // copysign(x, c1) -> fabs(x) iff ispos(c1) 9735 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 9736 if (!V.isNegative()) { 9737 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 9738 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9739 } else { 9740 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9741 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 9742 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 9743 } 9744 } 9745 9746 // copysign(fabs(x), y) -> copysign(x, y) 9747 // copysign(fneg(x), y) -> copysign(x, y) 9748 // copysign(copysign(x,z), y) -> copysign(x, y) 9749 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 9750 N0.getOpcode() == ISD::FCOPYSIGN) 9751 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1); 9752 9753 // copysign(x, abs(y)) -> abs(x) 9754 if (N1.getOpcode() == ISD::FABS) 9755 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9756 9757 // copysign(x, copysign(y,z)) -> copysign(x, z) 9758 if (N1.getOpcode() == ISD::FCOPYSIGN) 9759 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1)); 9760 9761 // copysign(x, fp_extend(y)) -> copysign(x, y) 9762 // copysign(x, fp_round(y)) -> copysign(x, y) 9763 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 9764 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0)); 9765 9766 return SDValue(); 9767 } 9768 9769 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 9770 SDValue N0 = N->getOperand(0); 9771 EVT VT = N->getValueType(0); 9772 EVT OpVT = N0.getValueType(); 9773 9774 // fold (sint_to_fp c1) -> c1fp 9775 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 9776 // ...but only if the target supports immediate floating-point values 9777 (!LegalOperations || 9778 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 9779 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 9780 9781 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 9782 // but UINT_TO_FP is legal on this target, try to convert. 9783 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 9784 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 9785 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 9786 if (DAG.SignBitIsZero(N0)) 9787 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 9788 } 9789 9790 // The next optimizations are desirable only if SELECT_CC can be lowered. 9791 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 9792 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 9793 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 9794 !VT.isVector() && 9795 (!LegalOperations || 9796 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9797 SDLoc DL(N); 9798 SDValue Ops[] = 9799 { N0.getOperand(0), N0.getOperand(1), 9800 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9801 N0.getOperand(2) }; 9802 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9803 } 9804 9805 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 9806 // (select_cc x, y, 1.0, 0.0,, cc) 9807 if (N0.getOpcode() == ISD::ZERO_EXTEND && 9808 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 9809 (!LegalOperations || 9810 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9811 SDLoc DL(N); 9812 SDValue Ops[] = 9813 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 9814 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9815 N0.getOperand(0).getOperand(2) }; 9816 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9817 } 9818 } 9819 9820 return SDValue(); 9821 } 9822 9823 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 9824 SDValue N0 = N->getOperand(0); 9825 EVT VT = N->getValueType(0); 9826 EVT OpVT = N0.getValueType(); 9827 9828 // fold (uint_to_fp c1) -> c1fp 9829 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 9830 // ...but only if the target supports immediate floating-point values 9831 (!LegalOperations || 9832 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 9833 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 9834 9835 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 9836 // but SINT_TO_FP is legal on this target, try to convert. 9837 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 9838 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 9839 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 9840 if (DAG.SignBitIsZero(N0)) 9841 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 9842 } 9843 9844 // The next optimizations are desirable only if SELECT_CC can be lowered. 9845 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 9846 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 9847 9848 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 9849 (!LegalOperations || 9850 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9851 SDLoc DL(N); 9852 SDValue Ops[] = 9853 { N0.getOperand(0), N0.getOperand(1), 9854 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9855 N0.getOperand(2) }; 9856 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9857 } 9858 } 9859 9860 return SDValue(); 9861 } 9862 9863 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 9864 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 9865 SDValue N0 = N->getOperand(0); 9866 EVT VT = N->getValueType(0); 9867 9868 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 9869 return SDValue(); 9870 9871 SDValue Src = N0.getOperand(0); 9872 EVT SrcVT = Src.getValueType(); 9873 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 9874 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 9875 9876 // We can safely assume the conversion won't overflow the output range, 9877 // because (for example) (uint8_t)18293.f is undefined behavior. 9878 9879 // Since we can assume the conversion won't overflow, our decision as to 9880 // whether the input will fit in the float should depend on the minimum 9881 // of the input range and output range. 9882 9883 // This means this is also safe for a signed input and unsigned output, since 9884 // a negative input would lead to undefined behavior. 9885 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 9886 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 9887 unsigned ActualSize = std::min(InputSize, OutputSize); 9888 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 9889 9890 // We can only fold away the float conversion if the input range can be 9891 // represented exactly in the float range. 9892 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 9893 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 9894 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 9895 : ISD::ZERO_EXTEND; 9896 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 9897 } 9898 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 9899 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 9900 return DAG.getBitcast(VT, Src); 9901 } 9902 return SDValue(); 9903 } 9904 9905 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 9906 SDValue N0 = N->getOperand(0); 9907 EVT VT = N->getValueType(0); 9908 9909 // fold (fp_to_sint c1fp) -> c1 9910 if (isConstantFPBuildVectorOrConstantFP(N0)) 9911 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 9912 9913 return FoldIntToFPToInt(N, DAG); 9914 } 9915 9916 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 9917 SDValue N0 = N->getOperand(0); 9918 EVT VT = N->getValueType(0); 9919 9920 // fold (fp_to_uint c1fp) -> c1 9921 if (isConstantFPBuildVectorOrConstantFP(N0)) 9922 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 9923 9924 return FoldIntToFPToInt(N, DAG); 9925 } 9926 9927 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 9928 SDValue N0 = N->getOperand(0); 9929 SDValue N1 = N->getOperand(1); 9930 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9931 EVT VT = N->getValueType(0); 9932 9933 // fold (fp_round c1fp) -> c1fp 9934 if (N0CFP) 9935 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 9936 9937 // fold (fp_round (fp_extend x)) -> x 9938 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 9939 return N0.getOperand(0); 9940 9941 // fold (fp_round (fp_round x)) -> (fp_round x) 9942 if (N0.getOpcode() == ISD::FP_ROUND) { 9943 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 9944 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1; 9945 9946 // Skip this folding if it results in an fp_round from f80 to f16. 9947 // 9948 // f80 to f16 always generates an expensive (and as yet, unimplemented) 9949 // libcall to __truncxfhf2 instead of selecting native f16 conversion 9950 // instructions from f32 or f64. Moreover, the first (value-preserving) 9951 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 9952 // x86. 9953 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 9954 return SDValue(); 9955 9956 // If the first fp_round isn't a value preserving truncation, it might 9957 // introduce a tie in the second fp_round, that wouldn't occur in the 9958 // single-step fp_round we want to fold to. 9959 // In other words, double rounding isn't the same as rounding. 9960 // Also, this is a value preserving truncation iff both fp_round's are. 9961 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 9962 SDLoc DL(N); 9963 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 9964 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 9965 } 9966 } 9967 9968 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 9969 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 9970 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 9971 N0.getOperand(0), N1); 9972 AddToWorklist(Tmp.getNode()); 9973 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 9974 Tmp, N0.getOperand(1)); 9975 } 9976 9977 return SDValue(); 9978 } 9979 9980 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 9981 SDValue N0 = N->getOperand(0); 9982 EVT VT = N->getValueType(0); 9983 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 9984 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9985 9986 // fold (fp_round_inreg c1fp) -> c1fp 9987 if (N0CFP && isTypeLegal(EVT)) { 9988 SDLoc DL(N); 9989 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 9990 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 9991 } 9992 9993 return SDValue(); 9994 } 9995 9996 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 9997 SDValue N0 = N->getOperand(0); 9998 EVT VT = N->getValueType(0); 9999 10000 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 10001 if (N->hasOneUse() && 10002 N->use_begin()->getOpcode() == ISD::FP_ROUND) 10003 return SDValue(); 10004 10005 // fold (fp_extend c1fp) -> c1fp 10006 if (isConstantFPBuildVectorOrConstantFP(N0)) 10007 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 10008 10009 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 10010 if (N0.getOpcode() == ISD::FP16_TO_FP && 10011 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 10012 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 10013 10014 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 10015 // value of X. 10016 if (N0.getOpcode() == ISD::FP_ROUND 10017 && N0.getConstantOperandVal(1) == 1) { 10018 SDValue In = N0.getOperand(0); 10019 if (In.getValueType() == VT) return In; 10020 if (VT.bitsLT(In.getValueType())) 10021 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 10022 In, N0.getOperand(1)); 10023 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 10024 } 10025 10026 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 10027 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10028 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 10029 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10030 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 10031 LN0->getChain(), 10032 LN0->getBasePtr(), N0.getValueType(), 10033 LN0->getMemOperand()); 10034 CombineTo(N, ExtLoad); 10035 CombineTo(N0.getNode(), 10036 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 10037 N0.getValueType(), ExtLoad, 10038 DAG.getIntPtrConstant(1, SDLoc(N0))), 10039 ExtLoad.getValue(1)); 10040 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10041 } 10042 10043 return SDValue(); 10044 } 10045 10046 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 10047 SDValue N0 = N->getOperand(0); 10048 EVT VT = N->getValueType(0); 10049 10050 // fold (fceil c1) -> fceil(c1) 10051 if (isConstantFPBuildVectorOrConstantFP(N0)) 10052 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 10053 10054 return SDValue(); 10055 } 10056 10057 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 10058 SDValue N0 = N->getOperand(0); 10059 EVT VT = N->getValueType(0); 10060 10061 // fold (ftrunc c1) -> ftrunc(c1) 10062 if (isConstantFPBuildVectorOrConstantFP(N0)) 10063 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 10064 10065 return SDValue(); 10066 } 10067 10068 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 10069 SDValue N0 = N->getOperand(0); 10070 EVT VT = N->getValueType(0); 10071 10072 // fold (ffloor c1) -> ffloor(c1) 10073 if (isConstantFPBuildVectorOrConstantFP(N0)) 10074 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 10075 10076 return SDValue(); 10077 } 10078 10079 // FIXME: FNEG and FABS have a lot in common; refactor. 10080 SDValue DAGCombiner::visitFNEG(SDNode *N) { 10081 SDValue N0 = N->getOperand(0); 10082 EVT VT = N->getValueType(0); 10083 10084 // Constant fold FNEG. 10085 if (isConstantFPBuildVectorOrConstantFP(N0)) 10086 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 10087 10088 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 10089 &DAG.getTarget().Options)) 10090 return GetNegatedExpression(N0, DAG, LegalOperations); 10091 10092 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 10093 // constant pool values. 10094 if (!TLI.isFNegFree(VT) && 10095 N0.getOpcode() == ISD::BITCAST && 10096 N0.getNode()->hasOneUse()) { 10097 SDValue Int = N0.getOperand(0); 10098 EVT IntVT = Int.getValueType(); 10099 if (IntVT.isInteger() && !IntVT.isVector()) { 10100 APInt SignMask; 10101 if (N0.getValueType().isVector()) { 10102 // For a vector, get a mask such as 0x80... per scalar element 10103 // and splat it. 10104 SignMask = APInt::getSignBit(N0.getScalarValueSizeInBits()); 10105 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 10106 } else { 10107 // For a scalar, just generate 0x80... 10108 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 10109 } 10110 SDLoc DL0(N0); 10111 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 10112 DAG.getConstant(SignMask, DL0, IntVT)); 10113 AddToWorklist(Int.getNode()); 10114 return DAG.getBitcast(VT, Int); 10115 } 10116 } 10117 10118 // (fneg (fmul c, x)) -> (fmul -c, x) 10119 if (N0.getOpcode() == ISD::FMUL && 10120 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 10121 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10122 if (CFP1) { 10123 APFloat CVal = CFP1->getValueAPF(); 10124 CVal.changeSign(); 10125 if (Level >= AfterLegalizeDAG && 10126 (TLI.isFPImmLegal(CVal, VT) || 10127 TLI.isOperationLegal(ISD::ConstantFP, VT))) 10128 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 10129 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 10130 N0.getOperand(1)), 10131 &cast<BinaryWithFlagsSDNode>(N0)->Flags); 10132 } 10133 } 10134 10135 return SDValue(); 10136 } 10137 10138 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 10139 SDValue N0 = N->getOperand(0); 10140 SDValue N1 = N->getOperand(1); 10141 EVT VT = N->getValueType(0); 10142 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10143 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10144 10145 if (N0CFP && N1CFP) { 10146 const APFloat &C0 = N0CFP->getValueAPF(); 10147 const APFloat &C1 = N1CFP->getValueAPF(); 10148 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 10149 } 10150 10151 // Canonicalize to constant on RHS. 10152 if (isConstantFPBuildVectorOrConstantFP(N0) && 10153 !isConstantFPBuildVectorOrConstantFP(N1)) 10154 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 10155 10156 return SDValue(); 10157 } 10158 10159 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 10160 SDValue N0 = N->getOperand(0); 10161 SDValue N1 = N->getOperand(1); 10162 EVT VT = N->getValueType(0); 10163 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10164 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10165 10166 if (N0CFP && N1CFP) { 10167 const APFloat &C0 = N0CFP->getValueAPF(); 10168 const APFloat &C1 = N1CFP->getValueAPF(); 10169 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 10170 } 10171 10172 // Canonicalize to constant on RHS. 10173 if (isConstantFPBuildVectorOrConstantFP(N0) && 10174 !isConstantFPBuildVectorOrConstantFP(N1)) 10175 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 10176 10177 return SDValue(); 10178 } 10179 10180 SDValue DAGCombiner::visitFABS(SDNode *N) { 10181 SDValue N0 = N->getOperand(0); 10182 EVT VT = N->getValueType(0); 10183 10184 // fold (fabs c1) -> fabs(c1) 10185 if (isConstantFPBuildVectorOrConstantFP(N0)) 10186 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10187 10188 // fold (fabs (fabs x)) -> (fabs x) 10189 if (N0.getOpcode() == ISD::FABS) 10190 return N->getOperand(0); 10191 10192 // fold (fabs (fneg x)) -> (fabs x) 10193 // fold (fabs (fcopysign x, y)) -> (fabs x) 10194 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 10195 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 10196 10197 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 10198 // constant pool values. 10199 if (!TLI.isFAbsFree(VT) && 10200 N0.getOpcode() == ISD::BITCAST && 10201 N0.getNode()->hasOneUse()) { 10202 SDValue Int = N0.getOperand(0); 10203 EVT IntVT = Int.getValueType(); 10204 if (IntVT.isInteger() && !IntVT.isVector()) { 10205 APInt SignMask; 10206 if (N0.getValueType().isVector()) { 10207 // For a vector, get a mask such as 0x7f... per scalar element 10208 // and splat it. 10209 SignMask = ~APInt::getSignBit(N0.getScalarValueSizeInBits()); 10210 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 10211 } else { 10212 // For a scalar, just generate 0x7f... 10213 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 10214 } 10215 SDLoc DL(N0); 10216 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 10217 DAG.getConstant(SignMask, DL, IntVT)); 10218 AddToWorklist(Int.getNode()); 10219 return DAG.getBitcast(N->getValueType(0), Int); 10220 } 10221 } 10222 10223 return SDValue(); 10224 } 10225 10226 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 10227 SDValue Chain = N->getOperand(0); 10228 SDValue N1 = N->getOperand(1); 10229 SDValue N2 = N->getOperand(2); 10230 10231 // If N is a constant we could fold this into a fallthrough or unconditional 10232 // branch. However that doesn't happen very often in normal code, because 10233 // Instcombine/SimplifyCFG should have handled the available opportunities. 10234 // If we did this folding here, it would be necessary to update the 10235 // MachineBasicBlock CFG, which is awkward. 10236 10237 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 10238 // on the target. 10239 if (N1.getOpcode() == ISD::SETCC && 10240 TLI.isOperationLegalOrCustom(ISD::BR_CC, 10241 N1.getOperand(0).getValueType())) { 10242 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 10243 Chain, N1.getOperand(2), 10244 N1.getOperand(0), N1.getOperand(1), N2); 10245 } 10246 10247 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 10248 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 10249 (N1.getOperand(0).hasOneUse() && 10250 N1.getOperand(0).getOpcode() == ISD::SRL))) { 10251 SDNode *Trunc = nullptr; 10252 if (N1.getOpcode() == ISD::TRUNCATE) { 10253 // Look pass the truncate. 10254 Trunc = N1.getNode(); 10255 N1 = N1.getOperand(0); 10256 } 10257 10258 // Match this pattern so that we can generate simpler code: 10259 // 10260 // %a = ... 10261 // %b = and i32 %a, 2 10262 // %c = srl i32 %b, 1 10263 // brcond i32 %c ... 10264 // 10265 // into 10266 // 10267 // %a = ... 10268 // %b = and i32 %a, 2 10269 // %c = setcc eq %b, 0 10270 // brcond %c ... 10271 // 10272 // This applies only when the AND constant value has one bit set and the 10273 // SRL constant is equal to the log2 of the AND constant. The back-end is 10274 // smart enough to convert the result into a TEST/JMP sequence. 10275 SDValue Op0 = N1.getOperand(0); 10276 SDValue Op1 = N1.getOperand(1); 10277 10278 if (Op0.getOpcode() == ISD::AND && 10279 Op1.getOpcode() == ISD::Constant) { 10280 SDValue AndOp1 = Op0.getOperand(1); 10281 10282 if (AndOp1.getOpcode() == ISD::Constant) { 10283 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 10284 10285 if (AndConst.isPowerOf2() && 10286 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 10287 SDLoc DL(N); 10288 SDValue SetCC = 10289 DAG.getSetCC(DL, 10290 getSetCCResultType(Op0.getValueType()), 10291 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 10292 ISD::SETNE); 10293 10294 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 10295 MVT::Other, Chain, SetCC, N2); 10296 // Don't add the new BRCond into the worklist or else SimplifySelectCC 10297 // will convert it back to (X & C1) >> C2. 10298 CombineTo(N, NewBRCond, false); 10299 // Truncate is dead. 10300 if (Trunc) 10301 deleteAndRecombine(Trunc); 10302 // Replace the uses of SRL with SETCC 10303 WorklistRemover DeadNodes(*this); 10304 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 10305 deleteAndRecombine(N1.getNode()); 10306 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10307 } 10308 } 10309 } 10310 10311 if (Trunc) 10312 // Restore N1 if the above transformation doesn't match. 10313 N1 = N->getOperand(1); 10314 } 10315 10316 // Transform br(xor(x, y)) -> br(x != y) 10317 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 10318 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 10319 SDNode *TheXor = N1.getNode(); 10320 SDValue Op0 = TheXor->getOperand(0); 10321 SDValue Op1 = TheXor->getOperand(1); 10322 if (Op0.getOpcode() == Op1.getOpcode()) { 10323 // Avoid missing important xor optimizations. 10324 if (SDValue Tmp = visitXOR(TheXor)) { 10325 if (Tmp.getNode() != TheXor) { 10326 DEBUG(dbgs() << "\nReplacing.8 "; 10327 TheXor->dump(&DAG); 10328 dbgs() << "\nWith: "; 10329 Tmp.getNode()->dump(&DAG); 10330 dbgs() << '\n'); 10331 WorklistRemover DeadNodes(*this); 10332 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 10333 deleteAndRecombine(TheXor); 10334 return DAG.getNode(ISD::BRCOND, SDLoc(N), 10335 MVT::Other, Chain, Tmp, N2); 10336 } 10337 10338 // visitXOR has changed XOR's operands or replaced the XOR completely, 10339 // bail out. 10340 return SDValue(N, 0); 10341 } 10342 } 10343 10344 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 10345 bool Equal = false; 10346 if (isOneConstant(Op0) && Op0.hasOneUse() && 10347 Op0.getOpcode() == ISD::XOR) { 10348 TheXor = Op0.getNode(); 10349 Equal = true; 10350 } 10351 10352 EVT SetCCVT = N1.getValueType(); 10353 if (LegalTypes) 10354 SetCCVT = getSetCCResultType(SetCCVT); 10355 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 10356 SetCCVT, 10357 Op0, Op1, 10358 Equal ? ISD::SETEQ : ISD::SETNE); 10359 // Replace the uses of XOR with SETCC 10360 WorklistRemover DeadNodes(*this); 10361 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 10362 deleteAndRecombine(N1.getNode()); 10363 return DAG.getNode(ISD::BRCOND, SDLoc(N), 10364 MVT::Other, Chain, SetCC, N2); 10365 } 10366 } 10367 10368 return SDValue(); 10369 } 10370 10371 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 10372 // 10373 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 10374 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 10375 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 10376 10377 // If N is a constant we could fold this into a fallthrough or unconditional 10378 // branch. However that doesn't happen very often in normal code, because 10379 // Instcombine/SimplifyCFG should have handled the available opportunities. 10380 // If we did this folding here, it would be necessary to update the 10381 // MachineBasicBlock CFG, which is awkward. 10382 10383 // Use SimplifySetCC to simplify SETCC's. 10384 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 10385 CondLHS, CondRHS, CC->get(), SDLoc(N), 10386 false); 10387 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 10388 10389 // fold to a simpler setcc 10390 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 10391 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 10392 N->getOperand(0), Simp.getOperand(2), 10393 Simp.getOperand(0), Simp.getOperand(1), 10394 N->getOperand(4)); 10395 10396 return SDValue(); 10397 } 10398 10399 /// Return true if 'Use' is a load or a store that uses N as its base pointer 10400 /// and that N may be folded in the load / store addressing mode. 10401 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 10402 SelectionDAG &DAG, 10403 const TargetLowering &TLI) { 10404 EVT VT; 10405 unsigned AS; 10406 10407 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 10408 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 10409 return false; 10410 VT = LD->getMemoryVT(); 10411 AS = LD->getAddressSpace(); 10412 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 10413 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 10414 return false; 10415 VT = ST->getMemoryVT(); 10416 AS = ST->getAddressSpace(); 10417 } else 10418 return false; 10419 10420 TargetLowering::AddrMode AM; 10421 if (N->getOpcode() == ISD::ADD) { 10422 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10423 if (Offset) 10424 // [reg +/- imm] 10425 AM.BaseOffs = Offset->getSExtValue(); 10426 else 10427 // [reg +/- reg] 10428 AM.Scale = 1; 10429 } else if (N->getOpcode() == ISD::SUB) { 10430 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10431 if (Offset) 10432 // [reg +/- imm] 10433 AM.BaseOffs = -Offset->getSExtValue(); 10434 else 10435 // [reg +/- reg] 10436 AM.Scale = 1; 10437 } else 10438 return false; 10439 10440 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 10441 VT.getTypeForEVT(*DAG.getContext()), AS); 10442 } 10443 10444 /// Try turning a load/store into a pre-indexed load/store when the base 10445 /// pointer is an add or subtract and it has other uses besides the load/store. 10446 /// After the transformation, the new indexed load/store has effectively folded 10447 /// the add/subtract in and all of its other uses are redirected to the 10448 /// new load/store. 10449 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 10450 if (Level < AfterLegalizeDAG) 10451 return false; 10452 10453 bool isLoad = true; 10454 SDValue Ptr; 10455 EVT VT; 10456 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10457 if (LD->isIndexed()) 10458 return false; 10459 VT = LD->getMemoryVT(); 10460 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 10461 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 10462 return false; 10463 Ptr = LD->getBasePtr(); 10464 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10465 if (ST->isIndexed()) 10466 return false; 10467 VT = ST->getMemoryVT(); 10468 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 10469 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 10470 return false; 10471 Ptr = ST->getBasePtr(); 10472 isLoad = false; 10473 } else { 10474 return false; 10475 } 10476 10477 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 10478 // out. There is no reason to make this a preinc/predec. 10479 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 10480 Ptr.getNode()->hasOneUse()) 10481 return false; 10482 10483 // Ask the target to do addressing mode selection. 10484 SDValue BasePtr; 10485 SDValue Offset; 10486 ISD::MemIndexedMode AM = ISD::UNINDEXED; 10487 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 10488 return false; 10489 10490 // Backends without true r+i pre-indexed forms may need to pass a 10491 // constant base with a variable offset so that constant coercion 10492 // will work with the patterns in canonical form. 10493 bool Swapped = false; 10494 if (isa<ConstantSDNode>(BasePtr)) { 10495 std::swap(BasePtr, Offset); 10496 Swapped = true; 10497 } 10498 10499 // Don't create a indexed load / store with zero offset. 10500 if (isNullConstant(Offset)) 10501 return false; 10502 10503 // Try turning it into a pre-indexed load / store except when: 10504 // 1) The new base ptr is a frame index. 10505 // 2) If N is a store and the new base ptr is either the same as or is a 10506 // predecessor of the value being stored. 10507 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 10508 // that would create a cycle. 10509 // 4) All uses are load / store ops that use it as old base ptr. 10510 10511 // Check #1. Preinc'ing a frame index would require copying the stack pointer 10512 // (plus the implicit offset) to a register to preinc anyway. 10513 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 10514 return false; 10515 10516 // Check #2. 10517 if (!isLoad) { 10518 SDValue Val = cast<StoreSDNode>(N)->getValue(); 10519 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 10520 return false; 10521 } 10522 10523 // Caches for hasPredecessorHelper. 10524 SmallPtrSet<const SDNode *, 32> Visited; 10525 SmallVector<const SDNode *, 16> Worklist; 10526 Worklist.push_back(N); 10527 10528 // If the offset is a constant, there may be other adds of constants that 10529 // can be folded with this one. We should do this to avoid having to keep 10530 // a copy of the original base pointer. 10531 SmallVector<SDNode *, 16> OtherUses; 10532 if (isa<ConstantSDNode>(Offset)) 10533 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 10534 UE = BasePtr.getNode()->use_end(); 10535 UI != UE; ++UI) { 10536 SDUse &Use = UI.getUse(); 10537 // Skip the use that is Ptr and uses of other results from BasePtr's 10538 // node (important for nodes that return multiple results). 10539 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 10540 continue; 10541 10542 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 10543 continue; 10544 10545 if (Use.getUser()->getOpcode() != ISD::ADD && 10546 Use.getUser()->getOpcode() != ISD::SUB) { 10547 OtherUses.clear(); 10548 break; 10549 } 10550 10551 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 10552 if (!isa<ConstantSDNode>(Op1)) { 10553 OtherUses.clear(); 10554 break; 10555 } 10556 10557 // FIXME: In some cases, we can be smarter about this. 10558 if (Op1.getValueType() != Offset.getValueType()) { 10559 OtherUses.clear(); 10560 break; 10561 } 10562 10563 OtherUses.push_back(Use.getUser()); 10564 } 10565 10566 if (Swapped) 10567 std::swap(BasePtr, Offset); 10568 10569 // Now check for #3 and #4. 10570 bool RealUse = false; 10571 10572 for (SDNode *Use : Ptr.getNode()->uses()) { 10573 if (Use == N) 10574 continue; 10575 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 10576 return false; 10577 10578 // If Ptr may be folded in addressing mode of other use, then it's 10579 // not profitable to do this transformation. 10580 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 10581 RealUse = true; 10582 } 10583 10584 if (!RealUse) 10585 return false; 10586 10587 SDValue Result; 10588 if (isLoad) 10589 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 10590 BasePtr, Offset, AM); 10591 else 10592 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 10593 BasePtr, Offset, AM); 10594 ++PreIndexedNodes; 10595 ++NodesCombined; 10596 DEBUG(dbgs() << "\nReplacing.4 "; 10597 N->dump(&DAG); 10598 dbgs() << "\nWith: "; 10599 Result.getNode()->dump(&DAG); 10600 dbgs() << '\n'); 10601 WorklistRemover DeadNodes(*this); 10602 if (isLoad) { 10603 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 10604 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 10605 } else { 10606 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 10607 } 10608 10609 // Finally, since the node is now dead, remove it from the graph. 10610 deleteAndRecombine(N); 10611 10612 if (Swapped) 10613 std::swap(BasePtr, Offset); 10614 10615 // Replace other uses of BasePtr that can be updated to use Ptr 10616 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 10617 unsigned OffsetIdx = 1; 10618 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 10619 OffsetIdx = 0; 10620 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 10621 BasePtr.getNode() && "Expected BasePtr operand"); 10622 10623 // We need to replace ptr0 in the following expression: 10624 // x0 * offset0 + y0 * ptr0 = t0 10625 // knowing that 10626 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 10627 // 10628 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 10629 // indexed load/store and the expresion that needs to be re-written. 10630 // 10631 // Therefore, we have: 10632 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 10633 10634 ConstantSDNode *CN = 10635 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 10636 int X0, X1, Y0, Y1; 10637 const APInt &Offset0 = CN->getAPIntValue(); 10638 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 10639 10640 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 10641 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 10642 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 10643 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 10644 10645 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 10646 10647 APInt CNV = Offset0; 10648 if (X0 < 0) CNV = -CNV; 10649 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 10650 else CNV = CNV - Offset1; 10651 10652 SDLoc DL(OtherUses[i]); 10653 10654 // We can now generate the new expression. 10655 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 10656 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 10657 10658 SDValue NewUse = DAG.getNode(Opcode, 10659 DL, 10660 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 10661 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 10662 deleteAndRecombine(OtherUses[i]); 10663 } 10664 10665 // Replace the uses of Ptr with uses of the updated base value. 10666 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 10667 deleteAndRecombine(Ptr.getNode()); 10668 10669 return true; 10670 } 10671 10672 /// Try to combine a load/store with a add/sub of the base pointer node into a 10673 /// post-indexed load/store. The transformation folded the add/subtract into the 10674 /// new indexed load/store effectively and all of its uses are redirected to the 10675 /// new load/store. 10676 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 10677 if (Level < AfterLegalizeDAG) 10678 return false; 10679 10680 bool isLoad = true; 10681 SDValue Ptr; 10682 EVT VT; 10683 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10684 if (LD->isIndexed()) 10685 return false; 10686 VT = LD->getMemoryVT(); 10687 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 10688 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 10689 return false; 10690 Ptr = LD->getBasePtr(); 10691 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10692 if (ST->isIndexed()) 10693 return false; 10694 VT = ST->getMemoryVT(); 10695 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 10696 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 10697 return false; 10698 Ptr = ST->getBasePtr(); 10699 isLoad = false; 10700 } else { 10701 return false; 10702 } 10703 10704 if (Ptr.getNode()->hasOneUse()) 10705 return false; 10706 10707 for (SDNode *Op : Ptr.getNode()->uses()) { 10708 if (Op == N || 10709 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 10710 continue; 10711 10712 SDValue BasePtr; 10713 SDValue Offset; 10714 ISD::MemIndexedMode AM = ISD::UNINDEXED; 10715 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 10716 // Don't create a indexed load / store with zero offset. 10717 if (isNullConstant(Offset)) 10718 continue; 10719 10720 // Try turning it into a post-indexed load / store except when 10721 // 1) All uses are load / store ops that use it as base ptr (and 10722 // it may be folded as addressing mmode). 10723 // 2) Op must be independent of N, i.e. Op is neither a predecessor 10724 // nor a successor of N. Otherwise, if Op is folded that would 10725 // create a cycle. 10726 10727 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 10728 continue; 10729 10730 // Check for #1. 10731 bool TryNext = false; 10732 for (SDNode *Use : BasePtr.getNode()->uses()) { 10733 if (Use == Ptr.getNode()) 10734 continue; 10735 10736 // If all the uses are load / store addresses, then don't do the 10737 // transformation. 10738 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 10739 bool RealUse = false; 10740 for (SDNode *UseUse : Use->uses()) { 10741 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 10742 RealUse = true; 10743 } 10744 10745 if (!RealUse) { 10746 TryNext = true; 10747 break; 10748 } 10749 } 10750 } 10751 10752 if (TryNext) 10753 continue; 10754 10755 // Check for #2 10756 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 10757 SDValue Result = isLoad 10758 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 10759 BasePtr, Offset, AM) 10760 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 10761 BasePtr, Offset, AM); 10762 ++PostIndexedNodes; 10763 ++NodesCombined; 10764 DEBUG(dbgs() << "\nReplacing.5 "; 10765 N->dump(&DAG); 10766 dbgs() << "\nWith: "; 10767 Result.getNode()->dump(&DAG); 10768 dbgs() << '\n'); 10769 WorklistRemover DeadNodes(*this); 10770 if (isLoad) { 10771 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 10772 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 10773 } else { 10774 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 10775 } 10776 10777 // Finally, since the node is now dead, remove it from the graph. 10778 deleteAndRecombine(N); 10779 10780 // Replace the uses of Use with uses of the updated base value. 10781 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 10782 Result.getValue(isLoad ? 1 : 0)); 10783 deleteAndRecombine(Op); 10784 return true; 10785 } 10786 } 10787 } 10788 10789 return false; 10790 } 10791 10792 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 10793 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 10794 ISD::MemIndexedMode AM = LD->getAddressingMode(); 10795 assert(AM != ISD::UNINDEXED); 10796 SDValue BP = LD->getOperand(1); 10797 SDValue Inc = LD->getOperand(2); 10798 10799 // Some backends use TargetConstants for load offsets, but don't expect 10800 // TargetConstants in general ADD nodes. We can convert these constants into 10801 // regular Constants (if the constant is not opaque). 10802 assert((Inc.getOpcode() != ISD::TargetConstant || 10803 !cast<ConstantSDNode>(Inc)->isOpaque()) && 10804 "Cannot split out indexing using opaque target constants"); 10805 if (Inc.getOpcode() == ISD::TargetConstant) { 10806 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 10807 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 10808 ConstInc->getValueType(0)); 10809 } 10810 10811 unsigned Opc = 10812 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 10813 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 10814 } 10815 10816 SDValue DAGCombiner::visitLOAD(SDNode *N) { 10817 LoadSDNode *LD = cast<LoadSDNode>(N); 10818 SDValue Chain = LD->getChain(); 10819 SDValue Ptr = LD->getBasePtr(); 10820 10821 // If load is not volatile and there are no uses of the loaded value (and 10822 // the updated indexed value in case of indexed loads), change uses of the 10823 // chain value into uses of the chain input (i.e. delete the dead load). 10824 if (!LD->isVolatile()) { 10825 if (N->getValueType(1) == MVT::Other) { 10826 // Unindexed loads. 10827 if (!N->hasAnyUseOfValue(0)) { 10828 // It's not safe to use the two value CombineTo variant here. e.g. 10829 // v1, chain2 = load chain1, loc 10830 // v2, chain3 = load chain2, loc 10831 // v3 = add v2, c 10832 // Now we replace use of chain2 with chain1. This makes the second load 10833 // isomorphic to the one we are deleting, and thus makes this load live. 10834 DEBUG(dbgs() << "\nReplacing.6 "; 10835 N->dump(&DAG); 10836 dbgs() << "\nWith chain: "; 10837 Chain.getNode()->dump(&DAG); 10838 dbgs() << "\n"); 10839 WorklistRemover DeadNodes(*this); 10840 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10841 10842 if (N->use_empty()) 10843 deleteAndRecombine(N); 10844 10845 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10846 } 10847 } else { 10848 // Indexed loads. 10849 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 10850 10851 // If this load has an opaque TargetConstant offset, then we cannot split 10852 // the indexing into an add/sub directly (that TargetConstant may not be 10853 // valid for a different type of node, and we cannot convert an opaque 10854 // target constant into a regular constant). 10855 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 10856 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 10857 10858 if (!N->hasAnyUseOfValue(0) && 10859 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 10860 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 10861 SDValue Index; 10862 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 10863 Index = SplitIndexingFromLoad(LD); 10864 // Try to fold the base pointer arithmetic into subsequent loads and 10865 // stores. 10866 AddUsersToWorklist(N); 10867 } else 10868 Index = DAG.getUNDEF(N->getValueType(1)); 10869 DEBUG(dbgs() << "\nReplacing.7 "; 10870 N->dump(&DAG); 10871 dbgs() << "\nWith: "; 10872 Undef.getNode()->dump(&DAG); 10873 dbgs() << " and 2 other values\n"); 10874 WorklistRemover DeadNodes(*this); 10875 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 10876 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 10877 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 10878 deleteAndRecombine(N); 10879 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10880 } 10881 } 10882 } 10883 10884 // If this load is directly stored, replace the load value with the stored 10885 // value. 10886 // TODO: Handle store large -> read small portion. 10887 // TODO: Handle TRUNCSTORE/LOADEXT 10888 if (OptLevel != CodeGenOpt::None && 10889 ISD::isNormalLoad(N) && !LD->isVolatile()) { 10890 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 10891 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 10892 if (PrevST->getBasePtr() == Ptr && 10893 PrevST->getValue().getValueType() == N->getValueType(0)) 10894 return CombineTo(N, Chain.getOperand(1), Chain); 10895 } 10896 } 10897 10898 // Try to infer better alignment information than the load already has. 10899 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 10900 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 10901 if (Align > LD->getMemOperand()->getBaseAlignment()) { 10902 SDValue NewLoad = DAG.getExtLoad( 10903 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 10904 LD->getPointerInfo(), LD->getMemoryVT(), Align, 10905 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 10906 if (NewLoad.getNode() != N) 10907 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 10908 } 10909 } 10910 } 10911 10912 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 10913 : DAG.getSubtarget().useAA(); 10914 #ifndef NDEBUG 10915 if (CombinerAAOnlyFunc.getNumOccurrences() && 10916 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 10917 UseAA = false; 10918 #endif 10919 if (UseAA && LD->isUnindexed()) { 10920 // Walk up chain skipping non-aliasing memory nodes. 10921 SDValue BetterChain = FindBetterChain(N, Chain); 10922 10923 // If there is a better chain. 10924 if (Chain != BetterChain) { 10925 SDValue ReplLoad; 10926 10927 // Replace the chain to void dependency. 10928 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 10929 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 10930 BetterChain, Ptr, LD->getMemOperand()); 10931 } else { 10932 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 10933 LD->getValueType(0), 10934 BetterChain, Ptr, LD->getMemoryVT(), 10935 LD->getMemOperand()); 10936 } 10937 10938 // Create token factor to keep old chain connected. 10939 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 10940 MVT::Other, Chain, ReplLoad.getValue(1)); 10941 10942 // Make sure the new and old chains are cleaned up. 10943 AddToWorklist(Token.getNode()); 10944 10945 // Replace uses with load result and token factor. Don't add users 10946 // to work list. 10947 return CombineTo(N, ReplLoad.getValue(0), Token, false); 10948 } 10949 } 10950 10951 // Try transforming N to an indexed load. 10952 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 10953 return SDValue(N, 0); 10954 10955 // Try to slice up N to more direct loads if the slices are mapped to 10956 // different register banks or pairing can take place. 10957 if (SliceUpLoad(N)) 10958 return SDValue(N, 0); 10959 10960 return SDValue(); 10961 } 10962 10963 namespace { 10964 /// \brief Helper structure used to slice a load in smaller loads. 10965 /// Basically a slice is obtained from the following sequence: 10966 /// Origin = load Ty1, Base 10967 /// Shift = srl Ty1 Origin, CstTy Amount 10968 /// Inst = trunc Shift to Ty2 10969 /// 10970 /// Then, it will be rewriten into: 10971 /// Slice = load SliceTy, Base + SliceOffset 10972 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 10973 /// 10974 /// SliceTy is deduced from the number of bits that are actually used to 10975 /// build Inst. 10976 struct LoadedSlice { 10977 /// \brief Helper structure used to compute the cost of a slice. 10978 struct Cost { 10979 /// Are we optimizing for code size. 10980 bool ForCodeSize; 10981 /// Various cost. 10982 unsigned Loads; 10983 unsigned Truncates; 10984 unsigned CrossRegisterBanksCopies; 10985 unsigned ZExts; 10986 unsigned Shift; 10987 10988 Cost(bool ForCodeSize = false) 10989 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 10990 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 10991 10992 /// \brief Get the cost of one isolated slice. 10993 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 10994 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 10995 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 10996 EVT TruncType = LS.Inst->getValueType(0); 10997 EVT LoadedType = LS.getLoadedType(); 10998 if (TruncType != LoadedType && 10999 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 11000 ZExts = 1; 11001 } 11002 11003 /// \brief Account for slicing gain in the current cost. 11004 /// Slicing provide a few gains like removing a shift or a 11005 /// truncate. This method allows to grow the cost of the original 11006 /// load with the gain from this slice. 11007 void addSliceGain(const LoadedSlice &LS) { 11008 // Each slice saves a truncate. 11009 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 11010 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 11011 LS.Inst->getValueType(0))) 11012 ++Truncates; 11013 // If there is a shift amount, this slice gets rid of it. 11014 if (LS.Shift) 11015 ++Shift; 11016 // If this slice can merge a cross register bank copy, account for it. 11017 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 11018 ++CrossRegisterBanksCopies; 11019 } 11020 11021 Cost &operator+=(const Cost &RHS) { 11022 Loads += RHS.Loads; 11023 Truncates += RHS.Truncates; 11024 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 11025 ZExts += RHS.ZExts; 11026 Shift += RHS.Shift; 11027 return *this; 11028 } 11029 11030 bool operator==(const Cost &RHS) const { 11031 return Loads == RHS.Loads && Truncates == RHS.Truncates && 11032 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 11033 ZExts == RHS.ZExts && Shift == RHS.Shift; 11034 } 11035 11036 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 11037 11038 bool operator<(const Cost &RHS) const { 11039 // Assume cross register banks copies are as expensive as loads. 11040 // FIXME: Do we want some more target hooks? 11041 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 11042 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 11043 // Unless we are optimizing for code size, consider the 11044 // expensive operation first. 11045 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 11046 return ExpensiveOpsLHS < ExpensiveOpsRHS; 11047 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 11048 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 11049 } 11050 11051 bool operator>(const Cost &RHS) const { return RHS < *this; } 11052 11053 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 11054 11055 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 11056 }; 11057 // The last instruction that represent the slice. This should be a 11058 // truncate instruction. 11059 SDNode *Inst; 11060 // The original load instruction. 11061 LoadSDNode *Origin; 11062 // The right shift amount in bits from the original load. 11063 unsigned Shift; 11064 // The DAG from which Origin came from. 11065 // This is used to get some contextual information about legal types, etc. 11066 SelectionDAG *DAG; 11067 11068 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 11069 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 11070 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 11071 11072 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 11073 /// \return Result is \p BitWidth and has used bits set to 1 and 11074 /// not used bits set to 0. 11075 APInt getUsedBits() const { 11076 // Reproduce the trunc(lshr) sequence: 11077 // - Start from the truncated value. 11078 // - Zero extend to the desired bit width. 11079 // - Shift left. 11080 assert(Origin && "No original load to compare against."); 11081 unsigned BitWidth = Origin->getValueSizeInBits(0); 11082 assert(Inst && "This slice is not bound to an instruction"); 11083 assert(Inst->getValueSizeInBits(0) <= BitWidth && 11084 "Extracted slice is bigger than the whole type!"); 11085 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 11086 UsedBits.setAllBits(); 11087 UsedBits = UsedBits.zext(BitWidth); 11088 UsedBits <<= Shift; 11089 return UsedBits; 11090 } 11091 11092 /// \brief Get the size of the slice to be loaded in bytes. 11093 unsigned getLoadedSize() const { 11094 unsigned SliceSize = getUsedBits().countPopulation(); 11095 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 11096 return SliceSize / 8; 11097 } 11098 11099 /// \brief Get the type that will be loaded for this slice. 11100 /// Note: This may not be the final type for the slice. 11101 EVT getLoadedType() const { 11102 assert(DAG && "Missing context"); 11103 LLVMContext &Ctxt = *DAG->getContext(); 11104 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 11105 } 11106 11107 /// \brief Get the alignment of the load used for this slice. 11108 unsigned getAlignment() const { 11109 unsigned Alignment = Origin->getAlignment(); 11110 unsigned Offset = getOffsetFromBase(); 11111 if (Offset != 0) 11112 Alignment = MinAlign(Alignment, Alignment + Offset); 11113 return Alignment; 11114 } 11115 11116 /// \brief Check if this slice can be rewritten with legal operations. 11117 bool isLegal() const { 11118 // An invalid slice is not legal. 11119 if (!Origin || !Inst || !DAG) 11120 return false; 11121 11122 // Offsets are for indexed load only, we do not handle that. 11123 if (!Origin->getOffset().isUndef()) 11124 return false; 11125 11126 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 11127 11128 // Check that the type is legal. 11129 EVT SliceType = getLoadedType(); 11130 if (!TLI.isTypeLegal(SliceType)) 11131 return false; 11132 11133 // Check that the load is legal for this type. 11134 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 11135 return false; 11136 11137 // Check that the offset can be computed. 11138 // 1. Check its type. 11139 EVT PtrType = Origin->getBasePtr().getValueType(); 11140 if (PtrType == MVT::Untyped || PtrType.isExtended()) 11141 return false; 11142 11143 // 2. Check that it fits in the immediate. 11144 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 11145 return false; 11146 11147 // 3. Check that the computation is legal. 11148 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 11149 return false; 11150 11151 // Check that the zext is legal if it needs one. 11152 EVT TruncateType = Inst->getValueType(0); 11153 if (TruncateType != SliceType && 11154 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 11155 return false; 11156 11157 return true; 11158 } 11159 11160 /// \brief Get the offset in bytes of this slice in the original chunk of 11161 /// bits. 11162 /// \pre DAG != nullptr. 11163 uint64_t getOffsetFromBase() const { 11164 assert(DAG && "Missing context."); 11165 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 11166 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 11167 uint64_t Offset = Shift / 8; 11168 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 11169 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 11170 "The size of the original loaded type is not a multiple of a" 11171 " byte."); 11172 // If Offset is bigger than TySizeInBytes, it means we are loading all 11173 // zeros. This should have been optimized before in the process. 11174 assert(TySizeInBytes > Offset && 11175 "Invalid shift amount for given loaded size"); 11176 if (IsBigEndian) 11177 Offset = TySizeInBytes - Offset - getLoadedSize(); 11178 return Offset; 11179 } 11180 11181 /// \brief Generate the sequence of instructions to load the slice 11182 /// represented by this object and redirect the uses of this slice to 11183 /// this new sequence of instructions. 11184 /// \pre this->Inst && this->Origin are valid Instructions and this 11185 /// object passed the legal check: LoadedSlice::isLegal returned true. 11186 /// \return The last instruction of the sequence used to load the slice. 11187 SDValue loadSlice() const { 11188 assert(Inst && Origin && "Unable to replace a non-existing slice."); 11189 const SDValue &OldBaseAddr = Origin->getBasePtr(); 11190 SDValue BaseAddr = OldBaseAddr; 11191 // Get the offset in that chunk of bytes w.r.t. the endianness. 11192 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 11193 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 11194 if (Offset) { 11195 // BaseAddr = BaseAddr + Offset. 11196 EVT ArithType = BaseAddr.getValueType(); 11197 SDLoc DL(Origin); 11198 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 11199 DAG->getConstant(Offset, DL, ArithType)); 11200 } 11201 11202 // Create the type of the loaded slice according to its size. 11203 EVT SliceType = getLoadedType(); 11204 11205 // Create the load for the slice. 11206 SDValue LastInst = 11207 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 11208 Origin->getPointerInfo().getWithOffset(Offset), 11209 getAlignment(), Origin->getMemOperand()->getFlags()); 11210 // If the final type is not the same as the loaded type, this means that 11211 // we have to pad with zero. Create a zero extend for that. 11212 EVT FinalType = Inst->getValueType(0); 11213 if (SliceType != FinalType) 11214 LastInst = 11215 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 11216 return LastInst; 11217 } 11218 11219 /// \brief Check if this slice can be merged with an expensive cross register 11220 /// bank copy. E.g., 11221 /// i = load i32 11222 /// f = bitcast i32 i to float 11223 bool canMergeExpensiveCrossRegisterBankCopy() const { 11224 if (!Inst || !Inst->hasOneUse()) 11225 return false; 11226 SDNode *Use = *Inst->use_begin(); 11227 if (Use->getOpcode() != ISD::BITCAST) 11228 return false; 11229 assert(DAG && "Missing context"); 11230 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 11231 EVT ResVT = Use->getValueType(0); 11232 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 11233 const TargetRegisterClass *ArgRC = 11234 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 11235 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 11236 return false; 11237 11238 // At this point, we know that we perform a cross-register-bank copy. 11239 // Check if it is expensive. 11240 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 11241 // Assume bitcasts are cheap, unless both register classes do not 11242 // explicitly share a common sub class. 11243 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 11244 return false; 11245 11246 // Check if it will be merged with the load. 11247 // 1. Check the alignment constraint. 11248 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 11249 ResVT.getTypeForEVT(*DAG->getContext())); 11250 11251 if (RequiredAlignment > getAlignment()) 11252 return false; 11253 11254 // 2. Check that the load is a legal operation for that type. 11255 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 11256 return false; 11257 11258 // 3. Check that we do not have a zext in the way. 11259 if (Inst->getValueType(0) != getLoadedType()) 11260 return false; 11261 11262 return true; 11263 } 11264 }; 11265 } 11266 11267 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 11268 /// \p UsedBits looks like 0..0 1..1 0..0. 11269 static bool areUsedBitsDense(const APInt &UsedBits) { 11270 // If all the bits are one, this is dense! 11271 if (UsedBits.isAllOnesValue()) 11272 return true; 11273 11274 // Get rid of the unused bits on the right. 11275 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 11276 // Get rid of the unused bits on the left. 11277 if (NarrowedUsedBits.countLeadingZeros()) 11278 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 11279 // Check that the chunk of bits is completely used. 11280 return NarrowedUsedBits.isAllOnesValue(); 11281 } 11282 11283 /// \brief Check whether or not \p First and \p Second are next to each other 11284 /// in memory. This means that there is no hole between the bits loaded 11285 /// by \p First and the bits loaded by \p Second. 11286 static bool areSlicesNextToEachOther(const LoadedSlice &First, 11287 const LoadedSlice &Second) { 11288 assert(First.Origin == Second.Origin && First.Origin && 11289 "Unable to match different memory origins."); 11290 APInt UsedBits = First.getUsedBits(); 11291 assert((UsedBits & Second.getUsedBits()) == 0 && 11292 "Slices are not supposed to overlap."); 11293 UsedBits |= Second.getUsedBits(); 11294 return areUsedBitsDense(UsedBits); 11295 } 11296 11297 /// \brief Adjust the \p GlobalLSCost according to the target 11298 /// paring capabilities and the layout of the slices. 11299 /// \pre \p GlobalLSCost should account for at least as many loads as 11300 /// there is in the slices in \p LoadedSlices. 11301 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 11302 LoadedSlice::Cost &GlobalLSCost) { 11303 unsigned NumberOfSlices = LoadedSlices.size(); 11304 // If there is less than 2 elements, no pairing is possible. 11305 if (NumberOfSlices < 2) 11306 return; 11307 11308 // Sort the slices so that elements that are likely to be next to each 11309 // other in memory are next to each other in the list. 11310 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 11311 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 11312 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 11313 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 11314 }); 11315 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 11316 // First (resp. Second) is the first (resp. Second) potentially candidate 11317 // to be placed in a paired load. 11318 const LoadedSlice *First = nullptr; 11319 const LoadedSlice *Second = nullptr; 11320 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 11321 // Set the beginning of the pair. 11322 First = Second) { 11323 11324 Second = &LoadedSlices[CurrSlice]; 11325 11326 // If First is NULL, it means we start a new pair. 11327 // Get to the next slice. 11328 if (!First) 11329 continue; 11330 11331 EVT LoadedType = First->getLoadedType(); 11332 11333 // If the types of the slices are different, we cannot pair them. 11334 if (LoadedType != Second->getLoadedType()) 11335 continue; 11336 11337 // Check if the target supplies paired loads for this type. 11338 unsigned RequiredAlignment = 0; 11339 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 11340 // move to the next pair, this type is hopeless. 11341 Second = nullptr; 11342 continue; 11343 } 11344 // Check if we meet the alignment requirement. 11345 if (RequiredAlignment > First->getAlignment()) 11346 continue; 11347 11348 // Check that both loads are next to each other in memory. 11349 if (!areSlicesNextToEachOther(*First, *Second)) 11350 continue; 11351 11352 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 11353 --GlobalLSCost.Loads; 11354 // Move to the next pair. 11355 Second = nullptr; 11356 } 11357 } 11358 11359 /// \brief Check the profitability of all involved LoadedSlice. 11360 /// Currently, it is considered profitable if there is exactly two 11361 /// involved slices (1) which are (2) next to each other in memory, and 11362 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 11363 /// 11364 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 11365 /// the elements themselves. 11366 /// 11367 /// FIXME: When the cost model will be mature enough, we can relax 11368 /// constraints (1) and (2). 11369 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 11370 const APInt &UsedBits, bool ForCodeSize) { 11371 unsigned NumberOfSlices = LoadedSlices.size(); 11372 if (StressLoadSlicing) 11373 return NumberOfSlices > 1; 11374 11375 // Check (1). 11376 if (NumberOfSlices != 2) 11377 return false; 11378 11379 // Check (2). 11380 if (!areUsedBitsDense(UsedBits)) 11381 return false; 11382 11383 // Check (3). 11384 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 11385 // The original code has one big load. 11386 OrigCost.Loads = 1; 11387 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 11388 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 11389 // Accumulate the cost of all the slices. 11390 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 11391 GlobalSlicingCost += SliceCost; 11392 11393 // Account as cost in the original configuration the gain obtained 11394 // with the current slices. 11395 OrigCost.addSliceGain(LS); 11396 } 11397 11398 // If the target supports paired load, adjust the cost accordingly. 11399 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 11400 return OrigCost > GlobalSlicingCost; 11401 } 11402 11403 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 11404 /// operations, split it in the various pieces being extracted. 11405 /// 11406 /// This sort of thing is introduced by SROA. 11407 /// This slicing takes care not to insert overlapping loads. 11408 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 11409 bool DAGCombiner::SliceUpLoad(SDNode *N) { 11410 if (Level < AfterLegalizeDAG) 11411 return false; 11412 11413 LoadSDNode *LD = cast<LoadSDNode>(N); 11414 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 11415 !LD->getValueType(0).isInteger()) 11416 return false; 11417 11418 // Keep track of already used bits to detect overlapping values. 11419 // In that case, we will just abort the transformation. 11420 APInt UsedBits(LD->getValueSizeInBits(0), 0); 11421 11422 SmallVector<LoadedSlice, 4> LoadedSlices; 11423 11424 // Check if this load is used as several smaller chunks of bits. 11425 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 11426 // of computation for each trunc. 11427 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 11428 UI != UIEnd; ++UI) { 11429 // Skip the uses of the chain. 11430 if (UI.getUse().getResNo() != 0) 11431 continue; 11432 11433 SDNode *User = *UI; 11434 unsigned Shift = 0; 11435 11436 // Check if this is a trunc(lshr). 11437 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 11438 isa<ConstantSDNode>(User->getOperand(1))) { 11439 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 11440 User = *User->use_begin(); 11441 } 11442 11443 // At this point, User is a Truncate, iff we encountered, trunc or 11444 // trunc(lshr). 11445 if (User->getOpcode() != ISD::TRUNCATE) 11446 return false; 11447 11448 // The width of the type must be a power of 2 and greater than 8-bits. 11449 // Otherwise the load cannot be represented in LLVM IR. 11450 // Moreover, if we shifted with a non-8-bits multiple, the slice 11451 // will be across several bytes. We do not support that. 11452 unsigned Width = User->getValueSizeInBits(0); 11453 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 11454 return 0; 11455 11456 // Build the slice for this chain of computations. 11457 LoadedSlice LS(User, LD, Shift, &DAG); 11458 APInt CurrentUsedBits = LS.getUsedBits(); 11459 11460 // Check if this slice overlaps with another. 11461 if ((CurrentUsedBits & UsedBits) != 0) 11462 return false; 11463 // Update the bits used globally. 11464 UsedBits |= CurrentUsedBits; 11465 11466 // Check if the new slice would be legal. 11467 if (!LS.isLegal()) 11468 return false; 11469 11470 // Record the slice. 11471 LoadedSlices.push_back(LS); 11472 } 11473 11474 // Abort slicing if it does not seem to be profitable. 11475 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 11476 return false; 11477 11478 ++SlicedLoads; 11479 11480 // Rewrite each chain to use an independent load. 11481 // By construction, each chain can be represented by a unique load. 11482 11483 // Prepare the argument for the new token factor for all the slices. 11484 SmallVector<SDValue, 8> ArgChains; 11485 for (SmallVectorImpl<LoadedSlice>::const_iterator 11486 LSIt = LoadedSlices.begin(), 11487 LSItEnd = LoadedSlices.end(); 11488 LSIt != LSItEnd; ++LSIt) { 11489 SDValue SliceInst = LSIt->loadSlice(); 11490 CombineTo(LSIt->Inst, SliceInst, true); 11491 if (SliceInst.getOpcode() != ISD::LOAD) 11492 SliceInst = SliceInst.getOperand(0); 11493 assert(SliceInst->getOpcode() == ISD::LOAD && 11494 "It takes more than a zext to get to the loaded slice!!"); 11495 ArgChains.push_back(SliceInst.getValue(1)); 11496 } 11497 11498 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 11499 ArgChains); 11500 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 11501 return true; 11502 } 11503 11504 /// Check to see if V is (and load (ptr), imm), where the load is having 11505 /// specific bytes cleared out. If so, return the byte size being masked out 11506 /// and the shift amount. 11507 static std::pair<unsigned, unsigned> 11508 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 11509 std::pair<unsigned, unsigned> Result(0, 0); 11510 11511 // Check for the structure we're looking for. 11512 if (V->getOpcode() != ISD::AND || 11513 !isa<ConstantSDNode>(V->getOperand(1)) || 11514 !ISD::isNormalLoad(V->getOperand(0).getNode())) 11515 return Result; 11516 11517 // Check the chain and pointer. 11518 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 11519 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 11520 11521 // The store should be chained directly to the load or be an operand of a 11522 // tokenfactor. 11523 if (LD == Chain.getNode()) 11524 ; // ok. 11525 else if (Chain->getOpcode() != ISD::TokenFactor) 11526 return Result; // Fail. 11527 else { 11528 bool isOk = false; 11529 for (const SDValue &ChainOp : Chain->op_values()) 11530 if (ChainOp.getNode() == LD) { 11531 isOk = true; 11532 break; 11533 } 11534 if (!isOk) return Result; 11535 } 11536 11537 // This only handles simple types. 11538 if (V.getValueType() != MVT::i16 && 11539 V.getValueType() != MVT::i32 && 11540 V.getValueType() != MVT::i64) 11541 return Result; 11542 11543 // Check the constant mask. Invert it so that the bits being masked out are 11544 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 11545 // follow the sign bit for uniformity. 11546 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 11547 unsigned NotMaskLZ = countLeadingZeros(NotMask); 11548 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 11549 unsigned NotMaskTZ = countTrailingZeros(NotMask); 11550 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 11551 if (NotMaskLZ == 64) return Result; // All zero mask. 11552 11553 // See if we have a continuous run of bits. If so, we have 0*1+0* 11554 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 11555 return Result; 11556 11557 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 11558 if (V.getValueType() != MVT::i64 && NotMaskLZ) 11559 NotMaskLZ -= 64-V.getValueSizeInBits(); 11560 11561 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 11562 switch (MaskedBytes) { 11563 case 1: 11564 case 2: 11565 case 4: break; 11566 default: return Result; // All one mask, or 5-byte mask. 11567 } 11568 11569 // Verify that the first bit starts at a multiple of mask so that the access 11570 // is aligned the same as the access width. 11571 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 11572 11573 Result.first = MaskedBytes; 11574 Result.second = NotMaskTZ/8; 11575 return Result; 11576 } 11577 11578 11579 /// Check to see if IVal is something that provides a value as specified by 11580 /// MaskInfo. If so, replace the specified store with a narrower store of 11581 /// truncated IVal. 11582 static SDNode * 11583 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 11584 SDValue IVal, StoreSDNode *St, 11585 DAGCombiner *DC) { 11586 unsigned NumBytes = MaskInfo.first; 11587 unsigned ByteShift = MaskInfo.second; 11588 SelectionDAG &DAG = DC->getDAG(); 11589 11590 // Check to see if IVal is all zeros in the part being masked in by the 'or' 11591 // that uses this. If not, this is not a replacement. 11592 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 11593 ByteShift*8, (ByteShift+NumBytes)*8); 11594 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 11595 11596 // Check that it is legal on the target to do this. It is legal if the new 11597 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 11598 // legalization. 11599 MVT VT = MVT::getIntegerVT(NumBytes*8); 11600 if (!DC->isTypeLegal(VT)) 11601 return nullptr; 11602 11603 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 11604 // shifted by ByteShift and truncated down to NumBytes. 11605 if (ByteShift) { 11606 SDLoc DL(IVal); 11607 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 11608 DAG.getConstant(ByteShift*8, DL, 11609 DC->getShiftAmountTy(IVal.getValueType()))); 11610 } 11611 11612 // Figure out the offset for the store and the alignment of the access. 11613 unsigned StOffset; 11614 unsigned NewAlign = St->getAlignment(); 11615 11616 if (DAG.getDataLayout().isLittleEndian()) 11617 StOffset = ByteShift; 11618 else 11619 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 11620 11621 SDValue Ptr = St->getBasePtr(); 11622 if (StOffset) { 11623 SDLoc DL(IVal); 11624 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 11625 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 11626 NewAlign = MinAlign(NewAlign, StOffset); 11627 } 11628 11629 // Truncate down to the new size. 11630 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 11631 11632 ++OpsNarrowed; 11633 return DAG 11634 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 11635 St->getPointerInfo().getWithOffset(StOffset), NewAlign) 11636 .getNode(); 11637 } 11638 11639 11640 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 11641 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 11642 /// narrowing the load and store if it would end up being a win for performance 11643 /// or code size. 11644 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 11645 StoreSDNode *ST = cast<StoreSDNode>(N); 11646 if (ST->isVolatile()) 11647 return SDValue(); 11648 11649 SDValue Chain = ST->getChain(); 11650 SDValue Value = ST->getValue(); 11651 SDValue Ptr = ST->getBasePtr(); 11652 EVT VT = Value.getValueType(); 11653 11654 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 11655 return SDValue(); 11656 11657 unsigned Opc = Value.getOpcode(); 11658 11659 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 11660 // is a byte mask indicating a consecutive number of bytes, check to see if 11661 // Y is known to provide just those bytes. If so, we try to replace the 11662 // load + replace + store sequence with a single (narrower) store, which makes 11663 // the load dead. 11664 if (Opc == ISD::OR) { 11665 std::pair<unsigned, unsigned> MaskedLoad; 11666 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 11667 if (MaskedLoad.first) 11668 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 11669 Value.getOperand(1), ST,this)) 11670 return SDValue(NewST, 0); 11671 11672 // Or is commutative, so try swapping X and Y. 11673 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 11674 if (MaskedLoad.first) 11675 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 11676 Value.getOperand(0), ST,this)) 11677 return SDValue(NewST, 0); 11678 } 11679 11680 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 11681 Value.getOperand(1).getOpcode() != ISD::Constant) 11682 return SDValue(); 11683 11684 SDValue N0 = Value.getOperand(0); 11685 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 11686 Chain == SDValue(N0.getNode(), 1)) { 11687 LoadSDNode *LD = cast<LoadSDNode>(N0); 11688 if (LD->getBasePtr() != Ptr || 11689 LD->getPointerInfo().getAddrSpace() != 11690 ST->getPointerInfo().getAddrSpace()) 11691 return SDValue(); 11692 11693 // Find the type to narrow it the load / op / store to. 11694 SDValue N1 = Value.getOperand(1); 11695 unsigned BitWidth = N1.getValueSizeInBits(); 11696 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 11697 if (Opc == ISD::AND) 11698 Imm ^= APInt::getAllOnesValue(BitWidth); 11699 if (Imm == 0 || Imm.isAllOnesValue()) 11700 return SDValue(); 11701 unsigned ShAmt = Imm.countTrailingZeros(); 11702 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 11703 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 11704 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 11705 // The narrowing should be profitable, the load/store operation should be 11706 // legal (or custom) and the store size should be equal to the NewVT width. 11707 while (NewBW < BitWidth && 11708 (NewVT.getStoreSizeInBits() != NewBW || 11709 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 11710 !TLI.isNarrowingProfitable(VT, NewVT))) { 11711 NewBW = NextPowerOf2(NewBW); 11712 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 11713 } 11714 if (NewBW >= BitWidth) 11715 return SDValue(); 11716 11717 // If the lsb changed does not start at the type bitwidth boundary, 11718 // start at the previous one. 11719 if (ShAmt % NewBW) 11720 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 11721 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 11722 std::min(BitWidth, ShAmt + NewBW)); 11723 if ((Imm & Mask) == Imm) { 11724 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 11725 if (Opc == ISD::AND) 11726 NewImm ^= APInt::getAllOnesValue(NewBW); 11727 uint64_t PtrOff = ShAmt / 8; 11728 // For big endian targets, we need to adjust the offset to the pointer to 11729 // load the correct bytes. 11730 if (DAG.getDataLayout().isBigEndian()) 11731 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 11732 11733 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 11734 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 11735 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 11736 return SDValue(); 11737 11738 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 11739 Ptr.getValueType(), Ptr, 11740 DAG.getConstant(PtrOff, SDLoc(LD), 11741 Ptr.getValueType())); 11742 SDValue NewLD = 11743 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 11744 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 11745 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 11746 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 11747 DAG.getConstant(NewImm, SDLoc(Value), 11748 NewVT)); 11749 SDValue NewST = 11750 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 11751 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 11752 11753 AddToWorklist(NewPtr.getNode()); 11754 AddToWorklist(NewLD.getNode()); 11755 AddToWorklist(NewVal.getNode()); 11756 WorklistRemover DeadNodes(*this); 11757 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 11758 ++OpsNarrowed; 11759 return NewST; 11760 } 11761 } 11762 11763 return SDValue(); 11764 } 11765 11766 /// For a given floating point load / store pair, if the load value isn't used 11767 /// by any other operations, then consider transforming the pair to integer 11768 /// load / store operations if the target deems the transformation profitable. 11769 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 11770 StoreSDNode *ST = cast<StoreSDNode>(N); 11771 SDValue Chain = ST->getChain(); 11772 SDValue Value = ST->getValue(); 11773 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 11774 Value.hasOneUse() && 11775 Chain == SDValue(Value.getNode(), 1)) { 11776 LoadSDNode *LD = cast<LoadSDNode>(Value); 11777 EVT VT = LD->getMemoryVT(); 11778 if (!VT.isFloatingPoint() || 11779 VT != ST->getMemoryVT() || 11780 LD->isNonTemporal() || 11781 ST->isNonTemporal() || 11782 LD->getPointerInfo().getAddrSpace() != 0 || 11783 ST->getPointerInfo().getAddrSpace() != 0) 11784 return SDValue(); 11785 11786 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 11787 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 11788 !TLI.isOperationLegal(ISD::STORE, IntVT) || 11789 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 11790 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 11791 return SDValue(); 11792 11793 unsigned LDAlign = LD->getAlignment(); 11794 unsigned STAlign = ST->getAlignment(); 11795 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 11796 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 11797 if (LDAlign < ABIAlign || STAlign < ABIAlign) 11798 return SDValue(); 11799 11800 SDValue NewLD = 11801 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 11802 LD->getPointerInfo(), LDAlign); 11803 11804 SDValue NewST = 11805 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(), 11806 ST->getPointerInfo(), STAlign); 11807 11808 AddToWorklist(NewLD.getNode()); 11809 AddToWorklist(NewST.getNode()); 11810 WorklistRemover DeadNodes(*this); 11811 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 11812 ++LdStFP2Int; 11813 return NewST; 11814 } 11815 11816 return SDValue(); 11817 } 11818 11819 // This is a helper function for visitMUL to check the profitability 11820 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 11821 // MulNode is the original multiply, AddNode is (add x, c1), 11822 // and ConstNode is c2. 11823 // 11824 // If the (add x, c1) has multiple uses, we could increase 11825 // the number of adds if we make this transformation. 11826 // It would only be worth doing this if we can remove a 11827 // multiply in the process. Check for that here. 11828 // To illustrate: 11829 // (A + c1) * c3 11830 // (A + c2) * c3 11831 // We're checking for cases where we have common "c3 * A" expressions. 11832 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 11833 SDValue &AddNode, 11834 SDValue &ConstNode) { 11835 APInt Val; 11836 11837 // If the add only has one use, this would be OK to do. 11838 if (AddNode.getNode()->hasOneUse()) 11839 return true; 11840 11841 // Walk all the users of the constant with which we're multiplying. 11842 for (SDNode *Use : ConstNode->uses()) { 11843 11844 if (Use == MulNode) // This use is the one we're on right now. Skip it. 11845 continue; 11846 11847 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 11848 SDNode *OtherOp; 11849 SDNode *MulVar = AddNode.getOperand(0).getNode(); 11850 11851 // OtherOp is what we're multiplying against the constant. 11852 if (Use->getOperand(0) == ConstNode) 11853 OtherOp = Use->getOperand(1).getNode(); 11854 else 11855 OtherOp = Use->getOperand(0).getNode(); 11856 11857 // Check to see if multiply is with the same operand of our "add". 11858 // 11859 // ConstNode = CONST 11860 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 11861 // ... 11862 // AddNode = (A + c1) <-- MulVar is A. 11863 // = AddNode * ConstNode <-- current visiting instruction. 11864 // 11865 // If we make this transformation, we will have a common 11866 // multiply (ConstNode * A) that we can save. 11867 if (OtherOp == MulVar) 11868 return true; 11869 11870 // Now check to see if a future expansion will give us a common 11871 // multiply. 11872 // 11873 // ConstNode = CONST 11874 // AddNode = (A + c1) 11875 // ... = AddNode * ConstNode <-- current visiting instruction. 11876 // ... 11877 // OtherOp = (A + c2) 11878 // Use = OtherOp * ConstNode <-- visiting Use. 11879 // 11880 // If we make this transformation, we will have a common 11881 // multiply (CONST * A) after we also do the same transformation 11882 // to the "t2" instruction. 11883 if (OtherOp->getOpcode() == ISD::ADD && 11884 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 11885 OtherOp->getOperand(0).getNode() == MulVar) 11886 return true; 11887 } 11888 } 11889 11890 // Didn't find a case where this would be profitable. 11891 return false; 11892 } 11893 11894 SDValue DAGCombiner::getMergedConstantVectorStore( 11895 SelectionDAG &DAG, const SDLoc &SL, ArrayRef<MemOpLink> Stores, 11896 SmallVectorImpl<SDValue> &Chains, EVT Ty) const { 11897 SmallVector<SDValue, 8> BuildVector; 11898 11899 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) { 11900 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode); 11901 Chains.push_back(St->getChain()); 11902 BuildVector.push_back(St->getValue()); 11903 } 11904 11905 return DAG.getBuildVector(Ty, SL, BuildVector); 11906 } 11907 11908 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 11909 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 11910 unsigned NumStores, bool IsConstantSrc, bool UseVector) { 11911 // Make sure we have something to merge. 11912 if (NumStores < 2) 11913 return false; 11914 11915 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11916 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11917 unsigned LatestNodeUsed = 0; 11918 11919 for (unsigned i=0; i < NumStores; ++i) { 11920 // Find a chain for the new wide-store operand. Notice that some 11921 // of the store nodes that we found may not be selected for inclusion 11922 // in the wide store. The chain we use needs to be the chain of the 11923 // latest store node which is *used* and replaced by the wide store. 11924 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11925 LatestNodeUsed = i; 11926 } 11927 11928 SmallVector<SDValue, 8> Chains; 11929 11930 // The latest Node in the DAG. 11931 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11932 SDLoc DL(StoreNodes[0].MemNode); 11933 11934 SDValue StoredVal; 11935 if (UseVector) { 11936 bool IsVec = MemVT.isVector(); 11937 unsigned Elts = NumStores; 11938 if (IsVec) { 11939 // When merging vector stores, get the total number of elements. 11940 Elts *= MemVT.getVectorNumElements(); 11941 } 11942 // Get the type for the merged vector store. 11943 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11944 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 11945 11946 if (IsConstantSrc) { 11947 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty); 11948 } else { 11949 SmallVector<SDValue, 8> Ops; 11950 for (unsigned i = 0; i < NumStores; ++i) { 11951 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11952 SDValue Val = St->getValue(); 11953 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 11954 if (Val.getValueType() != MemVT) 11955 return false; 11956 Ops.push_back(Val); 11957 Chains.push_back(St->getChain()); 11958 } 11959 11960 // Build the extracted vector elements back into a vector. 11961 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 11962 DL, Ty, Ops); } 11963 } else { 11964 // We should always use a vector store when merging extracted vector 11965 // elements, so this path implies a store of constants. 11966 assert(IsConstantSrc && "Merged vector elements should use vector store"); 11967 11968 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 11969 APInt StoreInt(SizeInBits, 0); 11970 11971 // Construct a single integer constant which is made of the smaller 11972 // constant inputs. 11973 bool IsLE = DAG.getDataLayout().isLittleEndian(); 11974 for (unsigned i = 0; i < NumStores; ++i) { 11975 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 11976 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 11977 Chains.push_back(St->getChain()); 11978 11979 SDValue Val = St->getValue(); 11980 StoreInt <<= ElementSizeBytes * 8; 11981 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 11982 StoreInt |= C->getAPIntValue().zext(SizeInBits); 11983 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 11984 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits); 11985 } else { 11986 llvm_unreachable("Invalid constant element type"); 11987 } 11988 } 11989 11990 // Create the new Load and Store operations. 11991 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 11992 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 11993 } 11994 11995 assert(!Chains.empty()); 11996 11997 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11998 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal, 11999 FirstInChain->getBasePtr(), 12000 FirstInChain->getPointerInfo(), 12001 FirstInChain->getAlignment()); 12002 12003 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 12004 : DAG.getSubtarget().useAA(); 12005 if (UseAA) { 12006 // Replace all merged stores with the new store. 12007 for (unsigned i = 0; i < NumStores; ++i) 12008 CombineTo(StoreNodes[i].MemNode, NewStore); 12009 } else { 12010 // Replace the last store with the new store. 12011 CombineTo(LatestOp, NewStore); 12012 // Erase all other stores. 12013 for (unsigned i = 0; i < NumStores; ++i) { 12014 if (StoreNodes[i].MemNode == LatestOp) 12015 continue; 12016 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12017 // ReplaceAllUsesWith will replace all uses that existed when it was 12018 // called, but graph optimizations may cause new ones to appear. For 12019 // example, the case in pr14333 looks like 12020 // 12021 // St's chain -> St -> another store -> X 12022 // 12023 // And the only difference from St to the other store is the chain. 12024 // When we change it's chain to be St's chain they become identical, 12025 // get CSEed and the net result is that X is now a use of St. 12026 // Since we know that St is redundant, just iterate. 12027 while (!St->use_empty()) 12028 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 12029 deleteAndRecombine(St); 12030 } 12031 } 12032 12033 StoreNodes.erase(StoreNodes.begin() + NumStores, StoreNodes.end()); 12034 return true; 12035 } 12036 12037 void DAGCombiner::getStoreMergeAndAliasCandidates( 12038 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 12039 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) { 12040 // This holds the base pointer, index, and the offset in bytes from the base 12041 // pointer. 12042 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 12043 12044 // We must have a base and an offset. 12045 if (!BasePtr.Base.getNode()) 12046 return; 12047 12048 // Do not handle stores to undef base pointers. 12049 if (BasePtr.Base.isUndef()) 12050 return; 12051 12052 // Walk up the chain and look for nodes with offsets from the same 12053 // base pointer. Stop when reaching an instruction with a different kind 12054 // or instruction which has a different base pointer. 12055 EVT MemVT = St->getMemoryVT(); 12056 unsigned Seq = 0; 12057 StoreSDNode *Index = St; 12058 12059 12060 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 12061 : DAG.getSubtarget().useAA(); 12062 12063 if (UseAA) { 12064 // Look at other users of the same chain. Stores on the same chain do not 12065 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized 12066 // to be on the same chain, so don't bother looking at adjacent chains. 12067 12068 SDValue Chain = St->getChain(); 12069 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) { 12070 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 12071 if (I.getOperandNo() != 0) 12072 continue; 12073 12074 if (OtherST->isVolatile() || OtherST->isIndexed()) 12075 continue; 12076 12077 if (OtherST->getMemoryVT() != MemVT) 12078 continue; 12079 12080 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG); 12081 12082 if (Ptr.equalBaseIndex(BasePtr)) 12083 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++)); 12084 } 12085 } 12086 12087 return; 12088 } 12089 12090 while (Index) { 12091 // If the chain has more than one use, then we can't reorder the mem ops. 12092 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 12093 break; 12094 12095 // Find the base pointer and offset for this memory node. 12096 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 12097 12098 // Check that the base pointer is the same as the original one. 12099 if (!Ptr.equalBaseIndex(BasePtr)) 12100 break; 12101 12102 // The memory operands must not be volatile. 12103 if (Index->isVolatile() || Index->isIndexed()) 12104 break; 12105 12106 // No truncation. 12107 if (Index->isTruncatingStore()) 12108 break; 12109 12110 // The stored memory type must be the same. 12111 if (Index->getMemoryVT() != MemVT) 12112 break; 12113 12114 // We do not allow under-aligned stores in order to prevent 12115 // overriding stores. NOTE: this is a bad hack. Alignment SHOULD 12116 // be irrelevant here; what MATTERS is that we not move memory 12117 // operations that potentially overlap past each-other. 12118 if (Index->getAlignment() < MemVT.getStoreSize()) 12119 break; 12120 12121 // We found a potential memory operand to merge. 12122 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 12123 12124 // Find the next memory operand in the chain. If the next operand in the 12125 // chain is a store then move up and continue the scan with the next 12126 // memory operand. If the next operand is a load save it and use alias 12127 // information to check if it interferes with anything. 12128 SDNode *NextInChain = Index->getChain().getNode(); 12129 while (1) { 12130 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 12131 // We found a store node. Use it for the next iteration. 12132 Index = STn; 12133 break; 12134 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 12135 if (Ldn->isVolatile()) { 12136 Index = nullptr; 12137 break; 12138 } 12139 12140 // Save the load node for later. Continue the scan. 12141 AliasLoadNodes.push_back(Ldn); 12142 NextInChain = Ldn->getChain().getNode(); 12143 continue; 12144 } else { 12145 Index = nullptr; 12146 break; 12147 } 12148 } 12149 } 12150 } 12151 12152 // We need to check that merging these stores does not cause a loop 12153 // in the DAG. Any store candidate may depend on another candidate 12154 // indirectly through its operand (we already consider dependencies 12155 // through the chain). Check in parallel by searching up from 12156 // non-chain operands of candidates. 12157 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 12158 SmallVectorImpl<MemOpLink> &StoreNodes) { 12159 SmallPtrSet<const SDNode *, 16> Visited; 12160 SmallVector<const SDNode *, 8> Worklist; 12161 // search ops of store candidates 12162 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 12163 SDNode *n = StoreNodes[i].MemNode; 12164 // Potential loops may happen only through non-chain operands 12165 for (unsigned j = 1; j < n->getNumOperands(); ++j) 12166 Worklist.push_back(n->getOperand(j).getNode()); 12167 } 12168 // search through DAG. We can stop early if we find a storenode 12169 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 12170 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist)) 12171 return false; 12172 } 12173 return true; 12174 } 12175 12176 bool DAGCombiner::MergeConsecutiveStores( 12177 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes) { 12178 if (OptLevel == CodeGenOpt::None) 12179 return false; 12180 12181 EVT MemVT = St->getMemoryVT(); 12182 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 12183 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 12184 Attribute::NoImplicitFloat); 12185 12186 // This function cannot currently deal with non-byte-sized memory sizes. 12187 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 12188 return false; 12189 12190 if (!MemVT.isSimple()) 12191 return false; 12192 12193 // Perform an early exit check. Do not bother looking at stored values that 12194 // are not constants, loads, or extracted vector elements. 12195 SDValue StoredVal = St->getValue(); 12196 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 12197 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 12198 isa<ConstantFPSDNode>(StoredVal); 12199 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12200 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 12201 12202 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 12203 return false; 12204 12205 // Don't merge vectors into wider vectors if the source data comes from loads. 12206 // TODO: This restriction can be lifted by using logic similar to the 12207 // ExtractVecSrc case. 12208 if (MemVT.isVector() && IsLoadSrc) 12209 return false; 12210 12211 // Only look at ends of store sequences. 12212 SDValue Chain = SDValue(St, 0); 12213 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 12214 return false; 12215 12216 // Save the LoadSDNodes that we find in the chain. 12217 // We need to make sure that these nodes do not interfere with 12218 // any of the store nodes. 12219 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 12220 12221 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes); 12222 12223 // Check if there is anything to merge. 12224 if (StoreNodes.size() < 2) 12225 return false; 12226 12227 // only do dependence check in AA case 12228 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 12229 : DAG.getSubtarget().useAA(); 12230 if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes)) 12231 return false; 12232 12233 // Sort the memory operands according to their distance from the 12234 // base pointer. As a secondary criteria: make sure stores coming 12235 // later in the code come first in the list. This is important for 12236 // the non-UseAA case, because we're merging stores into the FINAL 12237 // store along a chain which potentially contains aliasing stores. 12238 // Thus, if there are multiple stores to the same address, the last 12239 // one can be considered for merging but not the others. 12240 std::sort(StoreNodes.begin(), StoreNodes.end(), 12241 [](MemOpLink LHS, MemOpLink RHS) { 12242 return LHS.OffsetFromBase < RHS.OffsetFromBase || 12243 (LHS.OffsetFromBase == RHS.OffsetFromBase && 12244 LHS.SequenceNum < RHS.SequenceNum); 12245 }); 12246 12247 // Scan the memory operations on the chain and find the first non-consecutive 12248 // store memory address. 12249 unsigned LastConsecutiveStore = 0; 12250 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 12251 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 12252 12253 // Check that the addresses are consecutive starting from the second 12254 // element in the list of stores. 12255 if (i > 0) { 12256 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 12257 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 12258 break; 12259 } 12260 12261 // Check if this store interferes with any of the loads that we found. 12262 // If we find a load that alias with this store. Stop the sequence. 12263 if (any_of(AliasLoadNodes, [&](LSBaseSDNode *Ldn) { 12264 return isAlias(Ldn, StoreNodes[i].MemNode); 12265 })) 12266 break; 12267 12268 // Mark this node as useful. 12269 LastConsecutiveStore = i; 12270 } 12271 12272 // The node with the lowest store address. 12273 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12274 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 12275 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 12276 LLVMContext &Context = *DAG.getContext(); 12277 const DataLayout &DL = DAG.getDataLayout(); 12278 12279 // Store the constants into memory as one consecutive store. 12280 if (IsConstantSrc) { 12281 unsigned LastLegalType = 0; 12282 unsigned LastLegalVectorType = 0; 12283 bool NonZero = false; 12284 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 12285 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12286 SDValue StoredVal = St->getValue(); 12287 12288 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 12289 NonZero |= !C->isNullValue(); 12290 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 12291 NonZero |= !C->getConstantFPValue()->isNullValue(); 12292 } else { 12293 // Non-constant. 12294 break; 12295 } 12296 12297 // Find a legal type for the constant store. 12298 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 12299 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 12300 bool IsFast; 12301 if (TLI.isTypeLegal(StoreTy) && 12302 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 12303 FirstStoreAlign, &IsFast) && IsFast) { 12304 LastLegalType = i+1; 12305 // Or check whether a truncstore is legal. 12306 } else if (TLI.getTypeAction(Context, StoreTy) == 12307 TargetLowering::TypePromoteInteger) { 12308 EVT LegalizedStoredValueTy = 12309 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 12310 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 12311 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 12312 FirstStoreAS, FirstStoreAlign, &IsFast) && 12313 IsFast) { 12314 LastLegalType = i + 1; 12315 } 12316 } 12317 12318 // We only use vectors if the constant is known to be zero or the target 12319 // allows it and the function is not marked with the noimplicitfloat 12320 // attribute. 12321 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1, 12322 FirstStoreAS)) && 12323 !NoVectors) { 12324 // Find a legal type for the vector store. 12325 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1); 12326 if (TLI.isTypeLegal(Ty) && 12327 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 12328 FirstStoreAlign, &IsFast) && IsFast) 12329 LastLegalVectorType = i + 1; 12330 } 12331 } 12332 12333 // Check if we found a legal integer type to store. 12334 if (LastLegalType == 0 && LastLegalVectorType == 0) 12335 return false; 12336 12337 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 12338 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 12339 12340 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 12341 true, UseVector); 12342 } 12343 12344 // When extracting multiple vector elements, try to store them 12345 // in one vector store rather than a sequence of scalar stores. 12346 if (IsExtractVecSrc) { 12347 unsigned NumStoresToMerge = 0; 12348 bool IsVec = MemVT.isVector(); 12349 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 12350 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12351 unsigned StoreValOpcode = St->getValue().getOpcode(); 12352 // This restriction could be loosened. 12353 // Bail out if any stored values are not elements extracted from a vector. 12354 // It should be possible to handle mixed sources, but load sources need 12355 // more careful handling (see the block of code below that handles 12356 // consecutive loads). 12357 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT && 12358 StoreValOpcode != ISD::EXTRACT_SUBVECTOR) 12359 return false; 12360 12361 // Find a legal type for the vector store. 12362 unsigned Elts = i + 1; 12363 if (IsVec) { 12364 // When merging vector stores, get the total number of elements. 12365 Elts *= MemVT.getVectorNumElements(); 12366 } 12367 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 12368 bool IsFast; 12369 if (TLI.isTypeLegal(Ty) && 12370 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 12371 FirstStoreAlign, &IsFast) && IsFast) 12372 NumStoresToMerge = i + 1; 12373 } 12374 12375 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge, 12376 false, true); 12377 } 12378 12379 // Below we handle the case of multiple consecutive stores that 12380 // come from multiple consecutive loads. We merge them into a single 12381 // wide load and a single wide store. 12382 12383 // Look for load nodes which are used by the stored values. 12384 SmallVector<MemOpLink, 8> LoadNodes; 12385 12386 // Find acceptable loads. Loads need to have the same chain (token factor), 12387 // must not be zext, volatile, indexed, and they must be consecutive. 12388 BaseIndexOffset LdBasePtr; 12389 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 12390 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12391 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 12392 if (!Ld) break; 12393 12394 // Loads must only have one use. 12395 if (!Ld->hasNUsesOfValue(1, 0)) 12396 break; 12397 12398 // The memory operands must not be volatile. 12399 if (Ld->isVolatile() || Ld->isIndexed()) 12400 break; 12401 12402 // We do not accept ext loads. 12403 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 12404 break; 12405 12406 // The stored memory type must be the same. 12407 if (Ld->getMemoryVT() != MemVT) 12408 break; 12409 12410 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 12411 // If this is not the first ptr that we check. 12412 if (LdBasePtr.Base.getNode()) { 12413 // The base ptr must be the same. 12414 if (!LdPtr.equalBaseIndex(LdBasePtr)) 12415 break; 12416 } else { 12417 // Check that all other base pointers are the same as this one. 12418 LdBasePtr = LdPtr; 12419 } 12420 12421 // We found a potential memory operand to merge. 12422 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 12423 } 12424 12425 if (LoadNodes.size() < 2) 12426 return false; 12427 12428 // If we have load/store pair instructions and we only have two values, 12429 // don't bother. 12430 unsigned RequiredAlignment; 12431 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 12432 St->getAlignment() >= RequiredAlignment) 12433 return false; 12434 12435 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 12436 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 12437 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 12438 12439 // Scan the memory operations on the chain and find the first non-consecutive 12440 // load memory address. These variables hold the index in the store node 12441 // array. 12442 unsigned LastConsecutiveLoad = 0; 12443 // This variable refers to the size and not index in the array. 12444 unsigned LastLegalVectorType = 0; 12445 unsigned LastLegalIntegerType = 0; 12446 StartAddress = LoadNodes[0].OffsetFromBase; 12447 SDValue FirstChain = FirstLoad->getChain(); 12448 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 12449 // All loads must share the same chain. 12450 if (LoadNodes[i].MemNode->getChain() != FirstChain) 12451 break; 12452 12453 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 12454 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 12455 break; 12456 LastConsecutiveLoad = i; 12457 // Find a legal type for the vector store. 12458 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1); 12459 bool IsFastSt, IsFastLd; 12460 if (TLI.isTypeLegal(StoreTy) && 12461 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 12462 FirstStoreAlign, &IsFastSt) && IsFastSt && 12463 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 12464 FirstLoadAlign, &IsFastLd) && IsFastLd) { 12465 LastLegalVectorType = i + 1; 12466 } 12467 12468 // Find a legal type for the integer store. 12469 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 12470 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 12471 if (TLI.isTypeLegal(StoreTy) && 12472 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 12473 FirstStoreAlign, &IsFastSt) && IsFastSt && 12474 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 12475 FirstLoadAlign, &IsFastLd) && IsFastLd) 12476 LastLegalIntegerType = i + 1; 12477 // Or check whether a truncstore and extload is legal. 12478 else if (TLI.getTypeAction(Context, StoreTy) == 12479 TargetLowering::TypePromoteInteger) { 12480 EVT LegalizedStoredValueTy = 12481 TLI.getTypeToTransformTo(Context, StoreTy); 12482 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 12483 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 12484 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 12485 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 12486 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 12487 FirstStoreAS, FirstStoreAlign, &IsFastSt) && 12488 IsFastSt && 12489 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 12490 FirstLoadAS, FirstLoadAlign, &IsFastLd) && 12491 IsFastLd) 12492 LastLegalIntegerType = i+1; 12493 } 12494 } 12495 12496 // Only use vector types if the vector type is larger than the integer type. 12497 // If they are the same, use integers. 12498 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 12499 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 12500 12501 // We add +1 here because the LastXXX variables refer to location while 12502 // the NumElem refers to array/index size. 12503 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 12504 NumElem = std::min(LastLegalType, NumElem); 12505 12506 if (NumElem < 2) 12507 return false; 12508 12509 // Collect the chains from all merged stores. 12510 SmallVector<SDValue, 8> MergeStoreChains; 12511 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain()); 12512 12513 // The latest Node in the DAG. 12514 unsigned LatestNodeUsed = 0; 12515 for (unsigned i=1; i<NumElem; ++i) { 12516 // Find a chain for the new wide-store operand. Notice that some 12517 // of the store nodes that we found may not be selected for inclusion 12518 // in the wide store. The chain we use needs to be the chain of the 12519 // latest store node which is *used* and replaced by the wide store. 12520 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 12521 LatestNodeUsed = i; 12522 12523 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain()); 12524 } 12525 12526 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 12527 12528 // Find if it is better to use vectors or integers to load and store 12529 // to memory. 12530 EVT JointMemOpVT; 12531 if (UseVectorTy) { 12532 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 12533 } else { 12534 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 12535 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 12536 } 12537 12538 SDLoc LoadDL(LoadNodes[0].MemNode); 12539 SDLoc StoreDL(StoreNodes[0].MemNode); 12540 12541 // The merged loads are required to have the same incoming chain, so 12542 // using the first's chain is acceptable. 12543 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(), 12544 FirstLoad->getBasePtr(), 12545 FirstLoad->getPointerInfo(), FirstLoadAlign); 12546 12547 SDValue NewStoreChain = 12548 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains); 12549 12550 SDValue NewStore = 12551 DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 12552 FirstInChain->getPointerInfo(), FirstStoreAlign); 12553 12554 // Transfer chain users from old loads to the new load. 12555 for (unsigned i = 0; i < NumElem; ++i) { 12556 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 12557 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 12558 SDValue(NewLoad.getNode(), 1)); 12559 } 12560 12561 if (UseAA) { 12562 // Replace the all stores with the new store. 12563 for (unsigned i = 0; i < NumElem; ++i) 12564 CombineTo(StoreNodes[i].MemNode, NewStore); 12565 } else { 12566 // Replace the last store with the new store. 12567 CombineTo(LatestOp, NewStore); 12568 // Erase all other stores. 12569 for (unsigned i = 0; i < NumElem; ++i) { 12570 // Remove all Store nodes. 12571 if (StoreNodes[i].MemNode == LatestOp) 12572 continue; 12573 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12574 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 12575 deleteAndRecombine(St); 12576 } 12577 } 12578 12579 StoreNodes.erase(StoreNodes.begin() + NumElem, StoreNodes.end()); 12580 return true; 12581 } 12582 12583 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 12584 SDLoc SL(ST); 12585 SDValue ReplStore; 12586 12587 // Replace the chain to avoid dependency. 12588 if (ST->isTruncatingStore()) { 12589 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 12590 ST->getBasePtr(), ST->getMemoryVT(), 12591 ST->getMemOperand()); 12592 } else { 12593 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 12594 ST->getMemOperand()); 12595 } 12596 12597 // Create token to keep both nodes around. 12598 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 12599 MVT::Other, ST->getChain(), ReplStore); 12600 12601 // Make sure the new and old chains are cleaned up. 12602 AddToWorklist(Token.getNode()); 12603 12604 // Don't add users to work list. 12605 return CombineTo(ST, Token, false); 12606 } 12607 12608 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 12609 SDValue Value = ST->getValue(); 12610 if (Value.getOpcode() == ISD::TargetConstantFP) 12611 return SDValue(); 12612 12613 SDLoc DL(ST); 12614 12615 SDValue Chain = ST->getChain(); 12616 SDValue Ptr = ST->getBasePtr(); 12617 12618 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 12619 12620 // NOTE: If the original store is volatile, this transform must not increase 12621 // the number of stores. For example, on x86-32 an f64 can be stored in one 12622 // processor operation but an i64 (which is not legal) requires two. So the 12623 // transform should not be done in this case. 12624 12625 SDValue Tmp; 12626 switch (CFP->getSimpleValueType(0).SimpleTy) { 12627 default: 12628 llvm_unreachable("Unknown FP type"); 12629 case MVT::f16: // We don't do this for these yet. 12630 case MVT::f80: 12631 case MVT::f128: 12632 case MVT::ppcf128: 12633 return SDValue(); 12634 case MVT::f32: 12635 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 12636 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 12637 ; 12638 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 12639 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 12640 MVT::i32); 12641 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 12642 } 12643 12644 return SDValue(); 12645 case MVT::f64: 12646 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 12647 !ST->isVolatile()) || 12648 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 12649 ; 12650 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 12651 getZExtValue(), SDLoc(CFP), MVT::i64); 12652 return DAG.getStore(Chain, DL, Tmp, 12653 Ptr, ST->getMemOperand()); 12654 } 12655 12656 if (!ST->isVolatile() && 12657 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 12658 // Many FP stores are not made apparent until after legalize, e.g. for 12659 // argument passing. Since this is so common, custom legalize the 12660 // 64-bit integer store into two 32-bit stores. 12661 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 12662 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 12663 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 12664 if (DAG.getDataLayout().isBigEndian()) 12665 std::swap(Lo, Hi); 12666 12667 unsigned Alignment = ST->getAlignment(); 12668 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 12669 AAMDNodes AAInfo = ST->getAAInfo(); 12670 12671 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 12672 ST->getAlignment(), MMOFlags, AAInfo); 12673 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 12674 DAG.getConstant(4, DL, Ptr.getValueType())); 12675 Alignment = MinAlign(Alignment, 4U); 12676 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 12677 ST->getPointerInfo().getWithOffset(4), 12678 Alignment, MMOFlags, AAInfo); 12679 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 12680 St0, St1); 12681 } 12682 12683 return SDValue(); 12684 } 12685 } 12686 12687 SDValue DAGCombiner::visitSTORE(SDNode *N) { 12688 StoreSDNode *ST = cast<StoreSDNode>(N); 12689 SDValue Chain = ST->getChain(); 12690 SDValue Value = ST->getValue(); 12691 SDValue Ptr = ST->getBasePtr(); 12692 12693 // If this is a store of a bit convert, store the input value if the 12694 // resultant store does not need a higher alignment than the original. 12695 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 12696 ST->isUnindexed()) { 12697 EVT SVT = Value.getOperand(0).getValueType(); 12698 if (((!LegalOperations && !ST->isVolatile()) || 12699 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) && 12700 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 12701 unsigned OrigAlign = ST->getAlignment(); 12702 bool Fast = false; 12703 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 12704 ST->getAddressSpace(), OrigAlign, &Fast) && 12705 Fast) { 12706 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 12707 ST->getPointerInfo(), OrigAlign, 12708 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 12709 } 12710 } 12711 } 12712 12713 // Turn 'store undef, Ptr' -> nothing. 12714 if (Value.isUndef() && ST->isUnindexed()) 12715 return Chain; 12716 12717 // Try to infer better alignment information than the store already has. 12718 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 12719 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 12720 if (Align > ST->getAlignment()) { 12721 SDValue NewStore = 12722 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 12723 ST->getMemoryVT(), Align, 12724 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 12725 if (NewStore.getNode() != N) 12726 return CombineTo(ST, NewStore, true); 12727 } 12728 } 12729 } 12730 12731 // Try transforming a pair floating point load / store ops to integer 12732 // load / store ops. 12733 if (SDValue NewST = TransformFPLoadStorePair(N)) 12734 return NewST; 12735 12736 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 12737 : DAG.getSubtarget().useAA(); 12738 #ifndef NDEBUG 12739 if (CombinerAAOnlyFunc.getNumOccurrences() && 12740 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 12741 UseAA = false; 12742 #endif 12743 if (UseAA && ST->isUnindexed()) { 12744 // FIXME: We should do this even without AA enabled. AA will just allow 12745 // FindBetterChain to work in more situations. The problem with this is that 12746 // any combine that expects memory operations to be on consecutive chains 12747 // first needs to be updated to look for users of the same chain. 12748 12749 // Walk up chain skipping non-aliasing memory nodes, on this store and any 12750 // adjacent stores. 12751 if (findBetterNeighborChains(ST)) { 12752 // replaceStoreChain uses CombineTo, which handled all of the worklist 12753 // manipulation. Return the original node to not do anything else. 12754 return SDValue(ST, 0); 12755 } 12756 Chain = ST->getChain(); 12757 } 12758 12759 // Try transforming N to an indexed store. 12760 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 12761 return SDValue(N, 0); 12762 12763 // FIXME: is there such a thing as a truncating indexed store? 12764 if (ST->isTruncatingStore() && ST->isUnindexed() && 12765 Value.getValueType().isInteger()) { 12766 // See if we can simplify the input to this truncstore with knowledge that 12767 // only the low bits are being used. For example: 12768 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 12769 SDValue Shorter = GetDemandedBits( 12770 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 12771 ST->getMemoryVT().getScalarSizeInBits())); 12772 AddToWorklist(Value.getNode()); 12773 if (Shorter.getNode()) 12774 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 12775 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12776 12777 // Otherwise, see if we can simplify the operation with 12778 // SimplifyDemandedBits, which only works if the value has a single use. 12779 if (SimplifyDemandedBits( 12780 Value, 12781 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 12782 ST->getMemoryVT().getScalarSizeInBits()))) 12783 return SDValue(N, 0); 12784 } 12785 12786 // If this is a load followed by a store to the same location, then the store 12787 // is dead/noop. 12788 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 12789 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 12790 ST->isUnindexed() && !ST->isVolatile() && 12791 // There can't be any side effects between the load and store, such as 12792 // a call or store. 12793 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 12794 // The store is dead, remove it. 12795 return Chain; 12796 } 12797 } 12798 12799 // If this is a store followed by a store with the same value to the same 12800 // location, then the store is dead/noop. 12801 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 12802 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 12803 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 12804 ST1->isUnindexed() && !ST1->isVolatile()) { 12805 // The store is dead, remove it. 12806 return Chain; 12807 } 12808 } 12809 12810 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 12811 // truncating store. We can do this even if this is already a truncstore. 12812 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 12813 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 12814 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 12815 ST->getMemoryVT())) { 12816 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 12817 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12818 } 12819 12820 // Only perform this optimization before the types are legal, because we 12821 // don't want to perform this optimization on every DAGCombine invocation. 12822 if (!LegalTypes) { 12823 for (;;) { 12824 // There can be multiple store sequences on the same chain. 12825 // Keep trying to merge store sequences until we are unable to do so 12826 // or until we merge the last store on the chain. 12827 SmallVector<MemOpLink, 8> StoreNodes; 12828 bool Changed = MergeConsecutiveStores(ST, StoreNodes); 12829 if (!Changed) break; 12830 12831 if (any_of(StoreNodes, 12832 [ST](const MemOpLink &Link) { return Link.MemNode == ST; })) { 12833 // ST has been merged and no longer exists. 12834 return SDValue(N, 0); 12835 } 12836 } 12837 } 12838 12839 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 12840 // 12841 // Make sure to do this only after attempting to merge stores in order to 12842 // avoid changing the types of some subset of stores due to visit order, 12843 // preventing their merging. 12844 if (isa<ConstantFPSDNode>(Value)) { 12845 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 12846 return NewSt; 12847 } 12848 12849 if (SDValue NewSt = splitMergedValStore(ST)) 12850 return NewSt; 12851 12852 return ReduceLoadOpStoreWidth(N); 12853 } 12854 12855 /// For the instruction sequence of store below, F and I values 12856 /// are bundled together as an i64 value before being stored into memory. 12857 /// Sometimes it is more efficent to generate separate stores for F and I, 12858 /// which can remove the bitwise instructions or sink them to colder places. 12859 /// 12860 /// (store (or (zext (bitcast F to i32) to i64), 12861 /// (shl (zext I to i64), 32)), addr) --> 12862 /// (store F, addr) and (store I, addr+4) 12863 /// 12864 /// Similarly, splitting for other merged store can also be beneficial, like: 12865 /// For pair of {i32, i32}, i64 store --> two i32 stores. 12866 /// For pair of {i32, i16}, i64 store --> two i32 stores. 12867 /// For pair of {i16, i16}, i32 store --> two i16 stores. 12868 /// For pair of {i16, i8}, i32 store --> two i16 stores. 12869 /// For pair of {i8, i8}, i16 store --> two i8 stores. 12870 /// 12871 /// We allow each target to determine specifically which kind of splitting is 12872 /// supported. 12873 /// 12874 /// The store patterns are commonly seen from the simple code snippet below 12875 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 12876 /// void goo(const std::pair<int, float> &); 12877 /// hoo() { 12878 /// ... 12879 /// goo(std::make_pair(tmp, ftmp)); 12880 /// ... 12881 /// } 12882 /// 12883 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) { 12884 if (OptLevel == CodeGenOpt::None) 12885 return SDValue(); 12886 12887 SDValue Val = ST->getValue(); 12888 SDLoc DL(ST); 12889 12890 // Match OR operand. 12891 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR) 12892 return SDValue(); 12893 12894 // Match SHL operand and get Lower and Higher parts of Val. 12895 SDValue Op1 = Val.getOperand(0); 12896 SDValue Op2 = Val.getOperand(1); 12897 SDValue Lo, Hi; 12898 if (Op1.getOpcode() != ISD::SHL) { 12899 std::swap(Op1, Op2); 12900 if (Op1.getOpcode() != ISD::SHL) 12901 return SDValue(); 12902 } 12903 Lo = Op2; 12904 Hi = Op1.getOperand(0); 12905 if (!Op1.hasOneUse()) 12906 return SDValue(); 12907 12908 // Match shift amount to HalfValBitSize. 12909 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2; 12910 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1)); 12911 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize) 12912 return SDValue(); 12913 12914 // Lo and Hi are zero-extended from int with size less equal than 32 12915 // to i64. 12916 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() || 12917 !Lo.getOperand(0).getValueType().isScalarInteger() || 12918 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize || 12919 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() || 12920 !Hi.getOperand(0).getValueType().isScalarInteger() || 12921 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize) 12922 return SDValue(); 12923 12924 // Use the EVT of low and high parts before bitcast as the input 12925 // of target query. 12926 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST) 12927 ? Lo.getOperand(0).getValueType() 12928 : Lo.getValueType(); 12929 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST) 12930 ? Hi.getOperand(0).getValueType() 12931 : Hi.getValueType(); 12932 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) 12933 return SDValue(); 12934 12935 // Start to split store. 12936 unsigned Alignment = ST->getAlignment(); 12937 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 12938 AAMDNodes AAInfo = ST->getAAInfo(); 12939 12940 // Change the sizes of Lo and Hi's value types to HalfValBitSize. 12941 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize); 12942 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0)); 12943 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0)); 12944 12945 SDValue Chain = ST->getChain(); 12946 SDValue Ptr = ST->getBasePtr(); 12947 // Lower value store. 12948 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 12949 ST->getAlignment(), MMOFlags, AAInfo); 12950 Ptr = 12951 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 12952 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType())); 12953 // Higher value store. 12954 SDValue St1 = 12955 DAG.getStore(St0, DL, Hi, Ptr, 12956 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8), 12957 Alignment / 2, MMOFlags, AAInfo); 12958 return St1; 12959 } 12960 12961 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 12962 SDValue InVec = N->getOperand(0); 12963 SDValue InVal = N->getOperand(1); 12964 SDValue EltNo = N->getOperand(2); 12965 SDLoc DL(N); 12966 12967 // If the inserted element is an UNDEF, just use the input vector. 12968 if (InVal.isUndef()) 12969 return InVec; 12970 12971 EVT VT = InVec.getValueType(); 12972 12973 // Check that we know which element is being inserted 12974 if (!isa<ConstantSDNode>(EltNo)) 12975 return SDValue(); 12976 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12977 12978 // Canonicalize insert_vector_elt dag nodes. 12979 // Example: 12980 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 12981 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 12982 // 12983 // Do this only if the child insert_vector node has one use; also 12984 // do this only if indices are both constants and Idx1 < Idx0. 12985 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 12986 && isa<ConstantSDNode>(InVec.getOperand(2))) { 12987 unsigned OtherElt = 12988 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 12989 if (Elt < OtherElt) { 12990 // Swap nodes. 12991 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, 12992 InVec.getOperand(0), InVal, EltNo); 12993 AddToWorklist(NewOp.getNode()); 12994 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 12995 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 12996 } 12997 } 12998 12999 // If we can't generate a legal BUILD_VECTOR, exit 13000 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 13001 return SDValue(); 13002 13003 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 13004 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 13005 // vector elements. 13006 SmallVector<SDValue, 8> Ops; 13007 // Do not combine these two vectors if the output vector will not replace 13008 // the input vector. 13009 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 13010 Ops.append(InVec.getNode()->op_begin(), 13011 InVec.getNode()->op_end()); 13012 } else if (InVec.isUndef()) { 13013 unsigned NElts = VT.getVectorNumElements(); 13014 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 13015 } else { 13016 return SDValue(); 13017 } 13018 13019 // Insert the element 13020 if (Elt < Ops.size()) { 13021 // All the operands of BUILD_VECTOR must have the same type; 13022 // we enforce that here. 13023 EVT OpVT = Ops[0].getValueType(); 13024 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal; 13025 } 13026 13027 // Return the new vector 13028 return DAG.getBuildVector(VT, DL, Ops); 13029 } 13030 13031 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 13032 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 13033 assert(!OriginalLoad->isVolatile()); 13034 13035 EVT ResultVT = EVE->getValueType(0); 13036 EVT VecEltVT = InVecVT.getVectorElementType(); 13037 unsigned Align = OriginalLoad->getAlignment(); 13038 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 13039 VecEltVT.getTypeForEVT(*DAG.getContext())); 13040 13041 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 13042 return SDValue(); 13043 13044 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ? 13045 ISD::NON_EXTLOAD : ISD::EXTLOAD; 13046 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT)) 13047 return SDValue(); 13048 13049 Align = NewAlign; 13050 13051 SDValue NewPtr = OriginalLoad->getBasePtr(); 13052 SDValue Offset; 13053 EVT PtrType = NewPtr.getValueType(); 13054 MachinePointerInfo MPI; 13055 SDLoc DL(EVE); 13056 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 13057 int Elt = ConstEltNo->getZExtValue(); 13058 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 13059 Offset = DAG.getConstant(PtrOff, DL, PtrType); 13060 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 13061 } else { 13062 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 13063 Offset = DAG.getNode( 13064 ISD::MUL, DL, PtrType, Offset, 13065 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 13066 MPI = OriginalLoad->getPointerInfo(); 13067 } 13068 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 13069 13070 // The replacement we need to do here is a little tricky: we need to 13071 // replace an extractelement of a load with a load. 13072 // Use ReplaceAllUsesOfValuesWith to do the replacement. 13073 // Note that this replacement assumes that the extractvalue is the only 13074 // use of the load; that's okay because we don't want to perform this 13075 // transformation in other cases anyway. 13076 SDValue Load; 13077 SDValue Chain; 13078 if (ResultVT.bitsGT(VecEltVT)) { 13079 // If the result type of vextract is wider than the load, then issue an 13080 // extending load instead. 13081 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 13082 VecEltVT) 13083 ? ISD::ZEXTLOAD 13084 : ISD::EXTLOAD; 13085 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 13086 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 13087 Align, OriginalLoad->getMemOperand()->getFlags(), 13088 OriginalLoad->getAAInfo()); 13089 Chain = Load.getValue(1); 13090 } else { 13091 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, 13092 MPI, Align, OriginalLoad->getMemOperand()->getFlags(), 13093 OriginalLoad->getAAInfo()); 13094 Chain = Load.getValue(1); 13095 if (ResultVT.bitsLT(VecEltVT)) 13096 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 13097 else 13098 Load = DAG.getBitcast(ResultVT, Load); 13099 } 13100 WorklistRemover DeadNodes(*this); 13101 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 13102 SDValue To[] = { Load, Chain }; 13103 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 13104 // Since we're explicitly calling ReplaceAllUses, add the new node to the 13105 // worklist explicitly as well. 13106 AddToWorklist(Load.getNode()); 13107 AddUsersToWorklist(Load.getNode()); // Add users too 13108 // Make sure to revisit this node to clean it up; it will usually be dead. 13109 AddToWorklist(EVE); 13110 ++OpsNarrowed; 13111 return SDValue(EVE, 0); 13112 } 13113 13114 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 13115 // (vextract (scalar_to_vector val, 0) -> val 13116 SDValue InVec = N->getOperand(0); 13117 EVT VT = InVec.getValueType(); 13118 EVT NVT = N->getValueType(0); 13119 13120 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 13121 // Check if the result type doesn't match the inserted element type. A 13122 // SCALAR_TO_VECTOR may truncate the inserted element and the 13123 // EXTRACT_VECTOR_ELT may widen the extracted vector. 13124 SDValue InOp = InVec.getOperand(0); 13125 if (InOp.getValueType() != NVT) { 13126 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 13127 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 13128 } 13129 return InOp; 13130 } 13131 13132 SDValue EltNo = N->getOperand(1); 13133 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 13134 13135 // extract_vector_elt (build_vector x, y), 1 -> y 13136 if (ConstEltNo && 13137 InVec.getOpcode() == ISD::BUILD_VECTOR && 13138 TLI.isTypeLegal(VT) && 13139 (InVec.hasOneUse() || 13140 TLI.aggressivelyPreferBuildVectorSources(VT))) { 13141 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 13142 EVT InEltVT = Elt.getValueType(); 13143 13144 // Sometimes build_vector's scalar input types do not match result type. 13145 if (NVT == InEltVT) 13146 return Elt; 13147 13148 // TODO: It may be useful to truncate if free if the build_vector implicitly 13149 // converts. 13150 } 13151 13152 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x) 13153 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 13154 ConstEltNo->isNullValue() && VT.isInteger()) { 13155 SDValue BCSrc = InVec.getOperand(0); 13156 if (BCSrc.getValueType().isScalarInteger()) 13157 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 13158 } 13159 13160 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 13161 // 13162 // This only really matters if the index is non-constant since other combines 13163 // on the constant elements already work. 13164 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && 13165 EltNo == InVec.getOperand(2)) { 13166 SDValue Elt = InVec.getOperand(1); 13167 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt; 13168 } 13169 13170 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 13171 // We only perform this optimization before the op legalization phase because 13172 // we may introduce new vector instructions which are not backed by TD 13173 // patterns. For example on AVX, extracting elements from a wide vector 13174 // without using extract_subvector. However, if we can find an underlying 13175 // scalar value, then we can always use that. 13176 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 13177 int NumElem = VT.getVectorNumElements(); 13178 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 13179 // Find the new index to extract from. 13180 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 13181 13182 // Extracting an undef index is undef. 13183 if (OrigElt == -1) 13184 return DAG.getUNDEF(NVT); 13185 13186 // Select the right vector half to extract from. 13187 SDValue SVInVec; 13188 if (OrigElt < NumElem) { 13189 SVInVec = InVec->getOperand(0); 13190 } else { 13191 SVInVec = InVec->getOperand(1); 13192 OrigElt -= NumElem; 13193 } 13194 13195 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 13196 SDValue InOp = SVInVec.getOperand(OrigElt); 13197 if (InOp.getValueType() != NVT) { 13198 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 13199 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 13200 } 13201 13202 return InOp; 13203 } 13204 13205 // FIXME: We should handle recursing on other vector shuffles and 13206 // scalar_to_vector here as well. 13207 13208 if (!LegalOperations) { 13209 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 13210 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 13211 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 13212 } 13213 } 13214 13215 bool BCNumEltsChanged = false; 13216 EVT ExtVT = VT.getVectorElementType(); 13217 EVT LVT = ExtVT; 13218 13219 // If the result of load has to be truncated, then it's not necessarily 13220 // profitable. 13221 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 13222 return SDValue(); 13223 13224 if (InVec.getOpcode() == ISD::BITCAST) { 13225 // Don't duplicate a load with other uses. 13226 if (!InVec.hasOneUse()) 13227 return SDValue(); 13228 13229 EVT BCVT = InVec.getOperand(0).getValueType(); 13230 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 13231 return SDValue(); 13232 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 13233 BCNumEltsChanged = true; 13234 InVec = InVec.getOperand(0); 13235 ExtVT = BCVT.getVectorElementType(); 13236 } 13237 13238 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 13239 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 13240 ISD::isNormalLoad(InVec.getNode()) && 13241 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 13242 SDValue Index = N->getOperand(1); 13243 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) { 13244 if (!OrigLoad->isVolatile()) { 13245 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 13246 OrigLoad); 13247 } 13248 } 13249 } 13250 13251 // Perform only after legalization to ensure build_vector / vector_shuffle 13252 // optimizations have already been done. 13253 if (!LegalOperations) return SDValue(); 13254 13255 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 13256 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 13257 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 13258 13259 if (ConstEltNo) { 13260 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 13261 13262 LoadSDNode *LN0 = nullptr; 13263 const ShuffleVectorSDNode *SVN = nullptr; 13264 if (ISD::isNormalLoad(InVec.getNode())) { 13265 LN0 = cast<LoadSDNode>(InVec); 13266 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 13267 InVec.getOperand(0).getValueType() == ExtVT && 13268 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 13269 // Don't duplicate a load with other uses. 13270 if (!InVec.hasOneUse()) 13271 return SDValue(); 13272 13273 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 13274 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 13275 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 13276 // => 13277 // (load $addr+1*size) 13278 13279 // Don't duplicate a load with other uses. 13280 if (!InVec.hasOneUse()) 13281 return SDValue(); 13282 13283 // If the bit convert changed the number of elements, it is unsafe 13284 // to examine the mask. 13285 if (BCNumEltsChanged) 13286 return SDValue(); 13287 13288 // Select the input vector, guarding against out of range extract vector. 13289 unsigned NumElems = VT.getVectorNumElements(); 13290 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 13291 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 13292 13293 if (InVec.getOpcode() == ISD::BITCAST) { 13294 // Don't duplicate a load with other uses. 13295 if (!InVec.hasOneUse()) 13296 return SDValue(); 13297 13298 InVec = InVec.getOperand(0); 13299 } 13300 if (ISD::isNormalLoad(InVec.getNode())) { 13301 LN0 = cast<LoadSDNode>(InVec); 13302 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 13303 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 13304 } 13305 } 13306 13307 // Make sure we found a non-volatile load and the extractelement is 13308 // the only use. 13309 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 13310 return SDValue(); 13311 13312 // If Idx was -1 above, Elt is going to be -1, so just return undef. 13313 if (Elt == -1) 13314 return DAG.getUNDEF(LVT); 13315 13316 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 13317 } 13318 13319 return SDValue(); 13320 } 13321 13322 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 13323 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 13324 // We perform this optimization post type-legalization because 13325 // the type-legalizer often scalarizes integer-promoted vectors. 13326 // Performing this optimization before may create bit-casts which 13327 // will be type-legalized to complex code sequences. 13328 // We perform this optimization only before the operation legalizer because we 13329 // may introduce illegal operations. 13330 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 13331 return SDValue(); 13332 13333 unsigned NumInScalars = N->getNumOperands(); 13334 SDLoc DL(N); 13335 EVT VT = N->getValueType(0); 13336 13337 // Check to see if this is a BUILD_VECTOR of a bunch of values 13338 // which come from any_extend or zero_extend nodes. If so, we can create 13339 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 13340 // optimizations. We do not handle sign-extend because we can't fill the sign 13341 // using shuffles. 13342 EVT SourceType = MVT::Other; 13343 bool AllAnyExt = true; 13344 13345 for (unsigned i = 0; i != NumInScalars; ++i) { 13346 SDValue In = N->getOperand(i); 13347 // Ignore undef inputs. 13348 if (In.isUndef()) continue; 13349 13350 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 13351 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 13352 13353 // Abort if the element is not an extension. 13354 if (!ZeroExt && !AnyExt) { 13355 SourceType = MVT::Other; 13356 break; 13357 } 13358 13359 // The input is a ZeroExt or AnyExt. Check the original type. 13360 EVT InTy = In.getOperand(0).getValueType(); 13361 13362 // Check that all of the widened source types are the same. 13363 if (SourceType == MVT::Other) 13364 // First time. 13365 SourceType = InTy; 13366 else if (InTy != SourceType) { 13367 // Multiple income types. Abort. 13368 SourceType = MVT::Other; 13369 break; 13370 } 13371 13372 // Check if all of the extends are ANY_EXTENDs. 13373 AllAnyExt &= AnyExt; 13374 } 13375 13376 // In order to have valid types, all of the inputs must be extended from the 13377 // same source type and all of the inputs must be any or zero extend. 13378 // Scalar sizes must be a power of two. 13379 EVT OutScalarTy = VT.getScalarType(); 13380 bool ValidTypes = SourceType != MVT::Other && 13381 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 13382 isPowerOf2_32(SourceType.getSizeInBits()); 13383 13384 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 13385 // turn into a single shuffle instruction. 13386 if (!ValidTypes) 13387 return SDValue(); 13388 13389 bool isLE = DAG.getDataLayout().isLittleEndian(); 13390 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 13391 assert(ElemRatio > 1 && "Invalid element size ratio"); 13392 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 13393 DAG.getConstant(0, DL, SourceType); 13394 13395 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 13396 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 13397 13398 // Populate the new build_vector 13399 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13400 SDValue Cast = N->getOperand(i); 13401 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 13402 Cast.getOpcode() == ISD::ZERO_EXTEND || 13403 Cast.isUndef()) && "Invalid cast opcode"); 13404 SDValue In; 13405 if (Cast.isUndef()) 13406 In = DAG.getUNDEF(SourceType); 13407 else 13408 In = Cast->getOperand(0); 13409 unsigned Index = isLE ? (i * ElemRatio) : 13410 (i * ElemRatio + (ElemRatio - 1)); 13411 13412 assert(Index < Ops.size() && "Invalid index"); 13413 Ops[Index] = In; 13414 } 13415 13416 // The type of the new BUILD_VECTOR node. 13417 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 13418 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 13419 "Invalid vector size"); 13420 // Check if the new vector type is legal. 13421 if (!isTypeLegal(VecVT)) return SDValue(); 13422 13423 // Make the new BUILD_VECTOR. 13424 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops); 13425 13426 // The new BUILD_VECTOR node has the potential to be further optimized. 13427 AddToWorklist(BV.getNode()); 13428 // Bitcast to the desired type. 13429 return DAG.getBitcast(VT, BV); 13430 } 13431 13432 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 13433 EVT VT = N->getValueType(0); 13434 13435 unsigned NumInScalars = N->getNumOperands(); 13436 SDLoc DL(N); 13437 13438 EVT SrcVT = MVT::Other; 13439 unsigned Opcode = ISD::DELETED_NODE; 13440 unsigned NumDefs = 0; 13441 13442 for (unsigned i = 0; i != NumInScalars; ++i) { 13443 SDValue In = N->getOperand(i); 13444 unsigned Opc = In.getOpcode(); 13445 13446 if (Opc == ISD::UNDEF) 13447 continue; 13448 13449 // If all scalar values are floats and converted from integers. 13450 if (Opcode == ISD::DELETED_NODE && 13451 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 13452 Opcode = Opc; 13453 } 13454 13455 if (Opc != Opcode) 13456 return SDValue(); 13457 13458 EVT InVT = In.getOperand(0).getValueType(); 13459 13460 // If all scalar values are typed differently, bail out. It's chosen to 13461 // simplify BUILD_VECTOR of integer types. 13462 if (SrcVT == MVT::Other) 13463 SrcVT = InVT; 13464 if (SrcVT != InVT) 13465 return SDValue(); 13466 NumDefs++; 13467 } 13468 13469 // If the vector has just one element defined, it's not worth to fold it into 13470 // a vectorized one. 13471 if (NumDefs < 2) 13472 return SDValue(); 13473 13474 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 13475 && "Should only handle conversion from integer to float."); 13476 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 13477 13478 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 13479 13480 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 13481 return SDValue(); 13482 13483 // Just because the floating-point vector type is legal does not necessarily 13484 // mean that the corresponding integer vector type is. 13485 if (!isTypeLegal(NVT)) 13486 return SDValue(); 13487 13488 SmallVector<SDValue, 8> Opnds; 13489 for (unsigned i = 0; i != NumInScalars; ++i) { 13490 SDValue In = N->getOperand(i); 13491 13492 if (In.isUndef()) 13493 Opnds.push_back(DAG.getUNDEF(SrcVT)); 13494 else 13495 Opnds.push_back(In.getOperand(0)); 13496 } 13497 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds); 13498 AddToWorklist(BV.getNode()); 13499 13500 return DAG.getNode(Opcode, DL, VT, BV); 13501 } 13502 13503 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N, 13504 ArrayRef<int> VectorMask, 13505 SDValue VecIn1, SDValue VecIn2, 13506 unsigned LeftIdx) { 13507 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 13508 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy); 13509 13510 EVT VT = N->getValueType(0); 13511 EVT InVT1 = VecIn1.getValueType(); 13512 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1; 13513 13514 unsigned Vec2Offset = InVT1.getVectorNumElements(); 13515 unsigned NumElems = VT.getVectorNumElements(); 13516 unsigned ShuffleNumElems = NumElems; 13517 13518 // We can't generate a shuffle node with mismatched input and output types. 13519 // Try to make the types match the type of the output. 13520 if (InVT1 != VT || InVT2 != VT) { 13521 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) { 13522 // If the output vector length is a multiple of both input lengths, 13523 // we can concatenate them and pad the rest with undefs. 13524 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits(); 13525 assert(NumConcats >= 2 && "Concat needs at least two inputs!"); 13526 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1)); 13527 ConcatOps[0] = VecIn1; 13528 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1); 13529 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 13530 VecIn2 = SDValue(); 13531 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) { 13532 if (!TLI.isExtractSubvectorCheap(VT, NumElems)) 13533 return SDValue(); 13534 13535 if (!VecIn2.getNode()) { 13536 // If we only have one input vector, and it's twice the size of the 13537 // output, split it in two. 13538 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, 13539 DAG.getConstant(NumElems, DL, IdxTy)); 13540 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx); 13541 // Since we now have shorter input vectors, adjust the offset of the 13542 // second vector's start. 13543 Vec2Offset = NumElems; 13544 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) { 13545 // VecIn1 is wider than the output, and we have another, possibly 13546 // smaller input. Pad the smaller input with undefs, shuffle at the 13547 // input vector width, and extract the output. 13548 // The shuffle type is different than VT, so check legality again. 13549 if (LegalOperations && 13550 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1)) 13551 return SDValue(); 13552 13553 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to 13554 // lower it back into a BUILD_VECTOR. So if the inserted type is 13555 // illegal, don't even try. 13556 if (InVT1 != InVT2) { 13557 if (!TLI.isTypeLegal(InVT2)) 13558 return SDValue(); 13559 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1, 13560 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx); 13561 } 13562 ShuffleNumElems = NumElems * 2; 13563 } else { 13564 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider 13565 // than VecIn1. We can't handle this for now - this case will disappear 13566 // when we start sorting the vectors by type. 13567 return SDValue(); 13568 } 13569 } else { 13570 // TODO: Support cases where the length mismatch isn't exactly by a 13571 // factor of 2. 13572 // TODO: Move this check upwards, so that if we have bad type 13573 // mismatches, we don't create any DAG nodes. 13574 return SDValue(); 13575 } 13576 } 13577 13578 // Initialize mask to undef. 13579 SmallVector<int, 8> Mask(ShuffleNumElems, -1); 13580 13581 // Only need to run up to the number of elements actually used, not the 13582 // total number of elements in the shuffle - if we are shuffling a wider 13583 // vector, the high lanes should be set to undef. 13584 for (unsigned i = 0; i != NumElems; ++i) { 13585 if (VectorMask[i] <= 0) 13586 continue; 13587 13588 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1); 13589 if (VectorMask[i] == (int)LeftIdx) { 13590 Mask[i] = ExtIndex; 13591 } else if (VectorMask[i] == (int)LeftIdx + 1) { 13592 Mask[i] = Vec2Offset + ExtIndex; 13593 } 13594 } 13595 13596 // The type the input vectors may have changed above. 13597 InVT1 = VecIn1.getValueType(); 13598 13599 // If we already have a VecIn2, it should have the same type as VecIn1. 13600 // If we don't, get an undef/zero vector of the appropriate type. 13601 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1); 13602 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type."); 13603 13604 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask); 13605 if (ShuffleNumElems > NumElems) 13606 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx); 13607 13608 return Shuffle; 13609 } 13610 13611 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 13612 // operations. If the types of the vectors we're extracting from allow it, 13613 // turn this into a vector_shuffle node. 13614 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) { 13615 SDLoc DL(N); 13616 EVT VT = N->getValueType(0); 13617 13618 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 13619 if (!isTypeLegal(VT)) 13620 return SDValue(); 13621 13622 // May only combine to shuffle after legalize if shuffle is legal. 13623 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 13624 return SDValue(); 13625 13626 bool UsesZeroVector = false; 13627 unsigned NumElems = N->getNumOperands(); 13628 13629 // Record, for each element of the newly built vector, which input vector 13630 // that element comes from. -1 stands for undef, 0 for the zero vector, 13631 // and positive values for the input vectors. 13632 // VectorMask maps each element to its vector number, and VecIn maps vector 13633 // numbers to their initial SDValues. 13634 13635 SmallVector<int, 8> VectorMask(NumElems, -1); 13636 SmallVector<SDValue, 8> VecIn; 13637 VecIn.push_back(SDValue()); 13638 13639 for (unsigned i = 0; i != NumElems; ++i) { 13640 SDValue Op = N->getOperand(i); 13641 13642 if (Op.isUndef()) 13643 continue; 13644 13645 // See if we can use a blend with a zero vector. 13646 // TODO: Should we generalize this to a blend with an arbitrary constant 13647 // vector? 13648 if (isNullConstant(Op) || isNullFPConstant(Op)) { 13649 UsesZeroVector = true; 13650 VectorMask[i] = 0; 13651 continue; 13652 } 13653 13654 // Not an undef or zero. If the input is something other than an 13655 // EXTRACT_VECTOR_ELT with a constant index, bail out. 13656 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13657 !isa<ConstantSDNode>(Op.getOperand(1))) 13658 return SDValue(); 13659 13660 SDValue ExtractedFromVec = Op.getOperand(0); 13661 13662 // All inputs must have the same element type as the output. 13663 if (VT.getVectorElementType() != 13664 ExtractedFromVec.getValueType().getVectorElementType()) 13665 return SDValue(); 13666 13667 // Have we seen this input vector before? 13668 // The vectors are expected to be tiny (usually 1 or 2 elements), so using 13669 // a map back from SDValues to numbers isn't worth it. 13670 unsigned Idx = std::distance( 13671 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec)); 13672 if (Idx == VecIn.size()) 13673 VecIn.push_back(ExtractedFromVec); 13674 13675 VectorMask[i] = Idx; 13676 } 13677 13678 // If we didn't find at least one input vector, bail out. 13679 if (VecIn.size() < 2) 13680 return SDValue(); 13681 13682 // TODO: We want to sort the vectors by descending length, so that adjacent 13683 // pairs have similar length, and the longer vector is always first in the 13684 // pair. 13685 13686 // TODO: Should this fire if some of the input vectors has illegal type (like 13687 // it does now), or should we let legalization run its course first? 13688 13689 // Shuffle phase: 13690 // Take pairs of vectors, and shuffle them so that the result has elements 13691 // from these vectors in the correct places. 13692 // For example, given: 13693 // t10: i32 = extract_vector_elt t1, Constant:i64<0> 13694 // t11: i32 = extract_vector_elt t2, Constant:i64<0> 13695 // t12: i32 = extract_vector_elt t3, Constant:i64<0> 13696 // t13: i32 = extract_vector_elt t1, Constant:i64<1> 13697 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13 13698 // We will generate: 13699 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2 13700 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef 13701 SmallVector<SDValue, 4> Shuffles; 13702 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) { 13703 unsigned LeftIdx = 2 * In + 1; 13704 SDValue VecLeft = VecIn[LeftIdx]; 13705 SDValue VecRight = 13706 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue(); 13707 13708 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft, 13709 VecRight, LeftIdx)) 13710 Shuffles.push_back(Shuffle); 13711 else 13712 return SDValue(); 13713 } 13714 13715 // If we need the zero vector as an "ingredient" in the blend tree, add it 13716 // to the list of shuffles. 13717 if (UsesZeroVector) 13718 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT) 13719 : DAG.getConstantFP(0.0, DL, VT)); 13720 13721 // If we only have one shuffle, we're done. 13722 if (Shuffles.size() == 1) 13723 return Shuffles[0]; 13724 13725 // Update the vector mask to point to the post-shuffle vectors. 13726 for (int &Vec : VectorMask) 13727 if (Vec == 0) 13728 Vec = Shuffles.size() - 1; 13729 else 13730 Vec = (Vec - 1) / 2; 13731 13732 // More than one shuffle. Generate a binary tree of blends, e.g. if from 13733 // the previous step we got the set of shuffles t10, t11, t12, t13, we will 13734 // generate: 13735 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2 13736 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4 13737 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6 13738 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8 13739 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11 13740 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13 13741 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21 13742 13743 // Make sure the initial size of the shuffle list is even. 13744 if (Shuffles.size() % 2) 13745 Shuffles.push_back(DAG.getUNDEF(VT)); 13746 13747 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) { 13748 if (CurSize % 2) { 13749 Shuffles[CurSize] = DAG.getUNDEF(VT); 13750 CurSize++; 13751 } 13752 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) { 13753 int Left = 2 * In; 13754 int Right = 2 * In + 1; 13755 SmallVector<int, 8> Mask(NumElems, -1); 13756 for (unsigned i = 0; i != NumElems; ++i) { 13757 if (VectorMask[i] == Left) { 13758 Mask[i] = i; 13759 VectorMask[i] = In; 13760 } else if (VectorMask[i] == Right) { 13761 Mask[i] = i + NumElems; 13762 VectorMask[i] = In; 13763 } 13764 } 13765 13766 Shuffles[In] = 13767 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask); 13768 } 13769 } 13770 13771 return Shuffles[0]; 13772 } 13773 13774 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 13775 EVT VT = N->getValueType(0); 13776 13777 // A vector built entirely of undefs is undef. 13778 if (ISD::allOperandsUndef(N)) 13779 return DAG.getUNDEF(VT); 13780 13781 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 13782 return V; 13783 13784 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 13785 return V; 13786 13787 if (SDValue V = reduceBuildVecToShuffle(N)) 13788 return V; 13789 13790 return SDValue(); 13791 } 13792 13793 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 13794 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13795 EVT OpVT = N->getOperand(0).getValueType(); 13796 13797 // If the operands are legal vectors, leave them alone. 13798 if (TLI.isTypeLegal(OpVT)) 13799 return SDValue(); 13800 13801 SDLoc DL(N); 13802 EVT VT = N->getValueType(0); 13803 SmallVector<SDValue, 8> Ops; 13804 13805 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 13806 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 13807 13808 // Keep track of what we encounter. 13809 bool AnyInteger = false; 13810 bool AnyFP = false; 13811 for (const SDValue &Op : N->ops()) { 13812 if (ISD::BITCAST == Op.getOpcode() && 13813 !Op.getOperand(0).getValueType().isVector()) 13814 Ops.push_back(Op.getOperand(0)); 13815 else if (ISD::UNDEF == Op.getOpcode()) 13816 Ops.push_back(ScalarUndef); 13817 else 13818 return SDValue(); 13819 13820 // Note whether we encounter an integer or floating point scalar. 13821 // If it's neither, bail out, it could be something weird like x86mmx. 13822 EVT LastOpVT = Ops.back().getValueType(); 13823 if (LastOpVT.isFloatingPoint()) 13824 AnyFP = true; 13825 else if (LastOpVT.isInteger()) 13826 AnyInteger = true; 13827 else 13828 return SDValue(); 13829 } 13830 13831 // If any of the operands is a floating point scalar bitcast to a vector, 13832 // use floating point types throughout, and bitcast everything. 13833 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 13834 if (AnyFP) { 13835 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 13836 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 13837 if (AnyInteger) { 13838 for (SDValue &Op : Ops) { 13839 if (Op.getValueType() == SVT) 13840 continue; 13841 if (Op.isUndef()) 13842 Op = ScalarUndef; 13843 else 13844 Op = DAG.getBitcast(SVT, Op); 13845 } 13846 } 13847 } 13848 13849 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 13850 VT.getSizeInBits() / SVT.getSizeInBits()); 13851 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 13852 } 13853 13854 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 13855 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 13856 // most two distinct vectors the same size as the result, attempt to turn this 13857 // into a legal shuffle. 13858 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 13859 EVT VT = N->getValueType(0); 13860 EVT OpVT = N->getOperand(0).getValueType(); 13861 int NumElts = VT.getVectorNumElements(); 13862 int NumOpElts = OpVT.getVectorNumElements(); 13863 13864 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 13865 SmallVector<int, 8> Mask; 13866 13867 for (SDValue Op : N->ops()) { 13868 // Peek through any bitcast. 13869 while (Op.getOpcode() == ISD::BITCAST) 13870 Op = Op.getOperand(0); 13871 13872 // UNDEF nodes convert to UNDEF shuffle mask values. 13873 if (Op.isUndef()) { 13874 Mask.append((unsigned)NumOpElts, -1); 13875 continue; 13876 } 13877 13878 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13879 return SDValue(); 13880 13881 // What vector are we extracting the subvector from and at what index? 13882 SDValue ExtVec = Op.getOperand(0); 13883 13884 // We want the EVT of the original extraction to correctly scale the 13885 // extraction index. 13886 EVT ExtVT = ExtVec.getValueType(); 13887 13888 // Peek through any bitcast. 13889 while (ExtVec.getOpcode() == ISD::BITCAST) 13890 ExtVec = ExtVec.getOperand(0); 13891 13892 // UNDEF nodes convert to UNDEF shuffle mask values. 13893 if (ExtVec.isUndef()) { 13894 Mask.append((unsigned)NumOpElts, -1); 13895 continue; 13896 } 13897 13898 if (!isa<ConstantSDNode>(Op.getOperand(1))) 13899 return SDValue(); 13900 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 13901 13902 // Ensure that we are extracting a subvector from a vector the same 13903 // size as the result. 13904 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 13905 return SDValue(); 13906 13907 // Scale the subvector index to account for any bitcast. 13908 int NumExtElts = ExtVT.getVectorNumElements(); 13909 if (0 == (NumExtElts % NumElts)) 13910 ExtIdx /= (NumExtElts / NumElts); 13911 else if (0 == (NumElts % NumExtElts)) 13912 ExtIdx *= (NumElts / NumExtElts); 13913 else 13914 return SDValue(); 13915 13916 // At most we can reference 2 inputs in the final shuffle. 13917 if (SV0.isUndef() || SV0 == ExtVec) { 13918 SV0 = ExtVec; 13919 for (int i = 0; i != NumOpElts; ++i) 13920 Mask.push_back(i + ExtIdx); 13921 } else if (SV1.isUndef() || SV1 == ExtVec) { 13922 SV1 = ExtVec; 13923 for (int i = 0; i != NumOpElts; ++i) 13924 Mask.push_back(i + ExtIdx + NumElts); 13925 } else { 13926 return SDValue(); 13927 } 13928 } 13929 13930 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 13931 return SDValue(); 13932 13933 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 13934 DAG.getBitcast(VT, SV1), Mask); 13935 } 13936 13937 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 13938 // If we only have one input vector, we don't need to do any concatenation. 13939 if (N->getNumOperands() == 1) 13940 return N->getOperand(0); 13941 13942 // Check if all of the operands are undefs. 13943 EVT VT = N->getValueType(0); 13944 if (ISD::allOperandsUndef(N)) 13945 return DAG.getUNDEF(VT); 13946 13947 // Optimize concat_vectors where all but the first of the vectors are undef. 13948 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 13949 return Op.isUndef(); 13950 })) { 13951 SDValue In = N->getOperand(0); 13952 assert(In.getValueType().isVector() && "Must concat vectors"); 13953 13954 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 13955 if (In->getOpcode() == ISD::BITCAST && 13956 !In->getOperand(0)->getValueType(0).isVector()) { 13957 SDValue Scalar = In->getOperand(0); 13958 13959 // If the bitcast type isn't legal, it might be a trunc of a legal type; 13960 // look through the trunc so we can still do the transform: 13961 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 13962 if (Scalar->getOpcode() == ISD::TRUNCATE && 13963 !TLI.isTypeLegal(Scalar.getValueType()) && 13964 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 13965 Scalar = Scalar->getOperand(0); 13966 13967 EVT SclTy = Scalar->getValueType(0); 13968 13969 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 13970 return SDValue(); 13971 13972 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 13973 VT.getSizeInBits() / SclTy.getSizeInBits()); 13974 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 13975 return SDValue(); 13976 13977 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar); 13978 return DAG.getBitcast(VT, Res); 13979 } 13980 } 13981 13982 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 13983 // We have already tested above for an UNDEF only concatenation. 13984 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 13985 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 13986 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 13987 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 13988 }; 13989 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 13990 SmallVector<SDValue, 8> Opnds; 13991 EVT SVT = VT.getScalarType(); 13992 13993 EVT MinVT = SVT; 13994 if (!SVT.isFloatingPoint()) { 13995 // If BUILD_VECTOR are from built from integer, they may have different 13996 // operand types. Get the smallest type and truncate all operands to it. 13997 bool FoundMinVT = false; 13998 for (const SDValue &Op : N->ops()) 13999 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 14000 EVT OpSVT = Op.getOperand(0)->getValueType(0); 14001 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 14002 FoundMinVT = true; 14003 } 14004 assert(FoundMinVT && "Concat vector type mismatch"); 14005 } 14006 14007 for (const SDValue &Op : N->ops()) { 14008 EVT OpVT = Op.getValueType(); 14009 unsigned NumElts = OpVT.getVectorNumElements(); 14010 14011 if (ISD::UNDEF == Op.getOpcode()) 14012 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 14013 14014 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 14015 if (SVT.isFloatingPoint()) { 14016 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 14017 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 14018 } else { 14019 for (unsigned i = 0; i != NumElts; ++i) 14020 Opnds.push_back( 14021 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 14022 } 14023 } 14024 } 14025 14026 assert(VT.getVectorNumElements() == Opnds.size() && 14027 "Concat vector type mismatch"); 14028 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 14029 } 14030 14031 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 14032 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 14033 return V; 14034 14035 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 14036 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 14037 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 14038 return V; 14039 14040 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 14041 // nodes often generate nop CONCAT_VECTOR nodes. 14042 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 14043 // place the incoming vectors at the exact same location. 14044 SDValue SingleSource = SDValue(); 14045 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 14046 14047 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 14048 SDValue Op = N->getOperand(i); 14049 14050 if (Op.isUndef()) 14051 continue; 14052 14053 // Check if this is the identity extract: 14054 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 14055 return SDValue(); 14056 14057 // Find the single incoming vector for the extract_subvector. 14058 if (SingleSource.getNode()) { 14059 if (Op.getOperand(0) != SingleSource) 14060 return SDValue(); 14061 } else { 14062 SingleSource = Op.getOperand(0); 14063 14064 // Check the source type is the same as the type of the result. 14065 // If not, this concat may extend the vector, so we can not 14066 // optimize it away. 14067 if (SingleSource.getValueType() != N->getValueType(0)) 14068 return SDValue(); 14069 } 14070 14071 unsigned IdentityIndex = i * PartNumElem; 14072 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 14073 // The extract index must be constant. 14074 if (!CS) 14075 return SDValue(); 14076 14077 // Check that we are reading from the identity index. 14078 if (CS->getZExtValue() != IdentityIndex) 14079 return SDValue(); 14080 } 14081 14082 if (SingleSource.getNode()) 14083 return SingleSource; 14084 14085 return SDValue(); 14086 } 14087 14088 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 14089 EVT NVT = N->getValueType(0); 14090 SDValue V = N->getOperand(0); 14091 14092 // Extract from UNDEF is UNDEF. 14093 if (V.isUndef()) 14094 return DAG.getUNDEF(NVT); 14095 14096 // Combine: 14097 // (extract_subvec (concat V1, V2, ...), i) 14098 // Into: 14099 // Vi if possible 14100 // Only operand 0 is checked as 'concat' assumes all inputs of the same 14101 // type. 14102 if (V->getOpcode() == ISD::CONCAT_VECTORS && 14103 isa<ConstantSDNode>(N->getOperand(1)) && 14104 V->getOperand(0).getValueType() == NVT) { 14105 unsigned Idx = N->getConstantOperandVal(1); 14106 unsigned NumElems = NVT.getVectorNumElements(); 14107 assert((Idx % NumElems) == 0 && 14108 "IDX in concat is not a multiple of the result vector length."); 14109 return V->getOperand(Idx / NumElems); 14110 } 14111 14112 // Skip bitcasting 14113 if (V->getOpcode() == ISD::BITCAST) 14114 V = V.getOperand(0); 14115 14116 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 14117 // Handle only simple case where vector being inserted and vector 14118 // being extracted are of same size. 14119 EVT SmallVT = V->getOperand(1).getValueType(); 14120 if (!NVT.bitsEq(SmallVT)) 14121 return SDValue(); 14122 14123 // Only handle cases where both indexes are constants. 14124 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 14125 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 14126 14127 if (InsIdx && ExtIdx) { 14128 // Combine: 14129 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 14130 // Into: 14131 // indices are equal or bit offsets are equal => V1 14132 // otherwise => (extract_subvec V1, ExtIdx) 14133 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() == 14134 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits()) 14135 return DAG.getBitcast(NVT, V->getOperand(1)); 14136 return DAG.getNode( 14137 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, 14138 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)), 14139 N->getOperand(1)); 14140 } 14141 } 14142 14143 return SDValue(); 14144 } 14145 14146 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 14147 SDValue V, SelectionDAG &DAG) { 14148 SDLoc DL(V); 14149 EVT VT = V.getValueType(); 14150 14151 switch (V.getOpcode()) { 14152 default: 14153 return V; 14154 14155 case ISD::CONCAT_VECTORS: { 14156 EVT OpVT = V->getOperand(0).getValueType(); 14157 int OpSize = OpVT.getVectorNumElements(); 14158 SmallBitVector OpUsedElements(OpSize, false); 14159 bool FoundSimplification = false; 14160 SmallVector<SDValue, 4> NewOps; 14161 NewOps.reserve(V->getNumOperands()); 14162 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 14163 SDValue Op = V->getOperand(i); 14164 bool OpUsed = false; 14165 for (int j = 0; j < OpSize; ++j) 14166 if (UsedElements[i * OpSize + j]) { 14167 OpUsedElements[j] = true; 14168 OpUsed = true; 14169 } 14170 NewOps.push_back( 14171 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 14172 : DAG.getUNDEF(OpVT)); 14173 FoundSimplification |= Op == NewOps.back(); 14174 OpUsedElements.reset(); 14175 } 14176 if (FoundSimplification) 14177 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 14178 return V; 14179 } 14180 14181 case ISD::INSERT_SUBVECTOR: { 14182 SDValue BaseV = V->getOperand(0); 14183 SDValue SubV = V->getOperand(1); 14184 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 14185 if (!IdxN) 14186 return V; 14187 14188 int SubSize = SubV.getValueType().getVectorNumElements(); 14189 int Idx = IdxN->getZExtValue(); 14190 bool SubVectorUsed = false; 14191 SmallBitVector SubUsedElements(SubSize, false); 14192 for (int i = 0; i < SubSize; ++i) 14193 if (UsedElements[i + Idx]) { 14194 SubVectorUsed = true; 14195 SubUsedElements[i] = true; 14196 UsedElements[i + Idx] = false; 14197 } 14198 14199 // Now recurse on both the base and sub vectors. 14200 SDValue SimplifiedSubV = 14201 SubVectorUsed 14202 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 14203 : DAG.getUNDEF(SubV.getValueType()); 14204 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 14205 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 14206 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 14207 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 14208 return V; 14209 } 14210 } 14211 } 14212 14213 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 14214 SDValue N1, SelectionDAG &DAG) { 14215 EVT VT = SVN->getValueType(0); 14216 int NumElts = VT.getVectorNumElements(); 14217 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 14218 for (int M : SVN->getMask()) 14219 if (M >= 0 && M < NumElts) 14220 N0UsedElements[M] = true; 14221 else if (M >= NumElts) 14222 N1UsedElements[M - NumElts] = true; 14223 14224 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 14225 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 14226 if (S0 == N0 && S1 == N1) 14227 return SDValue(); 14228 14229 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 14230 } 14231 14232 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 14233 // or turn a shuffle of a single concat into simpler shuffle then concat. 14234 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 14235 EVT VT = N->getValueType(0); 14236 unsigned NumElts = VT.getVectorNumElements(); 14237 14238 SDValue N0 = N->getOperand(0); 14239 SDValue N1 = N->getOperand(1); 14240 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 14241 14242 SmallVector<SDValue, 4> Ops; 14243 EVT ConcatVT = N0.getOperand(0).getValueType(); 14244 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 14245 unsigned NumConcats = NumElts / NumElemsPerConcat; 14246 14247 // Special case: shuffle(concat(A,B)) can be more efficiently represented 14248 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 14249 // half vector elements. 14250 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 14251 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 14252 SVN->getMask().end(), [](int i) { return i == -1; })) { 14253 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 14254 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 14255 N1 = DAG.getUNDEF(ConcatVT); 14256 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 14257 } 14258 14259 // Look at every vector that's inserted. We're looking for exact 14260 // subvector-sized copies from a concatenated vector 14261 for (unsigned I = 0; I != NumConcats; ++I) { 14262 // Make sure we're dealing with a copy. 14263 unsigned Begin = I * NumElemsPerConcat; 14264 bool AllUndef = true, NoUndef = true; 14265 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 14266 if (SVN->getMaskElt(J) >= 0) 14267 AllUndef = false; 14268 else 14269 NoUndef = false; 14270 } 14271 14272 if (NoUndef) { 14273 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 14274 return SDValue(); 14275 14276 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 14277 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 14278 return SDValue(); 14279 14280 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 14281 if (FirstElt < N0.getNumOperands()) 14282 Ops.push_back(N0.getOperand(FirstElt)); 14283 else 14284 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 14285 14286 } else if (AllUndef) { 14287 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 14288 } else { // Mixed with general masks and undefs, can't do optimization. 14289 return SDValue(); 14290 } 14291 } 14292 14293 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 14294 } 14295 14296 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 14297 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 14298 // 14299 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always 14300 // a simplification in some sense, but it isn't appropriate in general: some 14301 // BUILD_VECTORs are substantially cheaper than others. The general case 14302 // of a BUILD_VECTOR requires inserting each element individually (or 14303 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of 14304 // all constants is a single constant pool load. A BUILD_VECTOR where each 14305 // element is identical is a splat. A BUILD_VECTOR where most of the operands 14306 // are undef lowers to a small number of element insertions. 14307 // 14308 // To deal with this, we currently use a bunch of mostly arbitrary heuristics. 14309 // We don't fold shuffles where one side is a non-zero constant, and we don't 14310 // fold shuffles if the resulting BUILD_VECTOR would have duplicate 14311 // non-constant operands. This seems to work out reasonably well in practice. 14312 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN, 14313 SelectionDAG &DAG, 14314 const TargetLowering &TLI) { 14315 EVT VT = SVN->getValueType(0); 14316 unsigned NumElts = VT.getVectorNumElements(); 14317 SDValue N0 = SVN->getOperand(0); 14318 SDValue N1 = SVN->getOperand(1); 14319 14320 if (!N0->hasOneUse() || !N1->hasOneUse()) 14321 return SDValue(); 14322 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as 14323 // discussed above. 14324 if (!N1.isUndef()) { 14325 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode()); 14326 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode()); 14327 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode())) 14328 return SDValue(); 14329 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode())) 14330 return SDValue(); 14331 } 14332 14333 SmallVector<SDValue, 8> Ops; 14334 SmallSet<SDValue, 16> DuplicateOps; 14335 for (int M : SVN->getMask()) { 14336 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 14337 if (M >= 0) { 14338 int Idx = M < (int)NumElts ? M : M - NumElts; 14339 SDValue &S = (M < (int)NumElts ? N0 : N1); 14340 if (S.getOpcode() == ISD::BUILD_VECTOR) { 14341 Op = S.getOperand(Idx); 14342 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) { 14343 if (Idx == 0) 14344 Op = S.getOperand(0); 14345 } else { 14346 // Operand can't be combined - bail out. 14347 return SDValue(); 14348 } 14349 } 14350 14351 // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is 14352 // fine, but it's likely to generate low-quality code if the target can't 14353 // reconstruct an appropriate shuffle. 14354 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op)) 14355 if (!DuplicateOps.insert(Op).second) 14356 return SDValue(); 14357 14358 Ops.push_back(Op); 14359 } 14360 // BUILD_VECTOR requires all inputs to be of the same type, find the 14361 // maximum type and extend them all. 14362 EVT SVT = VT.getScalarType(); 14363 if (SVT.isInteger()) 14364 for (SDValue &Op : Ops) 14365 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 14366 if (SVT != VT.getScalarType()) 14367 for (SDValue &Op : Ops) 14368 Op = TLI.isZExtFree(Op.getValueType(), SVT) 14369 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT) 14370 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT); 14371 return DAG.getBuildVector(VT, SDLoc(SVN), Ops); 14372 } 14373 14374 // Match shuffles that can be converted to any_vector_extend_in_reg. 14375 // This is often generated during legalization. 14376 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src)) 14377 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case. 14378 SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN, 14379 SelectionDAG &DAG, 14380 const TargetLowering &TLI, 14381 bool LegalOperations) { 14382 EVT VT = SVN->getValueType(0); 14383 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 14384 14385 // TODO Add support for big-endian when we have a test case. 14386 if (!VT.isInteger() || IsBigEndian) 14387 return SDValue(); 14388 14389 unsigned NumElts = VT.getVectorNumElements(); 14390 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 14391 ArrayRef<int> Mask = SVN->getMask(); 14392 SDValue N0 = SVN->getOperand(0); 14393 14394 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32)) 14395 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) { 14396 for (unsigned i = 0; i != NumElts; ++i) { 14397 if (Mask[i] < 0) 14398 continue; 14399 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale)) 14400 continue; 14401 return false; 14402 } 14403 return true; 14404 }; 14405 14406 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for 14407 // power-of-2 extensions as they are the most likely. 14408 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) { 14409 if (!isAnyExtend(Scale)) 14410 continue; 14411 14412 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale); 14413 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale); 14414 if (!LegalOperations || 14415 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT)) 14416 return DAG.getBitcast(VT, 14417 DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT)); 14418 } 14419 14420 return SDValue(); 14421 } 14422 14423 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of 14424 // each source element of a large type into the lowest elements of a smaller 14425 // destination type. This is often generated during legalization. 14426 // If the source node itself was a '*_extend_vector_inreg' node then we should 14427 // then be able to remove it. 14428 SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, SelectionDAG &DAG) { 14429 EVT VT = SVN->getValueType(0); 14430 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 14431 14432 // TODO Add support for big-endian when we have a test case. 14433 if (!VT.isInteger() || IsBigEndian) 14434 return SDValue(); 14435 14436 SDValue N0 = SVN->getOperand(0); 14437 while (N0.getOpcode() == ISD::BITCAST) 14438 N0 = N0.getOperand(0); 14439 14440 unsigned Opcode = N0.getOpcode(); 14441 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG && 14442 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG && 14443 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG) 14444 return SDValue(); 14445 14446 SDValue N00 = N0.getOperand(0); 14447 ArrayRef<int> Mask = SVN->getMask(); 14448 unsigned NumElts = VT.getVectorNumElements(); 14449 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 14450 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits(); 14451 14452 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1> 14453 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1> 14454 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1> 14455 auto isTruncate = [&Mask, &NumElts](unsigned Scale) { 14456 for (unsigned i = 0; i != NumElts; ++i) { 14457 if (Mask[i] < 0) 14458 continue; 14459 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale)) 14460 continue; 14461 return false; 14462 } 14463 return true; 14464 }; 14465 14466 // At the moment we just handle the case where we've truncated back to the 14467 // same size as before the extension. 14468 // TODO: handle more extension/truncation cases as cases arise. 14469 if (EltSizeInBits != ExtSrcSizeInBits) 14470 return SDValue(); 14471 14472 // Attempt to match a 'truncate_vector_inreg' shuffle, we just search for 14473 // power-of-2 truncations as they are the most likely. 14474 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) 14475 if (isTruncate(Scale)) 14476 return DAG.getBitcast(VT, N00); 14477 14478 return SDValue(); 14479 } 14480 14481 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 14482 EVT VT = N->getValueType(0); 14483 unsigned NumElts = VT.getVectorNumElements(); 14484 14485 SDValue N0 = N->getOperand(0); 14486 SDValue N1 = N->getOperand(1); 14487 14488 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 14489 14490 // Canonicalize shuffle undef, undef -> undef 14491 if (N0.isUndef() && N1.isUndef()) 14492 return DAG.getUNDEF(VT); 14493 14494 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 14495 14496 // Canonicalize shuffle v, v -> v, undef 14497 if (N0 == N1) { 14498 SmallVector<int, 8> NewMask; 14499 for (unsigned i = 0; i != NumElts; ++i) { 14500 int Idx = SVN->getMaskElt(i); 14501 if (Idx >= (int)NumElts) Idx -= NumElts; 14502 NewMask.push_back(Idx); 14503 } 14504 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 14505 } 14506 14507 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 14508 if (N0.isUndef()) 14509 return DAG.getCommutedVectorShuffle(*SVN); 14510 14511 // Remove references to rhs if it is undef 14512 if (N1.isUndef()) { 14513 bool Changed = false; 14514 SmallVector<int, 8> NewMask; 14515 for (unsigned i = 0; i != NumElts; ++i) { 14516 int Idx = SVN->getMaskElt(i); 14517 if (Idx >= (int)NumElts) { 14518 Idx = -1; 14519 Changed = true; 14520 } 14521 NewMask.push_back(Idx); 14522 } 14523 if (Changed) 14524 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 14525 } 14526 14527 // If it is a splat, check if the argument vector is another splat or a 14528 // build_vector. 14529 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 14530 SDNode *V = N0.getNode(); 14531 14532 // If this is a bit convert that changes the element type of the vector but 14533 // not the number of vector elements, look through it. Be careful not to 14534 // look though conversions that change things like v4f32 to v2f64. 14535 if (V->getOpcode() == ISD::BITCAST) { 14536 SDValue ConvInput = V->getOperand(0); 14537 if (ConvInput.getValueType().isVector() && 14538 ConvInput.getValueType().getVectorNumElements() == NumElts) 14539 V = ConvInput.getNode(); 14540 } 14541 14542 if (V->getOpcode() == ISD::BUILD_VECTOR) { 14543 assert(V->getNumOperands() == NumElts && 14544 "BUILD_VECTOR has wrong number of operands"); 14545 SDValue Base; 14546 bool AllSame = true; 14547 for (unsigned i = 0; i != NumElts; ++i) { 14548 if (!V->getOperand(i).isUndef()) { 14549 Base = V->getOperand(i); 14550 break; 14551 } 14552 } 14553 // Splat of <u, u, u, u>, return <u, u, u, u> 14554 if (!Base.getNode()) 14555 return N0; 14556 for (unsigned i = 0; i != NumElts; ++i) { 14557 if (V->getOperand(i) != Base) { 14558 AllSame = false; 14559 break; 14560 } 14561 } 14562 // Splat of <x, x, x, x>, return <x, x, x, x> 14563 if (AllSame) 14564 return N0; 14565 14566 // Canonicalize any other splat as a build_vector. 14567 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 14568 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 14569 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 14570 14571 // We may have jumped through bitcasts, so the type of the 14572 // BUILD_VECTOR may not match the type of the shuffle. 14573 if (V->getValueType(0) != VT) 14574 NewBV = DAG.getBitcast(VT, NewBV); 14575 return NewBV; 14576 } 14577 } 14578 14579 // There are various patterns used to build up a vector from smaller vectors, 14580 // subvectors, or elements. Scan chains of these and replace unused insertions 14581 // or components with undef. 14582 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 14583 return S; 14584 14585 // Match shuffles that can be converted to any_vector_extend_in_reg. 14586 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations)) 14587 return V; 14588 14589 // Combine "truncate_vector_in_reg" style shuffles. 14590 if (SDValue V = combineTruncationShuffle(SVN, DAG)) 14591 return V; 14592 14593 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 14594 Level < AfterLegalizeVectorOps && 14595 (N1.isUndef() || 14596 (N1.getOpcode() == ISD::CONCAT_VECTORS && 14597 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 14598 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 14599 return V; 14600 } 14601 14602 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 14603 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 14604 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 14605 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI)) 14606 return Res; 14607 14608 // If this shuffle only has a single input that is a bitcasted shuffle, 14609 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 14610 // back to their original types. 14611 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 14612 N1.isUndef() && Level < AfterLegalizeVectorOps && 14613 TLI.isTypeLegal(VT)) { 14614 14615 // Peek through the bitcast only if there is one user. 14616 SDValue BC0 = N0; 14617 while (BC0.getOpcode() == ISD::BITCAST) { 14618 if (!BC0.hasOneUse()) 14619 break; 14620 BC0 = BC0.getOperand(0); 14621 } 14622 14623 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 14624 if (Scale == 1) 14625 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 14626 14627 SmallVector<int, 8> NewMask; 14628 for (int M : Mask) 14629 for (int s = 0; s != Scale; ++s) 14630 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 14631 return NewMask; 14632 }; 14633 14634 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 14635 EVT SVT = VT.getScalarType(); 14636 EVT InnerVT = BC0->getValueType(0); 14637 EVT InnerSVT = InnerVT.getScalarType(); 14638 14639 // Determine which shuffle works with the smaller scalar type. 14640 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 14641 EVT ScaleSVT = ScaleVT.getScalarType(); 14642 14643 if (TLI.isTypeLegal(ScaleVT) && 14644 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 14645 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 14646 14647 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 14648 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 14649 14650 // Scale the shuffle masks to the smaller scalar type. 14651 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 14652 SmallVector<int, 8> InnerMask = 14653 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 14654 SmallVector<int, 8> OuterMask = 14655 ScaleShuffleMask(SVN->getMask(), OuterScale); 14656 14657 // Merge the shuffle masks. 14658 SmallVector<int, 8> NewMask; 14659 for (int M : OuterMask) 14660 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 14661 14662 // Test for shuffle mask legality over both commutations. 14663 SDValue SV0 = BC0->getOperand(0); 14664 SDValue SV1 = BC0->getOperand(1); 14665 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 14666 if (!LegalMask) { 14667 std::swap(SV0, SV1); 14668 ShuffleVectorSDNode::commuteMask(NewMask); 14669 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 14670 } 14671 14672 if (LegalMask) { 14673 SV0 = DAG.getBitcast(ScaleVT, SV0); 14674 SV1 = DAG.getBitcast(ScaleVT, SV1); 14675 return DAG.getBitcast( 14676 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 14677 } 14678 } 14679 } 14680 } 14681 14682 // Canonicalize shuffles according to rules: 14683 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 14684 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 14685 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 14686 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 14687 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 14688 TLI.isTypeLegal(VT)) { 14689 // The incoming shuffle must be of the same type as the result of the 14690 // current shuffle. 14691 assert(N1->getOperand(0).getValueType() == VT && 14692 "Shuffle types don't match"); 14693 14694 SDValue SV0 = N1->getOperand(0); 14695 SDValue SV1 = N1->getOperand(1); 14696 bool HasSameOp0 = N0 == SV0; 14697 bool IsSV1Undef = SV1.isUndef(); 14698 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 14699 // Commute the operands of this shuffle so that next rule 14700 // will trigger. 14701 return DAG.getCommutedVectorShuffle(*SVN); 14702 } 14703 14704 // Try to fold according to rules: 14705 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 14706 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 14707 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 14708 // Don't try to fold shuffles with illegal type. 14709 // Only fold if this shuffle is the only user of the other shuffle. 14710 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 14711 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 14712 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 14713 14714 // Don't try to fold splats; they're likely to simplify somehow, or they 14715 // might be free. 14716 if (OtherSV->isSplat()) 14717 return SDValue(); 14718 14719 // The incoming shuffle must be of the same type as the result of the 14720 // current shuffle. 14721 assert(OtherSV->getOperand(0).getValueType() == VT && 14722 "Shuffle types don't match"); 14723 14724 SDValue SV0, SV1; 14725 SmallVector<int, 4> Mask; 14726 // Compute the combined shuffle mask for a shuffle with SV0 as the first 14727 // operand, and SV1 as the second operand. 14728 for (unsigned i = 0; i != NumElts; ++i) { 14729 int Idx = SVN->getMaskElt(i); 14730 if (Idx < 0) { 14731 // Propagate Undef. 14732 Mask.push_back(Idx); 14733 continue; 14734 } 14735 14736 SDValue CurrentVec; 14737 if (Idx < (int)NumElts) { 14738 // This shuffle index refers to the inner shuffle N0. Lookup the inner 14739 // shuffle mask to identify which vector is actually referenced. 14740 Idx = OtherSV->getMaskElt(Idx); 14741 if (Idx < 0) { 14742 // Propagate Undef. 14743 Mask.push_back(Idx); 14744 continue; 14745 } 14746 14747 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 14748 : OtherSV->getOperand(1); 14749 } else { 14750 // This shuffle index references an element within N1. 14751 CurrentVec = N1; 14752 } 14753 14754 // Simple case where 'CurrentVec' is UNDEF. 14755 if (CurrentVec.isUndef()) { 14756 Mask.push_back(-1); 14757 continue; 14758 } 14759 14760 // Canonicalize the shuffle index. We don't know yet if CurrentVec 14761 // will be the first or second operand of the combined shuffle. 14762 Idx = Idx % NumElts; 14763 if (!SV0.getNode() || SV0 == CurrentVec) { 14764 // Ok. CurrentVec is the left hand side. 14765 // Update the mask accordingly. 14766 SV0 = CurrentVec; 14767 Mask.push_back(Idx); 14768 continue; 14769 } 14770 14771 // Bail out if we cannot convert the shuffle pair into a single shuffle. 14772 if (SV1.getNode() && SV1 != CurrentVec) 14773 return SDValue(); 14774 14775 // Ok. CurrentVec is the right hand side. 14776 // Update the mask accordingly. 14777 SV1 = CurrentVec; 14778 Mask.push_back(Idx + NumElts); 14779 } 14780 14781 // Check if all indices in Mask are Undef. In case, propagate Undef. 14782 bool isUndefMask = true; 14783 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 14784 isUndefMask &= Mask[i] < 0; 14785 14786 if (isUndefMask) 14787 return DAG.getUNDEF(VT); 14788 14789 if (!SV0.getNode()) 14790 SV0 = DAG.getUNDEF(VT); 14791 if (!SV1.getNode()) 14792 SV1 = DAG.getUNDEF(VT); 14793 14794 // Avoid introducing shuffles with illegal mask. 14795 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 14796 ShuffleVectorSDNode::commuteMask(Mask); 14797 14798 if (!TLI.isShuffleMaskLegal(Mask, VT)) 14799 return SDValue(); 14800 14801 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 14802 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 14803 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 14804 std::swap(SV0, SV1); 14805 } 14806 14807 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 14808 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 14809 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 14810 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask); 14811 } 14812 14813 return SDValue(); 14814 } 14815 14816 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 14817 SDValue InVal = N->getOperand(0); 14818 EVT VT = N->getValueType(0); 14819 14820 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 14821 // with a VECTOR_SHUFFLE. 14822 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14823 SDValue InVec = InVal->getOperand(0); 14824 SDValue EltNo = InVal->getOperand(1); 14825 14826 // FIXME: We could support implicit truncation if the shuffle can be 14827 // scaled to a smaller vector scalar type. 14828 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 14829 if (C0 && VT == InVec.getValueType() && 14830 VT.getScalarType() == InVal.getValueType()) { 14831 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 14832 int Elt = C0->getZExtValue(); 14833 NewMask[0] = Elt; 14834 14835 if (TLI.isShuffleMaskLegal(NewMask, VT)) 14836 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 14837 NewMask); 14838 } 14839 } 14840 14841 return SDValue(); 14842 } 14843 14844 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 14845 EVT VT = N->getValueType(0); 14846 SDValue N0 = N->getOperand(0); 14847 SDValue N1 = N->getOperand(1); 14848 SDValue N2 = N->getOperand(2); 14849 14850 // If inserting an UNDEF, just return the original vector. 14851 if (N1.isUndef()) 14852 return N0; 14853 14854 // If this is an insert of an extracted vector into an undef vector, we can 14855 // just use the input to the extract. 14856 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 14857 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT) 14858 return N1.getOperand(0); 14859 14860 // Combine INSERT_SUBVECTORs where we are inserting to the same index. 14861 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) 14862 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) 14863 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && 14864 N0.getOperand(1).getValueType() == N1.getValueType() && 14865 N0.getOperand(2) == N2) 14866 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), 14867 N1, N2); 14868 14869 if (!isa<ConstantSDNode>(N2)) 14870 return SDValue(); 14871 14872 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue(); 14873 14874 // Canonicalize insert_subvector dag nodes. 14875 // Example: 14876 // (insert_subvector (insert_subvector A, Idx0), Idx1) 14877 // -> (insert_subvector (insert_subvector A, Idx1), Idx0) 14878 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() && 14879 N1.getValueType() == N0.getOperand(1).getValueType() && 14880 isa<ConstantSDNode>(N0.getOperand(2))) { 14881 unsigned OtherIdx = cast<ConstantSDNode>(N0.getOperand(2))->getZExtValue(); 14882 if (InsIdx < OtherIdx) { 14883 // Swap nodes. 14884 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, 14885 N0.getOperand(0), N1, N2); 14886 AddToWorklist(NewOp.getNode()); 14887 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()), 14888 VT, NewOp, N0.getOperand(1), N0.getOperand(2)); 14889 } 14890 } 14891 14892 // If the input vector is a concatenation, and the insert replaces 14893 // one of the pieces, we can optimize into a single concat_vectors. 14894 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() && 14895 N0.getOperand(0).getValueType() == N1.getValueType()) { 14896 unsigned Factor = N1.getValueType().getVectorNumElements(); 14897 14898 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end()); 14899 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1; 14900 14901 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 14902 } 14903 14904 return SDValue(); 14905 } 14906 14907 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 14908 SDValue N0 = N->getOperand(0); 14909 14910 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 14911 if (N0->getOpcode() == ISD::FP16_TO_FP) 14912 return N0->getOperand(0); 14913 14914 return SDValue(); 14915 } 14916 14917 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 14918 SDValue N0 = N->getOperand(0); 14919 14920 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 14921 if (N0->getOpcode() == ISD::AND) { 14922 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 14923 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 14924 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 14925 N0.getOperand(0)); 14926 } 14927 } 14928 14929 return SDValue(); 14930 } 14931 14932 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 14933 /// with the destination vector and a zero vector. 14934 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 14935 /// vector_shuffle V, Zero, <0, 4, 2, 4> 14936 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 14937 EVT VT = N->getValueType(0); 14938 SDValue LHS = N->getOperand(0); 14939 SDValue RHS = N->getOperand(1); 14940 SDLoc DL(N); 14941 14942 // Make sure we're not running after operation legalization where it 14943 // may have custom lowered the vector shuffles. 14944 if (LegalOperations) 14945 return SDValue(); 14946 14947 if (N->getOpcode() != ISD::AND) 14948 return SDValue(); 14949 14950 if (RHS.getOpcode() == ISD::BITCAST) 14951 RHS = RHS.getOperand(0); 14952 14953 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 14954 return SDValue(); 14955 14956 EVT RVT = RHS.getValueType(); 14957 unsigned NumElts = RHS.getNumOperands(); 14958 14959 // Attempt to create a valid clear mask, splitting the mask into 14960 // sub elements and checking to see if each is 14961 // all zeros or all ones - suitable for shuffle masking. 14962 auto BuildClearMask = [&](int Split) { 14963 int NumSubElts = NumElts * Split; 14964 int NumSubBits = RVT.getScalarSizeInBits() / Split; 14965 14966 SmallVector<int, 8> Indices; 14967 for (int i = 0; i != NumSubElts; ++i) { 14968 int EltIdx = i / Split; 14969 int SubIdx = i % Split; 14970 SDValue Elt = RHS.getOperand(EltIdx); 14971 if (Elt.isUndef()) { 14972 Indices.push_back(-1); 14973 continue; 14974 } 14975 14976 APInt Bits; 14977 if (isa<ConstantSDNode>(Elt)) 14978 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 14979 else if (isa<ConstantFPSDNode>(Elt)) 14980 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 14981 else 14982 return SDValue(); 14983 14984 // Extract the sub element from the constant bit mask. 14985 if (DAG.getDataLayout().isBigEndian()) { 14986 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits); 14987 } else { 14988 Bits = Bits.lshr(SubIdx * NumSubBits); 14989 } 14990 14991 if (Split > 1) 14992 Bits = Bits.trunc(NumSubBits); 14993 14994 if (Bits.isAllOnesValue()) 14995 Indices.push_back(i); 14996 else if (Bits == 0) 14997 Indices.push_back(i + NumSubElts); 14998 else 14999 return SDValue(); 15000 } 15001 15002 // Let's see if the target supports this vector_shuffle. 15003 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 15004 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 15005 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 15006 return SDValue(); 15007 15008 SDValue Zero = DAG.getConstant(0, DL, ClearVT); 15009 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL, 15010 DAG.getBitcast(ClearVT, LHS), 15011 Zero, Indices)); 15012 }; 15013 15014 // Determine maximum split level (byte level masking). 15015 int MaxSplit = 1; 15016 if (RVT.getScalarSizeInBits() % 8 == 0) 15017 MaxSplit = RVT.getScalarSizeInBits() / 8; 15018 15019 for (int Split = 1; Split <= MaxSplit; ++Split) 15020 if (RVT.getScalarSizeInBits() % Split == 0) 15021 if (SDValue S = BuildClearMask(Split)) 15022 return S; 15023 15024 return SDValue(); 15025 } 15026 15027 /// Visit a binary vector operation, like ADD. 15028 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 15029 assert(N->getValueType(0).isVector() && 15030 "SimplifyVBinOp only works on vectors!"); 15031 15032 SDValue LHS = N->getOperand(0); 15033 SDValue RHS = N->getOperand(1); 15034 SDValue Ops[] = {LHS, RHS}; 15035 15036 // See if we can constant fold the vector operation. 15037 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 15038 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 15039 return Fold; 15040 15041 // Try to convert a constant mask AND into a shuffle clear mask. 15042 if (SDValue Shuffle = XformToShuffleWithZero(N)) 15043 return Shuffle; 15044 15045 // Type legalization might introduce new shuffles in the DAG. 15046 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 15047 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 15048 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 15049 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 15050 LHS.getOperand(1).isUndef() && 15051 RHS.getOperand(1).isUndef()) { 15052 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 15053 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 15054 15055 if (SVN0->getMask().equals(SVN1->getMask())) { 15056 EVT VT = N->getValueType(0); 15057 SDValue UndefVector = LHS.getOperand(1); 15058 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 15059 LHS.getOperand(0), RHS.getOperand(0), 15060 N->getFlags()); 15061 AddUsersToWorklist(N); 15062 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 15063 SVN0->getMask()); 15064 } 15065 } 15066 15067 return SDValue(); 15068 } 15069 15070 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 15071 SDValue N2) { 15072 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 15073 15074 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 15075 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 15076 15077 // If we got a simplified select_cc node back from SimplifySelectCC, then 15078 // break it down into a new SETCC node, and a new SELECT node, and then return 15079 // the SELECT node, since we were called with a SELECT node. 15080 if (SCC.getNode()) { 15081 // Check to see if we got a select_cc back (to turn into setcc/select). 15082 // Otherwise, just return whatever node we got back, like fabs. 15083 if (SCC.getOpcode() == ISD::SELECT_CC) { 15084 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 15085 N0.getValueType(), 15086 SCC.getOperand(0), SCC.getOperand(1), 15087 SCC.getOperand(4)); 15088 AddToWorklist(SETCC.getNode()); 15089 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 15090 SCC.getOperand(2), SCC.getOperand(3)); 15091 } 15092 15093 return SCC; 15094 } 15095 return SDValue(); 15096 } 15097 15098 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 15099 /// being selected between, see if we can simplify the select. Callers of this 15100 /// should assume that TheSelect is deleted if this returns true. As such, they 15101 /// should return the appropriate thing (e.g. the node) back to the top-level of 15102 /// the DAG combiner loop to avoid it being looked at. 15103 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 15104 SDValue RHS) { 15105 15106 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 15107 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 15108 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 15109 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 15110 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 15111 SDValue Sqrt = RHS; 15112 ISD::CondCode CC; 15113 SDValue CmpLHS; 15114 const ConstantFPSDNode *Zero = nullptr; 15115 15116 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 15117 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 15118 CmpLHS = TheSelect->getOperand(0); 15119 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 15120 } else { 15121 // SELECT or VSELECT 15122 SDValue Cmp = TheSelect->getOperand(0); 15123 if (Cmp.getOpcode() == ISD::SETCC) { 15124 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 15125 CmpLHS = Cmp.getOperand(0); 15126 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 15127 } 15128 } 15129 if (Zero && Zero->isZero() && 15130 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 15131 CC == ISD::SETULT || CC == ISD::SETLT)) { 15132 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 15133 CombineTo(TheSelect, Sqrt); 15134 return true; 15135 } 15136 } 15137 } 15138 // Cannot simplify select with vector condition 15139 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 15140 15141 // If this is a select from two identical things, try to pull the operation 15142 // through the select. 15143 if (LHS.getOpcode() != RHS.getOpcode() || 15144 !LHS.hasOneUse() || !RHS.hasOneUse()) 15145 return false; 15146 15147 // If this is a load and the token chain is identical, replace the select 15148 // of two loads with a load through a select of the address to load from. 15149 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 15150 // constants have been dropped into the constant pool. 15151 if (LHS.getOpcode() == ISD::LOAD) { 15152 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 15153 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 15154 15155 // Token chains must be identical. 15156 if (LHS.getOperand(0) != RHS.getOperand(0) || 15157 // Do not let this transformation reduce the number of volatile loads. 15158 LLD->isVolatile() || RLD->isVolatile() || 15159 // FIXME: If either is a pre/post inc/dec load, 15160 // we'd need to split out the address adjustment. 15161 LLD->isIndexed() || RLD->isIndexed() || 15162 // If this is an EXTLOAD, the VT's must match. 15163 LLD->getMemoryVT() != RLD->getMemoryVT() || 15164 // If this is an EXTLOAD, the kind of extension must match. 15165 (LLD->getExtensionType() != RLD->getExtensionType() && 15166 // The only exception is if one of the extensions is anyext. 15167 LLD->getExtensionType() != ISD::EXTLOAD && 15168 RLD->getExtensionType() != ISD::EXTLOAD) || 15169 // FIXME: this discards src value information. This is 15170 // over-conservative. It would be beneficial to be able to remember 15171 // both potential memory locations. Since we are discarding 15172 // src value info, don't do the transformation if the memory 15173 // locations are not in the default address space. 15174 LLD->getPointerInfo().getAddrSpace() != 0 || 15175 RLD->getPointerInfo().getAddrSpace() != 0 || 15176 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 15177 LLD->getBasePtr().getValueType())) 15178 return false; 15179 15180 // Check that the select condition doesn't reach either load. If so, 15181 // folding this will induce a cycle into the DAG. If not, this is safe to 15182 // xform, so create a select of the addresses. 15183 SDValue Addr; 15184 if (TheSelect->getOpcode() == ISD::SELECT) { 15185 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 15186 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 15187 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 15188 return false; 15189 // The loads must not depend on one another. 15190 if (LLD->isPredecessorOf(RLD) || 15191 RLD->isPredecessorOf(LLD)) 15192 return false; 15193 Addr = DAG.getSelect(SDLoc(TheSelect), 15194 LLD->getBasePtr().getValueType(), 15195 TheSelect->getOperand(0), LLD->getBasePtr(), 15196 RLD->getBasePtr()); 15197 } else { // Otherwise SELECT_CC 15198 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 15199 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 15200 15201 if ((LLD->hasAnyUseOfValue(1) && 15202 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 15203 (RLD->hasAnyUseOfValue(1) && 15204 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 15205 return false; 15206 15207 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 15208 LLD->getBasePtr().getValueType(), 15209 TheSelect->getOperand(0), 15210 TheSelect->getOperand(1), 15211 LLD->getBasePtr(), RLD->getBasePtr(), 15212 TheSelect->getOperand(4)); 15213 } 15214 15215 SDValue Load; 15216 // It is safe to replace the two loads if they have different alignments, 15217 // but the new load must be the minimum (most restrictive) alignment of the 15218 // inputs. 15219 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 15220 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 15221 if (!RLD->isInvariant()) 15222 MMOFlags &= ~MachineMemOperand::MOInvariant; 15223 if (!RLD->isDereferenceable()) 15224 MMOFlags &= ~MachineMemOperand::MODereferenceable; 15225 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 15226 // FIXME: Discards pointer and AA info. 15227 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 15228 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 15229 MMOFlags); 15230 } else { 15231 // FIXME: Discards pointer and AA info. 15232 Load = DAG.getExtLoad( 15233 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 15234 : LLD->getExtensionType(), 15235 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 15236 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 15237 } 15238 15239 // Users of the select now use the result of the load. 15240 CombineTo(TheSelect, Load); 15241 15242 // Users of the old loads now use the new load's chain. We know the 15243 // old-load value is dead now. 15244 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 15245 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 15246 return true; 15247 } 15248 15249 return false; 15250 } 15251 15252 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and 15253 /// bitwise 'and'. 15254 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, 15255 SDValue N1, SDValue N2, SDValue N3, 15256 ISD::CondCode CC) { 15257 // If this is a select where the false operand is zero and the compare is a 15258 // check of the sign bit, see if we can perform the "gzip trick": 15259 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A 15260 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A 15261 EVT XType = N0.getValueType(); 15262 EVT AType = N2.getValueType(); 15263 if (!isNullConstant(N3) || !XType.bitsGE(AType)) 15264 return SDValue(); 15265 15266 // If the comparison is testing for a positive value, we have to invert 15267 // the sign bit mask, so only do that transform if the target has a bitwise 15268 // 'and not' instruction (the invert is free). 15269 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) { 15270 // (X > -1) ? A : 0 15271 // (X > 0) ? X : 0 <-- This is canonical signed max. 15272 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2))) 15273 return SDValue(); 15274 } else if (CC == ISD::SETLT) { 15275 // (X < 0) ? A : 0 15276 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min. 15277 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2))) 15278 return SDValue(); 15279 } else { 15280 return SDValue(); 15281 } 15282 15283 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit 15284 // constant. 15285 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 15286 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 15287 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 15288 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1; 15289 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); 15290 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt); 15291 AddToWorklist(Shift.getNode()); 15292 15293 if (XType.bitsGT(AType)) { 15294 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 15295 AddToWorklist(Shift.getNode()); 15296 } 15297 15298 if (CC == ISD::SETGT) 15299 Shift = DAG.getNOT(DL, Shift, AType); 15300 15301 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 15302 } 15303 15304 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy); 15305 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt); 15306 AddToWorklist(Shift.getNode()); 15307 15308 if (XType.bitsGT(AType)) { 15309 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 15310 AddToWorklist(Shift.getNode()); 15311 } 15312 15313 if (CC == ISD::SETGT) 15314 Shift = DAG.getNOT(DL, Shift, AType); 15315 15316 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 15317 } 15318 15319 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 15320 /// where 'cond' is the comparison specified by CC. 15321 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 15322 SDValue N2, SDValue N3, ISD::CondCode CC, 15323 bool NotExtCompare) { 15324 // (x ? y : y) -> y. 15325 if (N2 == N3) return N2; 15326 15327 EVT VT = N2.getValueType(); 15328 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 15329 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 15330 15331 // Determine if the condition we're dealing with is constant 15332 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 15333 N0, N1, CC, DL, false); 15334 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 15335 15336 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 15337 // fold select_cc true, x, y -> x 15338 // fold select_cc false, x, y -> y 15339 return !SCCC->isNullValue() ? N2 : N3; 15340 } 15341 15342 // Check to see if we can simplify the select into an fabs node 15343 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 15344 // Allow either -0.0 or 0.0 15345 if (CFP->isZero()) { 15346 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 15347 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 15348 N0 == N2 && N3.getOpcode() == ISD::FNEG && 15349 N2 == N3.getOperand(0)) 15350 return DAG.getNode(ISD::FABS, DL, VT, N0); 15351 15352 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 15353 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 15354 N0 == N3 && N2.getOpcode() == ISD::FNEG && 15355 N2.getOperand(0) == N3) 15356 return DAG.getNode(ISD::FABS, DL, VT, N3); 15357 } 15358 } 15359 15360 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 15361 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 15362 // in it. This is a win when the constant is not otherwise available because 15363 // it replaces two constant pool loads with one. We only do this if the FP 15364 // type is known to be legal, because if it isn't, then we are before legalize 15365 // types an we want the other legalization to happen first (e.g. to avoid 15366 // messing with soft float) and if the ConstantFP is not legal, because if 15367 // it is legal, we may not need to store the FP constant in a constant pool. 15368 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 15369 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 15370 if (TLI.isTypeLegal(N2.getValueType()) && 15371 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 15372 TargetLowering::Legal && 15373 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 15374 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 15375 // If both constants have multiple uses, then we won't need to do an 15376 // extra load, they are likely around in registers for other users. 15377 (TV->hasOneUse() || FV->hasOneUse())) { 15378 Constant *Elts[] = { 15379 const_cast<ConstantFP*>(FV->getConstantFPValue()), 15380 const_cast<ConstantFP*>(TV->getConstantFPValue()) 15381 }; 15382 Type *FPTy = Elts[0]->getType(); 15383 const DataLayout &TD = DAG.getDataLayout(); 15384 15385 // Create a ConstantArray of the two constants. 15386 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 15387 SDValue CPIdx = 15388 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 15389 TD.getPrefTypeAlignment(FPTy)); 15390 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 15391 15392 // Get the offsets to the 0 and 1 element of the array so that we can 15393 // select between them. 15394 SDValue Zero = DAG.getIntPtrConstant(0, DL); 15395 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 15396 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 15397 15398 SDValue Cond = DAG.getSetCC(DL, 15399 getSetCCResultType(N0.getValueType()), 15400 N0, N1, CC); 15401 AddToWorklist(Cond.getNode()); 15402 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 15403 Cond, One, Zero); 15404 AddToWorklist(CstOffset.getNode()); 15405 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 15406 CstOffset); 15407 AddToWorklist(CPIdx.getNode()); 15408 return DAG.getLoad( 15409 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 15410 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 15411 Alignment); 15412 } 15413 } 15414 15415 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC)) 15416 return V; 15417 15418 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 15419 // where y is has a single bit set. 15420 // A plaintext description would be, we can turn the SELECT_CC into an AND 15421 // when the condition can be materialized as an all-ones register. Any 15422 // single bit-test can be materialized as an all-ones register with 15423 // shift-left and shift-right-arith. 15424 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 15425 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 15426 SDValue AndLHS = N0->getOperand(0); 15427 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 15428 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 15429 // Shift the tested bit over the sign bit. 15430 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 15431 SDValue ShlAmt = 15432 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 15433 getShiftAmountTy(AndLHS.getValueType())); 15434 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 15435 15436 // Now arithmetic right shift it all the way over, so the result is either 15437 // all-ones, or zero. 15438 SDValue ShrAmt = 15439 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 15440 getShiftAmountTy(Shl.getValueType())); 15441 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 15442 15443 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 15444 } 15445 } 15446 15447 // fold select C, 16, 0 -> shl C, 4 15448 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 15449 TLI.getBooleanContents(N0.getValueType()) == 15450 TargetLowering::ZeroOrOneBooleanContent) { 15451 15452 // If the caller doesn't want us to simplify this into a zext of a compare, 15453 // don't do it. 15454 if (NotExtCompare && N2C->isOne()) 15455 return SDValue(); 15456 15457 // Get a SetCC of the condition 15458 // NOTE: Don't create a SETCC if it's not legal on this target. 15459 if (!LegalOperations || 15460 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 15461 SDValue Temp, SCC; 15462 // cast from setcc result type to select result type 15463 if (LegalTypes) { 15464 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 15465 N0, N1, CC); 15466 if (N2.getValueType().bitsLT(SCC.getValueType())) 15467 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 15468 N2.getValueType()); 15469 else 15470 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 15471 N2.getValueType(), SCC); 15472 } else { 15473 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 15474 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 15475 N2.getValueType(), SCC); 15476 } 15477 15478 AddToWorklist(SCC.getNode()); 15479 AddToWorklist(Temp.getNode()); 15480 15481 if (N2C->isOne()) 15482 return Temp; 15483 15484 // shl setcc result by log2 n2c 15485 return DAG.getNode( 15486 ISD::SHL, DL, N2.getValueType(), Temp, 15487 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 15488 getShiftAmountTy(Temp.getValueType()))); 15489 } 15490 } 15491 15492 // Check to see if this is an integer abs. 15493 // select_cc setg[te] X, 0, X, -X -> 15494 // select_cc setgt X, -1, X, -X -> 15495 // select_cc setl[te] X, 0, -X, X -> 15496 // select_cc setlt X, 1, -X, X -> 15497 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 15498 if (N1C) { 15499 ConstantSDNode *SubC = nullptr; 15500 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 15501 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 15502 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 15503 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 15504 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 15505 (N1C->isOne() && CC == ISD::SETLT)) && 15506 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 15507 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 15508 15509 EVT XType = N0.getValueType(); 15510 if (SubC && SubC->isNullValue() && XType.isInteger()) { 15511 SDLoc DL(N0); 15512 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 15513 N0, 15514 DAG.getConstant(XType.getSizeInBits() - 1, DL, 15515 getShiftAmountTy(N0.getValueType()))); 15516 SDValue Add = DAG.getNode(ISD::ADD, DL, 15517 XType, N0, Shift); 15518 AddToWorklist(Shift.getNode()); 15519 AddToWorklist(Add.getNode()); 15520 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 15521 } 15522 } 15523 15524 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 15525 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 15526 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 15527 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 15528 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 15529 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 15530 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 15531 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 15532 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 15533 SDValue ValueOnZero = N2; 15534 SDValue Count = N3; 15535 // If the condition is NE instead of E, swap the operands. 15536 if (CC == ISD::SETNE) 15537 std::swap(ValueOnZero, Count); 15538 // Check if the value on zero is a constant equal to the bits in the type. 15539 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 15540 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 15541 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 15542 // legal, combine to just cttz. 15543 if ((Count.getOpcode() == ISD::CTTZ || 15544 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 15545 N0 == Count.getOperand(0) && 15546 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 15547 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 15548 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 15549 // legal, combine to just ctlz. 15550 if ((Count.getOpcode() == ISD::CTLZ || 15551 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 15552 N0 == Count.getOperand(0) && 15553 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 15554 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 15555 } 15556 } 15557 } 15558 15559 return SDValue(); 15560 } 15561 15562 /// This is a stub for TargetLowering::SimplifySetCC. 15563 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 15564 ISD::CondCode Cond, const SDLoc &DL, 15565 bool foldBooleans) { 15566 TargetLowering::DAGCombinerInfo 15567 DagCombineInfo(DAG, Level, false, this); 15568 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 15569 } 15570 15571 /// Given an ISD::SDIV node expressing a divide by constant, return 15572 /// a DAG expression to select that will generate the same value by multiplying 15573 /// by a magic number. 15574 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 15575 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 15576 // when optimising for minimum size, we don't want to expand a div to a mul 15577 // and a shift. 15578 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 15579 return SDValue(); 15580 15581 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 15582 if (!C) 15583 return SDValue(); 15584 15585 // Avoid division by zero. 15586 if (C->isNullValue()) 15587 return SDValue(); 15588 15589 std::vector<SDNode*> Built; 15590 SDValue S = 15591 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 15592 15593 for (SDNode *N : Built) 15594 AddToWorklist(N); 15595 return S; 15596 } 15597 15598 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 15599 /// DAG expression that will generate the same value by right shifting. 15600 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 15601 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 15602 if (!C) 15603 return SDValue(); 15604 15605 // Avoid division by zero. 15606 if (C->isNullValue()) 15607 return SDValue(); 15608 15609 std::vector<SDNode *> Built; 15610 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 15611 15612 for (SDNode *N : Built) 15613 AddToWorklist(N); 15614 return S; 15615 } 15616 15617 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 15618 /// expression that will generate the same value by multiplying by a magic 15619 /// number. 15620 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 15621 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 15622 // when optimising for minimum size, we don't want to expand a div to a mul 15623 // and a shift. 15624 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 15625 return SDValue(); 15626 15627 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 15628 if (!C) 15629 return SDValue(); 15630 15631 // Avoid division by zero. 15632 if (C->isNullValue()) 15633 return SDValue(); 15634 15635 std::vector<SDNode*> Built; 15636 SDValue S = 15637 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 15638 15639 for (SDNode *N : Built) 15640 AddToWorklist(N); 15641 return S; 15642 } 15643 15644 /// Determines the LogBase2 value for a non-null input value using the 15645 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V). 15646 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) { 15647 EVT VT = V.getValueType(); 15648 unsigned EltBits = VT.getScalarSizeInBits(); 15649 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V); 15650 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT); 15651 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz); 15652 return LogBase2; 15653 } 15654 15655 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 15656 /// For the reciprocal, we need to find the zero of the function: 15657 /// F(X) = A X - 1 [which has a zero at X = 1/A] 15658 /// => 15659 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 15660 /// does not require additional intermediate precision] 15661 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) { 15662 if (Level >= AfterLegalizeDAG) 15663 return SDValue(); 15664 15665 // TODO: Handle half and/or extended types? 15666 EVT VT = Op.getValueType(); 15667 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 15668 return SDValue(); 15669 15670 // If estimates are explicitly disabled for this function, we're done. 15671 MachineFunction &MF = DAG.getMachineFunction(); 15672 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF); 15673 if (Enabled == TLI.ReciprocalEstimate::Disabled) 15674 return SDValue(); 15675 15676 // Estimates may be explicitly enabled for this type with a custom number of 15677 // refinement steps. 15678 int Iterations = TLI.getDivRefinementSteps(VT, MF); 15679 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) { 15680 AddToWorklist(Est.getNode()); 15681 15682 if (Iterations) { 15683 EVT VT = Op.getValueType(); 15684 SDLoc DL(Op); 15685 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 15686 15687 // Newton iterations: Est = Est + Est (1 - Arg * Est) 15688 for (int i = 0; i < Iterations; ++i) { 15689 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 15690 AddToWorklist(NewEst.getNode()); 15691 15692 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 15693 AddToWorklist(NewEst.getNode()); 15694 15695 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 15696 AddToWorklist(NewEst.getNode()); 15697 15698 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 15699 AddToWorklist(Est.getNode()); 15700 } 15701 } 15702 return Est; 15703 } 15704 15705 return SDValue(); 15706 } 15707 15708 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 15709 /// For the reciprocal sqrt, we need to find the zero of the function: 15710 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 15711 /// => 15712 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 15713 /// As a result, we precompute A/2 prior to the iteration loop. 15714 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 15715 unsigned Iterations, 15716 SDNodeFlags *Flags, bool Reciprocal) { 15717 EVT VT = Arg.getValueType(); 15718 SDLoc DL(Arg); 15719 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 15720 15721 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 15722 // this entire sequence requires only one FP constant. 15723 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 15724 AddToWorklist(HalfArg.getNode()); 15725 15726 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 15727 AddToWorklist(HalfArg.getNode()); 15728 15729 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 15730 for (unsigned i = 0; i < Iterations; ++i) { 15731 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 15732 AddToWorklist(NewEst.getNode()); 15733 15734 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 15735 AddToWorklist(NewEst.getNode()); 15736 15737 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 15738 AddToWorklist(NewEst.getNode()); 15739 15740 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 15741 AddToWorklist(Est.getNode()); 15742 } 15743 15744 // If non-reciprocal square root is requested, multiply the result by Arg. 15745 if (!Reciprocal) { 15746 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 15747 AddToWorklist(Est.getNode()); 15748 } 15749 15750 return Est; 15751 } 15752 15753 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 15754 /// For the reciprocal sqrt, we need to find the zero of the function: 15755 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 15756 /// => 15757 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 15758 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 15759 unsigned Iterations, 15760 SDNodeFlags *Flags, bool Reciprocal) { 15761 EVT VT = Arg.getValueType(); 15762 SDLoc DL(Arg); 15763 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 15764 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 15765 15766 // This routine must enter the loop below to work correctly 15767 // when (Reciprocal == false). 15768 assert(Iterations > 0); 15769 15770 // Newton iterations for reciprocal square root: 15771 // E = (E * -0.5) * ((A * E) * E + -3.0) 15772 for (unsigned i = 0; i < Iterations; ++i) { 15773 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 15774 AddToWorklist(AE.getNode()); 15775 15776 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 15777 AddToWorklist(AEE.getNode()); 15778 15779 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 15780 AddToWorklist(RHS.getNode()); 15781 15782 // When calculating a square root at the last iteration build: 15783 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 15784 // (notice a common subexpression) 15785 SDValue LHS; 15786 if (Reciprocal || (i + 1) < Iterations) { 15787 // RSQRT: LHS = (E * -0.5) 15788 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 15789 } else { 15790 // SQRT: LHS = (A * E) * -0.5 15791 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 15792 } 15793 AddToWorklist(LHS.getNode()); 15794 15795 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 15796 AddToWorklist(Est.getNode()); 15797 } 15798 15799 return Est; 15800 } 15801 15802 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 15803 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 15804 /// Op can be zero. 15805 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, 15806 bool Reciprocal) { 15807 if (Level >= AfterLegalizeDAG) 15808 return SDValue(); 15809 15810 // TODO: Handle half and/or extended types? 15811 EVT VT = Op.getValueType(); 15812 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 15813 return SDValue(); 15814 15815 // If estimates are explicitly disabled for this function, we're done. 15816 MachineFunction &MF = DAG.getMachineFunction(); 15817 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF); 15818 if (Enabled == TLI.ReciprocalEstimate::Disabled) 15819 return SDValue(); 15820 15821 // Estimates may be explicitly enabled for this type with a custom number of 15822 // refinement steps. 15823 int Iterations = TLI.getSqrtRefinementSteps(VT, MF); 15824 15825 bool UseOneConstNR = false; 15826 if (SDValue Est = 15827 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR, 15828 Reciprocal)) { 15829 AddToWorklist(Est.getNode()); 15830 15831 if (Iterations) { 15832 Est = UseOneConstNR 15833 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 15834 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 15835 15836 if (!Reciprocal) { 15837 // Unfortunately, Est is now NaN if the input was exactly 0.0. 15838 // Select out this case and force the answer to 0.0. 15839 EVT VT = Op.getValueType(); 15840 SDLoc DL(Op); 15841 15842 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 15843 EVT CCVT = getSetCCResultType(VT); 15844 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 15845 AddToWorklist(ZeroCmp.getNode()); 15846 15847 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 15848 ZeroCmp, FPZero, Est); 15849 AddToWorklist(Est.getNode()); 15850 } 15851 } 15852 return Est; 15853 } 15854 15855 return SDValue(); 15856 } 15857 15858 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 15859 return buildSqrtEstimateImpl(Op, Flags, true); 15860 } 15861 15862 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 15863 return buildSqrtEstimateImpl(Op, Flags, false); 15864 } 15865 15866 /// Return true if base is a frame index, which is known not to alias with 15867 /// anything but itself. Provides base object and offset as results. 15868 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 15869 const GlobalValue *&GV, const void *&CV) { 15870 // Assume it is a primitive operation. 15871 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 15872 15873 // If it's an adding a simple constant then integrate the offset. 15874 if (Base.getOpcode() == ISD::ADD) { 15875 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 15876 Base = Base.getOperand(0); 15877 Offset += C->getZExtValue(); 15878 } 15879 } 15880 15881 // Return the underlying GlobalValue, and update the Offset. Return false 15882 // for GlobalAddressSDNode since the same GlobalAddress may be represented 15883 // by multiple nodes with different offsets. 15884 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 15885 GV = G->getGlobal(); 15886 Offset += G->getOffset(); 15887 return false; 15888 } 15889 15890 // Return the underlying Constant value, and update the Offset. Return false 15891 // for ConstantSDNodes since the same constant pool entry may be represented 15892 // by multiple nodes with different offsets. 15893 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 15894 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 15895 : (const void *)C->getConstVal(); 15896 Offset += C->getOffset(); 15897 return false; 15898 } 15899 // If it's any of the following then it can't alias with anything but itself. 15900 return isa<FrameIndexSDNode>(Base); 15901 } 15902 15903 /// Return true if there is any possibility that the two addresses overlap. 15904 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 15905 // If they are the same then they must be aliases. 15906 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 15907 15908 // If they are both volatile then they cannot be reordered. 15909 if (Op0->isVolatile() && Op1->isVolatile()) return true; 15910 15911 // If one operation reads from invariant memory, and the other may store, they 15912 // cannot alias. These should really be checking the equivalent of mayWrite, 15913 // but it only matters for memory nodes other than load /store. 15914 if (Op0->isInvariant() && Op1->writeMem()) 15915 return false; 15916 15917 if (Op1->isInvariant() && Op0->writeMem()) 15918 return false; 15919 15920 // Gather base node and offset information. 15921 SDValue Base1, Base2; 15922 int64_t Offset1, Offset2; 15923 const GlobalValue *GV1, *GV2; 15924 const void *CV1, *CV2; 15925 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 15926 Base1, Offset1, GV1, CV1); 15927 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 15928 Base2, Offset2, GV2, CV2); 15929 15930 // If they have a same base address then check to see if they overlap. 15931 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 15932 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 15933 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 15934 15935 // It is possible for different frame indices to alias each other, mostly 15936 // when tail call optimization reuses return address slots for arguments. 15937 // To catch this case, look up the actual index of frame indices to compute 15938 // the real alias relationship. 15939 if (isFrameIndex1 && isFrameIndex2) { 15940 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 15941 Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 15942 Offset2 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 15943 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 15944 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 15945 } 15946 15947 // Otherwise, if we know what the bases are, and they aren't identical, then 15948 // we know they cannot alias. 15949 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 15950 return false; 15951 15952 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 15953 // compared to the size and offset of the access, we may be able to prove they 15954 // do not alias. This check is conservative for now to catch cases created by 15955 // splitting vector types. 15956 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 15957 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 15958 (Op0->getMemoryVT().getSizeInBits() >> 3 == 15959 Op1->getMemoryVT().getSizeInBits() >> 3) && 15960 (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) { 15961 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 15962 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 15963 15964 // There is no overlap between these relatively aligned accesses of similar 15965 // size, return no alias. 15966 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 15967 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 15968 return false; 15969 } 15970 15971 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 15972 ? CombinerGlobalAA 15973 : DAG.getSubtarget().useAA(); 15974 #ifndef NDEBUG 15975 if (CombinerAAOnlyFunc.getNumOccurrences() && 15976 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 15977 UseAA = false; 15978 #endif 15979 if (UseAA && 15980 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 15981 // Use alias analysis information. 15982 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 15983 Op1->getSrcValueOffset()); 15984 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 15985 Op0->getSrcValueOffset() - MinOffset; 15986 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 15987 Op1->getSrcValueOffset() - MinOffset; 15988 AliasResult AAResult = 15989 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1, 15990 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 15991 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2, 15992 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 15993 if (AAResult == NoAlias) 15994 return false; 15995 } 15996 15997 // Otherwise we have to assume they alias. 15998 return true; 15999 } 16000 16001 /// Walk up chain skipping non-aliasing memory nodes, 16002 /// looking for aliasing nodes and adding them to the Aliases vector. 16003 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 16004 SmallVectorImpl<SDValue> &Aliases) { 16005 SmallVector<SDValue, 8> Chains; // List of chains to visit. 16006 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 16007 16008 // Get alias information for node. 16009 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 16010 16011 // Starting off. 16012 Chains.push_back(OriginalChain); 16013 unsigned Depth = 0; 16014 16015 // Look at each chain and determine if it is an alias. If so, add it to the 16016 // aliases list. If not, then continue up the chain looking for the next 16017 // candidate. 16018 while (!Chains.empty()) { 16019 SDValue Chain = Chains.pop_back_val(); 16020 16021 // For TokenFactor nodes, look at each operand and only continue up the 16022 // chain until we reach the depth limit. 16023 // 16024 // FIXME: The depth check could be made to return the last non-aliasing 16025 // chain we found before we hit a tokenfactor rather than the original 16026 // chain. 16027 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 16028 Aliases.clear(); 16029 Aliases.push_back(OriginalChain); 16030 return; 16031 } 16032 16033 // Don't bother if we've been before. 16034 if (!Visited.insert(Chain.getNode()).second) 16035 continue; 16036 16037 switch (Chain.getOpcode()) { 16038 case ISD::EntryToken: 16039 // Entry token is ideal chain operand, but handled in FindBetterChain. 16040 break; 16041 16042 case ISD::LOAD: 16043 case ISD::STORE: { 16044 // Get alias information for Chain. 16045 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 16046 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 16047 16048 // If chain is alias then stop here. 16049 if (!(IsLoad && IsOpLoad) && 16050 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 16051 Aliases.push_back(Chain); 16052 } else { 16053 // Look further up the chain. 16054 Chains.push_back(Chain.getOperand(0)); 16055 ++Depth; 16056 } 16057 break; 16058 } 16059 16060 case ISD::TokenFactor: 16061 // We have to check each of the operands of the token factor for "small" 16062 // token factors, so we queue them up. Adding the operands to the queue 16063 // (stack) in reverse order maintains the original order and increases the 16064 // likelihood that getNode will find a matching token factor (CSE.) 16065 if (Chain.getNumOperands() > 16) { 16066 Aliases.push_back(Chain); 16067 break; 16068 } 16069 for (unsigned n = Chain.getNumOperands(); n;) 16070 Chains.push_back(Chain.getOperand(--n)); 16071 ++Depth; 16072 break; 16073 16074 default: 16075 // For all other instructions we will just have to take what we can get. 16076 Aliases.push_back(Chain); 16077 break; 16078 } 16079 } 16080 } 16081 16082 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 16083 /// (aliasing node.) 16084 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 16085 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 16086 16087 // Accumulate all the aliases to this node. 16088 GatherAllAliases(N, OldChain, Aliases); 16089 16090 // If no operands then chain to entry token. 16091 if (Aliases.size() == 0) 16092 return DAG.getEntryNode(); 16093 16094 // If a single operand then chain to it. We don't need to revisit it. 16095 if (Aliases.size() == 1) 16096 return Aliases[0]; 16097 16098 // Construct a custom tailored token factor. 16099 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 16100 } 16101 16102 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 16103 // This holds the base pointer, index, and the offset in bytes from the base 16104 // pointer. 16105 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 16106 16107 // We must have a base and an offset. 16108 if (!BasePtr.Base.getNode()) 16109 return false; 16110 16111 // Do not handle stores to undef base pointers. 16112 if (BasePtr.Base.isUndef()) 16113 return false; 16114 16115 SmallVector<StoreSDNode *, 8> ChainedStores; 16116 ChainedStores.push_back(St); 16117 16118 // Walk up the chain and look for nodes with offsets from the same 16119 // base pointer. Stop when reaching an instruction with a different kind 16120 // or instruction which has a different base pointer. 16121 StoreSDNode *Index = St; 16122 while (Index) { 16123 // If the chain has more than one use, then we can't reorder the mem ops. 16124 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 16125 break; 16126 16127 if (Index->isVolatile() || Index->isIndexed()) 16128 break; 16129 16130 // Find the base pointer and offset for this memory node. 16131 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 16132 16133 // Check that the base pointer is the same as the original one. 16134 if (!Ptr.equalBaseIndex(BasePtr)) 16135 break; 16136 16137 // Find the next memory operand in the chain. If the next operand in the 16138 // chain is a store then move up and continue the scan with the next 16139 // memory operand. If the next operand is a load save it and use alias 16140 // information to check if it interferes with anything. 16141 SDNode *NextInChain = Index->getChain().getNode(); 16142 while (true) { 16143 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 16144 // We found a store node. Use it for the next iteration. 16145 if (STn->isVolatile() || STn->isIndexed()) { 16146 Index = nullptr; 16147 break; 16148 } 16149 ChainedStores.push_back(STn); 16150 Index = STn; 16151 break; 16152 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 16153 NextInChain = Ldn->getChain().getNode(); 16154 continue; 16155 } else { 16156 Index = nullptr; 16157 break; 16158 } 16159 } 16160 } 16161 16162 bool MadeChangeToSt = false; 16163 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 16164 16165 for (StoreSDNode *ChainedStore : ChainedStores) { 16166 SDValue Chain = ChainedStore->getChain(); 16167 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 16168 16169 if (Chain != BetterChain) { 16170 if (ChainedStore == St) 16171 MadeChangeToSt = true; 16172 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 16173 } 16174 } 16175 16176 // Do all replacements after finding the replacements to make to avoid making 16177 // the chains more complicated by introducing new TokenFactors. 16178 for (auto Replacement : BetterChains) 16179 replaceStoreChain(Replacement.first, Replacement.second); 16180 16181 return MadeChangeToSt; 16182 } 16183 16184 /// This is the entry point for the file. 16185 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 16186 CodeGenOpt::Level OptLevel) { 16187 /// This is the main entry point to this class. 16188 DAGCombiner(*this, AA, OptLevel).Run(Level); 16189 } 16190