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/CodeGen/SelectionDAG.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/SmallBitVector.h" 22 #include "llvm/ADT/SmallPtrSet.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/SelectionDAGTargetInfo.h" 28 #include "llvm/IR/DataLayout.h" 29 #include "llvm/IR/DerivedTypes.h" 30 #include "llvm/IR/Function.h" 31 #include "llvm/IR/LLVMContext.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/ErrorHandling.h" 35 #include "llvm/Support/MathExtras.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include "llvm/Target/TargetLowering.h" 38 #include "llvm/Target/TargetOptions.h" 39 #include "llvm/Target/TargetRegisterInfo.h" 40 #include "llvm/Target/TargetSubtargetInfo.h" 41 #include <algorithm> 42 using namespace llvm; 43 44 #define DEBUG_TYPE "dagcombine" 45 46 STATISTIC(NodesCombined , "Number of dag nodes combined"); 47 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 48 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 49 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 50 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 51 STATISTIC(SlicedLoads, "Number of load sliced"); 52 53 namespace { 54 static cl::opt<bool> 55 CombinerAA("combiner-alias-analysis", cl::Hidden, 56 cl::desc("Enable DAG combiner alias-analysis heuristics")); 57 58 static cl::opt<bool> 59 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 60 cl::desc("Enable DAG combiner's use of IR alias analysis")); 61 62 static cl::opt<bool> 63 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 64 cl::desc("Enable DAG combiner's use of TBAA")); 65 66 #ifndef NDEBUG 67 static cl::opt<std::string> 68 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 69 cl::desc("Only use DAG-combiner alias analysis in this" 70 " function")); 71 #endif 72 73 /// Hidden option to stress test load slicing, i.e., when this option 74 /// is enabled, load slicing bypasses most of its profitability guards. 75 static cl::opt<bool> 76 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 77 cl::desc("Bypass the profitability model of load " 78 "slicing"), 79 cl::init(false)); 80 81 static cl::opt<bool> 82 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 83 cl::desc("DAG combiner may split indexing from loads")); 84 85 //------------------------------ DAGCombiner ---------------------------------// 86 87 class DAGCombiner { 88 SelectionDAG &DAG; 89 const TargetLowering &TLI; 90 CombineLevel Level; 91 CodeGenOpt::Level OptLevel; 92 bool LegalOperations; 93 bool LegalTypes; 94 bool ForCodeSize; 95 96 /// \brief Worklist of all of the nodes that need to be simplified. 97 /// 98 /// This must behave as a stack -- new nodes to process are pushed onto the 99 /// back and when processing we pop off of the back. 100 /// 101 /// The worklist will not contain duplicates but may contain null entries 102 /// due to nodes being deleted from the underlying DAG. 103 SmallVector<SDNode *, 64> Worklist; 104 105 /// \brief Mapping from an SDNode to its position on the worklist. 106 /// 107 /// This is used to find and remove nodes from the worklist (by nulling 108 /// them) when they are deleted from the underlying DAG. It relies on 109 /// stable indices of nodes within the worklist. 110 DenseMap<SDNode *, unsigned> WorklistMap; 111 112 /// \brief Set of nodes which have been combined (at least once). 113 /// 114 /// This is used to allow us to reliably add any operands of a DAG node 115 /// which have not yet been combined to the worklist. 116 SmallPtrSet<SDNode *, 32> CombinedNodes; 117 118 // AA - Used for DAG load/store alias analysis. 119 AliasAnalysis &AA; 120 121 /// When an instruction is simplified, add all users of the instruction to 122 /// the work lists because they might get more simplified now. 123 void AddUsersToWorklist(SDNode *N) { 124 for (SDNode *Node : N->uses()) 125 AddToWorklist(Node); 126 } 127 128 /// Call the node-specific routine that folds each particular type of node. 129 SDValue visit(SDNode *N); 130 131 public: 132 /// Add to the worklist making sure its instance is at the back (next to be 133 /// processed.) 134 void AddToWorklist(SDNode *N) { 135 // Skip handle nodes as they can't usefully be combined and confuse the 136 // zero-use deletion strategy. 137 if (N->getOpcode() == ISD::HANDLENODE) 138 return; 139 140 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 141 Worklist.push_back(N); 142 } 143 144 /// Remove all instances of N from the worklist. 145 void removeFromWorklist(SDNode *N) { 146 CombinedNodes.erase(N); 147 148 auto It = WorklistMap.find(N); 149 if (It == WorklistMap.end()) 150 return; // Not in the worklist. 151 152 // Null out the entry rather than erasing it to avoid a linear operation. 153 Worklist[It->second] = nullptr; 154 WorklistMap.erase(It); 155 } 156 157 void deleteAndRecombine(SDNode *N); 158 bool recursivelyDeleteUnusedNodes(SDNode *N); 159 160 /// Replaces all uses of the results of one DAG node with new values. 161 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 162 bool AddTo = true); 163 164 /// Replaces all uses of the results of one DAG node with new values. 165 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 166 return CombineTo(N, &Res, 1, AddTo); 167 } 168 169 /// Replaces all uses of the results of one DAG node with new values. 170 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 171 bool AddTo = true) { 172 SDValue To[] = { Res0, Res1 }; 173 return CombineTo(N, To, 2, AddTo); 174 } 175 176 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 177 178 private: 179 180 /// Check the specified integer node value to see if it can be simplified or 181 /// if things it uses can be simplified by bit propagation. 182 /// If so, return true. 183 bool SimplifyDemandedBits(SDValue Op) { 184 unsigned BitWidth = Op.getScalarValueSizeInBits(); 185 APInt Demanded = APInt::getAllOnesValue(BitWidth); 186 return SimplifyDemandedBits(Op, Demanded); 187 } 188 189 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 190 191 bool CombineToPreIndexedLoadStore(SDNode *N); 192 bool CombineToPostIndexedLoadStore(SDNode *N); 193 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 194 bool SliceUpLoad(SDNode *N); 195 196 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 197 /// load. 198 /// 199 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 200 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 201 /// \param EltNo index of the vector element to load. 202 /// \param OriginalLoad load that EVE came from to be replaced. 203 /// \returns EVE on success SDValue() on failure. 204 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 205 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 206 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 207 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 208 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 209 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 210 SDValue PromoteIntBinOp(SDValue Op); 211 SDValue PromoteIntShiftOp(SDValue Op); 212 SDValue PromoteExtend(SDValue Op); 213 bool PromoteLoad(SDValue Op); 214 215 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc, 216 SDValue ExtLoad, const SDLoc &DL, 217 ISD::NodeType ExtType); 218 219 /// Call the node-specific routine that knows how to fold each 220 /// particular type of node. If that doesn't do anything, try the 221 /// target-specific DAG combines. 222 SDValue combine(SDNode *N); 223 224 // Visitation implementation - Implement dag node combining for different 225 // node types. The semantics are as follows: 226 // Return Value: 227 // SDValue.getNode() == 0 - No change was made 228 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 229 // otherwise - N should be replaced by the returned Operand. 230 // 231 SDValue visitTokenFactor(SDNode *N); 232 SDValue visitMERGE_VALUES(SDNode *N); 233 SDValue visitADD(SDNode *N); 234 SDValue visitSUB(SDNode *N); 235 SDValue visitADDC(SDNode *N); 236 SDValue visitSUBC(SDNode *N); 237 SDValue visitADDE(SDNode *N); 238 SDValue visitSUBE(SDNode *N); 239 SDValue visitMUL(SDNode *N); 240 SDValue useDivRem(SDNode *N); 241 SDValue visitSDIV(SDNode *N); 242 SDValue visitUDIV(SDNode *N); 243 SDValue visitREM(SDNode *N); 244 SDValue visitMULHU(SDNode *N); 245 SDValue visitMULHS(SDNode *N); 246 SDValue visitSMUL_LOHI(SDNode *N); 247 SDValue visitUMUL_LOHI(SDNode *N); 248 SDValue visitSMULO(SDNode *N); 249 SDValue visitUMULO(SDNode *N); 250 SDValue visitIMINMAX(SDNode *N); 251 SDValue visitAND(SDNode *N); 252 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference); 253 SDValue visitOR(SDNode *N); 254 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference); 255 SDValue visitXOR(SDNode *N); 256 SDValue SimplifyVBinOp(SDNode *N); 257 SDValue visitSHL(SDNode *N); 258 SDValue visitSRA(SDNode *N); 259 SDValue visitSRL(SDNode *N); 260 SDValue visitRotate(SDNode *N); 261 SDValue visitBSWAP(SDNode *N); 262 SDValue visitBITREVERSE(SDNode *N); 263 SDValue visitCTLZ(SDNode *N); 264 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 265 SDValue visitCTTZ(SDNode *N); 266 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 267 SDValue visitCTPOP(SDNode *N); 268 SDValue visitSELECT(SDNode *N); 269 SDValue visitVSELECT(SDNode *N); 270 SDValue visitSELECT_CC(SDNode *N); 271 SDValue visitSETCC(SDNode *N); 272 SDValue visitSETCCE(SDNode *N); 273 SDValue visitSIGN_EXTEND(SDNode *N); 274 SDValue visitZERO_EXTEND(SDNode *N); 275 SDValue visitANY_EXTEND(SDNode *N); 276 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 277 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 278 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N); 279 SDValue visitTRUNCATE(SDNode *N); 280 SDValue visitBITCAST(SDNode *N); 281 SDValue visitBUILD_PAIR(SDNode *N); 282 SDValue visitFADD(SDNode *N); 283 SDValue visitFSUB(SDNode *N); 284 SDValue visitFMUL(SDNode *N); 285 SDValue visitFMA(SDNode *N); 286 SDValue visitFDIV(SDNode *N); 287 SDValue visitFREM(SDNode *N); 288 SDValue visitFSQRT(SDNode *N); 289 SDValue visitFCOPYSIGN(SDNode *N); 290 SDValue visitSINT_TO_FP(SDNode *N); 291 SDValue visitUINT_TO_FP(SDNode *N); 292 SDValue visitFP_TO_SINT(SDNode *N); 293 SDValue visitFP_TO_UINT(SDNode *N); 294 SDValue visitFP_ROUND(SDNode *N); 295 SDValue visitFP_ROUND_INREG(SDNode *N); 296 SDValue visitFP_EXTEND(SDNode *N); 297 SDValue visitFNEG(SDNode *N); 298 SDValue visitFABS(SDNode *N); 299 SDValue visitFCEIL(SDNode *N); 300 SDValue visitFTRUNC(SDNode *N); 301 SDValue visitFFLOOR(SDNode *N); 302 SDValue visitFMINNUM(SDNode *N); 303 SDValue visitFMAXNUM(SDNode *N); 304 SDValue visitBRCOND(SDNode *N); 305 SDValue visitBR_CC(SDNode *N); 306 SDValue visitLOAD(SDNode *N); 307 308 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 309 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 310 311 SDValue visitSTORE(SDNode *N); 312 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 313 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 314 SDValue visitBUILD_VECTOR(SDNode *N); 315 SDValue visitCONCAT_VECTORS(SDNode *N); 316 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 317 SDValue visitVECTOR_SHUFFLE(SDNode *N); 318 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 319 SDValue visitINSERT_SUBVECTOR(SDNode *N); 320 SDValue visitMLOAD(SDNode *N); 321 SDValue visitMSTORE(SDNode *N); 322 SDValue visitMGATHER(SDNode *N); 323 SDValue visitMSCATTER(SDNode *N); 324 SDValue visitFP_TO_FP16(SDNode *N); 325 SDValue visitFP16_TO_FP(SDNode *N); 326 327 SDValue visitFADDForFMACombine(SDNode *N); 328 SDValue visitFSUBForFMACombine(SDNode *N); 329 SDValue visitFMULForFMADistributiveCombine(SDNode *N); 330 331 SDValue XformToShuffleWithZero(SDNode *N); 332 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS, 333 SDValue RHS); 334 335 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 336 337 SDValue foldSelectOfConstants(SDNode *N); 338 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 339 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 340 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2); 341 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 342 SDValue N2, SDValue N3, ISD::CondCode CC, 343 bool NotExtCompare = false); 344 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1, 345 SDValue N2, SDValue N3, ISD::CondCode CC); 346 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 347 const SDLoc &DL, bool foldBooleans = true); 348 349 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 350 SDValue &CC) const; 351 bool isOneUseSetCC(SDValue N) const; 352 353 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 354 unsigned HiOp); 355 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 356 SDValue CombineExtLoad(SDNode *N); 357 SDValue combineRepeatedFPDivisors(SDNode *N); 358 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 359 SDValue BuildSDIV(SDNode *N); 360 SDValue BuildSDIVPow2(SDNode *N); 361 SDValue BuildUDIV(SDNode *N); 362 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags); 363 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags); 364 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags); 365 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, bool Recip); 366 SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations, 367 SDNodeFlags *Flags, bool Reciprocal); 368 SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations, 369 SDNodeFlags *Flags, bool Reciprocal); 370 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 371 bool DemandHighBits = true); 372 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 373 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 374 SDValue InnerPos, SDValue InnerNeg, 375 unsigned PosOpcode, unsigned NegOpcode, 376 const SDLoc &DL); 377 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL); 378 SDValue ReduceLoadWidth(SDNode *N); 379 SDValue ReduceLoadOpStoreWidth(SDNode *N); 380 SDValue splitMergedValStore(StoreSDNode *ST); 381 SDValue TransformFPLoadStorePair(SDNode *N); 382 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 383 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 384 SDValue reduceBuildVecToShuffle(SDNode *N); 385 SDValue createBuildVecShuffle(SDLoc DL, SDNode *N, ArrayRef<int> VectorMask, 386 SDValue VecIn1, SDValue VecIn2, 387 unsigned LeftIdx); 388 389 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 390 391 /// Walk up chain skipping non-aliasing memory nodes, 392 /// looking for aliasing nodes and adding them to the Aliases vector. 393 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 394 SmallVectorImpl<SDValue> &Aliases); 395 396 /// Return true if there is any possibility that the two addresses overlap. 397 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 398 399 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 400 /// chain (aliasing node.) 401 SDValue FindBetterChain(SDNode *N, SDValue Chain); 402 403 /// Try to replace a store and any possibly adjacent stores on 404 /// consecutive chains with better chains. Return true only if St is 405 /// replaced. 406 /// 407 /// Notice that other chains may still be replaced even if the function 408 /// returns false. 409 bool findBetterNeighborChains(StoreSDNode *St); 410 411 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 412 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask); 413 414 /// Holds a pointer to an LSBaseSDNode as well as information on where it 415 /// is located in a sequence of memory operations connected by a chain. 416 struct MemOpLink { 417 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 418 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 419 // Ptr to the mem node. 420 LSBaseSDNode *MemNode; 421 // Offset from the base ptr. 422 int64_t OffsetFromBase; 423 // What is the sequence number of this mem node. 424 // Lowest mem operand in the DAG starts at zero. 425 unsigned SequenceNum; 426 }; 427 428 /// This is a helper function for visitMUL to check the profitability 429 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 430 /// MulNode is the original multiply, AddNode is (add x, c1), 431 /// and ConstNode is c2. 432 bool isMulAddWithConstProfitable(SDNode *MulNode, 433 SDValue &AddNode, 434 SDValue &ConstNode); 435 436 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a 437 /// constant build_vector of the stored constant values in Stores. 438 SDValue getMergedConstantVectorStore(SelectionDAG &DAG, const SDLoc &SL, 439 ArrayRef<MemOpLink> Stores, 440 SmallVectorImpl<SDValue> &Chains, 441 EVT Ty) const; 442 443 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 444 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 445 /// the type of the loaded value to be extended. LoadedVT returns the type 446 /// of the original loaded value. NarrowLoad returns whether the load would 447 /// need to be narrowed in order to match. 448 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 449 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 450 bool &NarrowLoad); 451 452 /// This is a helper function for MergeConsecutiveStores. When the source 453 /// elements of the consecutive stores are all constants or all extracted 454 /// vector elements, try to merge them into one larger store. 455 /// \return number of stores that were merged into a merged store (always 456 /// a prefix of \p StoreNode). 457 bool MergeStoresOfConstantsOrVecElts( 458 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores, 459 bool IsConstantSrc, bool UseVector); 460 461 /// This is a helper function for MergeConsecutiveStores. 462 /// Stores that may be merged are placed in StoreNodes. 463 /// Loads that may alias with those stores are placed in AliasLoadNodes. 464 void getStoreMergeAndAliasCandidates( 465 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 466 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes); 467 468 /// Helper function for MergeConsecutiveStores. Checks if 469 /// Candidate stores have indirect dependency through their 470 /// operands. \return True if safe to merge 471 bool checkMergeStoreCandidatesForDependencies( 472 SmallVectorImpl<MemOpLink> &StoreNodes); 473 474 /// Merge consecutive store operations into a wide store. 475 /// This optimization uses wide integers or vectors when possible. 476 /// \return number of stores that were merged into a merged store (the 477 /// affected nodes are stored as a prefix in \p StoreNodes). 478 bool MergeConsecutiveStores(StoreSDNode *N, 479 SmallVectorImpl<MemOpLink> &StoreNodes); 480 481 /// \brief Try to transform a truncation where C is a constant: 482 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 483 /// 484 /// \p N needs to be a truncation and its first operand an AND. Other 485 /// requirements are checked by the function (e.g. that trunc is 486 /// single-use) and if missed an empty SDValue is returned. 487 SDValue distributeTruncateThroughAnd(SDNode *N); 488 489 public: 490 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 491 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 492 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 493 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize(); 494 } 495 496 /// Runs the dag combiner on all nodes in the work list 497 void Run(CombineLevel AtLevel); 498 499 SelectionDAG &getDAG() const { return DAG; } 500 501 /// Returns a type large enough to hold any valid shift amount - before type 502 /// legalization these can be huge. 503 EVT getShiftAmountTy(EVT LHSTy) { 504 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 505 if (LHSTy.isVector()) 506 return LHSTy; 507 auto &DL = DAG.getDataLayout(); 508 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 509 : TLI.getPointerTy(DL); 510 } 511 512 /// This method returns true if we are running before type legalization or 513 /// if the specified VT is legal. 514 bool isTypeLegal(const EVT &VT) { 515 if (!LegalTypes) return true; 516 return TLI.isTypeLegal(VT); 517 } 518 519 /// Convenience wrapper around TargetLowering::getSetCCResultType 520 EVT getSetCCResultType(EVT VT) const { 521 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 522 } 523 }; 524 } 525 526 527 namespace { 528 /// This class is a DAGUpdateListener that removes any deleted 529 /// nodes from the worklist. 530 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 531 DAGCombiner &DC; 532 public: 533 explicit WorklistRemover(DAGCombiner &dc) 534 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 535 536 void NodeDeleted(SDNode *N, SDNode *E) override { 537 DC.removeFromWorklist(N); 538 } 539 }; 540 } 541 542 //===----------------------------------------------------------------------===// 543 // TargetLowering::DAGCombinerInfo implementation 544 //===----------------------------------------------------------------------===// 545 546 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 547 ((DAGCombiner*)DC)->AddToWorklist(N); 548 } 549 550 SDValue TargetLowering::DAGCombinerInfo:: 551 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 552 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 553 } 554 555 SDValue TargetLowering::DAGCombinerInfo:: 556 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 557 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 558 } 559 560 561 SDValue TargetLowering::DAGCombinerInfo:: 562 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 563 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 564 } 565 566 void TargetLowering::DAGCombinerInfo:: 567 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 568 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 569 } 570 571 //===----------------------------------------------------------------------===// 572 // Helper Functions 573 //===----------------------------------------------------------------------===// 574 575 void DAGCombiner::deleteAndRecombine(SDNode *N) { 576 removeFromWorklist(N); 577 578 // If the operands of this node are only used by the node, they will now be 579 // dead. Make sure to re-visit them and recursively delete dead nodes. 580 for (const SDValue &Op : N->ops()) 581 // For an operand generating multiple values, one of the values may 582 // become dead allowing further simplification (e.g. split index 583 // arithmetic from an indexed load). 584 if (Op->hasOneUse() || Op->getNumValues() > 1) 585 AddToWorklist(Op.getNode()); 586 587 DAG.DeleteNode(N); 588 } 589 590 /// Return 1 if we can compute the negated form of the specified expression for 591 /// the same cost as the expression itself, or 2 if we can compute the negated 592 /// form more cheaply than the expression itself. 593 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 594 const TargetLowering &TLI, 595 const TargetOptions *Options, 596 unsigned Depth = 0) { 597 // fneg is removable even if it has multiple uses. 598 if (Op.getOpcode() == ISD::FNEG) return 2; 599 600 // Don't allow anything with multiple uses. 601 if (!Op.hasOneUse()) return 0; 602 603 // Don't recurse exponentially. 604 if (Depth > 6) return 0; 605 606 switch (Op.getOpcode()) { 607 default: return false; 608 case ISD::ConstantFP: 609 // Don't invert constant FP values after legalize. The negated constant 610 // isn't necessarily legal. 611 return LegalOperations ? 0 : 1; 612 case ISD::FADD: 613 // FIXME: determine better conditions for this xform. 614 if (!Options->UnsafeFPMath) return 0; 615 616 // After operation legalization, it might not be legal to create new FSUBs. 617 if (LegalOperations && 618 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 619 return 0; 620 621 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 622 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 623 Options, Depth + 1)) 624 return V; 625 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 626 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 627 Depth + 1); 628 case ISD::FSUB: 629 // We can't turn -(A-B) into B-A when we honor signed zeros. 630 if (!Options->UnsafeFPMath && !Op.getNode()->getFlags()->hasNoSignedZeros()) 631 return 0; 632 633 // fold (fneg (fsub A, B)) -> (fsub B, A) 634 return 1; 635 636 case ISD::FMUL: 637 case ISD::FDIV: 638 if (Options->HonorSignDependentRoundingFPMath()) return 0; 639 640 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 641 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 642 Options, Depth + 1)) 643 return V; 644 645 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 646 Depth + 1); 647 648 case ISD::FP_EXTEND: 649 case ISD::FP_ROUND: 650 case ISD::FSIN: 651 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 652 Depth + 1); 653 } 654 } 655 656 /// If isNegatibleForFree returns true, return the newly negated expression. 657 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 658 bool LegalOperations, unsigned Depth = 0) { 659 const TargetOptions &Options = DAG.getTarget().Options; 660 // fneg is removable even if it has multiple uses. 661 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 662 663 // Don't allow anything with multiple uses. 664 assert(Op.hasOneUse() && "Unknown reuse!"); 665 666 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 667 668 const SDNodeFlags *Flags = Op.getNode()->getFlags(); 669 670 switch (Op.getOpcode()) { 671 default: llvm_unreachable("Unknown code"); 672 case ISD::ConstantFP: { 673 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 674 V.changeSign(); 675 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 676 } 677 case ISD::FADD: 678 // FIXME: determine better conditions for this xform. 679 assert(Options.UnsafeFPMath); 680 681 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 682 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 683 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 684 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 685 GetNegatedExpression(Op.getOperand(0), DAG, 686 LegalOperations, Depth+1), 687 Op.getOperand(1), Flags); 688 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 689 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 690 GetNegatedExpression(Op.getOperand(1), DAG, 691 LegalOperations, Depth+1), 692 Op.getOperand(0), Flags); 693 case ISD::FSUB: 694 // fold (fneg (fsub 0, B)) -> B 695 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 696 if (N0CFP->isZero()) 697 return Op.getOperand(1); 698 699 // fold (fneg (fsub A, B)) -> (fsub B, A) 700 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 701 Op.getOperand(1), Op.getOperand(0), Flags); 702 703 case ISD::FMUL: 704 case ISD::FDIV: 705 assert(!Options.HonorSignDependentRoundingFPMath()); 706 707 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 708 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 709 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 710 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 711 GetNegatedExpression(Op.getOperand(0), DAG, 712 LegalOperations, Depth+1), 713 Op.getOperand(1), Flags); 714 715 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 716 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 717 Op.getOperand(0), 718 GetNegatedExpression(Op.getOperand(1), DAG, 719 LegalOperations, Depth+1), Flags); 720 721 case ISD::FP_EXTEND: 722 case ISD::FSIN: 723 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 724 GetNegatedExpression(Op.getOperand(0), DAG, 725 LegalOperations, Depth+1)); 726 case ISD::FP_ROUND: 727 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 728 GetNegatedExpression(Op.getOperand(0), DAG, 729 LegalOperations, Depth+1), 730 Op.getOperand(1)); 731 } 732 } 733 734 // APInts must be the same size for most operations, this helper 735 // function zero extends the shorter of the pair so that they match. 736 // We provide an Offset so that we can create bitwidths that won't overflow. 737 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) { 738 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth()); 739 LHS = LHS.zextOrSelf(Bits); 740 RHS = RHS.zextOrSelf(Bits); 741 } 742 743 // Return true if this node is a setcc, or is a select_cc 744 // that selects between the target values used for true and false, making it 745 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 746 // the appropriate nodes based on the type of node we are checking. This 747 // simplifies life a bit for the callers. 748 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 749 SDValue &CC) const { 750 if (N.getOpcode() == ISD::SETCC) { 751 LHS = N.getOperand(0); 752 RHS = N.getOperand(1); 753 CC = N.getOperand(2); 754 return true; 755 } 756 757 if (N.getOpcode() != ISD::SELECT_CC || 758 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 759 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 760 return false; 761 762 if (TLI.getBooleanContents(N.getValueType()) == 763 TargetLowering::UndefinedBooleanContent) 764 return false; 765 766 LHS = N.getOperand(0); 767 RHS = N.getOperand(1); 768 CC = N.getOperand(4); 769 return true; 770 } 771 772 /// Return true if this is a SetCC-equivalent operation with only one use. 773 /// If this is true, it allows the users to invert the operation for free when 774 /// it is profitable to do so. 775 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 776 SDValue N0, N1, N2; 777 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 778 return true; 779 return false; 780 } 781 782 // \brief Returns the SDNode if it is a constant float BuildVector 783 // or constant float. 784 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 785 if (isa<ConstantFPSDNode>(N)) 786 return N.getNode(); 787 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 788 return N.getNode(); 789 return nullptr; 790 } 791 792 // Determines if it is a constant integer or a build vector of constant 793 // integers (and undefs). 794 // Do not permit build vector implicit truncation. 795 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) { 796 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N)) 797 return !(Const->isOpaque() && NoOpaques); 798 if (N.getOpcode() != ISD::BUILD_VECTOR) 799 return false; 800 unsigned BitWidth = N.getScalarValueSizeInBits(); 801 for (const SDValue &Op : N->op_values()) { 802 if (Op.isUndef()) 803 continue; 804 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op); 805 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth || 806 (Const->isOpaque() && NoOpaques)) 807 return false; 808 } 809 return true; 810 } 811 812 // Determines if it is a constant null integer or a splatted vector of a 813 // constant null integer (with no undefs). 814 // Build vector implicit truncation is not an issue for null values. 815 static bool isNullConstantOrNullSplatConstant(SDValue N) { 816 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 817 return Splat->isNullValue(); 818 return false; 819 } 820 821 // Determines if it is a constant integer of one or a splatted vector of a 822 // constant integer of one (with no undefs). 823 // Do not permit build vector implicit truncation. 824 static bool isOneConstantOrOneSplatConstant(SDValue N) { 825 unsigned BitWidth = N.getScalarValueSizeInBits(); 826 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 827 return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth; 828 return false; 829 } 830 831 // Determines if it is a constant integer of all ones or a splatted vector of a 832 // constant integer of all ones (with no undefs). 833 // Do not permit build vector implicit truncation. 834 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) { 835 unsigned BitWidth = N.getScalarValueSizeInBits(); 836 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 837 return Splat->isAllOnesValue() && 838 Splat->getAPIntValue().getBitWidth() == BitWidth; 839 return false; 840 } 841 842 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with 843 // undef's. 844 static bool isAnyConstantBuildVector(const SDNode *N) { 845 return ISD::isBuildVectorOfConstantSDNodes(N) || 846 ISD::isBuildVectorOfConstantFPSDNodes(N); 847 } 848 849 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 850 SDValue N1) { 851 EVT VT = N0.getValueType(); 852 if (N0.getOpcode() == Opc) { 853 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 854 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 855 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 856 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 857 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 858 return SDValue(); 859 } 860 if (N0.hasOneUse()) { 861 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 862 // use 863 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 864 if (!OpNode.getNode()) 865 return SDValue(); 866 AddToWorklist(OpNode.getNode()); 867 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 868 } 869 } 870 } 871 872 if (N1.getOpcode() == Opc) { 873 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 874 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 875 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 876 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 877 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 878 return SDValue(); 879 } 880 if (N1.hasOneUse()) { 881 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 882 // use 883 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 884 if (!OpNode.getNode()) 885 return SDValue(); 886 AddToWorklist(OpNode.getNode()); 887 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 888 } 889 } 890 } 891 892 return SDValue(); 893 } 894 895 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 896 bool AddTo) { 897 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 898 ++NodesCombined; 899 DEBUG(dbgs() << "\nReplacing.1 "; 900 N->dump(&DAG); 901 dbgs() << "\nWith: "; 902 To[0].getNode()->dump(&DAG); 903 dbgs() << " and " << NumTo-1 << " other values\n"); 904 for (unsigned i = 0, e = NumTo; i != e; ++i) 905 assert((!To[i].getNode() || 906 N->getValueType(i) == To[i].getValueType()) && 907 "Cannot combine value to value of different type!"); 908 909 WorklistRemover DeadNodes(*this); 910 DAG.ReplaceAllUsesWith(N, To); 911 if (AddTo) { 912 // Push the new nodes and any users onto the worklist 913 for (unsigned i = 0, e = NumTo; i != e; ++i) { 914 if (To[i].getNode()) { 915 AddToWorklist(To[i].getNode()); 916 AddUsersToWorklist(To[i].getNode()); 917 } 918 } 919 } 920 921 // Finally, if the node is now dead, remove it from the graph. The node 922 // may not be dead if the replacement process recursively simplified to 923 // something else needing this node. 924 if (N->use_empty()) 925 deleteAndRecombine(N); 926 return SDValue(N, 0); 927 } 928 929 void DAGCombiner:: 930 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 931 // Replace all uses. If any nodes become isomorphic to other nodes and 932 // are deleted, make sure to remove them from our worklist. 933 WorklistRemover DeadNodes(*this); 934 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 935 936 // Push the new node and any (possibly new) users onto the worklist. 937 AddToWorklist(TLO.New.getNode()); 938 AddUsersToWorklist(TLO.New.getNode()); 939 940 // Finally, if the node is now dead, remove it from the graph. The node 941 // may not be dead if the replacement process recursively simplified to 942 // something else needing this node. 943 if (TLO.Old.getNode()->use_empty()) 944 deleteAndRecombine(TLO.Old.getNode()); 945 } 946 947 /// Check the specified integer node value to see if it can be simplified or if 948 /// things it uses can be simplified by bit propagation. If so, return true. 949 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 950 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 951 APInt KnownZero, KnownOne; 952 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 953 return false; 954 955 // Revisit the node. 956 AddToWorklist(Op.getNode()); 957 958 // Replace the old value with the new one. 959 ++NodesCombined; 960 DEBUG(dbgs() << "\nReplacing.2 "; 961 TLO.Old.getNode()->dump(&DAG); 962 dbgs() << "\nWith: "; 963 TLO.New.getNode()->dump(&DAG); 964 dbgs() << '\n'); 965 966 CommitTargetLoweringOpt(TLO); 967 return true; 968 } 969 970 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 971 SDLoc DL(Load); 972 EVT VT = Load->getValueType(0); 973 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0)); 974 975 DEBUG(dbgs() << "\nReplacing.9 "; 976 Load->dump(&DAG); 977 dbgs() << "\nWith: "; 978 Trunc.getNode()->dump(&DAG); 979 dbgs() << '\n'); 980 WorklistRemover DeadNodes(*this); 981 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 982 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 983 deleteAndRecombine(Load); 984 AddToWorklist(Trunc.getNode()); 985 } 986 987 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 988 Replace = false; 989 SDLoc DL(Op); 990 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 991 LoadSDNode *LD = cast<LoadSDNode>(Op); 992 EVT MemVT = LD->getMemoryVT(); 993 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 994 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 995 : ISD::EXTLOAD) 996 : LD->getExtensionType(); 997 Replace = true; 998 return DAG.getExtLoad(ExtType, DL, PVT, 999 LD->getChain(), LD->getBasePtr(), 1000 MemVT, LD->getMemOperand()); 1001 } 1002 1003 unsigned Opc = Op.getOpcode(); 1004 switch (Opc) { 1005 default: break; 1006 case ISD::AssertSext: 1007 return DAG.getNode(ISD::AssertSext, DL, PVT, 1008 SExtPromoteOperand(Op.getOperand(0), PVT), 1009 Op.getOperand(1)); 1010 case ISD::AssertZext: 1011 return DAG.getNode(ISD::AssertZext, DL, PVT, 1012 ZExtPromoteOperand(Op.getOperand(0), PVT), 1013 Op.getOperand(1)); 1014 case ISD::Constant: { 1015 unsigned ExtOpc = 1016 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1017 return DAG.getNode(ExtOpc, DL, PVT, Op); 1018 } 1019 } 1020 1021 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 1022 return SDValue(); 1023 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op); 1024 } 1025 1026 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1027 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1028 return SDValue(); 1029 EVT OldVT = Op.getValueType(); 1030 SDLoc DL(Op); 1031 bool Replace = false; 1032 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1033 if (!NewOp.getNode()) 1034 return SDValue(); 1035 AddToWorklist(NewOp.getNode()); 1036 1037 if (Replace) 1038 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1039 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp, 1040 DAG.getValueType(OldVT)); 1041 } 1042 1043 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1044 EVT OldVT = Op.getValueType(); 1045 SDLoc DL(Op); 1046 bool Replace = false; 1047 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1048 if (!NewOp.getNode()) 1049 return SDValue(); 1050 AddToWorklist(NewOp.getNode()); 1051 1052 if (Replace) 1053 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1054 return DAG.getZeroExtendInReg(NewOp, DL, OldVT); 1055 } 1056 1057 /// Promote the specified integer binary operation if the target indicates it is 1058 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1059 /// i32 since i16 instructions are longer. 1060 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1061 if (!LegalOperations) 1062 return SDValue(); 1063 1064 EVT VT = Op.getValueType(); 1065 if (VT.isVector() || !VT.isInteger()) 1066 return SDValue(); 1067 1068 // If operation type is 'undesirable', e.g. i16 on x86, consider 1069 // promoting it. 1070 unsigned Opc = Op.getOpcode(); 1071 if (TLI.isTypeDesirableForOp(Opc, VT)) 1072 return SDValue(); 1073 1074 EVT PVT = VT; 1075 // Consult target whether it is a good idea to promote this operation and 1076 // what's the right type to promote it to. 1077 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1078 assert(PVT != VT && "Don't know what type to promote to!"); 1079 1080 bool Replace0 = false; 1081 SDValue N0 = Op.getOperand(0); 1082 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1083 if (!NN0.getNode()) 1084 return SDValue(); 1085 1086 bool Replace1 = false; 1087 SDValue N1 = Op.getOperand(1); 1088 SDValue NN1; 1089 if (N0 == N1) 1090 NN1 = NN0; 1091 else { 1092 NN1 = PromoteOperand(N1, PVT, Replace1); 1093 if (!NN1.getNode()) 1094 return SDValue(); 1095 } 1096 1097 AddToWorklist(NN0.getNode()); 1098 if (NN1.getNode()) 1099 AddToWorklist(NN1.getNode()); 1100 1101 if (Replace0) 1102 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1103 if (Replace1) 1104 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1105 1106 DEBUG(dbgs() << "\nPromoting "; 1107 Op.getNode()->dump(&DAG)); 1108 SDLoc DL(Op); 1109 return DAG.getNode(ISD::TRUNCATE, DL, VT, 1110 DAG.getNode(Opc, DL, PVT, NN0, NN1)); 1111 } 1112 return SDValue(); 1113 } 1114 1115 /// Promote the specified integer shift operation if the target indicates it is 1116 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1117 /// i32 since i16 instructions are longer. 1118 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1119 if (!LegalOperations) 1120 return SDValue(); 1121 1122 EVT VT = Op.getValueType(); 1123 if (VT.isVector() || !VT.isInteger()) 1124 return SDValue(); 1125 1126 // If operation type is 'undesirable', e.g. i16 on x86, consider 1127 // promoting it. 1128 unsigned Opc = Op.getOpcode(); 1129 if (TLI.isTypeDesirableForOp(Opc, VT)) 1130 return SDValue(); 1131 1132 EVT PVT = VT; 1133 // Consult target whether it is a good idea to promote this operation and 1134 // what's the right type to promote it to. 1135 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1136 assert(PVT != VT && "Don't know what type to promote to!"); 1137 1138 bool Replace = false; 1139 SDValue N0 = Op.getOperand(0); 1140 if (Opc == ISD::SRA) 1141 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1142 else if (Opc == ISD::SRL) 1143 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1144 else 1145 N0 = PromoteOperand(N0, PVT, Replace); 1146 if (!N0.getNode()) 1147 return SDValue(); 1148 1149 AddToWorklist(N0.getNode()); 1150 if (Replace) 1151 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1152 1153 DEBUG(dbgs() << "\nPromoting "; 1154 Op.getNode()->dump(&DAG)); 1155 SDLoc DL(Op); 1156 return DAG.getNode(ISD::TRUNCATE, DL, VT, 1157 DAG.getNode(Opc, DL, PVT, N0, Op.getOperand(1))); 1158 } 1159 return SDValue(); 1160 } 1161 1162 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1163 if (!LegalOperations) 1164 return SDValue(); 1165 1166 EVT VT = Op.getValueType(); 1167 if (VT.isVector() || !VT.isInteger()) 1168 return SDValue(); 1169 1170 // If operation type is 'undesirable', e.g. i16 on x86, consider 1171 // promoting it. 1172 unsigned Opc = Op.getOpcode(); 1173 if (TLI.isTypeDesirableForOp(Opc, VT)) 1174 return SDValue(); 1175 1176 EVT PVT = VT; 1177 // Consult target whether it is a good idea to promote this operation and 1178 // what's the right type to promote it to. 1179 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1180 assert(PVT != VT && "Don't know what type to promote to!"); 1181 // fold (aext (aext x)) -> (aext x) 1182 // fold (aext (zext x)) -> (zext x) 1183 // fold (aext (sext x)) -> (sext x) 1184 DEBUG(dbgs() << "\nPromoting "; 1185 Op.getNode()->dump(&DAG)); 1186 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1187 } 1188 return SDValue(); 1189 } 1190 1191 bool DAGCombiner::PromoteLoad(SDValue Op) { 1192 if (!LegalOperations) 1193 return false; 1194 1195 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1196 return false; 1197 1198 EVT VT = Op.getValueType(); 1199 if (VT.isVector() || !VT.isInteger()) 1200 return false; 1201 1202 // If operation type is 'undesirable', e.g. i16 on x86, consider 1203 // promoting it. 1204 unsigned Opc = Op.getOpcode(); 1205 if (TLI.isTypeDesirableForOp(Opc, VT)) 1206 return false; 1207 1208 EVT PVT = VT; 1209 // Consult target whether it is a good idea to promote this operation and 1210 // what's the right type to promote it to. 1211 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1212 assert(PVT != VT && "Don't know what type to promote to!"); 1213 1214 SDLoc DL(Op); 1215 SDNode *N = Op.getNode(); 1216 LoadSDNode *LD = cast<LoadSDNode>(N); 1217 EVT MemVT = LD->getMemoryVT(); 1218 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1219 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1220 : ISD::EXTLOAD) 1221 : LD->getExtensionType(); 1222 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT, 1223 LD->getChain(), LD->getBasePtr(), 1224 MemVT, LD->getMemOperand()); 1225 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD); 1226 1227 DEBUG(dbgs() << "\nPromoting "; 1228 N->dump(&DAG); 1229 dbgs() << "\nTo: "; 1230 Result.getNode()->dump(&DAG); 1231 dbgs() << '\n'); 1232 WorklistRemover DeadNodes(*this); 1233 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1234 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1235 deleteAndRecombine(N); 1236 AddToWorklist(Result.getNode()); 1237 return true; 1238 } 1239 return false; 1240 } 1241 1242 /// \brief Recursively delete a node which has no uses and any operands for 1243 /// which it is the only use. 1244 /// 1245 /// Note that this both deletes the nodes and removes them from the worklist. 1246 /// It also adds any nodes who have had a user deleted to the worklist as they 1247 /// may now have only one use and subject to other combines. 1248 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1249 if (!N->use_empty()) 1250 return false; 1251 1252 SmallSetVector<SDNode *, 16> Nodes; 1253 Nodes.insert(N); 1254 do { 1255 N = Nodes.pop_back_val(); 1256 if (!N) 1257 continue; 1258 1259 if (N->use_empty()) { 1260 for (const SDValue &ChildN : N->op_values()) 1261 Nodes.insert(ChildN.getNode()); 1262 1263 removeFromWorklist(N); 1264 DAG.DeleteNode(N); 1265 } else { 1266 AddToWorklist(N); 1267 } 1268 } while (!Nodes.empty()); 1269 return true; 1270 } 1271 1272 //===----------------------------------------------------------------------===// 1273 // Main DAG Combiner implementation 1274 //===----------------------------------------------------------------------===// 1275 1276 void DAGCombiner::Run(CombineLevel AtLevel) { 1277 // set the instance variables, so that the various visit routines may use it. 1278 Level = AtLevel; 1279 LegalOperations = Level >= AfterLegalizeVectorOps; 1280 LegalTypes = Level >= AfterLegalizeTypes; 1281 1282 // Add all the dag nodes to the worklist. 1283 for (SDNode &Node : DAG.allnodes()) 1284 AddToWorklist(&Node); 1285 1286 // Create a dummy node (which is not added to allnodes), that adds a reference 1287 // to the root node, preventing it from being deleted, and tracking any 1288 // changes of the root. 1289 HandleSDNode Dummy(DAG.getRoot()); 1290 1291 // While the worklist isn't empty, find a node and try to combine it. 1292 while (!WorklistMap.empty()) { 1293 SDNode *N; 1294 // The Worklist holds the SDNodes in order, but it may contain null entries. 1295 do { 1296 N = Worklist.pop_back_val(); 1297 } while (!N); 1298 1299 bool GoodWorklistEntry = WorklistMap.erase(N); 1300 (void)GoodWorklistEntry; 1301 assert(GoodWorklistEntry && 1302 "Found a worklist entry without a corresponding map entry!"); 1303 1304 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1305 // N is deleted from the DAG, since they too may now be dead or may have a 1306 // reduced number of uses, allowing other xforms. 1307 if (recursivelyDeleteUnusedNodes(N)) 1308 continue; 1309 1310 WorklistRemover DeadNodes(*this); 1311 1312 // If this combine is running after legalizing the DAG, re-legalize any 1313 // nodes pulled off the worklist. 1314 if (Level == AfterLegalizeDAG) { 1315 SmallSetVector<SDNode *, 16> UpdatedNodes; 1316 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1317 1318 for (SDNode *LN : UpdatedNodes) { 1319 AddToWorklist(LN); 1320 AddUsersToWorklist(LN); 1321 } 1322 if (!NIsValid) 1323 continue; 1324 } 1325 1326 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1327 1328 // Add any operands of the new node which have not yet been combined to the 1329 // worklist as well. Because the worklist uniques things already, this 1330 // won't repeatedly process the same operand. 1331 CombinedNodes.insert(N); 1332 for (const SDValue &ChildN : N->op_values()) 1333 if (!CombinedNodes.count(ChildN.getNode())) 1334 AddToWorklist(ChildN.getNode()); 1335 1336 SDValue RV = combine(N); 1337 1338 if (!RV.getNode()) 1339 continue; 1340 1341 ++NodesCombined; 1342 1343 // If we get back the same node we passed in, rather than a new node or 1344 // zero, we know that the node must have defined multiple values and 1345 // CombineTo was used. Since CombineTo takes care of the worklist 1346 // mechanics for us, we have no work to do in this case. 1347 if (RV.getNode() == N) 1348 continue; 1349 1350 assert(N->getOpcode() != ISD::DELETED_NODE && 1351 RV.getOpcode() != ISD::DELETED_NODE && 1352 "Node was deleted but visit returned new node!"); 1353 1354 DEBUG(dbgs() << " ... into: "; 1355 RV.getNode()->dump(&DAG)); 1356 1357 if (N->getNumValues() == RV.getNode()->getNumValues()) 1358 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1359 else { 1360 assert(N->getValueType(0) == RV.getValueType() && 1361 N->getNumValues() == 1 && "Type mismatch"); 1362 SDValue OpV = RV; 1363 DAG.ReplaceAllUsesWith(N, &OpV); 1364 } 1365 1366 // Push the new node and any users onto the worklist 1367 AddToWorklist(RV.getNode()); 1368 AddUsersToWorklist(RV.getNode()); 1369 1370 // Finally, if the node is now dead, remove it from the graph. The node 1371 // may not be dead if the replacement process recursively simplified to 1372 // something else needing this node. This will also take care of adding any 1373 // operands which have lost a user to the worklist. 1374 recursivelyDeleteUnusedNodes(N); 1375 } 1376 1377 // If the root changed (e.g. it was a dead load, update the root). 1378 DAG.setRoot(Dummy.getValue()); 1379 DAG.RemoveDeadNodes(); 1380 } 1381 1382 SDValue DAGCombiner::visit(SDNode *N) { 1383 switch (N->getOpcode()) { 1384 default: break; 1385 case ISD::TokenFactor: return visitTokenFactor(N); 1386 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1387 case ISD::ADD: return visitADD(N); 1388 case ISD::SUB: return visitSUB(N); 1389 case ISD::ADDC: return visitADDC(N); 1390 case ISD::SUBC: return visitSUBC(N); 1391 case ISD::ADDE: return visitADDE(N); 1392 case ISD::SUBE: return visitSUBE(N); 1393 case ISD::MUL: return visitMUL(N); 1394 case ISD::SDIV: return visitSDIV(N); 1395 case ISD::UDIV: return visitUDIV(N); 1396 case ISD::SREM: 1397 case ISD::UREM: return visitREM(N); 1398 case ISD::MULHU: return visitMULHU(N); 1399 case ISD::MULHS: return visitMULHS(N); 1400 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1401 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1402 case ISD::SMULO: return visitSMULO(N); 1403 case ISD::UMULO: return visitUMULO(N); 1404 case ISD::SMIN: 1405 case ISD::SMAX: 1406 case ISD::UMIN: 1407 case ISD::UMAX: return visitIMINMAX(N); 1408 case ISD::AND: return visitAND(N); 1409 case ISD::OR: return visitOR(N); 1410 case ISD::XOR: return visitXOR(N); 1411 case ISD::SHL: return visitSHL(N); 1412 case ISD::SRA: return visitSRA(N); 1413 case ISD::SRL: return visitSRL(N); 1414 case ISD::ROTR: 1415 case ISD::ROTL: return visitRotate(N); 1416 case ISD::BSWAP: return visitBSWAP(N); 1417 case ISD::BITREVERSE: return visitBITREVERSE(N); 1418 case ISD::CTLZ: return visitCTLZ(N); 1419 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1420 case ISD::CTTZ: return visitCTTZ(N); 1421 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1422 case ISD::CTPOP: return visitCTPOP(N); 1423 case ISD::SELECT: return visitSELECT(N); 1424 case ISD::VSELECT: return visitVSELECT(N); 1425 case ISD::SELECT_CC: return visitSELECT_CC(N); 1426 case ISD::SETCC: return visitSETCC(N); 1427 case ISD::SETCCE: return visitSETCCE(N); 1428 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1429 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1430 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1431 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1432 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1433 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1434 case ISD::TRUNCATE: return visitTRUNCATE(N); 1435 case ISD::BITCAST: return visitBITCAST(N); 1436 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1437 case ISD::FADD: return visitFADD(N); 1438 case ISD::FSUB: return visitFSUB(N); 1439 case ISD::FMUL: return visitFMUL(N); 1440 case ISD::FMA: return visitFMA(N); 1441 case ISD::FDIV: return visitFDIV(N); 1442 case ISD::FREM: return visitFREM(N); 1443 case ISD::FSQRT: return visitFSQRT(N); 1444 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1445 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1446 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1447 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1448 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1449 case ISD::FP_ROUND: return visitFP_ROUND(N); 1450 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1451 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1452 case ISD::FNEG: return visitFNEG(N); 1453 case ISD::FABS: return visitFABS(N); 1454 case ISD::FFLOOR: return visitFFLOOR(N); 1455 case ISD::FMINNUM: return visitFMINNUM(N); 1456 case ISD::FMAXNUM: return visitFMAXNUM(N); 1457 case ISD::FCEIL: return visitFCEIL(N); 1458 case ISD::FTRUNC: return visitFTRUNC(N); 1459 case ISD::BRCOND: return visitBRCOND(N); 1460 case ISD::BR_CC: return visitBR_CC(N); 1461 case ISD::LOAD: return visitLOAD(N); 1462 case ISD::STORE: return visitSTORE(N); 1463 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1464 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1465 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1466 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1467 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1468 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1469 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1470 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1471 case ISD::MGATHER: return visitMGATHER(N); 1472 case ISD::MLOAD: return visitMLOAD(N); 1473 case ISD::MSCATTER: return visitMSCATTER(N); 1474 case ISD::MSTORE: return visitMSTORE(N); 1475 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1476 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1477 } 1478 return SDValue(); 1479 } 1480 1481 SDValue DAGCombiner::combine(SDNode *N) { 1482 SDValue RV = visit(N); 1483 1484 // If nothing happened, try a target-specific DAG combine. 1485 if (!RV.getNode()) { 1486 assert(N->getOpcode() != ISD::DELETED_NODE && 1487 "Node was deleted but visit returned NULL!"); 1488 1489 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1490 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1491 1492 // Expose the DAG combiner to the target combiner impls. 1493 TargetLowering::DAGCombinerInfo 1494 DagCombineInfo(DAG, Level, false, this); 1495 1496 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1497 } 1498 } 1499 1500 // If nothing happened still, try promoting the operation. 1501 if (!RV.getNode()) { 1502 switch (N->getOpcode()) { 1503 default: break; 1504 case ISD::ADD: 1505 case ISD::SUB: 1506 case ISD::MUL: 1507 case ISD::AND: 1508 case ISD::OR: 1509 case ISD::XOR: 1510 RV = PromoteIntBinOp(SDValue(N, 0)); 1511 break; 1512 case ISD::SHL: 1513 case ISD::SRA: 1514 case ISD::SRL: 1515 RV = PromoteIntShiftOp(SDValue(N, 0)); 1516 break; 1517 case ISD::SIGN_EXTEND: 1518 case ISD::ZERO_EXTEND: 1519 case ISD::ANY_EXTEND: 1520 RV = PromoteExtend(SDValue(N, 0)); 1521 break; 1522 case ISD::LOAD: 1523 if (PromoteLoad(SDValue(N, 0))) 1524 RV = SDValue(N, 0); 1525 break; 1526 } 1527 } 1528 1529 // If N is a commutative binary node, try commuting it to enable more 1530 // sdisel CSE. 1531 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1532 N->getNumValues() == 1) { 1533 SDValue N0 = N->getOperand(0); 1534 SDValue N1 = N->getOperand(1); 1535 1536 // Constant operands are canonicalized to RHS. 1537 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1538 SDValue Ops[] = {N1, N0}; 1539 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1540 N->getFlags()); 1541 if (CSENode) 1542 return SDValue(CSENode, 0); 1543 } 1544 } 1545 1546 return RV; 1547 } 1548 1549 /// Given a node, return its input chain if it has one, otherwise return a null 1550 /// sd operand. 1551 static SDValue getInputChainForNode(SDNode *N) { 1552 if (unsigned NumOps = N->getNumOperands()) { 1553 if (N->getOperand(0).getValueType() == MVT::Other) 1554 return N->getOperand(0); 1555 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1556 return N->getOperand(NumOps-1); 1557 for (unsigned i = 1; i < NumOps-1; ++i) 1558 if (N->getOperand(i).getValueType() == MVT::Other) 1559 return N->getOperand(i); 1560 } 1561 return SDValue(); 1562 } 1563 1564 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1565 // If N has two operands, where one has an input chain equal to the other, 1566 // the 'other' chain is redundant. 1567 if (N->getNumOperands() == 2) { 1568 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1569 return N->getOperand(0); 1570 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1571 return N->getOperand(1); 1572 } 1573 1574 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1575 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1576 SmallPtrSet<SDNode*, 16> SeenOps; 1577 bool Changed = false; // If we should replace this token factor. 1578 1579 // Start out with this token factor. 1580 TFs.push_back(N); 1581 1582 // Iterate through token factors. The TFs grows when new token factors are 1583 // encountered. 1584 for (unsigned i = 0; i < TFs.size(); ++i) { 1585 SDNode *TF = TFs[i]; 1586 1587 // Check each of the operands. 1588 for (const SDValue &Op : TF->op_values()) { 1589 1590 switch (Op.getOpcode()) { 1591 case ISD::EntryToken: 1592 // Entry tokens don't need to be added to the list. They are 1593 // redundant. 1594 Changed = true; 1595 break; 1596 1597 case ISD::TokenFactor: 1598 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) { 1599 // Queue up for processing. 1600 TFs.push_back(Op.getNode()); 1601 // Clean up in case the token factor is removed. 1602 AddToWorklist(Op.getNode()); 1603 Changed = true; 1604 break; 1605 } 1606 LLVM_FALLTHROUGH; 1607 1608 default: 1609 // Only add if it isn't already in the list. 1610 if (SeenOps.insert(Op.getNode()).second) 1611 Ops.push_back(Op); 1612 else 1613 Changed = true; 1614 break; 1615 } 1616 } 1617 } 1618 1619 SDValue Result; 1620 1621 // If we've changed things around then replace token factor. 1622 if (Changed) { 1623 if (Ops.empty()) { 1624 // The entry token is the only possible outcome. 1625 Result = DAG.getEntryNode(); 1626 } else { 1627 // New and improved token factor. 1628 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1629 } 1630 1631 // Add users to worklist if AA is enabled, since it may introduce 1632 // a lot of new chained token factors while removing memory deps. 1633 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1634 : DAG.getSubtarget().useAA(); 1635 return CombineTo(N, Result, UseAA /*add to worklist*/); 1636 } 1637 1638 return Result; 1639 } 1640 1641 /// MERGE_VALUES can always be eliminated. 1642 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1643 WorklistRemover DeadNodes(*this); 1644 // Replacing results may cause a different MERGE_VALUES to suddenly 1645 // be CSE'd with N, and carry its uses with it. Iterate until no 1646 // uses remain, to ensure that the node can be safely deleted. 1647 // First add the users of this node to the work list so that they 1648 // can be tried again once they have new operands. 1649 AddUsersToWorklist(N); 1650 do { 1651 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1652 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1653 } while (!N->use_empty()); 1654 deleteAndRecombine(N); 1655 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1656 } 1657 1658 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1659 /// ConstantSDNode pointer else nullptr. 1660 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1661 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1662 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1663 } 1664 1665 SDValue DAGCombiner::visitADD(SDNode *N) { 1666 SDValue N0 = N->getOperand(0); 1667 SDValue N1 = N->getOperand(1); 1668 EVT VT = N0.getValueType(); 1669 SDLoc DL(N); 1670 1671 // fold vector ops 1672 if (VT.isVector()) { 1673 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1674 return FoldedVOp; 1675 1676 // fold (add x, 0) -> x, vector edition 1677 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1678 return N0; 1679 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1680 return N1; 1681 } 1682 1683 // fold (add x, undef) -> undef 1684 if (N0.isUndef()) 1685 return N0; 1686 1687 if (N1.isUndef()) 1688 return N1; 1689 1690 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 1691 // canonicalize constant to RHS 1692 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 1693 return DAG.getNode(ISD::ADD, DL, VT, N1, N0); 1694 // fold (add c1, c2) -> c1+c2 1695 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(), 1696 N1.getNode()); 1697 } 1698 1699 // fold (add x, 0) -> x 1700 if (isNullConstant(N1)) 1701 return N0; 1702 1703 // fold ((c1-A)+c2) -> (c1+c2)-A 1704 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) { 1705 if (N0.getOpcode() == ISD::SUB) 1706 if (isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) { 1707 return DAG.getNode(ISD::SUB, DL, VT, 1708 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)), 1709 N0.getOperand(1)); 1710 } 1711 } 1712 1713 // reassociate add 1714 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1)) 1715 return RADD; 1716 1717 // fold ((0-A) + B) -> B-A 1718 if (N0.getOpcode() == ISD::SUB && 1719 isNullConstantOrNullSplatConstant(N0.getOperand(0))) 1720 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); 1721 1722 // fold (A + (0-B)) -> A-B 1723 if (N1.getOpcode() == ISD::SUB && 1724 isNullConstantOrNullSplatConstant(N1.getOperand(0))) 1725 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1)); 1726 1727 // fold (A+(B-A)) -> B 1728 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1729 return N1.getOperand(0); 1730 1731 // fold ((B-A)+A) -> B 1732 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1733 return N0.getOperand(0); 1734 1735 // fold (A+(B-(A+C))) to (B-C) 1736 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1737 N0 == N1.getOperand(1).getOperand(0)) 1738 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 1739 N1.getOperand(1).getOperand(1)); 1740 1741 // fold (A+(B-(C+A))) to (B-C) 1742 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1743 N0 == N1.getOperand(1).getOperand(1)) 1744 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 1745 N1.getOperand(1).getOperand(0)); 1746 1747 // fold (A+((B-A)+or-C)) to (B+or-C) 1748 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1749 N1.getOperand(0).getOpcode() == ISD::SUB && 1750 N0 == N1.getOperand(0).getOperand(1)) 1751 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0), 1752 N1.getOperand(1)); 1753 1754 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1755 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1756 SDValue N00 = N0.getOperand(0); 1757 SDValue N01 = N0.getOperand(1); 1758 SDValue N10 = N1.getOperand(0); 1759 SDValue N11 = N1.getOperand(1); 1760 1761 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10)) 1762 return DAG.getNode(ISD::SUB, DL, VT, 1763 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1764 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1765 } 1766 1767 if (SimplifyDemandedBits(SDValue(N, 0))) 1768 return SDValue(N, 0); 1769 1770 // fold (a+b) -> (a|b) iff a and b share no bits. 1771 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 1772 VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1)) 1773 return DAG.getNode(ISD::OR, DL, VT, N0, N1); 1774 1775 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1776 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 1777 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0))) 1778 return DAG.getNode(ISD::SUB, DL, VT, N0, 1779 DAG.getNode(ISD::SHL, DL, VT, 1780 N1.getOperand(0).getOperand(1), 1781 N1.getOperand(1))); 1782 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB && 1783 isNullConstantOrNullSplatConstant(N0.getOperand(0).getOperand(0))) 1784 return DAG.getNode(ISD::SUB, DL, VT, N1, 1785 DAG.getNode(ISD::SHL, DL, VT, 1786 N0.getOperand(0).getOperand(1), 1787 N0.getOperand(1))); 1788 1789 if (N1.getOpcode() == ISD::AND) { 1790 SDValue AndOp0 = N1.getOperand(0); 1791 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1792 unsigned DestBits = VT.getScalarSizeInBits(); 1793 1794 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1795 // and similar xforms where the inner op is either ~0 or 0. 1796 if (NumSignBits == DestBits && 1797 isOneConstantOrOneSplatConstant(N1->getOperand(1))) 1798 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1799 } 1800 1801 // add (sext i1), X -> sub X, (zext i1) 1802 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1803 N0.getOperand(0).getValueType() == MVT::i1 && 1804 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1805 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1806 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1807 } 1808 1809 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1810 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1811 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1812 if (TN->getVT() == MVT::i1) { 1813 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1814 DAG.getConstant(1, DL, VT)); 1815 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1816 } 1817 } 1818 1819 return SDValue(); 1820 } 1821 1822 SDValue DAGCombiner::visitADDC(SDNode *N) { 1823 SDValue N0 = N->getOperand(0); 1824 SDValue N1 = N->getOperand(1); 1825 EVT VT = N0.getValueType(); 1826 1827 // If the flag result is dead, turn this into an ADD. 1828 if (!N->hasAnyUseOfValue(1)) 1829 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1830 DAG.getNode(ISD::CARRY_FALSE, 1831 SDLoc(N), MVT::Glue)); 1832 1833 // canonicalize constant to RHS. 1834 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1835 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1836 if (N0C && !N1C) 1837 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1838 1839 // fold (addc x, 0) -> x + no carry out 1840 if (isNullConstant(N1)) 1841 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1842 SDLoc(N), MVT::Glue)); 1843 1844 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1845 APInt LHSZero, LHSOne; 1846 APInt RHSZero, RHSOne; 1847 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1848 1849 if (LHSZero.getBoolValue()) { 1850 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1851 1852 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1853 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1854 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1855 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1856 DAG.getNode(ISD::CARRY_FALSE, 1857 SDLoc(N), MVT::Glue)); 1858 } 1859 1860 return SDValue(); 1861 } 1862 1863 SDValue DAGCombiner::visitADDE(SDNode *N) { 1864 SDValue N0 = N->getOperand(0); 1865 SDValue N1 = N->getOperand(1); 1866 SDValue CarryIn = N->getOperand(2); 1867 1868 // canonicalize constant to RHS 1869 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1870 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1871 if (N0C && !N1C) 1872 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1873 N1, N0, CarryIn); 1874 1875 // fold (adde x, y, false) -> (addc x, y) 1876 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1877 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1878 1879 return SDValue(); 1880 } 1881 1882 // Since it may not be valid to emit a fold to zero for vector initializers 1883 // check if we can before folding. 1884 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 1885 SelectionDAG &DAG, bool LegalOperations, 1886 bool LegalTypes) { 1887 if (!VT.isVector()) 1888 return DAG.getConstant(0, DL, VT); 1889 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1890 return DAG.getConstant(0, DL, VT); 1891 return SDValue(); 1892 } 1893 1894 SDValue DAGCombiner::visitSUB(SDNode *N) { 1895 SDValue N0 = N->getOperand(0); 1896 SDValue N1 = N->getOperand(1); 1897 EVT VT = N0.getValueType(); 1898 SDLoc DL(N); 1899 1900 // fold vector ops 1901 if (VT.isVector()) { 1902 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1903 return FoldedVOp; 1904 1905 // fold (sub x, 0) -> x, vector edition 1906 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1907 return N0; 1908 } 1909 1910 // fold (sub x, x) -> 0 1911 // FIXME: Refactor this and xor and other similar operations together. 1912 if (N0 == N1) 1913 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes); 1914 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 1915 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 1916 // fold (sub c1, c2) -> c1-c2 1917 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(), 1918 N1.getNode()); 1919 } 1920 1921 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1922 1923 // fold (sub x, c) -> (add x, -c) 1924 if (N1C) { 1925 return DAG.getNode(ISD::ADD, DL, VT, N0, 1926 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 1927 } 1928 1929 if (isNullConstantOrNullSplatConstant(N0)) { 1930 unsigned BitWidth = VT.getScalarSizeInBits(); 1931 // Right-shifting everything out but the sign bit followed by negation is 1932 // the same as flipping arithmetic/logical shift type without the negation: 1933 // -(X >>u 31) -> (X >>s 31) 1934 // -(X >>s 31) -> (X >>u 31) 1935 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) { 1936 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1)); 1937 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) { 1938 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA; 1939 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT)) 1940 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1)); 1941 } 1942 } 1943 1944 // 0 - X --> 0 if the sub is NUW. 1945 if (N->getFlags()->hasNoUnsignedWrap()) 1946 return N0; 1947 1948 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignBit(BitWidth))) { 1949 // N1 is either 0 or the minimum signed value. If the sub is NSW, then 1950 // N1 must be 0 because negating the minimum signed value is undefined. 1951 if (N->getFlags()->hasNoSignedWrap()) 1952 return N0; 1953 1954 // 0 - X --> X if X is 0 or the minimum signed value. 1955 return N1; 1956 } 1957 } 1958 1959 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1960 if (isAllOnesConstantOrAllOnesSplatConstant(N0)) 1961 return DAG.getNode(ISD::XOR, DL, VT, N1, N0); 1962 1963 // fold A-(A-B) -> B 1964 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1965 return N1.getOperand(1); 1966 1967 // fold (A+B)-A -> B 1968 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1969 return N0.getOperand(1); 1970 1971 // fold (A+B)-B -> A 1972 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1973 return N0.getOperand(0); 1974 1975 // fold C2-(A+C1) -> (C2-C1)-A 1976 if (N1.getOpcode() == ISD::ADD) { 1977 SDValue N11 = N1.getOperand(1); 1978 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) && 1979 isConstantOrConstantVector(N11, /* NoOpaques */ true)) { 1980 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11); 1981 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0)); 1982 } 1983 } 1984 1985 // fold ((A+(B+or-C))-B) -> A+or-C 1986 if (N0.getOpcode() == ISD::ADD && 1987 (N0.getOperand(1).getOpcode() == ISD::SUB || 1988 N0.getOperand(1).getOpcode() == ISD::ADD) && 1989 N0.getOperand(1).getOperand(0) == N1) 1990 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0), 1991 N0.getOperand(1).getOperand(1)); 1992 1993 // fold ((A+(C+B))-B) -> A+C 1994 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD && 1995 N0.getOperand(1).getOperand(1) == N1) 1996 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), 1997 N0.getOperand(1).getOperand(0)); 1998 1999 // fold ((A-(B-C))-C) -> A-B 2000 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB && 2001 N0.getOperand(1).getOperand(1) == N1) 2002 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), 2003 N0.getOperand(1).getOperand(0)); 2004 2005 // If either operand of a sub is undef, the result is undef 2006 if (N0.isUndef()) 2007 return N0; 2008 if (N1.isUndef()) 2009 return N1; 2010 2011 // If the relocation model supports it, consider symbol offsets. 2012 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 2013 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 2014 // fold (sub Sym, c) -> Sym-c 2015 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 2016 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 2017 GA->getOffset() - 2018 (uint64_t)N1C->getSExtValue()); 2019 // fold (sub Sym+c1, Sym+c2) -> c1-c2 2020 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 2021 if (GA->getGlobal() == GB->getGlobal()) 2022 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 2023 DL, VT); 2024 } 2025 2026 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 2027 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2028 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2029 if (TN->getVT() == MVT::i1) { 2030 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2031 DAG.getConstant(1, DL, VT)); 2032 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 2033 } 2034 } 2035 2036 return SDValue(); 2037 } 2038 2039 SDValue DAGCombiner::visitSUBC(SDNode *N) { 2040 SDValue N0 = N->getOperand(0); 2041 SDValue N1 = N->getOperand(1); 2042 EVT VT = N0.getValueType(); 2043 SDLoc DL(N); 2044 2045 // If the flag result is dead, turn this into an SUB. 2046 if (!N->hasAnyUseOfValue(1)) 2047 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2048 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2049 2050 // fold (subc x, x) -> 0 + no borrow 2051 if (N0 == N1) 2052 return CombineTo(N, DAG.getConstant(0, DL, VT), 2053 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2054 2055 // fold (subc x, 0) -> x + no borrow 2056 if (isNullConstant(N1)) 2057 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2058 2059 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2060 if (isAllOnesConstant(N0)) 2061 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2062 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2063 2064 return SDValue(); 2065 } 2066 2067 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2068 SDValue N0 = N->getOperand(0); 2069 SDValue N1 = N->getOperand(1); 2070 SDValue CarryIn = N->getOperand(2); 2071 2072 // fold (sube x, y, false) -> (subc x, y) 2073 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2074 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2075 2076 return SDValue(); 2077 } 2078 2079 SDValue DAGCombiner::visitMUL(SDNode *N) { 2080 SDValue N0 = N->getOperand(0); 2081 SDValue N1 = N->getOperand(1); 2082 EVT VT = N0.getValueType(); 2083 2084 // fold (mul x, undef) -> 0 2085 if (N0.isUndef() || N1.isUndef()) 2086 return DAG.getConstant(0, SDLoc(N), VT); 2087 2088 bool N0IsConst = false; 2089 bool N1IsConst = false; 2090 bool N1IsOpaqueConst = false; 2091 bool N0IsOpaqueConst = false; 2092 APInt ConstValue0, ConstValue1; 2093 // fold vector ops 2094 if (VT.isVector()) { 2095 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2096 return FoldedVOp; 2097 2098 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0); 2099 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 2100 } else { 2101 N0IsConst = isa<ConstantSDNode>(N0); 2102 if (N0IsConst) { 2103 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2104 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2105 } 2106 N1IsConst = isa<ConstantSDNode>(N1); 2107 if (N1IsConst) { 2108 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2109 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2110 } 2111 } 2112 2113 // fold (mul c1, c2) -> c1*c2 2114 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2115 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2116 N0.getNode(), N1.getNode()); 2117 2118 // canonicalize constant to RHS (vector doesn't have to splat) 2119 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2120 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2121 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2122 // fold (mul x, 0) -> 0 2123 if (N1IsConst && ConstValue1 == 0) 2124 return N1; 2125 // We require a splat of the entire scalar bit width for non-contiguous 2126 // bit patterns. 2127 bool IsFullSplat = 2128 ConstValue1.getBitWidth() == VT.getScalarSizeInBits(); 2129 // fold (mul x, 1) -> x 2130 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2131 return N0; 2132 // fold (mul x, -1) -> 0-x 2133 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2134 SDLoc DL(N); 2135 return DAG.getNode(ISD::SUB, DL, VT, 2136 DAG.getConstant(0, DL, VT), N0); 2137 } 2138 // fold (mul x, (1 << c)) -> x << c 2139 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2140 IsFullSplat) { 2141 SDLoc DL(N); 2142 return DAG.getNode(ISD::SHL, DL, VT, N0, 2143 DAG.getConstant(ConstValue1.logBase2(), DL, 2144 getShiftAmountTy(N0.getValueType()))); 2145 } 2146 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2147 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2148 IsFullSplat) { 2149 unsigned Log2Val = (-ConstValue1).logBase2(); 2150 SDLoc DL(N); 2151 // FIXME: If the input is something that is easily negated (e.g. a 2152 // single-use add), we should put the negate there. 2153 return DAG.getNode(ISD::SUB, DL, VT, 2154 DAG.getConstant(0, DL, VT), 2155 DAG.getNode(ISD::SHL, DL, VT, N0, 2156 DAG.getConstant(Log2Val, DL, 2157 getShiftAmountTy(N0.getValueType())))); 2158 } 2159 2160 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2161 if (N0.getOpcode() == ISD::SHL && 2162 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 2163 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 2164 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 2165 if (isConstantOrConstantVector(C3)) 2166 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 2167 } 2168 2169 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2170 // use. 2171 { 2172 SDValue Sh(nullptr, 0), Y(nullptr, 0); 2173 2174 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2175 if (N0.getOpcode() == ISD::SHL && 2176 isConstantOrConstantVector(N0.getOperand(1)) && 2177 N0.getNode()->hasOneUse()) { 2178 Sh = N0; Y = N1; 2179 } else if (N1.getOpcode() == ISD::SHL && 2180 isConstantOrConstantVector(N1.getOperand(1)) && 2181 N1.getNode()->hasOneUse()) { 2182 Sh = N1; Y = N0; 2183 } 2184 2185 if (Sh.getNode()) { 2186 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 2187 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 2188 } 2189 } 2190 2191 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2192 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2193 N0.getOpcode() == ISD::ADD && 2194 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2195 isMulAddWithConstProfitable(N, N0, N1)) 2196 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2197 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2198 N0.getOperand(0), N1), 2199 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2200 N0.getOperand(1), N1)); 2201 2202 // reassociate mul 2203 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2204 return RMUL; 2205 2206 return SDValue(); 2207 } 2208 2209 /// Return true if divmod libcall is available. 2210 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2211 const TargetLowering &TLI) { 2212 RTLIB::Libcall LC; 2213 EVT NodeType = Node->getValueType(0); 2214 if (!NodeType.isSimple()) 2215 return false; 2216 switch (NodeType.getSimpleVT().SimpleTy) { 2217 default: return false; // No libcall for vector types. 2218 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2219 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2220 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2221 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2222 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2223 } 2224 2225 return TLI.getLibcallName(LC) != nullptr; 2226 } 2227 2228 /// Issue divrem if both quotient and remainder are needed. 2229 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2230 if (Node->use_empty()) 2231 return SDValue(); // This is a dead node, leave it alone. 2232 2233 unsigned Opcode = Node->getOpcode(); 2234 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2235 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2236 2237 // DivMod lib calls can still work on non-legal types if using lib-calls. 2238 EVT VT = Node->getValueType(0); 2239 if (VT.isVector() || !VT.isInteger()) 2240 return SDValue(); 2241 2242 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 2243 return SDValue(); 2244 2245 // If DIVREM is going to get expanded into a libcall, 2246 // but there is no libcall available, then don't combine. 2247 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2248 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2249 return SDValue(); 2250 2251 // If div is legal, it's better to do the normal expansion 2252 unsigned OtherOpcode = 0; 2253 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2254 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2255 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2256 return SDValue(); 2257 } else { 2258 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2259 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2260 return SDValue(); 2261 } 2262 2263 SDValue Op0 = Node->getOperand(0); 2264 SDValue Op1 = Node->getOperand(1); 2265 SDValue combined; 2266 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2267 UE = Op0.getNode()->use_end(); UI != UE;) { 2268 SDNode *User = *UI++; 2269 if (User == Node || User->use_empty()) 2270 continue; 2271 // Convert the other matching node(s), too; 2272 // otherwise, the DIVREM may get target-legalized into something 2273 // target-specific that we won't be able to recognize. 2274 unsigned UserOpc = User->getOpcode(); 2275 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2276 User->getOperand(0) == Op0 && 2277 User->getOperand(1) == Op1) { 2278 if (!combined) { 2279 if (UserOpc == OtherOpcode) { 2280 SDVTList VTs = DAG.getVTList(VT, VT); 2281 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2282 } else if (UserOpc == DivRemOpc) { 2283 combined = SDValue(User, 0); 2284 } else { 2285 assert(UserOpc == Opcode); 2286 continue; 2287 } 2288 } 2289 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2290 CombineTo(User, combined); 2291 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2292 CombineTo(User, combined.getValue(1)); 2293 } 2294 } 2295 return combined; 2296 } 2297 2298 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2299 SDValue N0 = N->getOperand(0); 2300 SDValue N1 = N->getOperand(1); 2301 EVT VT = N->getValueType(0); 2302 2303 // fold vector ops 2304 if (VT.isVector()) 2305 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2306 return FoldedVOp; 2307 2308 SDLoc DL(N); 2309 2310 // fold (sdiv c1, c2) -> c1/c2 2311 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2312 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2313 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2314 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2315 // fold (sdiv X, 1) -> X 2316 if (N1C && N1C->isOne()) 2317 return N0; 2318 // fold (sdiv X, -1) -> 0-X 2319 if (N1C && N1C->isAllOnesValue()) 2320 return DAG.getNode(ISD::SUB, DL, VT, 2321 DAG.getConstant(0, DL, VT), N0); 2322 2323 // If we know the sign bits of both operands are zero, strength reduce to a 2324 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2325 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2326 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2327 2328 // fold (sdiv X, pow2) -> simple ops after legalize 2329 // FIXME: We check for the exact bit here because the generic lowering gives 2330 // better results in that case. The target-specific lowering should learn how 2331 // to handle exact sdivs efficiently. 2332 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2333 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() && 2334 (N1C->getAPIntValue().isPowerOf2() || 2335 (-N1C->getAPIntValue()).isPowerOf2())) { 2336 // Target-specific implementation of sdiv x, pow2. 2337 if (SDValue Res = BuildSDIVPow2(N)) 2338 return Res; 2339 2340 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2341 2342 // Splat the sign bit into the register 2343 SDValue SGN = 2344 DAG.getNode(ISD::SRA, DL, VT, N0, 2345 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2346 getShiftAmountTy(N0.getValueType()))); 2347 AddToWorklist(SGN.getNode()); 2348 2349 // Add (N0 < 0) ? abs2 - 1 : 0; 2350 SDValue SRL = 2351 DAG.getNode(ISD::SRL, DL, VT, SGN, 2352 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2353 getShiftAmountTy(SGN.getValueType()))); 2354 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2355 AddToWorklist(SRL.getNode()); 2356 AddToWorklist(ADD.getNode()); // Divide by pow2 2357 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2358 DAG.getConstant(lg2, DL, 2359 getShiftAmountTy(ADD.getValueType()))); 2360 2361 // If we're dividing by a positive value, we're done. Otherwise, we must 2362 // negate the result. 2363 if (N1C->getAPIntValue().isNonNegative()) 2364 return SRA; 2365 2366 AddToWorklist(SRA.getNode()); 2367 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2368 } 2369 2370 // If integer divide is expensive and we satisfy the requirements, emit an 2371 // alternate sequence. Targets may check function attributes for size/speed 2372 // trade-offs. 2373 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2374 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2375 if (SDValue Op = BuildSDIV(N)) 2376 return Op; 2377 2378 // sdiv, srem -> sdivrem 2379 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 2380 // true. Otherwise, we break the simplification logic in visitREM(). 2381 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2382 if (SDValue DivRem = useDivRem(N)) 2383 return DivRem; 2384 2385 // undef / X -> 0 2386 if (N0.isUndef()) 2387 return DAG.getConstant(0, DL, VT); 2388 // X / undef -> undef 2389 if (N1.isUndef()) 2390 return N1; 2391 2392 return SDValue(); 2393 } 2394 2395 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2396 SDValue N0 = N->getOperand(0); 2397 SDValue N1 = N->getOperand(1); 2398 EVT VT = N->getValueType(0); 2399 2400 // fold vector ops 2401 if (VT.isVector()) 2402 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2403 return FoldedVOp; 2404 2405 SDLoc DL(N); 2406 2407 // fold (udiv c1, c2) -> c1/c2 2408 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2409 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2410 if (N0C && N1C) 2411 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2412 N0C, N1C)) 2413 return Folded; 2414 2415 // fold (udiv x, (1 << c)) -> x >>u c 2416 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) 2417 return DAG.getNode(ISD::SRL, DL, VT, N0, 2418 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL, 2419 getShiftAmountTy(N0.getValueType()))); 2420 2421 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2422 if (N1.getOpcode() == ISD::SHL) { 2423 if (ConstantSDNode *SHC = isConstOrConstSplat(N1.getOperand(0))) { 2424 if (!SHC->isOpaque() && SHC->getAPIntValue().isPowerOf2()) { 2425 EVT ADDVT = N1.getOperand(1).getValueType(); 2426 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, 2427 N1.getOperand(1), 2428 DAG.getConstant(SHC->getAPIntValue() 2429 .logBase2(), 2430 DL, ADDVT)); 2431 AddToWorklist(Add.getNode()); 2432 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2433 } 2434 } 2435 } 2436 2437 // fold (udiv x, c) -> alternate 2438 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2439 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2440 if (SDValue Op = BuildUDIV(N)) 2441 return Op; 2442 2443 // sdiv, srem -> sdivrem 2444 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 2445 // true. Otherwise, we break the simplification logic in visitREM(). 2446 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2447 if (SDValue DivRem = useDivRem(N)) 2448 return DivRem; 2449 2450 // undef / X -> 0 2451 if (N0.isUndef()) 2452 return DAG.getConstant(0, DL, VT); 2453 // X / undef -> undef 2454 if (N1.isUndef()) 2455 return N1; 2456 2457 return SDValue(); 2458 } 2459 2460 // handles ISD::SREM and ISD::UREM 2461 SDValue DAGCombiner::visitREM(SDNode *N) { 2462 unsigned Opcode = N->getOpcode(); 2463 SDValue N0 = N->getOperand(0); 2464 SDValue N1 = N->getOperand(1); 2465 EVT VT = N->getValueType(0); 2466 bool isSigned = (Opcode == ISD::SREM); 2467 SDLoc DL(N); 2468 2469 // fold (rem c1, c2) -> c1%c2 2470 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2471 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2472 if (N0C && N1C) 2473 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 2474 return Folded; 2475 2476 if (isSigned) { 2477 // If we know the sign bits of both operands are zero, strength reduce to a 2478 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2479 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2480 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 2481 } else { 2482 // fold (urem x, pow2) -> (and x, pow2-1) 2483 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2484 N1C->getAPIntValue().isPowerOf2()) { 2485 return DAG.getNode(ISD::AND, DL, VT, N0, 2486 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT)); 2487 } 2488 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2489 if (N1.getOpcode() == ISD::SHL) { 2490 ConstantSDNode *SHC = isConstOrConstSplat(N1.getOperand(0)); 2491 if (SHC && !SHC->isOpaque() && SHC->getAPIntValue().isPowerOf2()) { 2492 APInt NegOne = APInt::getAllOnesValue(VT.getScalarSizeInBits()); 2493 SDValue Add = 2494 DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getConstant(NegOne, DL, VT)); 2495 AddToWorklist(Add.getNode()); 2496 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2497 } 2498 } 2499 } 2500 2501 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2502 2503 // If X/C can be simplified by the division-by-constant logic, lower 2504 // X%C to the equivalent of X-X/C*C. 2505 // To avoid mangling nodes, this simplification requires that the combine() 2506 // call for the speculative DIV must not cause a DIVREM conversion. We guard 2507 // against this by skipping the simplification if isIntDivCheap(). When 2508 // div is not cheap, combine will not return a DIVREM. Regardless, 2509 // checking cheapness here makes sense since the simplification results in 2510 // fatter code. 2511 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 2512 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2513 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 2514 AddToWorklist(Div.getNode()); 2515 SDValue OptimizedDiv = combine(Div.getNode()); 2516 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2517 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 2518 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 2519 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 2520 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 2521 AddToWorklist(Mul.getNode()); 2522 return Sub; 2523 } 2524 } 2525 2526 // sdiv, srem -> sdivrem 2527 if (SDValue DivRem = useDivRem(N)) 2528 return DivRem.getValue(1); 2529 2530 // undef % X -> 0 2531 if (N0.isUndef()) 2532 return DAG.getConstant(0, DL, VT); 2533 // X % undef -> undef 2534 if (N1.isUndef()) 2535 return N1; 2536 2537 return SDValue(); 2538 } 2539 2540 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2541 SDValue N0 = N->getOperand(0); 2542 SDValue N1 = N->getOperand(1); 2543 EVT VT = N->getValueType(0); 2544 SDLoc DL(N); 2545 2546 // fold (mulhs x, 0) -> 0 2547 if (isNullConstant(N1)) 2548 return N1; 2549 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2550 if (isOneConstant(N1)) { 2551 SDLoc DL(N); 2552 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2553 DAG.getConstant(N0.getValueSizeInBits() - 1, DL, 2554 getShiftAmountTy(N0.getValueType()))); 2555 } 2556 // fold (mulhs x, undef) -> 0 2557 if (N0.isUndef() || N1.isUndef()) 2558 return DAG.getConstant(0, SDLoc(N), VT); 2559 2560 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2561 // plus a shift. 2562 if (VT.isSimple() && !VT.isVector()) { 2563 MVT Simple = VT.getSimpleVT(); 2564 unsigned SimpleSize = Simple.getSizeInBits(); 2565 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2566 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2567 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2568 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2569 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2570 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2571 DAG.getConstant(SimpleSize, DL, 2572 getShiftAmountTy(N1.getValueType()))); 2573 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2574 } 2575 } 2576 2577 return SDValue(); 2578 } 2579 2580 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2581 SDValue N0 = N->getOperand(0); 2582 SDValue N1 = N->getOperand(1); 2583 EVT VT = N->getValueType(0); 2584 SDLoc DL(N); 2585 2586 // fold (mulhu x, 0) -> 0 2587 if (isNullConstant(N1)) 2588 return N1; 2589 // fold (mulhu x, 1) -> 0 2590 if (isOneConstant(N1)) 2591 return DAG.getConstant(0, DL, N0.getValueType()); 2592 // fold (mulhu x, undef) -> 0 2593 if (N0.isUndef() || N1.isUndef()) 2594 return DAG.getConstant(0, DL, VT); 2595 2596 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2597 // plus a shift. 2598 if (VT.isSimple() && !VT.isVector()) { 2599 MVT Simple = VT.getSimpleVT(); 2600 unsigned SimpleSize = Simple.getSizeInBits(); 2601 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2602 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2603 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2604 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2605 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2606 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2607 DAG.getConstant(SimpleSize, DL, 2608 getShiftAmountTy(N1.getValueType()))); 2609 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2610 } 2611 } 2612 2613 return SDValue(); 2614 } 2615 2616 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2617 /// give the opcodes for the two computations that are being performed. Return 2618 /// true if a simplification was made. 2619 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2620 unsigned HiOp) { 2621 // If the high half is not needed, just compute the low half. 2622 bool HiExists = N->hasAnyUseOfValue(1); 2623 if (!HiExists && 2624 (!LegalOperations || 2625 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2626 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2627 return CombineTo(N, Res, Res); 2628 } 2629 2630 // If the low half is not needed, just compute the high half. 2631 bool LoExists = N->hasAnyUseOfValue(0); 2632 if (!LoExists && 2633 (!LegalOperations || 2634 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2635 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2636 return CombineTo(N, Res, Res); 2637 } 2638 2639 // If both halves are used, return as it is. 2640 if (LoExists && HiExists) 2641 return SDValue(); 2642 2643 // If the two computed results can be simplified separately, separate them. 2644 if (LoExists) { 2645 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2646 AddToWorklist(Lo.getNode()); 2647 SDValue LoOpt = combine(Lo.getNode()); 2648 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2649 (!LegalOperations || 2650 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2651 return CombineTo(N, LoOpt, LoOpt); 2652 } 2653 2654 if (HiExists) { 2655 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2656 AddToWorklist(Hi.getNode()); 2657 SDValue HiOpt = combine(Hi.getNode()); 2658 if (HiOpt.getNode() && HiOpt != Hi && 2659 (!LegalOperations || 2660 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2661 return CombineTo(N, HiOpt, HiOpt); 2662 } 2663 2664 return SDValue(); 2665 } 2666 2667 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2668 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 2669 return Res; 2670 2671 EVT VT = N->getValueType(0); 2672 SDLoc DL(N); 2673 2674 // If the type is twice as wide is legal, transform the mulhu to a wider 2675 // multiply plus a shift. 2676 if (VT.isSimple() && !VT.isVector()) { 2677 MVT Simple = VT.getSimpleVT(); 2678 unsigned SimpleSize = Simple.getSizeInBits(); 2679 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2680 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2681 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2682 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2683 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2684 // Compute the high part as N1. 2685 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2686 DAG.getConstant(SimpleSize, DL, 2687 getShiftAmountTy(Lo.getValueType()))); 2688 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2689 // Compute the low part as N0. 2690 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2691 return CombineTo(N, Lo, Hi); 2692 } 2693 } 2694 2695 return SDValue(); 2696 } 2697 2698 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2699 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 2700 return Res; 2701 2702 EVT VT = N->getValueType(0); 2703 SDLoc DL(N); 2704 2705 // If the type is twice as wide is legal, transform the mulhu to a wider 2706 // multiply plus a shift. 2707 if (VT.isSimple() && !VT.isVector()) { 2708 MVT Simple = VT.getSimpleVT(); 2709 unsigned SimpleSize = Simple.getSizeInBits(); 2710 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2711 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2712 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2713 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2714 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2715 // Compute the high part as N1. 2716 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2717 DAG.getConstant(SimpleSize, DL, 2718 getShiftAmountTy(Lo.getValueType()))); 2719 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2720 // Compute the low part as N0. 2721 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2722 return CombineTo(N, Lo, Hi); 2723 } 2724 } 2725 2726 return SDValue(); 2727 } 2728 2729 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2730 // (smulo x, 2) -> (saddo x, x) 2731 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2732 if (C2->getAPIntValue() == 2) 2733 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2734 N->getOperand(0), N->getOperand(0)); 2735 2736 return SDValue(); 2737 } 2738 2739 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2740 // (umulo x, 2) -> (uaddo x, x) 2741 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2742 if (C2->getAPIntValue() == 2) 2743 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2744 N->getOperand(0), N->getOperand(0)); 2745 2746 return SDValue(); 2747 } 2748 2749 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 2750 SDValue N0 = N->getOperand(0); 2751 SDValue N1 = N->getOperand(1); 2752 EVT VT = N0.getValueType(); 2753 2754 // fold vector ops 2755 if (VT.isVector()) 2756 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2757 return FoldedVOp; 2758 2759 // fold (add c1, c2) -> c1+c2 2760 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 2761 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2762 if (N0C && N1C) 2763 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 2764 2765 // canonicalize constant to RHS 2766 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2767 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2768 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 2769 2770 return SDValue(); 2771 } 2772 2773 /// If this is a binary operator with two operands of the same opcode, try to 2774 /// simplify it. 2775 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2776 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2777 EVT VT = N0.getValueType(); 2778 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2779 2780 // Bail early if none of these transforms apply. 2781 if (N0.getNumOperands() == 0) return SDValue(); 2782 2783 // For each of OP in AND/OR/XOR: 2784 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2785 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2786 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2787 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2788 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2789 // 2790 // do not sink logical op inside of a vector extend, since it may combine 2791 // into a vsetcc. 2792 EVT Op0VT = N0.getOperand(0).getValueType(); 2793 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2794 N0.getOpcode() == ISD::SIGN_EXTEND || 2795 N0.getOpcode() == ISD::BSWAP || 2796 // Avoid infinite looping with PromoteIntBinOp. 2797 (N0.getOpcode() == ISD::ANY_EXTEND && 2798 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2799 (N0.getOpcode() == ISD::TRUNCATE && 2800 (!TLI.isZExtFree(VT, Op0VT) || 2801 !TLI.isTruncateFree(Op0VT, VT)) && 2802 TLI.isTypeLegal(Op0VT))) && 2803 !VT.isVector() && 2804 Op0VT == N1.getOperand(0).getValueType() && 2805 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2806 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2807 N0.getOperand(0).getValueType(), 2808 N0.getOperand(0), N1.getOperand(0)); 2809 AddToWorklist(ORNode.getNode()); 2810 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2811 } 2812 2813 // For each of OP in SHL/SRL/SRA/AND... 2814 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2815 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2816 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2817 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2818 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2819 N0.getOperand(1) == N1.getOperand(1)) { 2820 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2821 N0.getOperand(0).getValueType(), 2822 N0.getOperand(0), N1.getOperand(0)); 2823 AddToWorklist(ORNode.getNode()); 2824 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2825 ORNode, N0.getOperand(1)); 2826 } 2827 2828 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2829 // Only perform this optimization up until type legalization, before 2830 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2831 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2832 // we don't want to undo this promotion. 2833 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2834 // on scalars. 2835 if ((N0.getOpcode() == ISD::BITCAST || 2836 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2837 Level <= AfterLegalizeTypes) { 2838 SDValue In0 = N0.getOperand(0); 2839 SDValue In1 = N1.getOperand(0); 2840 EVT In0Ty = In0.getValueType(); 2841 EVT In1Ty = In1.getValueType(); 2842 SDLoc DL(N); 2843 // If both incoming values are integers, and the original types are the 2844 // same. 2845 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2846 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2847 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2848 AddToWorklist(Op.getNode()); 2849 return BC; 2850 } 2851 } 2852 2853 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2854 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2855 // If both shuffles use the same mask, and both shuffle within a single 2856 // vector, then it is worthwhile to move the swizzle after the operation. 2857 // The type-legalizer generates this pattern when loading illegal 2858 // vector types from memory. In many cases this allows additional shuffle 2859 // optimizations. 2860 // There are other cases where moving the shuffle after the xor/and/or 2861 // is profitable even if shuffles don't perform a swizzle. 2862 // If both shuffles use the same mask, and both shuffles have the same first 2863 // or second operand, then it might still be profitable to move the shuffle 2864 // after the xor/and/or operation. 2865 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2866 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2867 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2868 2869 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2870 "Inputs to shuffles are not the same type"); 2871 2872 // Check that both shuffles use the same mask. The masks are known to be of 2873 // the same length because the result vector type is the same. 2874 // Check also that shuffles have only one use to avoid introducing extra 2875 // instructions. 2876 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2877 SVN0->getMask().equals(SVN1->getMask())) { 2878 SDValue ShOp = N0->getOperand(1); 2879 2880 // Don't try to fold this node if it requires introducing a 2881 // build vector of all zeros that might be illegal at this stage. 2882 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 2883 if (!LegalTypes) 2884 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2885 else 2886 ShOp = SDValue(); 2887 } 2888 2889 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2890 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2891 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2892 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2893 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2894 N0->getOperand(0), N1->getOperand(0)); 2895 AddToWorklist(NewNode.getNode()); 2896 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2897 SVN0->getMask()); 2898 } 2899 2900 // Don't try to fold this node if it requires introducing a 2901 // build vector of all zeros that might be illegal at this stage. 2902 ShOp = N0->getOperand(0); 2903 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 2904 if (!LegalTypes) 2905 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2906 else 2907 ShOp = SDValue(); 2908 } 2909 2910 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2911 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2912 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2913 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2914 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2915 N0->getOperand(1), N1->getOperand(1)); 2916 AddToWorklist(NewNode.getNode()); 2917 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2918 SVN0->getMask()); 2919 } 2920 } 2921 } 2922 2923 return SDValue(); 2924 } 2925 2926 /// This contains all DAGCombine rules which reduce two values combined by 2927 /// an And operation to a single value. This makes them reusable in the context 2928 /// of visitSELECT(). Rules involving constants are not included as 2929 /// visitSELECT() already handles those cases. 2930 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 2931 SDNode *LocReference) { 2932 EVT VT = N1.getValueType(); 2933 2934 // fold (and x, undef) -> 0 2935 if (N0.isUndef() || N1.isUndef()) 2936 return DAG.getConstant(0, SDLoc(LocReference), VT); 2937 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2938 SDValue LL, LR, RL, RR, CC0, CC1; 2939 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2940 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2941 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2942 2943 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2944 LL.getValueType().isInteger()) { 2945 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2946 if (isNullConstant(LR) && Op1 == ISD::SETEQ) { 2947 EVT CCVT = getSetCCResultType(LR.getValueType()); 2948 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 2949 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2950 LR.getValueType(), LL, RL); 2951 AddToWorklist(ORNode.getNode()); 2952 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2953 } 2954 } 2955 if (isAllOnesConstant(LR)) { 2956 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2957 if (Op1 == ISD::SETEQ) { 2958 EVT CCVT = getSetCCResultType(LR.getValueType()); 2959 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 2960 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2961 LR.getValueType(), LL, RL); 2962 AddToWorklist(ANDNode.getNode()); 2963 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 2964 } 2965 } 2966 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2967 if (Op1 == ISD::SETGT) { 2968 EVT CCVT = getSetCCResultType(LR.getValueType()); 2969 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 2970 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2971 LR.getValueType(), LL, RL); 2972 AddToWorklist(ORNode.getNode()); 2973 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2974 } 2975 } 2976 } 2977 } 2978 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2979 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2980 Op0 == Op1 && LL.getValueType().isInteger() && 2981 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) || 2982 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 2983 EVT CCVT = getSetCCResultType(LL.getValueType()); 2984 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 2985 SDLoc DL(N0); 2986 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(), 2987 LL, DAG.getConstant(1, DL, 2988 LL.getValueType())); 2989 AddToWorklist(ADDNode.getNode()); 2990 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 2991 DAG.getConstant(2, DL, LL.getValueType()), 2992 ISD::SETUGE); 2993 } 2994 } 2995 // canonicalize equivalent to ll == rl 2996 if (LL == RR && LR == RL) { 2997 Op1 = ISD::getSetCCSwappedOperands(Op1); 2998 std::swap(RL, RR); 2999 } 3000 if (LL == RL && LR == RR) { 3001 bool isInteger = LL.getValueType().isInteger(); 3002 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 3003 if (Result != ISD::SETCC_INVALID && 3004 (!LegalOperations || 3005 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3006 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 3007 EVT CCVT = getSetCCResultType(LL.getValueType()); 3008 if (N0.getValueType() == CCVT || 3009 (!LegalOperations && N0.getValueType() == MVT::i1)) 3010 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3011 LL, LR, Result); 3012 } 3013 } 3014 } 3015 3016 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 3017 VT.getSizeInBits() <= 64) { 3018 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3019 APInt ADDC = ADDI->getAPIntValue(); 3020 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3021 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 3022 // immediate for an add, but it is legal if its top c2 bits are set, 3023 // transform the ADD so the immediate doesn't need to be materialized 3024 // in a register. 3025 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 3026 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3027 SRLI->getZExtValue()); 3028 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 3029 ADDC |= Mask; 3030 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3031 SDLoc DL(N0); 3032 SDValue NewAdd = 3033 DAG.getNode(ISD::ADD, DL, VT, 3034 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 3035 CombineTo(N0.getNode(), NewAdd); 3036 // Return N so it doesn't get rechecked! 3037 return SDValue(LocReference, 0); 3038 } 3039 } 3040 } 3041 } 3042 } 3043 } 3044 3045 // Reduce bit extract of low half of an integer to the narrower type. 3046 // (and (srl i64:x, K), KMask) -> 3047 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 3048 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 3049 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 3050 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3051 unsigned Size = VT.getSizeInBits(); 3052 const APInt &AndMask = CAnd->getAPIntValue(); 3053 unsigned ShiftBits = CShift->getZExtValue(); 3054 3055 // Bail out, this node will probably disappear anyway. 3056 if (ShiftBits == 0) 3057 return SDValue(); 3058 3059 unsigned MaskBits = AndMask.countTrailingOnes(); 3060 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 3061 3062 if (APIntOps::isMask(AndMask) && 3063 // Required bits must not span the two halves of the integer and 3064 // must fit in the half size type. 3065 (ShiftBits + MaskBits <= Size / 2) && 3066 TLI.isNarrowingProfitable(VT, HalfVT) && 3067 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 3068 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 3069 TLI.isTruncateFree(VT, HalfVT) && 3070 TLI.isZExtFree(HalfVT, VT)) { 3071 // The isNarrowingProfitable is to avoid regressions on PPC and 3072 // AArch64 which match a few 64-bit bit insert / bit extract patterns 3073 // on downstream users of this. Those patterns could probably be 3074 // extended to handle extensions mixed in. 3075 3076 SDValue SL(N0); 3077 assert(MaskBits <= Size); 3078 3079 // Extracting the highest bit of the low half. 3080 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 3081 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 3082 N0.getOperand(0)); 3083 3084 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 3085 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 3086 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 3087 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 3088 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 3089 } 3090 } 3091 } 3092 } 3093 3094 return SDValue(); 3095 } 3096 3097 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 3098 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 3099 bool &NarrowLoad) { 3100 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits(); 3101 3102 if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue())) 3103 return false; 3104 3105 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3106 LoadedVT = LoadN->getMemoryVT(); 3107 3108 if (ExtVT == LoadedVT && 3109 (!LegalOperations || 3110 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 3111 // ZEXTLOAD will match without needing to change the size of the value being 3112 // loaded. 3113 NarrowLoad = false; 3114 return true; 3115 } 3116 3117 // Do not change the width of a volatile load. 3118 if (LoadN->isVolatile()) 3119 return false; 3120 3121 // Do not generate loads of non-round integer types since these can 3122 // be expensive (and would be wrong if the type is not byte sized). 3123 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 3124 return false; 3125 3126 if (LegalOperations && 3127 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 3128 return false; 3129 3130 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 3131 return false; 3132 3133 NarrowLoad = true; 3134 return true; 3135 } 3136 3137 SDValue DAGCombiner::visitAND(SDNode *N) { 3138 SDValue N0 = N->getOperand(0); 3139 SDValue N1 = N->getOperand(1); 3140 EVT VT = N1.getValueType(); 3141 3142 // x & x --> x 3143 if (N0 == N1) 3144 return N0; 3145 3146 // fold vector ops 3147 if (VT.isVector()) { 3148 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3149 return FoldedVOp; 3150 3151 // fold (and x, 0) -> 0, vector edition 3152 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3153 // do not return N0, because undef node may exist in N0 3154 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()), 3155 SDLoc(N), N0.getValueType()); 3156 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3157 // do not return N1, because undef node may exist in N1 3158 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()), 3159 SDLoc(N), N1.getValueType()); 3160 3161 // fold (and x, -1) -> x, vector edition 3162 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3163 return N1; 3164 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3165 return N0; 3166 } 3167 3168 // fold (and c1, c2) -> c1&c2 3169 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3170 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3171 if (N0C && N1C && !N1C->isOpaque()) 3172 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3173 // canonicalize constant to RHS 3174 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3175 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3176 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3177 // fold (and x, -1) -> x 3178 if (isAllOnesConstant(N1)) 3179 return N0; 3180 // if (and x, c) is known to be zero, return 0 3181 unsigned BitWidth = VT.getScalarSizeInBits(); 3182 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3183 APInt::getAllOnesValue(BitWidth))) 3184 return DAG.getConstant(0, SDLoc(N), VT); 3185 // reassociate and 3186 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3187 return RAND; 3188 // fold (and (or x, C), D) -> D if (C & D) == D 3189 if (N1C && N0.getOpcode() == ISD::OR) 3190 if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1))) 3191 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 3192 return N1; 3193 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 3194 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3195 SDValue N0Op0 = N0.getOperand(0); 3196 APInt Mask = ~N1C->getAPIntValue(); 3197 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits()); 3198 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 3199 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 3200 N0.getValueType(), N0Op0); 3201 3202 // Replace uses of the AND with uses of the Zero extend node. 3203 CombineTo(N, Zext); 3204 3205 // We actually want to replace all uses of the any_extend with the 3206 // zero_extend, to avoid duplicating things. This will later cause this 3207 // AND to be folded. 3208 CombineTo(N0.getNode(), Zext); 3209 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3210 } 3211 } 3212 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3213 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3214 // already be zero by virtue of the width of the base type of the load. 3215 // 3216 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3217 // more cases. 3218 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3219 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 3220 N0.getOperand(0).getOpcode() == ISD::LOAD && 3221 N0.getOperand(0).getResNo() == 0) || 3222 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 3223 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3224 N0 : N0.getOperand(0) ); 3225 3226 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3227 // This can be a pure constant or a vector splat, in which case we treat the 3228 // vector as a scalar and use the splat value. 3229 APInt Constant = APInt::getNullValue(1); 3230 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3231 Constant = C->getAPIntValue(); 3232 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3233 APInt SplatValue, SplatUndef; 3234 unsigned SplatBitSize; 3235 bool HasAnyUndefs; 3236 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3237 SplatBitSize, HasAnyUndefs); 3238 if (IsSplat) { 3239 // Undef bits can contribute to a possible optimisation if set, so 3240 // set them. 3241 SplatValue |= SplatUndef; 3242 3243 // The splat value may be something like "0x00FFFFFF", which means 0 for 3244 // the first vector value and FF for the rest, repeating. We need a mask 3245 // that will apply equally to all members of the vector, so AND all the 3246 // lanes of the constant together. 3247 EVT VT = Vector->getValueType(0); 3248 unsigned BitWidth = VT.getScalarSizeInBits(); 3249 3250 // If the splat value has been compressed to a bitlength lower 3251 // than the size of the vector lane, we need to re-expand it to 3252 // the lane size. 3253 if (BitWidth > SplatBitSize) 3254 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3255 SplatBitSize < BitWidth; 3256 SplatBitSize = SplatBitSize * 2) 3257 SplatValue |= SplatValue.shl(SplatBitSize); 3258 3259 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3260 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3261 if (SplatBitSize % BitWidth == 0) { 3262 Constant = APInt::getAllOnesValue(BitWidth); 3263 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3264 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3265 } 3266 } 3267 } 3268 3269 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3270 // actually legal and isn't going to get expanded, else this is a false 3271 // optimisation. 3272 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3273 Load->getValueType(0), 3274 Load->getMemoryVT()); 3275 3276 // Resize the constant to the same size as the original memory access before 3277 // extension. If it is still the AllOnesValue then this AND is completely 3278 // unneeded. 3279 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits()); 3280 3281 bool B; 3282 switch (Load->getExtensionType()) { 3283 default: B = false; break; 3284 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3285 case ISD::ZEXTLOAD: 3286 case ISD::NON_EXTLOAD: B = true; break; 3287 } 3288 3289 if (B && Constant.isAllOnesValue()) { 3290 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3291 // preserve semantics once we get rid of the AND. 3292 SDValue NewLoad(Load, 0); 3293 if (Load->getExtensionType() == ISD::EXTLOAD) { 3294 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3295 Load->getValueType(0), SDLoc(Load), 3296 Load->getChain(), Load->getBasePtr(), 3297 Load->getOffset(), Load->getMemoryVT(), 3298 Load->getMemOperand()); 3299 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3300 if (Load->getNumValues() == 3) { 3301 // PRE/POST_INC loads have 3 values. 3302 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3303 NewLoad.getValue(2) }; 3304 CombineTo(Load, To, 3, true); 3305 } else { 3306 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3307 } 3308 } 3309 3310 // Fold the AND away, taking care not to fold to the old load node if we 3311 // replaced it. 3312 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3313 3314 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3315 } 3316 } 3317 3318 // fold (and (load x), 255) -> (zextload x, i8) 3319 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3320 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3321 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD || 3322 (N0.getOpcode() == ISD::ANY_EXTEND && 3323 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3324 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3325 LoadSDNode *LN0 = HasAnyExt 3326 ? cast<LoadSDNode>(N0.getOperand(0)) 3327 : cast<LoadSDNode>(N0); 3328 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3329 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3330 auto NarrowLoad = false; 3331 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3332 EVT ExtVT, LoadedVT; 3333 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT, 3334 NarrowLoad)) { 3335 if (!NarrowLoad) { 3336 SDValue NewLoad = 3337 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3338 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3339 LN0->getMemOperand()); 3340 AddToWorklist(N); 3341 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3342 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3343 } else { 3344 EVT PtrType = LN0->getOperand(1).getValueType(); 3345 3346 unsigned Alignment = LN0->getAlignment(); 3347 SDValue NewPtr = LN0->getBasePtr(); 3348 3349 // For big endian targets, we need to add an offset to the pointer 3350 // to load the correct bytes. For little endian systems, we merely 3351 // need to read fewer bytes from the same pointer. 3352 if (DAG.getDataLayout().isBigEndian()) { 3353 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3354 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3355 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3356 SDLoc DL(LN0); 3357 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3358 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3359 Alignment = MinAlign(Alignment, PtrOff); 3360 } 3361 3362 AddToWorklist(NewPtr.getNode()); 3363 3364 SDValue Load = DAG.getExtLoad( 3365 ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr, 3366 LN0->getPointerInfo(), ExtVT, Alignment, 3367 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 3368 AddToWorklist(N); 3369 CombineTo(LN0, Load, Load.getValue(1)); 3370 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3371 } 3372 } 3373 } 3374 } 3375 3376 if (SDValue Combined = visitANDLike(N0, N1, N)) 3377 return Combined; 3378 3379 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3380 if (N0.getOpcode() == N1.getOpcode()) 3381 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3382 return Tmp; 3383 3384 // Masking the negated extension of a boolean is just the zero-extended 3385 // boolean: 3386 // and (sub 0, zext(bool X)), 1 --> zext(bool X) 3387 // and (sub 0, sext(bool X)), 1 --> zext(bool X) 3388 // 3389 // Note: the SimplifyDemandedBits fold below can make an information-losing 3390 // transform, and then we have no way to find this better fold. 3391 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) { 3392 ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0)); 3393 SDValue SubRHS = N0.getOperand(1); 3394 if (SubLHS && SubLHS->isNullValue()) { 3395 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND && 3396 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 3397 return SubRHS; 3398 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND && 3399 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 3400 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0)); 3401 } 3402 } 3403 3404 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3405 // fold (and (sra)) -> (and (srl)) when possible. 3406 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 3407 return SDValue(N, 0); 3408 3409 // fold (zext_inreg (extload x)) -> (zextload x) 3410 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3411 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3412 EVT MemVT = LN0->getMemoryVT(); 3413 // If we zero all the possible extended bits, then we can turn this into 3414 // a zextload if we are running before legalize or the operation is legal. 3415 unsigned BitWidth = N1.getScalarValueSizeInBits(); 3416 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3417 BitWidth - MemVT.getScalarSizeInBits())) && 3418 ((!LegalOperations && !LN0->isVolatile()) || 3419 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3420 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3421 LN0->getChain(), LN0->getBasePtr(), 3422 MemVT, LN0->getMemOperand()); 3423 AddToWorklist(N); 3424 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3425 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3426 } 3427 } 3428 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3429 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3430 N0.hasOneUse()) { 3431 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3432 EVT MemVT = LN0->getMemoryVT(); 3433 // If we zero all the possible extended bits, then we can turn this into 3434 // a zextload if we are running before legalize or the operation is legal. 3435 unsigned BitWidth = N1.getScalarValueSizeInBits(); 3436 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3437 BitWidth - MemVT.getScalarSizeInBits())) && 3438 ((!LegalOperations && !LN0->isVolatile()) || 3439 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3440 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3441 LN0->getChain(), LN0->getBasePtr(), 3442 MemVT, LN0->getMemOperand()); 3443 AddToWorklist(N); 3444 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3445 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3446 } 3447 } 3448 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3449 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3450 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3451 N0.getOperand(1), false)) 3452 return BSwap; 3453 } 3454 3455 return SDValue(); 3456 } 3457 3458 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3459 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3460 bool DemandHighBits) { 3461 if (!LegalOperations) 3462 return SDValue(); 3463 3464 EVT VT = N->getValueType(0); 3465 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3466 return SDValue(); 3467 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3468 return SDValue(); 3469 3470 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3471 bool LookPassAnd0 = false; 3472 bool LookPassAnd1 = false; 3473 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3474 std::swap(N0, N1); 3475 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3476 std::swap(N0, N1); 3477 if (N0.getOpcode() == ISD::AND) { 3478 if (!N0.getNode()->hasOneUse()) 3479 return SDValue(); 3480 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3481 if (!N01C || N01C->getZExtValue() != 0xFF00) 3482 return SDValue(); 3483 N0 = N0.getOperand(0); 3484 LookPassAnd0 = true; 3485 } 3486 3487 if (N1.getOpcode() == ISD::AND) { 3488 if (!N1.getNode()->hasOneUse()) 3489 return SDValue(); 3490 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3491 if (!N11C || N11C->getZExtValue() != 0xFF) 3492 return SDValue(); 3493 N1 = N1.getOperand(0); 3494 LookPassAnd1 = true; 3495 } 3496 3497 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3498 std::swap(N0, N1); 3499 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3500 return SDValue(); 3501 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse()) 3502 return SDValue(); 3503 3504 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3505 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3506 if (!N01C || !N11C) 3507 return SDValue(); 3508 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3509 return SDValue(); 3510 3511 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3512 SDValue N00 = N0->getOperand(0); 3513 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3514 if (!N00.getNode()->hasOneUse()) 3515 return SDValue(); 3516 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3517 if (!N001C || N001C->getZExtValue() != 0xFF) 3518 return SDValue(); 3519 N00 = N00.getOperand(0); 3520 LookPassAnd0 = true; 3521 } 3522 3523 SDValue N10 = N1->getOperand(0); 3524 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3525 if (!N10.getNode()->hasOneUse()) 3526 return SDValue(); 3527 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3528 if (!N101C || N101C->getZExtValue() != 0xFF00) 3529 return SDValue(); 3530 N10 = N10.getOperand(0); 3531 LookPassAnd1 = true; 3532 } 3533 3534 if (N00 != N10) 3535 return SDValue(); 3536 3537 // Make sure everything beyond the low halfword gets set to zero since the SRL 3538 // 16 will clear the top bits. 3539 unsigned OpSizeInBits = VT.getSizeInBits(); 3540 if (DemandHighBits && OpSizeInBits > 16) { 3541 // If the left-shift isn't masked out then the only way this is a bswap is 3542 // if all bits beyond the low 8 are 0. In that case the entire pattern 3543 // reduces to a left shift anyway: leave it for other parts of the combiner. 3544 if (!LookPassAnd0) 3545 return SDValue(); 3546 3547 // However, if the right shift isn't masked out then it might be because 3548 // it's not needed. See if we can spot that too. 3549 if (!LookPassAnd1 && 3550 !DAG.MaskedValueIsZero( 3551 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3552 return SDValue(); 3553 } 3554 3555 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3556 if (OpSizeInBits > 16) { 3557 SDLoc DL(N); 3558 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3559 DAG.getConstant(OpSizeInBits - 16, DL, 3560 getShiftAmountTy(VT))); 3561 } 3562 return Res; 3563 } 3564 3565 /// Return true if the specified node is an element that makes up a 32-bit 3566 /// packed halfword byteswap. 3567 /// ((x & 0x000000ff) << 8) | 3568 /// ((x & 0x0000ff00) >> 8) | 3569 /// ((x & 0x00ff0000) << 8) | 3570 /// ((x & 0xff000000) >> 8) 3571 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3572 if (!N.getNode()->hasOneUse()) 3573 return false; 3574 3575 unsigned Opc = N.getOpcode(); 3576 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3577 return false; 3578 3579 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3580 if (!N1C) 3581 return false; 3582 3583 unsigned Num; 3584 switch (N1C->getZExtValue()) { 3585 default: 3586 return false; 3587 case 0xFF: Num = 0; break; 3588 case 0xFF00: Num = 1; break; 3589 case 0xFF0000: Num = 2; break; 3590 case 0xFF000000: Num = 3; break; 3591 } 3592 3593 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3594 SDValue N0 = N.getOperand(0); 3595 if (Opc == ISD::AND) { 3596 if (Num == 0 || Num == 2) { 3597 // (x >> 8) & 0xff 3598 // (x >> 8) & 0xff0000 3599 if (N0.getOpcode() != ISD::SRL) 3600 return false; 3601 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3602 if (!C || C->getZExtValue() != 8) 3603 return false; 3604 } else { 3605 // (x << 8) & 0xff00 3606 // (x << 8) & 0xff000000 3607 if (N0.getOpcode() != ISD::SHL) 3608 return false; 3609 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3610 if (!C || C->getZExtValue() != 8) 3611 return false; 3612 } 3613 } else if (Opc == ISD::SHL) { 3614 // (x & 0xff) << 8 3615 // (x & 0xff0000) << 8 3616 if (Num != 0 && Num != 2) 3617 return false; 3618 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3619 if (!C || C->getZExtValue() != 8) 3620 return false; 3621 } else { // Opc == ISD::SRL 3622 // (x & 0xff00) >> 8 3623 // (x & 0xff000000) >> 8 3624 if (Num != 1 && Num != 3) 3625 return false; 3626 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3627 if (!C || C->getZExtValue() != 8) 3628 return false; 3629 } 3630 3631 if (Parts[Num]) 3632 return false; 3633 3634 Parts[Num] = N0.getOperand(0).getNode(); 3635 return true; 3636 } 3637 3638 /// Match a 32-bit packed halfword bswap. That is 3639 /// ((x & 0x000000ff) << 8) | 3640 /// ((x & 0x0000ff00) >> 8) | 3641 /// ((x & 0x00ff0000) << 8) | 3642 /// ((x & 0xff000000) >> 8) 3643 /// => (rotl (bswap x), 16) 3644 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3645 if (!LegalOperations) 3646 return SDValue(); 3647 3648 EVT VT = N->getValueType(0); 3649 if (VT != MVT::i32) 3650 return SDValue(); 3651 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3652 return SDValue(); 3653 3654 // Look for either 3655 // (or (or (and), (and)), (or (and), (and))) 3656 // (or (or (or (and), (and)), (and)), (and)) 3657 if (N0.getOpcode() != ISD::OR) 3658 return SDValue(); 3659 SDValue N00 = N0.getOperand(0); 3660 SDValue N01 = N0.getOperand(1); 3661 SDNode *Parts[4] = {}; 3662 3663 if (N1.getOpcode() == ISD::OR && 3664 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3665 // (or (or (and), (and)), (or (and), (and))) 3666 SDValue N000 = N00.getOperand(0); 3667 if (!isBSwapHWordElement(N000, Parts)) 3668 return SDValue(); 3669 3670 SDValue N001 = N00.getOperand(1); 3671 if (!isBSwapHWordElement(N001, Parts)) 3672 return SDValue(); 3673 SDValue N010 = N01.getOperand(0); 3674 if (!isBSwapHWordElement(N010, Parts)) 3675 return SDValue(); 3676 SDValue N011 = N01.getOperand(1); 3677 if (!isBSwapHWordElement(N011, Parts)) 3678 return SDValue(); 3679 } else { 3680 // (or (or (or (and), (and)), (and)), (and)) 3681 if (!isBSwapHWordElement(N1, Parts)) 3682 return SDValue(); 3683 if (!isBSwapHWordElement(N01, Parts)) 3684 return SDValue(); 3685 if (N00.getOpcode() != ISD::OR) 3686 return SDValue(); 3687 SDValue N000 = N00.getOperand(0); 3688 if (!isBSwapHWordElement(N000, Parts)) 3689 return SDValue(); 3690 SDValue N001 = N00.getOperand(1); 3691 if (!isBSwapHWordElement(N001, Parts)) 3692 return SDValue(); 3693 } 3694 3695 // Make sure the parts are all coming from the same node. 3696 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3697 return SDValue(); 3698 3699 SDLoc DL(N); 3700 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 3701 SDValue(Parts[0], 0)); 3702 3703 // Result of the bswap should be rotated by 16. If it's not legal, then 3704 // do (x << 16) | (x >> 16). 3705 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 3706 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3707 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 3708 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3709 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 3710 return DAG.getNode(ISD::OR, DL, VT, 3711 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 3712 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 3713 } 3714 3715 /// This contains all DAGCombine rules which reduce two values combined by 3716 /// an Or operation to a single value \see visitANDLike(). 3717 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3718 EVT VT = N1.getValueType(); 3719 // fold (or x, undef) -> -1 3720 if (!LegalOperations && 3721 (N0.isUndef() || N1.isUndef())) { 3722 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3723 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), 3724 SDLoc(LocReference), VT); 3725 } 3726 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3727 SDValue LL, LR, RL, RR, CC0, CC1; 3728 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3729 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3730 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3731 3732 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) { 3733 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3734 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3735 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3736 EVT CCVT = getSetCCResultType(LR.getValueType()); 3737 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 3738 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3739 LR.getValueType(), LL, RL); 3740 AddToWorklist(ORNode.getNode()); 3741 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3742 } 3743 } 3744 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3745 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3746 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3747 EVT CCVT = getSetCCResultType(LR.getValueType()); 3748 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 3749 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3750 LR.getValueType(), LL, RL); 3751 AddToWorklist(ANDNode.getNode()); 3752 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3753 } 3754 } 3755 } 3756 // canonicalize equivalent to ll == rl 3757 if (LL == RR && LR == RL) { 3758 Op1 = ISD::getSetCCSwappedOperands(Op1); 3759 std::swap(RL, RR); 3760 } 3761 if (LL == RL && LR == RR) { 3762 bool isInteger = LL.getValueType().isInteger(); 3763 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3764 if (Result != ISD::SETCC_INVALID && 3765 (!LegalOperations || 3766 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3767 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 3768 EVT CCVT = getSetCCResultType(LL.getValueType()); 3769 if (N0.getValueType() == CCVT || 3770 (!LegalOperations && N0.getValueType() == MVT::i1)) 3771 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3772 LL, LR, Result); 3773 } 3774 } 3775 } 3776 3777 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3778 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 3779 // Don't increase # computations. 3780 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3781 // We can only do this xform if we know that bits from X that are set in C2 3782 // but not in C1 are already zero. Likewise for Y. 3783 if (const ConstantSDNode *N0O1C = 3784 getAsNonOpaqueConstant(N0.getOperand(1))) { 3785 if (const ConstantSDNode *N1O1C = 3786 getAsNonOpaqueConstant(N1.getOperand(1))) { 3787 // We can only do this xform if we know that bits from X that are set in 3788 // C2 but not in C1 are already zero. Likewise for Y. 3789 const APInt &LHSMask = N0O1C->getAPIntValue(); 3790 const APInt &RHSMask = N1O1C->getAPIntValue(); 3791 3792 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3793 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3794 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3795 N0.getOperand(0), N1.getOperand(0)); 3796 SDLoc DL(LocReference); 3797 return DAG.getNode(ISD::AND, DL, VT, X, 3798 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 3799 } 3800 } 3801 } 3802 } 3803 3804 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3805 if (N0.getOpcode() == ISD::AND && 3806 N1.getOpcode() == ISD::AND && 3807 N0.getOperand(0) == N1.getOperand(0) && 3808 // Don't increase # computations. 3809 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3810 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3811 N0.getOperand(1), N1.getOperand(1)); 3812 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3813 } 3814 3815 return SDValue(); 3816 } 3817 3818 SDValue DAGCombiner::visitOR(SDNode *N) { 3819 SDValue N0 = N->getOperand(0); 3820 SDValue N1 = N->getOperand(1); 3821 EVT VT = N1.getValueType(); 3822 3823 // x | x --> x 3824 if (N0 == N1) 3825 return N0; 3826 3827 // fold vector ops 3828 if (VT.isVector()) { 3829 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3830 return FoldedVOp; 3831 3832 // fold (or x, 0) -> x, vector edition 3833 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3834 return N1; 3835 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3836 return N0; 3837 3838 // fold (or x, -1) -> -1, vector edition 3839 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3840 // do not return N0, because undef node may exist in N0 3841 return DAG.getConstant( 3842 APInt::getAllOnesValue(N0.getScalarValueSizeInBits()), SDLoc(N), 3843 N0.getValueType()); 3844 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3845 // do not return N1, because undef node may exist in N1 3846 return DAG.getConstant( 3847 APInt::getAllOnesValue(N1.getScalarValueSizeInBits()), SDLoc(N), 3848 N1.getValueType()); 3849 3850 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 3851 // Do this only if the resulting shuffle is legal. 3852 if (isa<ShuffleVectorSDNode>(N0) && 3853 isa<ShuffleVectorSDNode>(N1) && 3854 // Avoid folding a node with illegal type. 3855 TLI.isTypeLegal(VT)) { 3856 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 3857 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 3858 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 3859 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 3860 // Ensure both shuffles have a zero input. 3861 if ((ZeroN00 || ZeroN01) && (ZeroN10 || ZeroN11)) { 3862 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 3863 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 3864 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3865 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3866 bool CanFold = true; 3867 int NumElts = VT.getVectorNumElements(); 3868 SmallVector<int, 4> Mask(NumElts); 3869 3870 for (int i = 0; i != NumElts; ++i) { 3871 int M0 = SV0->getMaskElt(i); 3872 int M1 = SV1->getMaskElt(i); 3873 3874 // Determine if either index is pointing to a zero vector. 3875 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 3876 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 3877 3878 // If one element is zero and the otherside is undef, keep undef. 3879 // This also handles the case that both are undef. 3880 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 3881 Mask[i] = -1; 3882 continue; 3883 } 3884 3885 // Make sure only one of the elements is zero. 3886 if (M0Zero == M1Zero) { 3887 CanFold = false; 3888 break; 3889 } 3890 3891 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 3892 3893 // We have a zero and non-zero element. If the non-zero came from 3894 // SV0 make the index a LHS index. If it came from SV1, make it 3895 // a RHS index. We need to mod by NumElts because we don't care 3896 // which operand it came from in the original shuffles. 3897 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 3898 } 3899 3900 if (CanFold) { 3901 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 3902 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 3903 3904 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 3905 if (!LegalMask) { 3906 std::swap(NewLHS, NewRHS); 3907 ShuffleVectorSDNode::commuteMask(Mask); 3908 LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 3909 } 3910 3911 if (LegalMask) 3912 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask); 3913 } 3914 } 3915 } 3916 } 3917 3918 // fold (or c1, c2) -> c1|c2 3919 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3920 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3921 if (N0C && N1C && !N1C->isOpaque()) 3922 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 3923 // canonicalize constant to RHS 3924 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3925 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3926 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3927 // fold (or x, 0) -> x 3928 if (isNullConstant(N1)) 3929 return N0; 3930 // fold (or x, -1) -> -1 3931 if (isAllOnesConstant(N1)) 3932 return N1; 3933 // fold (or x, c) -> c iff (x & ~c) == 0 3934 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3935 return N1; 3936 3937 if (SDValue Combined = visitORLike(N0, N1, N)) 3938 return Combined; 3939 3940 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3941 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 3942 return BSwap; 3943 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 3944 return BSwap; 3945 3946 // reassociate or 3947 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 3948 return ROR; 3949 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3950 // iff (c1 & c2) == 0. 3951 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3952 isa<ConstantSDNode>(N0.getOperand(1))) { 3953 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3954 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3955 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 3956 N1C, C1)) 3957 return DAG.getNode( 3958 ISD::AND, SDLoc(N), VT, 3959 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3960 return SDValue(); 3961 } 3962 } 3963 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3964 if (N0.getOpcode() == N1.getOpcode()) 3965 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3966 return Tmp; 3967 3968 // See if this is some rotate idiom. 3969 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3970 return SDValue(Rot, 0); 3971 3972 // Simplify the operands using demanded-bits information. 3973 if (!VT.isVector() && 3974 SimplifyDemandedBits(SDValue(N, 0))) 3975 return SDValue(N, 0); 3976 3977 return SDValue(); 3978 } 3979 3980 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3981 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3982 if (Op.getOpcode() == ISD::AND) { 3983 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 3984 Mask = Op.getOperand(1); 3985 Op = Op.getOperand(0); 3986 } else { 3987 return false; 3988 } 3989 } 3990 3991 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3992 Shift = Op; 3993 return true; 3994 } 3995 3996 return false; 3997 } 3998 3999 // Return true if we can prove that, whenever Neg and Pos are both in the 4000 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 4001 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 4002 // 4003 // (or (shift1 X, Neg), (shift2 X, Pos)) 4004 // 4005 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 4006 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 4007 // to consider shift amounts with defined behavior. 4008 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 4009 // If EltSize is a power of 2 then: 4010 // 4011 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 4012 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 4013 // 4014 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 4015 // for the stronger condition: 4016 // 4017 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 4018 // 4019 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 4020 // we can just replace Neg with Neg' for the rest of the function. 4021 // 4022 // In other cases we check for the even stronger condition: 4023 // 4024 // Neg == EltSize - Pos [B] 4025 // 4026 // for all Neg and Pos. Note that the (or ...) then invokes undefined 4027 // behavior if Pos == 0 (and consequently Neg == EltSize). 4028 // 4029 // We could actually use [A] whenever EltSize is a power of 2, but the 4030 // only extra cases that it would match are those uninteresting ones 4031 // where Neg and Pos are never in range at the same time. E.g. for 4032 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 4033 // as well as (sub 32, Pos), but: 4034 // 4035 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 4036 // 4037 // always invokes undefined behavior for 32-bit X. 4038 // 4039 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 4040 unsigned MaskLoBits = 0; 4041 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 4042 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 4043 if (NegC->getAPIntValue() == EltSize - 1) { 4044 Neg = Neg.getOperand(0); 4045 MaskLoBits = Log2_64(EltSize); 4046 } 4047 } 4048 } 4049 4050 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 4051 if (Neg.getOpcode() != ISD::SUB) 4052 return false; 4053 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 4054 if (!NegC) 4055 return false; 4056 SDValue NegOp1 = Neg.getOperand(1); 4057 4058 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 4059 // Pos'. The truncation is redundant for the purpose of the equality. 4060 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 4061 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4062 if (PosC->getAPIntValue() == EltSize - 1) 4063 Pos = Pos.getOperand(0); 4064 4065 // The condition we need is now: 4066 // 4067 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 4068 // 4069 // If NegOp1 == Pos then we need: 4070 // 4071 // EltSize & Mask == NegC & Mask 4072 // 4073 // (because "x & Mask" is a truncation and distributes through subtraction). 4074 APInt Width; 4075 if (Pos == NegOp1) 4076 Width = NegC->getAPIntValue(); 4077 4078 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 4079 // Then the condition we want to prove becomes: 4080 // 4081 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 4082 // 4083 // which, again because "x & Mask" is a truncation, becomes: 4084 // 4085 // NegC & Mask == (EltSize - PosC) & Mask 4086 // EltSize & Mask == (NegC + PosC) & Mask 4087 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 4088 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4089 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 4090 else 4091 return false; 4092 } else 4093 return false; 4094 4095 // Now we just need to check that EltSize & Mask == Width & Mask. 4096 if (MaskLoBits) 4097 // EltSize & Mask is 0 since Mask is EltSize - 1. 4098 return Width.getLoBits(MaskLoBits) == 0; 4099 return Width == EltSize; 4100 } 4101 4102 // A subroutine of MatchRotate used once we have found an OR of two opposite 4103 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 4104 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 4105 // former being preferred if supported. InnerPos and InnerNeg are Pos and 4106 // Neg with outer conversions stripped away. 4107 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 4108 SDValue Neg, SDValue InnerPos, 4109 SDValue InnerNeg, unsigned PosOpcode, 4110 unsigned NegOpcode, const SDLoc &DL) { 4111 // fold (or (shl x, (*ext y)), 4112 // (srl x, (*ext (sub 32, y)))) -> 4113 // (rotl x, y) or (rotr x, (sub 32, y)) 4114 // 4115 // fold (or (shl x, (*ext (sub 32, y))), 4116 // (srl x, (*ext y))) -> 4117 // (rotr x, y) or (rotl x, (sub 32, y)) 4118 EVT VT = Shifted.getValueType(); 4119 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 4120 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 4121 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 4122 HasPos ? Pos : Neg).getNode(); 4123 } 4124 4125 return nullptr; 4126 } 4127 4128 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 4129 // idioms for rotate, and if the target supports rotation instructions, generate 4130 // a rot[lr]. 4131 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 4132 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 4133 EVT VT = LHS.getValueType(); 4134 if (!TLI.isTypeLegal(VT)) return nullptr; 4135 4136 // The target must have at least one rotate flavor. 4137 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 4138 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 4139 if (!HasROTL && !HasROTR) return nullptr; 4140 4141 // Match "(X shl/srl V1) & V2" where V2 may not be present. 4142 SDValue LHSShift; // The shift. 4143 SDValue LHSMask; // AND value if any. 4144 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 4145 return nullptr; // Not part of a rotate. 4146 4147 SDValue RHSShift; // The shift. 4148 SDValue RHSMask; // AND value if any. 4149 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 4150 return nullptr; // Not part of a rotate. 4151 4152 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 4153 return nullptr; // Not shifting the same value. 4154 4155 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 4156 return nullptr; // Shifts must disagree. 4157 4158 // Canonicalize shl to left side in a shl/srl pair. 4159 if (RHSShift.getOpcode() == ISD::SHL) { 4160 std::swap(LHS, RHS); 4161 std::swap(LHSShift, RHSShift); 4162 std::swap(LHSMask, RHSMask); 4163 } 4164 4165 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4166 SDValue LHSShiftArg = LHSShift.getOperand(0); 4167 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4168 SDValue RHSShiftArg = RHSShift.getOperand(0); 4169 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4170 4171 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4172 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4173 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) { 4174 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue(); 4175 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue(); 4176 if ((LShVal + RShVal) != EltSizeInBits) 4177 return nullptr; 4178 4179 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4180 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4181 4182 // If there is an AND of either shifted operand, apply it to the result. 4183 if (LHSMask.getNode() || RHSMask.getNode()) { 4184 APInt AllBits = APInt::getAllOnesValue(EltSizeInBits); 4185 SDValue Mask = DAG.getConstant(AllBits, DL, VT); 4186 4187 if (LHSMask.getNode()) { 4188 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal); 4189 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4190 DAG.getNode(ISD::OR, DL, VT, LHSMask, 4191 DAG.getConstant(RHSBits, DL, VT))); 4192 } 4193 if (RHSMask.getNode()) { 4194 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal); 4195 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4196 DAG.getNode(ISD::OR, DL, VT, RHSMask, 4197 DAG.getConstant(LHSBits, DL, VT))); 4198 } 4199 4200 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4201 } 4202 4203 return Rot.getNode(); 4204 } 4205 4206 // If there is a mask here, and we have a variable shift, we can't be sure 4207 // that we're masking out the right stuff. 4208 if (LHSMask.getNode() || RHSMask.getNode()) 4209 return nullptr; 4210 4211 // If the shift amount is sign/zext/any-extended just peel it off. 4212 SDValue LExtOp0 = LHSShiftAmt; 4213 SDValue RExtOp0 = RHSShiftAmt; 4214 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4215 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4216 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4217 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4218 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4219 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4220 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4221 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4222 LExtOp0 = LHSShiftAmt.getOperand(0); 4223 RExtOp0 = RHSShiftAmt.getOperand(0); 4224 } 4225 4226 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4227 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4228 if (TryL) 4229 return TryL; 4230 4231 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4232 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4233 if (TryR) 4234 return TryR; 4235 4236 return nullptr; 4237 } 4238 4239 SDValue DAGCombiner::visitXOR(SDNode *N) { 4240 SDValue N0 = N->getOperand(0); 4241 SDValue N1 = N->getOperand(1); 4242 EVT VT = N0.getValueType(); 4243 4244 // fold vector ops 4245 if (VT.isVector()) { 4246 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4247 return FoldedVOp; 4248 4249 // fold (xor x, 0) -> x, vector edition 4250 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4251 return N1; 4252 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4253 return N0; 4254 } 4255 4256 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 4257 if (N0.isUndef() && N1.isUndef()) 4258 return DAG.getConstant(0, SDLoc(N), VT); 4259 // fold (xor x, undef) -> undef 4260 if (N0.isUndef()) 4261 return N0; 4262 if (N1.isUndef()) 4263 return N1; 4264 // fold (xor c1, c2) -> c1^c2 4265 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4266 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 4267 if (N0C && N1C) 4268 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 4269 // canonicalize constant to RHS 4270 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4271 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4272 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 4273 // fold (xor x, 0) -> x 4274 if (isNullConstant(N1)) 4275 return N0; 4276 // reassociate xor 4277 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 4278 return RXOR; 4279 4280 // fold !(x cc y) -> (x !cc y) 4281 SDValue LHS, RHS, CC; 4282 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 4283 bool isInt = LHS.getValueType().isInteger(); 4284 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 4285 isInt); 4286 4287 if (!LegalOperations || 4288 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 4289 switch (N0.getOpcode()) { 4290 default: 4291 llvm_unreachable("Unhandled SetCC Equivalent!"); 4292 case ISD::SETCC: 4293 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 4294 case ISD::SELECT_CC: 4295 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 4296 N0.getOperand(3), NotCC); 4297 } 4298 } 4299 } 4300 4301 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 4302 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 4303 N0.getNode()->hasOneUse() && 4304 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 4305 SDValue V = N0.getOperand(0); 4306 SDLoc DL(N0); 4307 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 4308 DAG.getConstant(1, DL, V.getValueType())); 4309 AddToWorklist(V.getNode()); 4310 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 4311 } 4312 4313 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 4314 if (isOneConstant(N1) && VT == MVT::i1 && 4315 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4316 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4317 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 4318 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4319 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4320 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4321 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4322 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4323 } 4324 } 4325 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 4326 if (isAllOnesConstant(N1) && 4327 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4328 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4329 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 4330 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4331 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4332 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4333 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4334 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4335 } 4336 } 4337 // fold (xor (and x, y), y) -> (and (not x), y) 4338 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4339 N0->getOperand(1) == N1) { 4340 SDValue X = N0->getOperand(0); 4341 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 4342 AddToWorklist(NotX.getNode()); 4343 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 4344 } 4345 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 4346 if (N1C && N0.getOpcode() == ISD::XOR) { 4347 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 4348 SDLoc DL(N); 4349 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 4350 DAG.getConstant(N1C->getAPIntValue() ^ 4351 N00C->getAPIntValue(), DL, VT)); 4352 } 4353 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 4354 SDLoc DL(N); 4355 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 4356 DAG.getConstant(N1C->getAPIntValue() ^ 4357 N01C->getAPIntValue(), DL, VT)); 4358 } 4359 } 4360 // fold (xor x, x) -> 0 4361 if (N0 == N1) 4362 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 4363 4364 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 4365 // Here is a concrete example of this equivalence: 4366 // i16 x == 14 4367 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 4368 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 4369 // 4370 // => 4371 // 4372 // i16 ~1 == 0b1111111111111110 4373 // i16 rol(~1, 14) == 0b1011111111111111 4374 // 4375 // Some additional tips to help conceptualize this transform: 4376 // - Try to see the operation as placing a single zero in a value of all ones. 4377 // - There exists no value for x which would allow the result to contain zero. 4378 // - Values of x larger than the bitwidth are undefined and do not require a 4379 // consistent result. 4380 // - Pushing the zero left requires shifting one bits in from the right. 4381 // A rotate left of ~1 is a nice way of achieving the desired result. 4382 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 4383 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 4384 SDLoc DL(N); 4385 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 4386 N0.getOperand(1)); 4387 } 4388 4389 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4390 if (N0.getOpcode() == N1.getOpcode()) 4391 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4392 return Tmp; 4393 4394 // Simplify the expression using non-local knowledge. 4395 if (!VT.isVector() && 4396 SimplifyDemandedBits(SDValue(N, 0))) 4397 return SDValue(N, 0); 4398 4399 return SDValue(); 4400 } 4401 4402 /// Handle transforms common to the three shifts, when the shift amount is a 4403 /// constant. 4404 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4405 SDNode *LHS = N->getOperand(0).getNode(); 4406 if (!LHS->hasOneUse()) return SDValue(); 4407 4408 // We want to pull some binops through shifts, so that we have (and (shift)) 4409 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4410 // thing happens with address calculations, so it's important to canonicalize 4411 // it. 4412 bool HighBitSet = false; // Can we transform this if the high bit is set? 4413 4414 switch (LHS->getOpcode()) { 4415 default: return SDValue(); 4416 case ISD::OR: 4417 case ISD::XOR: 4418 HighBitSet = false; // We can only transform sra if the high bit is clear. 4419 break; 4420 case ISD::AND: 4421 HighBitSet = true; // We can only transform sra if the high bit is set. 4422 break; 4423 case ISD::ADD: 4424 if (N->getOpcode() != ISD::SHL) 4425 return SDValue(); // only shl(add) not sr[al](add). 4426 HighBitSet = false; // We can only transform sra if the high bit is clear. 4427 break; 4428 } 4429 4430 // We require the RHS of the binop to be a constant and not opaque as well. 4431 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 4432 if (!BinOpCst) return SDValue(); 4433 4434 // FIXME: disable this unless the input to the binop is a shift by a constant. 4435 // If it is not a shift, it pessimizes some common cases like: 4436 // 4437 // void foo(int *X, int i) { X[i & 1235] = 1; } 4438 // int bar(int *X, int i) { return X[i & 255]; } 4439 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4440 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 4441 BinOpLHSVal->getOpcode() != ISD::SRA && 4442 BinOpLHSVal->getOpcode() != ISD::SRL) || 4443 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 4444 return SDValue(); 4445 4446 EVT VT = N->getValueType(0); 4447 4448 // If this is a signed shift right, and the high bit is modified by the 4449 // logical operation, do not perform the transformation. The highBitSet 4450 // boolean indicates the value of the high bit of the constant which would 4451 // cause it to be modified for this operation. 4452 if (N->getOpcode() == ISD::SRA) { 4453 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4454 if (BinOpRHSSignSet != HighBitSet) 4455 return SDValue(); 4456 } 4457 4458 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4459 return SDValue(); 4460 4461 // Fold the constants, shifting the binop RHS by the shift amount. 4462 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4463 N->getValueType(0), 4464 LHS->getOperand(1), N->getOperand(1)); 4465 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4466 4467 // Create the new shift. 4468 SDValue NewShift = DAG.getNode(N->getOpcode(), 4469 SDLoc(LHS->getOperand(0)), 4470 VT, LHS->getOperand(0), N->getOperand(1)); 4471 4472 // Create the new binop. 4473 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4474 } 4475 4476 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4477 assert(N->getOpcode() == ISD::TRUNCATE); 4478 assert(N->getOperand(0).getOpcode() == ISD::AND); 4479 4480 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4481 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4482 SDValue N01 = N->getOperand(0).getOperand(1); 4483 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) { 4484 SDLoc DL(N); 4485 EVT TruncVT = N->getValueType(0); 4486 SDValue N00 = N->getOperand(0).getOperand(0); 4487 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00); 4488 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01); 4489 AddToWorklist(Trunc00.getNode()); 4490 AddToWorklist(Trunc01.getNode()); 4491 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01); 4492 } 4493 } 4494 4495 return SDValue(); 4496 } 4497 4498 SDValue DAGCombiner::visitRotate(SDNode *N) { 4499 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4500 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4501 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4502 if (SDValue NewOp1 = 4503 distributeTruncateThroughAnd(N->getOperand(1).getNode())) 4504 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4505 N->getOperand(0), NewOp1); 4506 } 4507 return SDValue(); 4508 } 4509 4510 SDValue DAGCombiner::visitSHL(SDNode *N) { 4511 SDValue N0 = N->getOperand(0); 4512 SDValue N1 = N->getOperand(1); 4513 EVT VT = N0.getValueType(); 4514 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4515 4516 // fold vector ops 4517 if (VT.isVector()) { 4518 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4519 return FoldedVOp; 4520 4521 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4522 // If setcc produces all-one true value then: 4523 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4524 if (N1CV && N1CV->isConstant()) { 4525 if (N0.getOpcode() == ISD::AND) { 4526 SDValue N00 = N0->getOperand(0); 4527 SDValue N01 = N0->getOperand(1); 4528 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4529 4530 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4531 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4532 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4533 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 4534 N01CV, N1CV)) 4535 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4536 } 4537 } 4538 } 4539 } 4540 4541 ConstantSDNode *N1C = isConstOrConstSplat(N1); 4542 4543 // fold (shl c1, c2) -> c1<<c2 4544 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4545 if (N0C && N1C && !N1C->isOpaque()) 4546 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 4547 // fold (shl 0, x) -> 0 4548 if (isNullConstant(N0)) 4549 return N0; 4550 // fold (shl x, c >= size(x)) -> undef 4551 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4552 return DAG.getUNDEF(VT); 4553 // fold (shl x, 0) -> x 4554 if (N1C && N1C->isNullValue()) 4555 return N0; 4556 // fold (shl undef, x) -> 0 4557 if (N0.isUndef()) 4558 return DAG.getConstant(0, SDLoc(N), VT); 4559 // if (shl x, c) is known to be zero, return 0 4560 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4561 APInt::getAllOnesValue(OpSizeInBits))) 4562 return DAG.getConstant(0, SDLoc(N), VT); 4563 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4564 if (N1.getOpcode() == ISD::TRUNCATE && 4565 N1.getOperand(0).getOpcode() == ISD::AND) { 4566 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4567 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4568 } 4569 4570 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4571 return SDValue(N, 0); 4572 4573 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4574 if (N1C && N0.getOpcode() == ISD::SHL) { 4575 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4576 SDLoc DL(N); 4577 APInt c1 = N0C1->getAPIntValue(); 4578 APInt c2 = N1C->getAPIntValue(); 4579 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 4580 4581 APInt Sum = c1 + c2; 4582 if (Sum.uge(OpSizeInBits)) 4583 return DAG.getConstant(0, DL, VT); 4584 4585 return DAG.getNode( 4586 ISD::SHL, DL, VT, N0.getOperand(0), 4587 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 4588 } 4589 } 4590 4591 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4592 // For this to be valid, the second form must not preserve any of the bits 4593 // that are shifted out by the inner shift in the first form. This means 4594 // the outer shift size must be >= the number of bits added by the ext. 4595 // As a corollary, we don't care what kind of ext it is. 4596 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4597 N0.getOpcode() == ISD::ANY_EXTEND || 4598 N0.getOpcode() == ISD::SIGN_EXTEND) && 4599 N0.getOperand(0).getOpcode() == ISD::SHL) { 4600 SDValue N0Op0 = N0.getOperand(0); 4601 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4602 APInt c1 = N0Op0C1->getAPIntValue(); 4603 APInt c2 = N1C->getAPIntValue(); 4604 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 4605 4606 EVT InnerShiftVT = N0Op0.getValueType(); 4607 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4608 if (c2.uge(OpSizeInBits - InnerShiftSize)) { 4609 SDLoc DL(N0); 4610 APInt Sum = c1 + c2; 4611 if (Sum.uge(OpSizeInBits)) 4612 return DAG.getConstant(0, DL, VT); 4613 4614 return DAG.getNode( 4615 ISD::SHL, DL, VT, 4616 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)), 4617 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 4618 } 4619 } 4620 } 4621 4622 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4623 // Only fold this if the inner zext has no other uses to avoid increasing 4624 // the total number of instructions. 4625 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4626 N0.getOperand(0).getOpcode() == ISD::SRL) { 4627 SDValue N0Op0 = N0.getOperand(0); 4628 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4629 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) { 4630 uint64_t c1 = N0Op0C1->getZExtValue(); 4631 uint64_t c2 = N1C->getZExtValue(); 4632 if (c1 == c2) { 4633 SDValue NewOp0 = N0.getOperand(0); 4634 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4635 SDLoc DL(N); 4636 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 4637 NewOp0, 4638 DAG.getConstant(c2, DL, CountVT)); 4639 AddToWorklist(NewSHL.getNode()); 4640 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4641 } 4642 } 4643 } 4644 } 4645 4646 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 4647 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 4648 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 4649 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) { 4650 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4651 uint64_t C1 = N0C1->getZExtValue(); 4652 uint64_t C2 = N1C->getZExtValue(); 4653 SDLoc DL(N); 4654 if (C1 <= C2) 4655 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4656 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 4657 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 4658 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 4659 } 4660 } 4661 4662 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4663 // (and (srl x, (sub c1, c2), MASK) 4664 // Only fold this if the inner shift has no other uses -- if it does, folding 4665 // this will increase the total number of instructions. 4666 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4667 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4668 uint64_t c1 = N0C1->getZExtValue(); 4669 if (c1 < OpSizeInBits) { 4670 uint64_t c2 = N1C->getZExtValue(); 4671 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4672 SDValue Shift; 4673 if (c2 > c1) { 4674 Mask = Mask.shl(c2 - c1); 4675 SDLoc DL(N); 4676 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4677 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 4678 } else { 4679 Mask = Mask.lshr(c1 - c2); 4680 SDLoc DL(N); 4681 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4682 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 4683 } 4684 SDLoc DL(N0); 4685 return DAG.getNode(ISD::AND, DL, VT, Shift, 4686 DAG.getConstant(Mask, DL, VT)); 4687 } 4688 } 4689 } 4690 4691 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4692 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) && 4693 isConstantOrConstantVector(N1, /* No Opaques */ true)) { 4694 unsigned BitSize = VT.getScalarSizeInBits(); 4695 SDLoc DL(N); 4696 SDValue AllBits = DAG.getConstant(APInt::getAllOnesValue(BitSize), DL, VT); 4697 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1); 4698 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask); 4699 } 4700 4701 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4702 // Variant of version done on multiply, except mul by a power of 2 is turned 4703 // into a shift. 4704 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4705 isConstantOrConstantVector(N1, /* No Opaques */ true) && 4706 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 4707 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4708 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4709 AddToWorklist(Shl0.getNode()); 4710 AddToWorklist(Shl1.getNode()); 4711 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4712 } 4713 4714 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 4715 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() && 4716 isConstantOrConstantVector(N1, /* No Opaques */ true) && 4717 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 4718 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4719 if (isConstantOrConstantVector(Shl)) 4720 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl); 4721 } 4722 4723 if (N1C && !N1C->isOpaque()) 4724 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 4725 return NewSHL; 4726 4727 return SDValue(); 4728 } 4729 4730 SDValue DAGCombiner::visitSRA(SDNode *N) { 4731 SDValue N0 = N->getOperand(0); 4732 SDValue N1 = N->getOperand(1); 4733 EVT VT = N0.getValueType(); 4734 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4735 4736 // Arithmetic shifting an all-sign-bit value is a no-op. 4737 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits) 4738 return N0; 4739 4740 // fold vector ops 4741 if (VT.isVector()) 4742 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4743 return FoldedVOp; 4744 4745 ConstantSDNode *N1C = isConstOrConstSplat(N1); 4746 4747 // fold (sra c1, c2) -> (sra c1, c2) 4748 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4749 if (N0C && N1C && !N1C->isOpaque()) 4750 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 4751 // fold (sra 0, x) -> 0 4752 if (isNullConstant(N0)) 4753 return N0; 4754 // fold (sra -1, x) -> -1 4755 if (isAllOnesConstant(N0)) 4756 return N0; 4757 // fold (sra x, c >= size(x)) -> undef 4758 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4759 return DAG.getUNDEF(VT); 4760 // fold (sra x, 0) -> x 4761 if (N1C && N1C->isNullValue()) 4762 return N0; 4763 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4764 // sext_inreg. 4765 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4766 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4767 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4768 if (VT.isVector()) 4769 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4770 ExtVT, VT.getVectorNumElements()); 4771 if ((!LegalOperations || 4772 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4773 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4774 N0.getOperand(0), DAG.getValueType(ExtVT)); 4775 } 4776 4777 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4778 if (N1C && N0.getOpcode() == ISD::SRA) { 4779 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4780 SDLoc DL(N); 4781 APInt c1 = N0C1->getAPIntValue(); 4782 APInt c2 = N1C->getAPIntValue(); 4783 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 4784 4785 APInt Sum = c1 + c2; 4786 if (Sum.uge(OpSizeInBits)) 4787 Sum = APInt(OpSizeInBits, OpSizeInBits - 1); 4788 4789 return DAG.getNode( 4790 ISD::SRA, DL, VT, N0.getOperand(0), 4791 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 4792 } 4793 } 4794 4795 // fold (sra (shl X, m), (sub result_size, n)) 4796 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4797 // result_size - n != m. 4798 // If truncate is free for the target sext(shl) is likely to result in better 4799 // code. 4800 if (N0.getOpcode() == ISD::SHL && N1C) { 4801 // Get the two constanst of the shifts, CN0 = m, CN = n. 4802 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4803 if (N01C) { 4804 LLVMContext &Ctx = *DAG.getContext(); 4805 // Determine what the truncate's result bitsize and type would be. 4806 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4807 4808 if (VT.isVector()) 4809 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4810 4811 // Determine the residual right-shift amount. 4812 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4813 4814 // If the shift is not a no-op (in which case this should be just a sign 4815 // extend already), the truncated to type is legal, sign_extend is legal 4816 // on that type, and the truncate to that type is both legal and free, 4817 // perform the transform. 4818 if ((ShiftAmt > 0) && 4819 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4820 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4821 TLI.isTruncateFree(VT, TruncVT)) { 4822 4823 SDLoc DL(N); 4824 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 4825 getShiftAmountTy(N0.getOperand(0).getValueType())); 4826 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 4827 N0.getOperand(0), Amt); 4828 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 4829 Shift); 4830 return DAG.getNode(ISD::SIGN_EXTEND, DL, 4831 N->getValueType(0), Trunc); 4832 } 4833 } 4834 } 4835 4836 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4837 if (N1.getOpcode() == ISD::TRUNCATE && 4838 N1.getOperand(0).getOpcode() == ISD::AND) { 4839 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4840 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4841 } 4842 4843 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4844 // if c1 is equal to the number of bits the trunc removes 4845 if (N0.getOpcode() == ISD::TRUNCATE && 4846 (N0.getOperand(0).getOpcode() == ISD::SRL || 4847 N0.getOperand(0).getOpcode() == ISD::SRA) && 4848 N0.getOperand(0).hasOneUse() && 4849 N0.getOperand(0).getOperand(1).hasOneUse() && 4850 N1C) { 4851 SDValue N0Op0 = N0.getOperand(0); 4852 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4853 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4854 EVT LargeVT = N0Op0.getValueType(); 4855 4856 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4857 SDLoc DL(N); 4858 SDValue Amt = 4859 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 4860 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4861 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 4862 N0Op0.getOperand(0), Amt); 4863 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 4864 } 4865 } 4866 } 4867 4868 // Simplify, based on bits shifted out of the LHS. 4869 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4870 return SDValue(N, 0); 4871 4872 4873 // If the sign bit is known to be zero, switch this to a SRL. 4874 if (DAG.SignBitIsZero(N0)) 4875 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4876 4877 if (N1C && !N1C->isOpaque()) 4878 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 4879 return NewSRA; 4880 4881 return SDValue(); 4882 } 4883 4884 SDValue DAGCombiner::visitSRL(SDNode *N) { 4885 SDValue N0 = N->getOperand(0); 4886 SDValue N1 = N->getOperand(1); 4887 EVT VT = N0.getValueType(); 4888 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4889 4890 // fold vector ops 4891 if (VT.isVector()) 4892 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4893 return FoldedVOp; 4894 4895 ConstantSDNode *N1C = isConstOrConstSplat(N1); 4896 4897 // fold (srl c1, c2) -> c1 >>u c2 4898 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4899 if (N0C && N1C && !N1C->isOpaque()) 4900 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 4901 // fold (srl 0, x) -> 0 4902 if (isNullConstant(N0)) 4903 return N0; 4904 // fold (srl x, c >= size(x)) -> undef 4905 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4906 return DAG.getUNDEF(VT); 4907 // fold (srl x, 0) -> x 4908 if (N1C && N1C->isNullValue()) 4909 return N0; 4910 // if (srl x, c) is known to be zero, return 0 4911 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4912 APInt::getAllOnesValue(OpSizeInBits))) 4913 return DAG.getConstant(0, SDLoc(N), VT); 4914 4915 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4916 if (N1C && N0.getOpcode() == ISD::SRL) { 4917 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4918 SDLoc DL(N); 4919 APInt c1 = N0C1->getAPIntValue(); 4920 APInt c2 = N1C->getAPIntValue(); 4921 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 4922 4923 APInt Sum = c1 + c2; 4924 if (Sum.uge(OpSizeInBits)) 4925 return DAG.getConstant(0, DL, VT); 4926 4927 return DAG.getNode( 4928 ISD::SRL, DL, VT, N0.getOperand(0), 4929 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 4930 } 4931 } 4932 4933 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4934 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4935 N0.getOperand(0).getOpcode() == ISD::SRL && 4936 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4937 uint64_t c1 = 4938 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4939 uint64_t c2 = N1C->getZExtValue(); 4940 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4941 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4942 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4943 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4944 if (c1 + OpSizeInBits == InnerShiftSize) { 4945 SDLoc DL(N0); 4946 if (c1 + c2 >= InnerShiftSize) 4947 return DAG.getConstant(0, DL, VT); 4948 return DAG.getNode(ISD::TRUNCATE, DL, VT, 4949 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 4950 N0.getOperand(0)->getOperand(0), 4951 DAG.getConstant(c1 + c2, DL, 4952 ShiftCountVT))); 4953 } 4954 } 4955 4956 // fold (srl (shl x, c), c) -> (and x, cst2) 4957 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 4958 isConstantOrConstantVector(N1, /* NoOpaques */ true)) { 4959 SDLoc DL(N); 4960 APInt AllBits = APInt::getAllOnesValue(N0.getScalarValueSizeInBits()); 4961 SDValue Mask = 4962 DAG.getNode(ISD::SRL, DL, VT, DAG.getConstant(AllBits, DL, VT), N1); 4963 AddToWorklist(Mask.getNode()); 4964 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask); 4965 } 4966 4967 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4968 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4969 // Shifting in all undef bits? 4970 EVT SmallVT = N0.getOperand(0).getValueType(); 4971 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4972 if (N1C->getZExtValue() >= BitSize) 4973 return DAG.getUNDEF(VT); 4974 4975 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4976 uint64_t ShiftAmt = N1C->getZExtValue(); 4977 SDLoc DL0(N0); 4978 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 4979 N0.getOperand(0), 4980 DAG.getConstant(ShiftAmt, DL0, 4981 getShiftAmountTy(SmallVT))); 4982 AddToWorklist(SmallShift.getNode()); 4983 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4984 SDLoc DL(N); 4985 return DAG.getNode(ISD::AND, DL, VT, 4986 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 4987 DAG.getConstant(Mask, DL, VT)); 4988 } 4989 } 4990 4991 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4992 // bit, which is unmodified by sra. 4993 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4994 if (N0.getOpcode() == ISD::SRA) 4995 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4996 } 4997 4998 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4999 if (N1C && N0.getOpcode() == ISD::CTLZ && 5000 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 5001 APInt KnownZero, KnownOne; 5002 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 5003 5004 // If any of the input bits are KnownOne, then the input couldn't be all 5005 // zeros, thus the result of the srl will always be zero. 5006 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 5007 5008 // If all of the bits input the to ctlz node are known to be zero, then 5009 // the result of the ctlz is "32" and the result of the shift is one. 5010 APInt UnknownBits = ~KnownZero; 5011 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 5012 5013 // Otherwise, check to see if there is exactly one bit input to the ctlz. 5014 if ((UnknownBits & (UnknownBits - 1)) == 0) { 5015 // Okay, we know that only that the single bit specified by UnknownBits 5016 // could be set on input to the CTLZ node. If this bit is set, the SRL 5017 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 5018 // to an SRL/XOR pair, which is likely to simplify more. 5019 unsigned ShAmt = UnknownBits.countTrailingZeros(); 5020 SDValue Op = N0.getOperand(0); 5021 5022 if (ShAmt) { 5023 SDLoc DL(N0); 5024 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 5025 DAG.getConstant(ShAmt, DL, 5026 getShiftAmountTy(Op.getValueType()))); 5027 AddToWorklist(Op.getNode()); 5028 } 5029 5030 SDLoc DL(N); 5031 return DAG.getNode(ISD::XOR, DL, VT, 5032 Op, DAG.getConstant(1, DL, VT)); 5033 } 5034 } 5035 5036 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 5037 if (N1.getOpcode() == ISD::TRUNCATE && 5038 N1.getOperand(0).getOpcode() == ISD::AND) { 5039 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5040 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 5041 } 5042 5043 // fold operands of srl based on knowledge that the low bits are not 5044 // demanded. 5045 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5046 return SDValue(N, 0); 5047 5048 if (N1C && !N1C->isOpaque()) 5049 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 5050 return NewSRL; 5051 5052 // Attempt to convert a srl of a load into a narrower zero-extending load. 5053 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 5054 return NarrowLoad; 5055 5056 // Here is a common situation. We want to optimize: 5057 // 5058 // %a = ... 5059 // %b = and i32 %a, 2 5060 // %c = srl i32 %b, 1 5061 // brcond i32 %c ... 5062 // 5063 // into 5064 // 5065 // %a = ... 5066 // %b = and %a, 2 5067 // %c = setcc eq %b, 0 5068 // brcond %c ... 5069 // 5070 // However when after the source operand of SRL is optimized into AND, the SRL 5071 // itself may not be optimized further. Look for it and add the BRCOND into 5072 // the worklist. 5073 if (N->hasOneUse()) { 5074 SDNode *Use = *N->use_begin(); 5075 if (Use->getOpcode() == ISD::BRCOND) 5076 AddToWorklist(Use); 5077 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 5078 // Also look pass the truncate. 5079 Use = *Use->use_begin(); 5080 if (Use->getOpcode() == ISD::BRCOND) 5081 AddToWorklist(Use); 5082 } 5083 } 5084 5085 return SDValue(); 5086 } 5087 5088 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 5089 SDValue N0 = N->getOperand(0); 5090 EVT VT = N->getValueType(0); 5091 5092 // fold (bswap c1) -> c2 5093 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5094 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 5095 // fold (bswap (bswap x)) -> x 5096 if (N0.getOpcode() == ISD::BSWAP) 5097 return N0->getOperand(0); 5098 return SDValue(); 5099 } 5100 5101 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 5102 SDValue N0 = N->getOperand(0); 5103 5104 // fold (bitreverse (bitreverse x)) -> x 5105 if (N0.getOpcode() == ISD::BITREVERSE) 5106 return N0.getOperand(0); 5107 return SDValue(); 5108 } 5109 5110 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 5111 SDValue N0 = N->getOperand(0); 5112 EVT VT = N->getValueType(0); 5113 5114 // fold (ctlz c1) -> c2 5115 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5116 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 5117 return SDValue(); 5118 } 5119 5120 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 5121 SDValue N0 = N->getOperand(0); 5122 EVT VT = N->getValueType(0); 5123 5124 // fold (ctlz_zero_undef c1) -> c2 5125 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5126 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5127 return SDValue(); 5128 } 5129 5130 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 5131 SDValue N0 = N->getOperand(0); 5132 EVT VT = N->getValueType(0); 5133 5134 // fold (cttz c1) -> c2 5135 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5136 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 5137 return SDValue(); 5138 } 5139 5140 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 5141 SDValue N0 = N->getOperand(0); 5142 EVT VT = N->getValueType(0); 5143 5144 // fold (cttz_zero_undef c1) -> c2 5145 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5146 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5147 return SDValue(); 5148 } 5149 5150 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 5151 SDValue N0 = N->getOperand(0); 5152 EVT VT = N->getValueType(0); 5153 5154 // fold (ctpop c1) -> c2 5155 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5156 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 5157 return SDValue(); 5158 } 5159 5160 5161 /// \brief Generate Min/Max node 5162 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 5163 SDValue RHS, SDValue True, SDValue False, 5164 ISD::CondCode CC, const TargetLowering &TLI, 5165 SelectionDAG &DAG) { 5166 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 5167 return SDValue(); 5168 5169 switch (CC) { 5170 case ISD::SETOLT: 5171 case ISD::SETOLE: 5172 case ISD::SETLT: 5173 case ISD::SETLE: 5174 case ISD::SETULT: 5175 case ISD::SETULE: { 5176 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 5177 if (TLI.isOperationLegal(Opcode, VT)) 5178 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5179 return SDValue(); 5180 } 5181 case ISD::SETOGT: 5182 case ISD::SETOGE: 5183 case ISD::SETGT: 5184 case ISD::SETGE: 5185 case ISD::SETUGT: 5186 case ISD::SETUGE: { 5187 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 5188 if (TLI.isOperationLegal(Opcode, VT)) 5189 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5190 return SDValue(); 5191 } 5192 default: 5193 return SDValue(); 5194 } 5195 } 5196 5197 // TODO: We should handle other cases of selecting between {-1,0,1} here. 5198 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) { 5199 SDValue Cond = N->getOperand(0); 5200 SDValue N1 = N->getOperand(1); 5201 SDValue N2 = N->getOperand(2); 5202 EVT VT = N->getValueType(0); 5203 EVT CondVT = Cond.getValueType(); 5204 SDLoc DL(N); 5205 5206 // fold (select Cond, 0, 1) -> (xor Cond, 1) 5207 // We can't do this reliably if integer based booleans have different contents 5208 // to floating point based booleans. This is because we can't tell whether we 5209 // have an integer-based boolean or a floating-point-based boolean unless we 5210 // can find the SETCC that produced it and inspect its operands. This is 5211 // fairly easy if C is the SETCC node, but it can potentially be 5212 // undiscoverable (or not reasonably discoverable). For example, it could be 5213 // in another basic block or it could require searching a complicated 5214 // expression. 5215 if (VT.isInteger() && 5216 (CondVT == MVT::i1 || (CondVT.isInteger() && 5217 TLI.getBooleanContents(false, true) == 5218 TargetLowering::ZeroOrOneBooleanContent && 5219 TLI.getBooleanContents(false, false) == 5220 TargetLowering::ZeroOrOneBooleanContent)) && 5221 isNullConstant(N1) && isOneConstant(N2)) { 5222 SDValue NotCond = DAG.getNode(ISD::XOR, DL, CondVT, Cond, 5223 DAG.getConstant(1, DL, CondVT)); 5224 if (VT.bitsEq(CondVT)) 5225 return NotCond; 5226 return DAG.getZExtOrTrunc(NotCond, DL, VT); 5227 } 5228 5229 return SDValue(); 5230 } 5231 5232 SDValue DAGCombiner::visitSELECT(SDNode *N) { 5233 SDValue N0 = N->getOperand(0); 5234 SDValue N1 = N->getOperand(1); 5235 SDValue N2 = N->getOperand(2); 5236 EVT VT = N->getValueType(0); 5237 EVT VT0 = N0.getValueType(); 5238 5239 // fold (select C, X, X) -> X 5240 if (N1 == N2) 5241 return N1; 5242 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 5243 // fold (select true, X, Y) -> X 5244 // fold (select false, X, Y) -> Y 5245 return !N0C->isNullValue() ? N1 : N2; 5246 } 5247 // fold (select C, 1, X) -> (or C, X) 5248 if (VT == MVT::i1 && isOneConstant(N1)) 5249 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5250 5251 if (SDValue V = foldSelectOfConstants(N)) 5252 return V; 5253 5254 // fold (select C, 0, X) -> (and (not C), X) 5255 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 5256 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5257 AddToWorklist(NOTNode.getNode()); 5258 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 5259 } 5260 // fold (select C, X, 1) -> (or (not C), X) 5261 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 5262 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5263 AddToWorklist(NOTNode.getNode()); 5264 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 5265 } 5266 // fold (select C, X, 0) -> (and C, X) 5267 if (VT == MVT::i1 && isNullConstant(N2)) 5268 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5269 // fold (select X, X, Y) -> (or X, Y) 5270 // fold (select X, 1, Y) -> (or X, Y) 5271 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 5272 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5273 // fold (select X, Y, X) -> (and X, Y) 5274 // fold (select X, Y, 0) -> (and X, Y) 5275 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 5276 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5277 5278 // If we can fold this based on the true/false value, do so. 5279 if (SimplifySelectOps(N, N1, N2)) 5280 return SDValue(N, 0); // Don't revisit N. 5281 5282 if (VT0 == MVT::i1) { 5283 // The code in this block deals with the following 2 equivalences: 5284 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 5285 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 5286 // The target can specify its preferred form with the 5287 // shouldNormalizeToSelectSequence() callback. However we always transform 5288 // to the right anyway if we find the inner select exists in the DAG anyway 5289 // and we always transform to the left side if we know that we can further 5290 // optimize the combination of the conditions. 5291 bool normalizeToSequence 5292 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 5293 // select (and Cond0, Cond1), X, Y 5294 // -> select Cond0, (select Cond1, X, Y), Y 5295 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 5296 SDValue Cond0 = N0->getOperand(0); 5297 SDValue Cond1 = N0->getOperand(1); 5298 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5299 N1.getValueType(), Cond1, N1, N2); 5300 if (normalizeToSequence || !InnerSelect.use_empty()) 5301 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 5302 InnerSelect, N2); 5303 } 5304 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 5305 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 5306 SDValue Cond0 = N0->getOperand(0); 5307 SDValue Cond1 = N0->getOperand(1); 5308 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5309 N1.getValueType(), Cond1, N1, N2); 5310 if (normalizeToSequence || !InnerSelect.use_empty()) 5311 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 5312 InnerSelect); 5313 } 5314 5315 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 5316 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 5317 SDValue N1_0 = N1->getOperand(0); 5318 SDValue N1_1 = N1->getOperand(1); 5319 SDValue N1_2 = N1->getOperand(2); 5320 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 5321 // Create the actual and node if we can generate good code for it. 5322 if (!normalizeToSequence) { 5323 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 5324 N0, N1_0); 5325 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 5326 N1_1, N2); 5327 } 5328 // Otherwise see if we can optimize the "and" to a better pattern. 5329 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 5330 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5331 N1_1, N2); 5332 } 5333 } 5334 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 5335 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 5336 SDValue N2_0 = N2->getOperand(0); 5337 SDValue N2_1 = N2->getOperand(1); 5338 SDValue N2_2 = N2->getOperand(2); 5339 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 5340 // Create the actual or node if we can generate good code for it. 5341 if (!normalizeToSequence) { 5342 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 5343 N0, N2_0); 5344 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 5345 N1, N2_2); 5346 } 5347 // Otherwise see if we can optimize to a better pattern. 5348 if (SDValue Combined = visitORLike(N0, N2_0, N)) 5349 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5350 N1, N2_2); 5351 } 5352 } 5353 } 5354 5355 // select (xor Cond, 1), X, Y -> select Cond, Y, X 5356 // select (xor Cond, 0), X, Y -> selext Cond, X, Y 5357 if (VT0 == MVT::i1) { 5358 if (N0->getOpcode() == ISD::XOR) { 5359 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) { 5360 SDValue Cond0 = N0->getOperand(0); 5361 if (C->isOne()) 5362 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), 5363 Cond0, N2, N1); 5364 else 5365 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), 5366 Cond0, N1, N2); 5367 } 5368 } 5369 } 5370 5371 // fold selects based on a setcc into other things, such as min/max/abs 5372 if (N0.getOpcode() == ISD::SETCC) { 5373 // select x, y (fcmp lt x, y) -> fminnum x, y 5374 // select x, y (fcmp gt x, y) -> fmaxnum x, y 5375 // 5376 // This is OK if we don't care about what happens if either operand is a 5377 // NaN. 5378 // 5379 5380 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 5381 // no signed zeros as well as no nans. 5382 const TargetOptions &Options = DAG.getTarget().Options; 5383 if (Options.UnsafeFPMath && 5384 VT.isFloatingPoint() && N0.hasOneUse() && 5385 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 5386 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5387 5388 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 5389 N0.getOperand(1), N1, N2, CC, 5390 TLI, DAG)) 5391 return FMinMax; 5392 } 5393 5394 if ((!LegalOperations && 5395 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 5396 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 5397 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 5398 N0.getOperand(0), N0.getOperand(1), 5399 N1, N2, N0.getOperand(2)); 5400 return SimplifySelect(SDLoc(N), N0, N1, N2); 5401 } 5402 5403 return SDValue(); 5404 } 5405 5406 static 5407 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 5408 SDLoc DL(N); 5409 EVT LoVT, HiVT; 5410 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 5411 5412 // Split the inputs. 5413 SDValue Lo, Hi, LL, LH, RL, RH; 5414 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 5415 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 5416 5417 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 5418 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 5419 5420 return std::make_pair(Lo, Hi); 5421 } 5422 5423 // This function assumes all the vselect's arguments are CONCAT_VECTOR 5424 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 5425 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 5426 SDLoc DL(N); 5427 SDValue Cond = N->getOperand(0); 5428 SDValue LHS = N->getOperand(1); 5429 SDValue RHS = N->getOperand(2); 5430 EVT VT = N->getValueType(0); 5431 int NumElems = VT.getVectorNumElements(); 5432 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 5433 RHS.getOpcode() == ISD::CONCAT_VECTORS && 5434 Cond.getOpcode() == ISD::BUILD_VECTOR); 5435 5436 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 5437 // binary ones here. 5438 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 5439 return SDValue(); 5440 5441 // We're sure we have an even number of elements due to the 5442 // concat_vectors we have as arguments to vselect. 5443 // Skip BV elements until we find one that's not an UNDEF 5444 // After we find an UNDEF element, keep looping until we get to half the 5445 // length of the BV and see if all the non-undef nodes are the same. 5446 ConstantSDNode *BottomHalf = nullptr; 5447 for (int i = 0; i < NumElems / 2; ++i) { 5448 if (Cond->getOperand(i)->isUndef()) 5449 continue; 5450 5451 if (BottomHalf == nullptr) 5452 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5453 else if (Cond->getOperand(i).getNode() != BottomHalf) 5454 return SDValue(); 5455 } 5456 5457 // Do the same for the second half of the BuildVector 5458 ConstantSDNode *TopHalf = nullptr; 5459 for (int i = NumElems / 2; i < NumElems; ++i) { 5460 if (Cond->getOperand(i)->isUndef()) 5461 continue; 5462 5463 if (TopHalf == nullptr) 5464 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5465 else if (Cond->getOperand(i).getNode() != TopHalf) 5466 return SDValue(); 5467 } 5468 5469 assert(TopHalf && BottomHalf && 5470 "One half of the selector was all UNDEFs and the other was all the " 5471 "same value. This should have been addressed before this function."); 5472 return DAG.getNode( 5473 ISD::CONCAT_VECTORS, DL, VT, 5474 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 5475 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 5476 } 5477 5478 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 5479 5480 if (Level >= AfterLegalizeTypes) 5481 return SDValue(); 5482 5483 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 5484 SDValue Mask = MSC->getMask(); 5485 SDValue Data = MSC->getValue(); 5486 SDLoc DL(N); 5487 5488 // If the MSCATTER data type requires splitting and the mask is provided by a 5489 // SETCC, then split both nodes and its operands before legalization. This 5490 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5491 // and enables future optimizations (e.g. min/max pattern matching on X86). 5492 if (Mask.getOpcode() != ISD::SETCC) 5493 return SDValue(); 5494 5495 // Check if any splitting is required. 5496 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5497 TargetLowering::TypeSplitVector) 5498 return SDValue(); 5499 SDValue MaskLo, MaskHi, Lo, Hi; 5500 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5501 5502 EVT LoVT, HiVT; 5503 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 5504 5505 SDValue Chain = MSC->getChain(); 5506 5507 EVT MemoryVT = MSC->getMemoryVT(); 5508 unsigned Alignment = MSC->getOriginalAlignment(); 5509 5510 EVT LoMemVT, HiMemVT; 5511 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5512 5513 SDValue DataLo, DataHi; 5514 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5515 5516 SDValue BasePtr = MSC->getBasePtr(); 5517 SDValue IndexLo, IndexHi; 5518 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 5519 5520 MachineMemOperand *MMO = DAG.getMachineFunction(). 5521 getMachineMemOperand(MSC->getPointerInfo(), 5522 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5523 Alignment, MSC->getAAInfo(), MSC->getRanges()); 5524 5525 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 5526 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 5527 DL, OpsLo, MMO); 5528 5529 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 5530 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 5531 DL, OpsHi, MMO); 5532 5533 AddToWorklist(Lo.getNode()); 5534 AddToWorklist(Hi.getNode()); 5535 5536 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5537 } 5538 5539 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 5540 5541 if (Level >= AfterLegalizeTypes) 5542 return SDValue(); 5543 5544 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 5545 SDValue Mask = MST->getMask(); 5546 SDValue Data = MST->getValue(); 5547 EVT VT = Data.getValueType(); 5548 SDLoc DL(N); 5549 5550 // If the MSTORE data type requires splitting and the mask is provided by a 5551 // SETCC, then split both nodes and its operands before legalization. This 5552 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5553 // and enables future optimizations (e.g. min/max pattern matching on X86). 5554 if (Mask.getOpcode() == ISD::SETCC) { 5555 5556 // Check if any splitting is required. 5557 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5558 TargetLowering::TypeSplitVector) 5559 return SDValue(); 5560 5561 SDValue MaskLo, MaskHi, Lo, Hi; 5562 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5563 5564 SDValue Chain = MST->getChain(); 5565 SDValue Ptr = MST->getBasePtr(); 5566 5567 EVT MemoryVT = MST->getMemoryVT(); 5568 unsigned Alignment = MST->getOriginalAlignment(); 5569 5570 // if Alignment is equal to the vector size, 5571 // take the half of it for the second part 5572 unsigned SecondHalfAlignment = 5573 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment; 5574 5575 EVT LoMemVT, HiMemVT; 5576 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5577 5578 SDValue DataLo, DataHi; 5579 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5580 5581 MachineMemOperand *MMO = DAG.getMachineFunction(). 5582 getMachineMemOperand(MST->getPointerInfo(), 5583 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5584 Alignment, MST->getAAInfo(), MST->getRanges()); 5585 5586 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 5587 MST->isTruncatingStore(), 5588 MST->isCompressingStore()); 5589 5590 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 5591 MST->isCompressingStore()); 5592 5593 MMO = DAG.getMachineFunction(). 5594 getMachineMemOperand(MST->getPointerInfo(), 5595 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 5596 SecondHalfAlignment, MST->getAAInfo(), 5597 MST->getRanges()); 5598 5599 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 5600 MST->isTruncatingStore(), 5601 MST->isCompressingStore()); 5602 5603 AddToWorklist(Lo.getNode()); 5604 AddToWorklist(Hi.getNode()); 5605 5606 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5607 } 5608 return SDValue(); 5609 } 5610 5611 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 5612 5613 if (Level >= AfterLegalizeTypes) 5614 return SDValue(); 5615 5616 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 5617 SDValue Mask = MGT->getMask(); 5618 SDLoc DL(N); 5619 5620 // If the MGATHER result requires splitting and the mask is provided by a 5621 // SETCC, then split both nodes and its operands before legalization. This 5622 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5623 // and enables future optimizations (e.g. min/max pattern matching on X86). 5624 5625 if (Mask.getOpcode() != ISD::SETCC) 5626 return SDValue(); 5627 5628 EVT VT = N->getValueType(0); 5629 5630 // Check if any splitting is required. 5631 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5632 TargetLowering::TypeSplitVector) 5633 return SDValue(); 5634 5635 SDValue MaskLo, MaskHi, Lo, Hi; 5636 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5637 5638 SDValue Src0 = MGT->getValue(); 5639 SDValue Src0Lo, Src0Hi; 5640 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5641 5642 EVT LoVT, HiVT; 5643 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 5644 5645 SDValue Chain = MGT->getChain(); 5646 EVT MemoryVT = MGT->getMemoryVT(); 5647 unsigned Alignment = MGT->getOriginalAlignment(); 5648 5649 EVT LoMemVT, HiMemVT; 5650 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5651 5652 SDValue BasePtr = MGT->getBasePtr(); 5653 SDValue Index = MGT->getIndex(); 5654 SDValue IndexLo, IndexHi; 5655 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 5656 5657 MachineMemOperand *MMO = DAG.getMachineFunction(). 5658 getMachineMemOperand(MGT->getPointerInfo(), 5659 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5660 Alignment, MGT->getAAInfo(), MGT->getRanges()); 5661 5662 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 5663 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 5664 MMO); 5665 5666 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 5667 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 5668 MMO); 5669 5670 AddToWorklist(Lo.getNode()); 5671 AddToWorklist(Hi.getNode()); 5672 5673 // Build a factor node to remember that this load is independent of the 5674 // other one. 5675 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5676 Hi.getValue(1)); 5677 5678 // Legalized the chain result - switch anything that used the old chain to 5679 // use the new one. 5680 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 5681 5682 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5683 5684 SDValue RetOps[] = { GatherRes, Chain }; 5685 return DAG.getMergeValues(RetOps, DL); 5686 } 5687 5688 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 5689 5690 if (Level >= AfterLegalizeTypes) 5691 return SDValue(); 5692 5693 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 5694 SDValue Mask = MLD->getMask(); 5695 SDLoc DL(N); 5696 5697 // If the MLOAD result requires splitting and the mask is provided by a 5698 // SETCC, then split both nodes and its operands before legalization. This 5699 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5700 // and enables future optimizations (e.g. min/max pattern matching on X86). 5701 5702 if (Mask.getOpcode() == ISD::SETCC) { 5703 EVT VT = N->getValueType(0); 5704 5705 // Check if any splitting is required. 5706 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5707 TargetLowering::TypeSplitVector) 5708 return SDValue(); 5709 5710 SDValue MaskLo, MaskHi, Lo, Hi; 5711 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5712 5713 SDValue Src0 = MLD->getSrc0(); 5714 SDValue Src0Lo, Src0Hi; 5715 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5716 5717 EVT LoVT, HiVT; 5718 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 5719 5720 SDValue Chain = MLD->getChain(); 5721 SDValue Ptr = MLD->getBasePtr(); 5722 EVT MemoryVT = MLD->getMemoryVT(); 5723 unsigned Alignment = MLD->getOriginalAlignment(); 5724 5725 // if Alignment is equal to the vector size, 5726 // take the half of it for the second part 5727 unsigned SecondHalfAlignment = 5728 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 5729 Alignment/2 : Alignment; 5730 5731 EVT LoMemVT, HiMemVT; 5732 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5733 5734 MachineMemOperand *MMO = DAG.getMachineFunction(). 5735 getMachineMemOperand(MLD->getPointerInfo(), 5736 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5737 Alignment, MLD->getAAInfo(), MLD->getRanges()); 5738 5739 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 5740 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 5741 5742 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 5743 MLD->isExpandingLoad()); 5744 5745 MMO = DAG.getMachineFunction(). 5746 getMachineMemOperand(MLD->getPointerInfo(), 5747 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5748 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5749 5750 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5751 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 5752 5753 AddToWorklist(Lo.getNode()); 5754 AddToWorklist(Hi.getNode()); 5755 5756 // Build a factor node to remember that this load is independent of the 5757 // other one. 5758 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5759 Hi.getValue(1)); 5760 5761 // Legalized the chain result - switch anything that used the old chain to 5762 // use the new one. 5763 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5764 5765 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5766 5767 SDValue RetOps[] = { LoadRes, Chain }; 5768 return DAG.getMergeValues(RetOps, DL); 5769 } 5770 return SDValue(); 5771 } 5772 5773 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5774 SDValue N0 = N->getOperand(0); 5775 SDValue N1 = N->getOperand(1); 5776 SDValue N2 = N->getOperand(2); 5777 SDLoc DL(N); 5778 5779 // fold (vselect C, X, X) -> X 5780 if (N1 == N2) 5781 return N1; 5782 5783 // Canonicalize integer abs. 5784 // vselect (setg[te] X, 0), X, -X -> 5785 // vselect (setgt X, -1), X, -X -> 5786 // vselect (setl[te] X, 0), -X, X -> 5787 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5788 if (N0.getOpcode() == ISD::SETCC) { 5789 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5790 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5791 bool isAbs = false; 5792 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5793 5794 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5795 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5796 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5797 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5798 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5799 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5800 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5801 5802 if (isAbs) { 5803 EVT VT = LHS.getValueType(); 5804 SDValue Shift = DAG.getNode( 5805 ISD::SRA, DL, VT, LHS, 5806 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT)); 5807 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5808 AddToWorklist(Shift.getNode()); 5809 AddToWorklist(Add.getNode()); 5810 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5811 } 5812 } 5813 5814 if (SimplifySelectOps(N, N1, N2)) 5815 return SDValue(N, 0); // Don't revisit N. 5816 5817 // If the VSELECT result requires splitting and the mask is provided by a 5818 // SETCC, then split both nodes and its operands before legalization. This 5819 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5820 // and enables future optimizations (e.g. min/max pattern matching on X86). 5821 if (N0.getOpcode() == ISD::SETCC) { 5822 EVT VT = N->getValueType(0); 5823 5824 // Check if any splitting is required. 5825 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5826 TargetLowering::TypeSplitVector) 5827 return SDValue(); 5828 5829 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5830 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5831 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5832 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5833 5834 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5835 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5836 5837 // Add the new VSELECT nodes to the work list in case they need to be split 5838 // again. 5839 AddToWorklist(Lo.getNode()); 5840 AddToWorklist(Hi.getNode()); 5841 5842 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5843 } 5844 5845 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5846 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5847 return N1; 5848 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5849 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5850 return N2; 5851 5852 // The ConvertSelectToConcatVector function is assuming both the above 5853 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5854 // and addressed. 5855 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5856 N2.getOpcode() == ISD::CONCAT_VECTORS && 5857 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5858 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 5859 return CV; 5860 } 5861 5862 return SDValue(); 5863 } 5864 5865 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5866 SDValue N0 = N->getOperand(0); 5867 SDValue N1 = N->getOperand(1); 5868 SDValue N2 = N->getOperand(2); 5869 SDValue N3 = N->getOperand(3); 5870 SDValue N4 = N->getOperand(4); 5871 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5872 5873 // fold select_cc lhs, rhs, x, x, cc -> x 5874 if (N2 == N3) 5875 return N2; 5876 5877 // Determine if the condition we're dealing with is constant 5878 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 5879 CC, SDLoc(N), false)) { 5880 AddToWorklist(SCC.getNode()); 5881 5882 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5883 if (!SCCC->isNullValue()) 5884 return N2; // cond always true -> true val 5885 else 5886 return N3; // cond always false -> false val 5887 } else if (SCC->isUndef()) { 5888 // When the condition is UNDEF, just return the first operand. This is 5889 // coherent the DAG creation, no setcc node is created in this case 5890 return N2; 5891 } else if (SCC.getOpcode() == ISD::SETCC) { 5892 // Fold to a simpler select_cc 5893 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5894 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5895 SCC.getOperand(2)); 5896 } 5897 } 5898 5899 // If we can fold this based on the true/false value, do so. 5900 if (SimplifySelectOps(N, N2, N3)) 5901 return SDValue(N, 0); // Don't revisit N. 5902 5903 // fold select_cc into other things, such as min/max/abs 5904 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5905 } 5906 5907 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5908 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5909 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5910 SDLoc(N)); 5911 } 5912 5913 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 5914 SDValue LHS = N->getOperand(0); 5915 SDValue RHS = N->getOperand(1); 5916 SDValue Carry = N->getOperand(2); 5917 SDValue Cond = N->getOperand(3); 5918 5919 // If Carry is false, fold to a regular SETCC. 5920 if (Carry.getOpcode() == ISD::CARRY_FALSE) 5921 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 5922 5923 return SDValue(); 5924 } 5925 5926 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 5927 /// a build_vector of constants. 5928 /// This function is called by the DAGCombiner when visiting sext/zext/aext 5929 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5930 /// Vector extends are not folded if operations are legal; this is to 5931 /// avoid introducing illegal build_vector dag nodes. 5932 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5933 SelectionDAG &DAG, bool LegalTypes, 5934 bool LegalOperations) { 5935 unsigned Opcode = N->getOpcode(); 5936 SDValue N0 = N->getOperand(0); 5937 EVT VT = N->getValueType(0); 5938 5939 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5940 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 5941 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 5942 && "Expected EXTEND dag node in input!"); 5943 5944 // fold (sext c1) -> c1 5945 // fold (zext c1) -> c1 5946 // fold (aext c1) -> c1 5947 if (isa<ConstantSDNode>(N0)) 5948 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5949 5950 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5951 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5952 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5953 EVT SVT = VT.getScalarType(); 5954 if (!(VT.isVector() && 5955 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5956 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5957 return nullptr; 5958 5959 // We can fold this node into a build_vector. 5960 unsigned VTBits = SVT.getSizeInBits(); 5961 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits(); 5962 SmallVector<SDValue, 8> Elts; 5963 unsigned NumElts = VT.getVectorNumElements(); 5964 SDLoc DL(N); 5965 5966 for (unsigned i=0; i != NumElts; ++i) { 5967 SDValue Op = N0->getOperand(i); 5968 if (Op->isUndef()) { 5969 Elts.push_back(DAG.getUNDEF(SVT)); 5970 continue; 5971 } 5972 5973 SDLoc DL(Op); 5974 // Get the constant value and if needed trunc it to the size of the type. 5975 // Nodes like build_vector might have constants wider than the scalar type. 5976 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 5977 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5978 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 5979 else 5980 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 5981 } 5982 5983 return DAG.getBuildVector(VT, DL, Elts).getNode(); 5984 } 5985 5986 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5987 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5988 // transformation. Returns true if extension are possible and the above 5989 // mentioned transformation is profitable. 5990 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5991 unsigned ExtOpc, 5992 SmallVectorImpl<SDNode *> &ExtendNodes, 5993 const TargetLowering &TLI) { 5994 bool HasCopyToRegUses = false; 5995 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5996 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5997 UE = N0.getNode()->use_end(); 5998 UI != UE; ++UI) { 5999 SDNode *User = *UI; 6000 if (User == N) 6001 continue; 6002 if (UI.getUse().getResNo() != N0.getResNo()) 6003 continue; 6004 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 6005 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 6006 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 6007 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 6008 // Sign bits will be lost after a zext. 6009 return false; 6010 bool Add = false; 6011 for (unsigned i = 0; i != 2; ++i) { 6012 SDValue UseOp = User->getOperand(i); 6013 if (UseOp == N0) 6014 continue; 6015 if (!isa<ConstantSDNode>(UseOp)) 6016 return false; 6017 Add = true; 6018 } 6019 if (Add) 6020 ExtendNodes.push_back(User); 6021 continue; 6022 } 6023 // If truncates aren't free and there are users we can't 6024 // extend, it isn't worthwhile. 6025 if (!isTruncFree) 6026 return false; 6027 // Remember if this value is live-out. 6028 if (User->getOpcode() == ISD::CopyToReg) 6029 HasCopyToRegUses = true; 6030 } 6031 6032 if (HasCopyToRegUses) { 6033 bool BothLiveOut = false; 6034 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 6035 UI != UE; ++UI) { 6036 SDUse &Use = UI.getUse(); 6037 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 6038 BothLiveOut = true; 6039 break; 6040 } 6041 } 6042 if (BothLiveOut) 6043 // Both unextended and extended values are live out. There had better be 6044 // a good reason for the transformation. 6045 return ExtendNodes.size(); 6046 } 6047 return true; 6048 } 6049 6050 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 6051 SDValue Trunc, SDValue ExtLoad, 6052 const SDLoc &DL, ISD::NodeType ExtType) { 6053 // Extend SetCC uses if necessary. 6054 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 6055 SDNode *SetCC = SetCCs[i]; 6056 SmallVector<SDValue, 4> Ops; 6057 6058 for (unsigned j = 0; j != 2; ++j) { 6059 SDValue SOp = SetCC->getOperand(j); 6060 if (SOp == Trunc) 6061 Ops.push_back(ExtLoad); 6062 else 6063 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 6064 } 6065 6066 Ops.push_back(SetCC->getOperand(2)); 6067 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 6068 } 6069 } 6070 6071 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 6072 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 6073 SDValue N0 = N->getOperand(0); 6074 EVT DstVT = N->getValueType(0); 6075 EVT SrcVT = N0.getValueType(); 6076 6077 assert((N->getOpcode() == ISD::SIGN_EXTEND || 6078 N->getOpcode() == ISD::ZERO_EXTEND) && 6079 "Unexpected node type (not an extend)!"); 6080 6081 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 6082 // For example, on a target with legal v4i32, but illegal v8i32, turn: 6083 // (v8i32 (sext (v8i16 (load x)))) 6084 // into: 6085 // (v8i32 (concat_vectors (v4i32 (sextload x)), 6086 // (v4i32 (sextload (x + 16))))) 6087 // Where uses of the original load, i.e.: 6088 // (v8i16 (load x)) 6089 // are replaced with: 6090 // (v8i16 (truncate 6091 // (v8i32 (concat_vectors (v4i32 (sextload x)), 6092 // (v4i32 (sextload (x + 16))))))) 6093 // 6094 // This combine is only applicable to illegal, but splittable, vectors. 6095 // All legal types, and illegal non-vector types, are handled elsewhere. 6096 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 6097 // 6098 if (N0->getOpcode() != ISD::LOAD) 6099 return SDValue(); 6100 6101 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6102 6103 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 6104 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 6105 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 6106 return SDValue(); 6107 6108 SmallVector<SDNode *, 4> SetCCs; 6109 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 6110 return SDValue(); 6111 6112 ISD::LoadExtType ExtType = 6113 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 6114 6115 // Try to split the vector types to get down to legal types. 6116 EVT SplitSrcVT = SrcVT; 6117 EVT SplitDstVT = DstVT; 6118 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 6119 SplitSrcVT.getVectorNumElements() > 1) { 6120 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 6121 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 6122 } 6123 6124 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 6125 return SDValue(); 6126 6127 SDLoc DL(N); 6128 const unsigned NumSplits = 6129 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 6130 const unsigned Stride = SplitSrcVT.getStoreSize(); 6131 SmallVector<SDValue, 4> Loads; 6132 SmallVector<SDValue, 4> Chains; 6133 6134 SDValue BasePtr = LN0->getBasePtr(); 6135 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 6136 const unsigned Offset = Idx * Stride; 6137 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 6138 6139 SDValue SplitLoad = DAG.getExtLoad( 6140 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 6141 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 6142 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 6143 6144 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 6145 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 6146 6147 Loads.push_back(SplitLoad.getValue(0)); 6148 Chains.push_back(SplitLoad.getValue(1)); 6149 } 6150 6151 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 6152 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 6153 6154 CombineTo(N, NewValue); 6155 6156 // Replace uses of the original load (before extension) 6157 // with a truncate of the concatenated sextloaded vectors. 6158 SDValue Trunc = 6159 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 6160 CombineTo(N0.getNode(), Trunc, NewChain); 6161 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 6162 (ISD::NodeType)N->getOpcode()); 6163 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6164 } 6165 6166 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 6167 SDValue N0 = N->getOperand(0); 6168 EVT VT = N->getValueType(0); 6169 6170 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6171 LegalOperations)) 6172 return SDValue(Res, 0); 6173 6174 // fold (sext (sext x)) -> (sext x) 6175 // fold (sext (aext x)) -> (sext x) 6176 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6177 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 6178 N0.getOperand(0)); 6179 6180 if (N0.getOpcode() == ISD::TRUNCATE) { 6181 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 6182 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 6183 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6184 SDNode *oye = N0.getOperand(0).getNode(); 6185 if (NarrowLoad.getNode() != N0.getNode()) { 6186 CombineTo(N0.getNode(), NarrowLoad); 6187 // CombineTo deleted the truncate, if needed, but not what's under it. 6188 AddToWorklist(oye); 6189 } 6190 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6191 } 6192 6193 // See if the value being truncated is already sign extended. If so, just 6194 // eliminate the trunc/sext pair. 6195 SDValue Op = N0.getOperand(0); 6196 unsigned OpBits = Op.getScalarValueSizeInBits(); 6197 unsigned MidBits = N0.getScalarValueSizeInBits(); 6198 unsigned DestBits = VT.getScalarSizeInBits(); 6199 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 6200 6201 if (OpBits == DestBits) { 6202 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 6203 // bits, it is already ready. 6204 if (NumSignBits > DestBits-MidBits) 6205 return Op; 6206 } else if (OpBits < DestBits) { 6207 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 6208 // bits, just sext from i32. 6209 if (NumSignBits > OpBits-MidBits) 6210 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 6211 } else { 6212 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 6213 // bits, just truncate to i32. 6214 if (NumSignBits > OpBits-MidBits) 6215 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6216 } 6217 6218 // fold (sext (truncate x)) -> (sextinreg x). 6219 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 6220 N0.getValueType())) { 6221 if (OpBits < DestBits) 6222 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 6223 else if (OpBits > DestBits) 6224 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 6225 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 6226 DAG.getValueType(N0.getValueType())); 6227 } 6228 } 6229 6230 // fold (sext (load x)) -> (sext (truncate (sextload x))) 6231 // Only generate vector extloads when 1) they're legal, and 2) they are 6232 // deemed desirable by the target. 6233 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6234 ((!LegalOperations && !VT.isVector() && 6235 !cast<LoadSDNode>(N0)->isVolatile()) || 6236 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 6237 bool DoXform = true; 6238 SmallVector<SDNode*, 4> SetCCs; 6239 if (!N0.hasOneUse()) 6240 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 6241 if (VT.isVector()) 6242 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6243 if (DoXform) { 6244 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6245 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6246 LN0->getChain(), 6247 LN0->getBasePtr(), N0.getValueType(), 6248 LN0->getMemOperand()); 6249 CombineTo(N, ExtLoad); 6250 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6251 N0.getValueType(), ExtLoad); 6252 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6253 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6254 ISD::SIGN_EXTEND); 6255 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6256 } 6257 } 6258 6259 // fold (sext (load x)) to multiple smaller sextloads. 6260 // Only on illegal but splittable vectors. 6261 if (SDValue ExtLoad = CombineExtLoad(N)) 6262 return ExtLoad; 6263 6264 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 6265 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 6266 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6267 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6268 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6269 EVT MemVT = LN0->getMemoryVT(); 6270 if ((!LegalOperations && !LN0->isVolatile()) || 6271 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 6272 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6273 LN0->getChain(), 6274 LN0->getBasePtr(), MemVT, 6275 LN0->getMemOperand()); 6276 CombineTo(N, ExtLoad); 6277 CombineTo(N0.getNode(), 6278 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6279 N0.getValueType(), ExtLoad), 6280 ExtLoad.getValue(1)); 6281 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6282 } 6283 } 6284 6285 // fold (sext (and/or/xor (load x), cst)) -> 6286 // (and/or/xor (sextload x), (sext cst)) 6287 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6288 N0.getOpcode() == ISD::XOR) && 6289 isa<LoadSDNode>(N0.getOperand(0)) && 6290 N0.getOperand(1).getOpcode() == ISD::Constant && 6291 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 6292 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6293 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6294 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 6295 bool DoXform = true; 6296 SmallVector<SDNode*, 4> SetCCs; 6297 if (!N0.hasOneUse()) 6298 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 6299 SetCCs, TLI); 6300 if (DoXform) { 6301 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 6302 LN0->getChain(), LN0->getBasePtr(), 6303 LN0->getMemoryVT(), 6304 LN0->getMemOperand()); 6305 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6306 Mask = Mask.sext(VT.getSizeInBits()); 6307 SDLoc DL(N); 6308 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6309 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6310 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6311 SDLoc(N0.getOperand(0)), 6312 N0.getOperand(0).getValueType(), ExtLoad); 6313 CombineTo(N, And); 6314 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6315 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6316 ISD::SIGN_EXTEND); 6317 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6318 } 6319 } 6320 } 6321 6322 if (N0.getOpcode() == ISD::SETCC) { 6323 EVT N0VT = N0.getOperand(0).getValueType(); 6324 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 6325 // Only do this before legalize for now. 6326 if (VT.isVector() && !LegalOperations && 6327 TLI.getBooleanContents(N0VT) == 6328 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6329 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 6330 // of the same size as the compared operands. Only optimize sext(setcc()) 6331 // if this is the case. 6332 EVT SVT = getSetCCResultType(N0VT); 6333 6334 // We know that the # elements of the results is the same as the 6335 // # elements of the compare (and the # elements of the compare result 6336 // for that matter). Check to see that they are the same size. If so, 6337 // we know that the element size of the sext'd result matches the 6338 // element size of the compare operands. 6339 if (VT.getSizeInBits() == SVT.getSizeInBits()) 6340 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6341 N0.getOperand(1), 6342 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6343 6344 // If the desired elements are smaller or larger than the source 6345 // elements we can use a matching integer vector type and then 6346 // truncate/sign extend 6347 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6348 if (SVT == MatchingVectorType) { 6349 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 6350 N0.getOperand(0), N0.getOperand(1), 6351 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6352 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 6353 } 6354 } 6355 6356 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 6357 // Here, T can be 1 or -1, depending on the type of the setcc and 6358 // getBooleanContents(). 6359 unsigned SetCCWidth = N0.getScalarValueSizeInBits(); 6360 6361 SDLoc DL(N); 6362 // To determine the "true" side of the select, we need to know the high bit 6363 // of the value returned by the setcc if it evaluates to true. 6364 // If the type of the setcc is i1, then the true case of the select is just 6365 // sext(i1 1), that is, -1. 6366 // If the type of the setcc is larger (say, i8) then the value of the high 6367 // bit depends on getBooleanContents(). So, ask TLI for a real "true" value 6368 // of the appropriate width. 6369 SDValue ExtTrueVal = 6370 (SetCCWidth == 1) 6371 ? DAG.getConstant(APInt::getAllOnesValue(VT.getScalarSizeInBits()), 6372 DL, VT) 6373 : TLI.getConstTrueVal(DAG, VT, DL); 6374 6375 if (SDValue SCC = SimplifySelectCC( 6376 DL, N0.getOperand(0), N0.getOperand(1), ExtTrueVal, 6377 DAG.getConstant(0, DL, VT), 6378 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6379 return SCC; 6380 6381 if (!VT.isVector()) { 6382 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 6383 if (!LegalOperations || 6384 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) { 6385 SDLoc DL(N); 6386 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6387 SDValue SetCC = 6388 DAG.getSetCC(DL, SetCCVT, N0.getOperand(0), N0.getOperand(1), CC); 6389 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, 6390 DAG.getConstant(0, DL, VT)); 6391 } 6392 } 6393 } 6394 6395 // fold (sext x) -> (zext x) if the sign bit is known zero. 6396 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 6397 DAG.SignBitIsZero(N0)) 6398 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 6399 6400 return SDValue(); 6401 } 6402 6403 // isTruncateOf - If N is a truncate of some other value, return true, record 6404 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 6405 // This function computes KnownZero to avoid a duplicated call to 6406 // computeKnownBits in the caller. 6407 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 6408 APInt &KnownZero) { 6409 APInt KnownOne; 6410 if (N->getOpcode() == ISD::TRUNCATE) { 6411 Op = N->getOperand(0); 6412 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6413 return true; 6414 } 6415 6416 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 6417 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 6418 return false; 6419 6420 SDValue Op0 = N->getOperand(0); 6421 SDValue Op1 = N->getOperand(1); 6422 assert(Op0.getValueType() == Op1.getValueType()); 6423 6424 if (isNullConstant(Op0)) 6425 Op = Op1; 6426 else if (isNullConstant(Op1)) 6427 Op = Op0; 6428 else 6429 return false; 6430 6431 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6432 6433 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 6434 return false; 6435 6436 return true; 6437 } 6438 6439 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 6440 SDValue N0 = N->getOperand(0); 6441 EVT VT = N->getValueType(0); 6442 6443 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6444 LegalOperations)) 6445 return SDValue(Res, 0); 6446 6447 // fold (zext (zext x)) -> (zext x) 6448 // fold (zext (aext x)) -> (zext x) 6449 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6450 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 6451 N0.getOperand(0)); 6452 6453 // fold (zext (truncate x)) -> (zext x) or 6454 // (zext (truncate x)) -> (truncate x) 6455 // This is valid when the truncated bits of x are already zero. 6456 // FIXME: We should extend this to work for vectors too. 6457 SDValue Op; 6458 APInt KnownZero; 6459 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 6460 APInt TruncatedBits = 6461 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 6462 APInt(Op.getValueSizeInBits(), 0) : 6463 APInt::getBitsSet(Op.getValueSizeInBits(), 6464 N0.getValueSizeInBits(), 6465 std::min(Op.getValueSizeInBits(), 6466 VT.getSizeInBits())); 6467 if (TruncatedBits == (KnownZero & TruncatedBits)) { 6468 if (VT.bitsGT(Op.getValueType())) 6469 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 6470 if (VT.bitsLT(Op.getValueType())) 6471 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6472 6473 return Op; 6474 } 6475 } 6476 6477 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6478 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 6479 if (N0.getOpcode() == ISD::TRUNCATE) { 6480 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6481 SDNode *oye = N0.getOperand(0).getNode(); 6482 if (NarrowLoad.getNode() != N0.getNode()) { 6483 CombineTo(N0.getNode(), NarrowLoad); 6484 // CombineTo deleted the truncate, if needed, but not what's under it. 6485 AddToWorklist(oye); 6486 } 6487 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6488 } 6489 } 6490 6491 // fold (zext (truncate x)) -> (and x, mask) 6492 if (N0.getOpcode() == ISD::TRUNCATE) { 6493 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6494 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 6495 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6496 SDNode *oye = N0.getOperand(0).getNode(); 6497 if (NarrowLoad.getNode() != N0.getNode()) { 6498 CombineTo(N0.getNode(), NarrowLoad); 6499 // CombineTo deleted the truncate, if needed, but not what's under it. 6500 AddToWorklist(oye); 6501 } 6502 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6503 } 6504 6505 EVT SrcVT = N0.getOperand(0).getValueType(); 6506 EVT MinVT = N0.getValueType(); 6507 6508 // Try to mask before the extension to avoid having to generate a larger mask, 6509 // possibly over several sub-vectors. 6510 if (SrcVT.bitsLT(VT)) { 6511 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 6512 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 6513 SDValue Op = N0.getOperand(0); 6514 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6515 AddToWorklist(Op.getNode()); 6516 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 6517 } 6518 } 6519 6520 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 6521 SDValue Op = N0.getOperand(0); 6522 if (SrcVT.bitsLT(VT)) { 6523 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 6524 AddToWorklist(Op.getNode()); 6525 } else if (SrcVT.bitsGT(VT)) { 6526 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6527 AddToWorklist(Op.getNode()); 6528 } 6529 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6530 } 6531 } 6532 6533 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 6534 // if either of the casts is not free. 6535 if (N0.getOpcode() == ISD::AND && 6536 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6537 N0.getOperand(1).getOpcode() == ISD::Constant && 6538 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6539 N0.getValueType()) || 6540 !TLI.isZExtFree(N0.getValueType(), VT))) { 6541 SDValue X = N0.getOperand(0).getOperand(0); 6542 if (X.getValueType().bitsLT(VT)) { 6543 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 6544 } else if (X.getValueType().bitsGT(VT)) { 6545 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6546 } 6547 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6548 Mask = Mask.zext(VT.getSizeInBits()); 6549 SDLoc DL(N); 6550 return DAG.getNode(ISD::AND, DL, VT, 6551 X, DAG.getConstant(Mask, DL, VT)); 6552 } 6553 6554 // fold (zext (load x)) -> (zext (truncate (zextload x))) 6555 // Only generate vector extloads when 1) they're legal, and 2) they are 6556 // deemed desirable by the target. 6557 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6558 ((!LegalOperations && !VT.isVector() && 6559 !cast<LoadSDNode>(N0)->isVolatile()) || 6560 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 6561 bool DoXform = true; 6562 SmallVector<SDNode*, 4> SetCCs; 6563 if (!N0.hasOneUse()) 6564 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 6565 if (VT.isVector()) 6566 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6567 if (DoXform) { 6568 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6569 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6570 LN0->getChain(), 6571 LN0->getBasePtr(), N0.getValueType(), 6572 LN0->getMemOperand()); 6573 CombineTo(N, ExtLoad); 6574 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6575 N0.getValueType(), ExtLoad); 6576 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6577 6578 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6579 ISD::ZERO_EXTEND); 6580 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6581 } 6582 } 6583 6584 // fold (zext (load x)) to multiple smaller zextloads. 6585 // Only on illegal but splittable vectors. 6586 if (SDValue ExtLoad = CombineExtLoad(N)) 6587 return ExtLoad; 6588 6589 // fold (zext (and/or/xor (load x), cst)) -> 6590 // (and/or/xor (zextload x), (zext cst)) 6591 // Unless (and (load x) cst) will match as a zextload already and has 6592 // additional users. 6593 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6594 N0.getOpcode() == ISD::XOR) && 6595 isa<LoadSDNode>(N0.getOperand(0)) && 6596 N0.getOperand(1).getOpcode() == ISD::Constant && 6597 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 6598 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6599 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6600 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 6601 bool DoXform = true; 6602 SmallVector<SDNode*, 4> SetCCs; 6603 if (!N0.hasOneUse()) { 6604 if (N0.getOpcode() == ISD::AND) { 6605 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 6606 auto NarrowLoad = false; 6607 EVT LoadResultTy = AndC->getValueType(0); 6608 EVT ExtVT, LoadedVT; 6609 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT, 6610 NarrowLoad)) 6611 DoXform = false; 6612 } 6613 if (DoXform) 6614 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 6615 ISD::ZERO_EXTEND, SetCCs, TLI); 6616 } 6617 if (DoXform) { 6618 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 6619 LN0->getChain(), LN0->getBasePtr(), 6620 LN0->getMemoryVT(), 6621 LN0->getMemOperand()); 6622 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6623 Mask = Mask.zext(VT.getSizeInBits()); 6624 SDLoc DL(N); 6625 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6626 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6627 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6628 SDLoc(N0.getOperand(0)), 6629 N0.getOperand(0).getValueType(), ExtLoad); 6630 CombineTo(N, And); 6631 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6632 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6633 ISD::ZERO_EXTEND); 6634 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6635 } 6636 } 6637 } 6638 6639 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 6640 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 6641 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6642 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6643 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6644 EVT MemVT = LN0->getMemoryVT(); 6645 if ((!LegalOperations && !LN0->isVolatile()) || 6646 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 6647 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6648 LN0->getChain(), 6649 LN0->getBasePtr(), MemVT, 6650 LN0->getMemOperand()); 6651 CombineTo(N, ExtLoad); 6652 CombineTo(N0.getNode(), 6653 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 6654 ExtLoad), 6655 ExtLoad.getValue(1)); 6656 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6657 } 6658 } 6659 6660 if (N0.getOpcode() == ISD::SETCC) { 6661 // Only do this before legalize for now. 6662 if (!LegalOperations && VT.isVector() && 6663 N0.getValueType().getVectorElementType() == MVT::i1) { 6664 EVT N00VT = N0.getOperand(0).getValueType(); 6665 if (getSetCCResultType(N00VT) == N0.getValueType()) 6666 return SDValue(); 6667 6668 // We know that the # elements of the results is the same as the # 6669 // elements of the compare (and the # elements of the compare result for 6670 // that matter). Check to see that they are the same size. If so, we know 6671 // that the element size of the sext'd result matches the element size of 6672 // the compare operands. 6673 SDLoc DL(N); 6674 SDValue VecOnes = DAG.getConstant(1, DL, VT); 6675 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 6676 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 6677 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 6678 N0.getOperand(1), N0.getOperand(2)); 6679 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes); 6680 } 6681 6682 // If the desired elements are smaller or larger than the source 6683 // elements we can use a matching integer vector type and then 6684 // truncate/sign extend. 6685 EVT MatchingElementType = EVT::getIntegerVT( 6686 *DAG.getContext(), N00VT.getScalarSizeInBits()); 6687 EVT MatchingVectorType = EVT::getVectorVT( 6688 *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements()); 6689 SDValue VsetCC = 6690 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 6691 N0.getOperand(1), N0.getOperand(2)); 6692 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT), 6693 VecOnes); 6694 } 6695 6696 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6697 SDLoc DL(N); 6698 if (SDValue SCC = SimplifySelectCC( 6699 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 6700 DAG.getConstant(0, DL, VT), 6701 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6702 return SCC; 6703 } 6704 6705 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 6706 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 6707 isa<ConstantSDNode>(N0.getOperand(1)) && 6708 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 6709 N0.hasOneUse()) { 6710 SDValue ShAmt = N0.getOperand(1); 6711 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 6712 if (N0.getOpcode() == ISD::SHL) { 6713 SDValue InnerZExt = N0.getOperand(0); 6714 // If the original shl may be shifting out bits, do not perform this 6715 // transformation. 6716 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() - 6717 InnerZExt.getOperand(0).getValueSizeInBits(); 6718 if (ShAmtVal > KnownZeroBits) 6719 return SDValue(); 6720 } 6721 6722 SDLoc DL(N); 6723 6724 // Ensure that the shift amount is wide enough for the shifted value. 6725 if (VT.getSizeInBits() >= 256) 6726 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 6727 6728 return DAG.getNode(N0.getOpcode(), DL, VT, 6729 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 6730 ShAmt); 6731 } 6732 6733 return SDValue(); 6734 } 6735 6736 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 6737 SDValue N0 = N->getOperand(0); 6738 EVT VT = N->getValueType(0); 6739 6740 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6741 LegalOperations)) 6742 return SDValue(Res, 0); 6743 6744 // fold (aext (aext x)) -> (aext x) 6745 // fold (aext (zext x)) -> (zext x) 6746 // fold (aext (sext x)) -> (sext x) 6747 if (N0.getOpcode() == ISD::ANY_EXTEND || 6748 N0.getOpcode() == ISD::ZERO_EXTEND || 6749 N0.getOpcode() == ISD::SIGN_EXTEND) 6750 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 6751 6752 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 6753 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 6754 if (N0.getOpcode() == ISD::TRUNCATE) { 6755 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6756 SDNode *oye = N0.getOperand(0).getNode(); 6757 if (NarrowLoad.getNode() != N0.getNode()) { 6758 CombineTo(N0.getNode(), NarrowLoad); 6759 // CombineTo deleted the truncate, if needed, but not what's under it. 6760 AddToWorklist(oye); 6761 } 6762 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6763 } 6764 } 6765 6766 // fold (aext (truncate x)) 6767 if (N0.getOpcode() == ISD::TRUNCATE) { 6768 SDValue TruncOp = N0.getOperand(0); 6769 if (TruncOp.getValueType() == VT) 6770 return TruncOp; // x iff x size == zext size. 6771 if (TruncOp.getValueType().bitsGT(VT)) 6772 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 6773 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 6774 } 6775 6776 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 6777 // if the trunc is not free. 6778 if (N0.getOpcode() == ISD::AND && 6779 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6780 N0.getOperand(1).getOpcode() == ISD::Constant && 6781 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6782 N0.getValueType())) { 6783 SDLoc DL(N); 6784 SDValue X = N0.getOperand(0).getOperand(0); 6785 if (X.getValueType().bitsLT(VT)) { 6786 X = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X); 6787 } else if (X.getValueType().bitsGT(VT)) { 6788 X = DAG.getNode(ISD::TRUNCATE, DL, VT, X); 6789 } 6790 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6791 Mask = Mask.zext(VT.getSizeInBits()); 6792 return DAG.getNode(ISD::AND, DL, VT, 6793 X, DAG.getConstant(Mask, DL, VT)); 6794 } 6795 6796 // fold (aext (load x)) -> (aext (truncate (extload x))) 6797 // None of the supported targets knows how to perform load and any_ext 6798 // on vectors in one instruction. We only perform this transformation on 6799 // scalars. 6800 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 6801 ISD::isUNINDEXEDLoad(N0.getNode()) && 6802 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 6803 bool DoXform = true; 6804 SmallVector<SDNode*, 4> SetCCs; 6805 if (!N0.hasOneUse()) 6806 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 6807 if (DoXform) { 6808 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6809 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6810 LN0->getChain(), 6811 LN0->getBasePtr(), N0.getValueType(), 6812 LN0->getMemOperand()); 6813 CombineTo(N, ExtLoad); 6814 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6815 N0.getValueType(), ExtLoad); 6816 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6817 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6818 ISD::ANY_EXTEND); 6819 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6820 } 6821 } 6822 6823 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 6824 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 6825 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 6826 if (N0.getOpcode() == ISD::LOAD && 6827 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6828 N0.hasOneUse()) { 6829 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6830 ISD::LoadExtType ExtType = LN0->getExtensionType(); 6831 EVT MemVT = LN0->getMemoryVT(); 6832 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 6833 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 6834 VT, LN0->getChain(), LN0->getBasePtr(), 6835 MemVT, LN0->getMemOperand()); 6836 CombineTo(N, ExtLoad); 6837 CombineTo(N0.getNode(), 6838 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6839 N0.getValueType(), ExtLoad), 6840 ExtLoad.getValue(1)); 6841 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6842 } 6843 } 6844 6845 if (N0.getOpcode() == ISD::SETCC) { 6846 // For vectors: 6847 // aext(setcc) -> vsetcc 6848 // aext(setcc) -> truncate(vsetcc) 6849 // aext(setcc) -> aext(vsetcc) 6850 // Only do this before legalize for now. 6851 if (VT.isVector() && !LegalOperations) { 6852 EVT N0VT = N0.getOperand(0).getValueType(); 6853 // We know that the # elements of the results is the same as the 6854 // # elements of the compare (and the # elements of the compare result 6855 // for that matter). Check to see that they are the same size. If so, 6856 // we know that the element size of the sext'd result matches the 6857 // element size of the compare operands. 6858 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6859 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6860 N0.getOperand(1), 6861 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6862 // If the desired elements are smaller or larger than the source 6863 // elements we can use a matching integer vector type and then 6864 // truncate/any extend 6865 else { 6866 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6867 SDValue VsetCC = 6868 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6869 N0.getOperand(1), 6870 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6871 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 6872 } 6873 } 6874 6875 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6876 SDLoc DL(N); 6877 if (SDValue SCC = SimplifySelectCC( 6878 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 6879 DAG.getConstant(0, DL, VT), 6880 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6881 return SCC; 6882 } 6883 6884 return SDValue(); 6885 } 6886 6887 /// See if the specified operand can be simplified with the knowledge that only 6888 /// the bits specified by Mask are used. If so, return the simpler operand, 6889 /// otherwise return a null SDValue. 6890 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 6891 switch (V.getOpcode()) { 6892 default: break; 6893 case ISD::Constant: { 6894 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 6895 assert(CV && "Const value should be ConstSDNode."); 6896 const APInt &CVal = CV->getAPIntValue(); 6897 APInt NewVal = CVal & Mask; 6898 if (NewVal != CVal) 6899 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 6900 break; 6901 } 6902 case ISD::OR: 6903 case ISD::XOR: 6904 // If the LHS or RHS don't contribute bits to the or, drop them. 6905 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6906 return V.getOperand(1); 6907 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6908 return V.getOperand(0); 6909 break; 6910 case ISD::SRL: 6911 // Only look at single-use SRLs. 6912 if (!V.getNode()->hasOneUse()) 6913 break; 6914 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 6915 // See if we can recursively simplify the LHS. 6916 unsigned Amt = RHSC->getZExtValue(); 6917 6918 // Watch out for shift count overflow though. 6919 if (Amt >= Mask.getBitWidth()) break; 6920 APInt NewMask = Mask << Amt; 6921 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 6922 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6923 SimplifyLHS, V.getOperand(1)); 6924 } 6925 } 6926 return SDValue(); 6927 } 6928 6929 /// If the result of a wider load is shifted to right of N bits and then 6930 /// truncated to a narrower type and where N is a multiple of number of bits of 6931 /// the narrower type, transform it to a narrower load from address + N / num of 6932 /// bits of new type. If the result is to be extended, also fold the extension 6933 /// to form a extending load. 6934 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6935 unsigned Opc = N->getOpcode(); 6936 6937 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6938 SDValue N0 = N->getOperand(0); 6939 EVT VT = N->getValueType(0); 6940 EVT ExtVT = VT; 6941 6942 // This transformation isn't valid for vector loads. 6943 if (VT.isVector()) 6944 return SDValue(); 6945 6946 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6947 // extended to VT. 6948 if (Opc == ISD::SIGN_EXTEND_INREG) { 6949 ExtType = ISD::SEXTLOAD; 6950 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6951 } else if (Opc == ISD::SRL) { 6952 // Another special-case: SRL is basically zero-extending a narrower value. 6953 ExtType = ISD::ZEXTLOAD; 6954 N0 = SDValue(N, 0); 6955 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6956 if (!N01) return SDValue(); 6957 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6958 VT.getSizeInBits() - N01->getZExtValue()); 6959 } 6960 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6961 return SDValue(); 6962 6963 unsigned EVTBits = ExtVT.getSizeInBits(); 6964 6965 // Do not generate loads of non-round integer types since these can 6966 // be expensive (and would be wrong if the type is not byte sized). 6967 if (!ExtVT.isRound()) 6968 return SDValue(); 6969 6970 unsigned ShAmt = 0; 6971 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6972 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6973 ShAmt = N01->getZExtValue(); 6974 // Is the shift amount a multiple of size of VT? 6975 if ((ShAmt & (EVTBits-1)) == 0) { 6976 N0 = N0.getOperand(0); 6977 // Is the load width a multiple of size of VT? 6978 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0) 6979 return SDValue(); 6980 } 6981 6982 // At this point, we must have a load or else we can't do the transform. 6983 if (!isa<LoadSDNode>(N0)) return SDValue(); 6984 6985 // Because a SRL must be assumed to *need* to zero-extend the high bits 6986 // (as opposed to anyext the high bits), we can't combine the zextload 6987 // lowering of SRL and an sextload. 6988 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6989 return SDValue(); 6990 6991 // If the shift amount is larger than the input type then we're not 6992 // accessing any of the loaded bytes. If the load was a zextload/extload 6993 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6994 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6995 return SDValue(); 6996 } 6997 } 6998 6999 // If the load is shifted left (and the result isn't shifted back right), 7000 // we can fold the truncate through the shift. 7001 unsigned ShLeftAmt = 0; 7002 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 7003 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 7004 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 7005 ShLeftAmt = N01->getZExtValue(); 7006 N0 = N0.getOperand(0); 7007 } 7008 } 7009 7010 // If we haven't found a load, we can't narrow it. Don't transform one with 7011 // multiple uses, this would require adding a new load. 7012 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 7013 return SDValue(); 7014 7015 // Don't change the width of a volatile load. 7016 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7017 if (LN0->isVolatile()) 7018 return SDValue(); 7019 7020 // Verify that we are actually reducing a load width here. 7021 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 7022 return SDValue(); 7023 7024 // For the transform to be legal, the load must produce only two values 7025 // (the value loaded and the chain). Don't transform a pre-increment 7026 // load, for example, which produces an extra value. Otherwise the 7027 // transformation is not equivalent, and the downstream logic to replace 7028 // uses gets things wrong. 7029 if (LN0->getNumValues() > 2) 7030 return SDValue(); 7031 7032 // If the load that we're shrinking is an extload and we're not just 7033 // discarding the extension we can't simply shrink the load. Bail. 7034 // TODO: It would be possible to merge the extensions in some cases. 7035 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 7036 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 7037 return SDValue(); 7038 7039 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 7040 return SDValue(); 7041 7042 EVT PtrType = N0.getOperand(1).getValueType(); 7043 7044 if (PtrType == MVT::Untyped || PtrType.isExtended()) 7045 // It's not possible to generate a constant of extended or untyped type. 7046 return SDValue(); 7047 7048 // For big endian targets, we need to adjust the offset to the pointer to 7049 // load the correct bytes. 7050 if (DAG.getDataLayout().isBigEndian()) { 7051 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 7052 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 7053 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 7054 } 7055 7056 uint64_t PtrOff = ShAmt / 8; 7057 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 7058 SDLoc DL(LN0); 7059 // The original load itself didn't wrap, so an offset within it doesn't. 7060 SDNodeFlags Flags; 7061 Flags.setNoUnsignedWrap(true); 7062 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 7063 PtrType, LN0->getBasePtr(), 7064 DAG.getConstant(PtrOff, DL, PtrType), 7065 &Flags); 7066 AddToWorklist(NewPtr.getNode()); 7067 7068 SDValue Load; 7069 if (ExtType == ISD::NON_EXTLOAD) 7070 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 7071 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 7072 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 7073 else 7074 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr, 7075 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 7076 NewAlign, LN0->getMemOperand()->getFlags(), 7077 LN0->getAAInfo()); 7078 7079 // Replace the old load's chain with the new load's chain. 7080 WorklistRemover DeadNodes(*this); 7081 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7082 7083 // Shift the result left, if we've swallowed a left shift. 7084 SDValue Result = Load; 7085 if (ShLeftAmt != 0) { 7086 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 7087 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 7088 ShImmTy = VT; 7089 // If the shift amount is as large as the result size (but, presumably, 7090 // no larger than the source) then the useful bits of the result are 7091 // zero; we can't simply return the shortened shift, because the result 7092 // of that operation is undefined. 7093 SDLoc DL(N0); 7094 if (ShLeftAmt >= VT.getSizeInBits()) 7095 Result = DAG.getConstant(0, DL, VT); 7096 else 7097 Result = DAG.getNode(ISD::SHL, DL, VT, 7098 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 7099 } 7100 7101 // Return the new loaded value. 7102 return Result; 7103 } 7104 7105 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 7106 SDValue N0 = N->getOperand(0); 7107 SDValue N1 = N->getOperand(1); 7108 EVT VT = N->getValueType(0); 7109 EVT EVT = cast<VTSDNode>(N1)->getVT(); 7110 unsigned VTBits = VT.getScalarSizeInBits(); 7111 unsigned EVTBits = EVT.getScalarSizeInBits(); 7112 7113 if (N0.isUndef()) 7114 return DAG.getUNDEF(VT); 7115 7116 // fold (sext_in_reg c1) -> c1 7117 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7118 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 7119 7120 // If the input is already sign extended, just drop the extension. 7121 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 7122 return N0; 7123 7124 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 7125 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 7126 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 7127 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 7128 N0.getOperand(0), N1); 7129 7130 // fold (sext_in_reg (sext x)) -> (sext x) 7131 // fold (sext_in_reg (aext x)) -> (sext x) 7132 // if x is small enough. 7133 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 7134 SDValue N00 = N0.getOperand(0); 7135 if (N00.getScalarValueSizeInBits() <= EVTBits && 7136 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 7137 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 7138 } 7139 7140 // fold (sext_in_reg (zext x)) -> (sext x) 7141 // iff we are extending the source sign bit. 7142 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 7143 SDValue N00 = N0.getOperand(0); 7144 if (N00.getScalarValueSizeInBits() == EVTBits && 7145 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 7146 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 7147 } 7148 7149 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 7150 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 7151 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType()); 7152 7153 // fold operands of sext_in_reg based on knowledge that the top bits are not 7154 // demanded. 7155 if (SimplifyDemandedBits(SDValue(N, 0))) 7156 return SDValue(N, 0); 7157 7158 // fold (sext_in_reg (load x)) -> (smaller sextload x) 7159 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 7160 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 7161 return NarrowLoad; 7162 7163 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 7164 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 7165 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 7166 if (N0.getOpcode() == ISD::SRL) { 7167 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 7168 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 7169 // We can turn this into an SRA iff the input to the SRL is already sign 7170 // extended enough. 7171 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 7172 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 7173 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 7174 N0.getOperand(0), N0.getOperand(1)); 7175 } 7176 } 7177 7178 // fold (sext_inreg (extload x)) -> (sextload x) 7179 if (ISD::isEXTLoad(N0.getNode()) && 7180 ISD::isUNINDEXEDLoad(N0.getNode()) && 7181 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 7182 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7183 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 7184 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7185 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 7186 LN0->getChain(), 7187 LN0->getBasePtr(), EVT, 7188 LN0->getMemOperand()); 7189 CombineTo(N, ExtLoad); 7190 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 7191 AddToWorklist(ExtLoad.getNode()); 7192 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7193 } 7194 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 7195 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7196 N0.hasOneUse() && 7197 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 7198 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7199 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 7200 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7201 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 7202 LN0->getChain(), 7203 LN0->getBasePtr(), EVT, 7204 LN0->getMemOperand()); 7205 CombineTo(N, ExtLoad); 7206 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 7207 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7208 } 7209 7210 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 7211 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 7212 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 7213 N0.getOperand(1), false)) 7214 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 7215 BSwap, N1); 7216 } 7217 7218 return SDValue(); 7219 } 7220 7221 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 7222 SDValue N0 = N->getOperand(0); 7223 EVT VT = N->getValueType(0); 7224 7225 if (N0.isUndef()) 7226 return DAG.getUNDEF(VT); 7227 7228 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7229 LegalOperations)) 7230 return SDValue(Res, 0); 7231 7232 return SDValue(); 7233 } 7234 7235 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 7236 SDValue N0 = N->getOperand(0); 7237 EVT VT = N->getValueType(0); 7238 7239 if (N0.isUndef()) 7240 return DAG.getUNDEF(VT); 7241 7242 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7243 LegalOperations)) 7244 return SDValue(Res, 0); 7245 7246 return SDValue(); 7247 } 7248 7249 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 7250 SDValue N0 = N->getOperand(0); 7251 EVT VT = N->getValueType(0); 7252 bool isLE = DAG.getDataLayout().isLittleEndian(); 7253 7254 // noop truncate 7255 if (N0.getValueType() == N->getValueType(0)) 7256 return N0; 7257 // fold (truncate c1) -> c1 7258 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7259 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 7260 // fold (truncate (truncate x)) -> (truncate x) 7261 if (N0.getOpcode() == ISD::TRUNCATE) 7262 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7263 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 7264 if (N0.getOpcode() == ISD::ZERO_EXTEND || 7265 N0.getOpcode() == ISD::SIGN_EXTEND || 7266 N0.getOpcode() == ISD::ANY_EXTEND) { 7267 // if the source is smaller than the dest, we still need an extend. 7268 if (N0.getOperand(0).getValueType().bitsLT(VT)) 7269 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7270 // if the source is larger than the dest, than we just need the truncate. 7271 if (N0.getOperand(0).getValueType().bitsGT(VT)) 7272 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7273 // if the source and dest are the same type, we can drop both the extend 7274 // and the truncate. 7275 return N0.getOperand(0); 7276 } 7277 7278 // If this is anyext(trunc), don't fold it, allow ourselves to be folded. 7279 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND)) 7280 return SDValue(); 7281 7282 // Fold extract-and-trunc into a narrow extract. For example: 7283 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 7284 // i32 y = TRUNCATE(i64 x) 7285 // -- becomes -- 7286 // v16i8 b = BITCAST (v2i64 val) 7287 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 7288 // 7289 // Note: We only run this optimization after type legalization (which often 7290 // creates this pattern) and before operation legalization after which 7291 // we need to be more careful about the vector instructions that we generate. 7292 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7293 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 7294 7295 EVT VecTy = N0.getOperand(0).getValueType(); 7296 EVT ExTy = N0.getValueType(); 7297 EVT TrTy = N->getValueType(0); 7298 7299 unsigned NumElem = VecTy.getVectorNumElements(); 7300 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 7301 7302 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 7303 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 7304 7305 SDValue EltNo = N0->getOperand(1); 7306 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 7307 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7308 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7309 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 7310 7311 SDLoc DL(N); 7312 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 7313 DAG.getBitcast(NVT, N0.getOperand(0)), 7314 DAG.getConstant(Index, DL, IndexTy)); 7315 } 7316 } 7317 7318 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 7319 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) { 7320 EVT SrcVT = N0.getValueType(); 7321 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 7322 TLI.isTruncateFree(SrcVT, VT)) { 7323 SDLoc SL(N0); 7324 SDValue Cond = N0.getOperand(0); 7325 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 7326 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 7327 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 7328 } 7329 } 7330 7331 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits() 7332 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 7333 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 7334 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 7335 if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) { 7336 uint64_t Amt = CAmt->getZExtValue(); 7337 unsigned Size = VT.getScalarSizeInBits(); 7338 7339 if (Amt < Size) { 7340 SDLoc SL(N); 7341 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 7342 7343 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 7344 return DAG.getNode(ISD::SHL, SL, VT, Trunc, 7345 DAG.getConstant(Amt, SL, AmtVT)); 7346 } 7347 } 7348 } 7349 7350 // Fold a series of buildvector, bitcast, and truncate if possible. 7351 // For example fold 7352 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 7353 // (2xi32 (buildvector x, y)). 7354 if (Level == AfterLegalizeVectorOps && VT.isVector() && 7355 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 7356 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 7357 N0.getOperand(0).hasOneUse()) { 7358 7359 SDValue BuildVect = N0.getOperand(0); 7360 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 7361 EVT TruncVecEltTy = VT.getVectorElementType(); 7362 7363 // Check that the element types match. 7364 if (BuildVectEltTy == TruncVecEltTy) { 7365 // Now we only need to compute the offset of the truncated elements. 7366 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 7367 unsigned TruncVecNumElts = VT.getVectorNumElements(); 7368 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 7369 7370 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 7371 "Invalid number of elements"); 7372 7373 SmallVector<SDValue, 8> Opnds; 7374 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 7375 Opnds.push_back(BuildVect.getOperand(i)); 7376 7377 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 7378 } 7379 } 7380 7381 // See if we can simplify the input to this truncate through knowledge that 7382 // only the low bits are being used. 7383 // For example "trunc (or (shl x, 8), y)" // -> trunc y 7384 // Currently we only perform this optimization on scalars because vectors 7385 // may have different active low bits. 7386 if (!VT.isVector()) { 7387 if (SDValue Shorter = 7388 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 7389 VT.getSizeInBits()))) 7390 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 7391 } 7392 // fold (truncate (load x)) -> (smaller load x) 7393 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 7394 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 7395 if (SDValue Reduced = ReduceLoadWidth(N)) 7396 return Reduced; 7397 7398 // Handle the case where the load remains an extending load even 7399 // after truncation. 7400 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 7401 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7402 if (!LN0->isVolatile() && 7403 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 7404 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 7405 VT, LN0->getChain(), LN0->getBasePtr(), 7406 LN0->getMemoryVT(), 7407 LN0->getMemOperand()); 7408 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 7409 return NewLoad; 7410 } 7411 } 7412 } 7413 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 7414 // where ... are all 'undef'. 7415 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 7416 SmallVector<EVT, 8> VTs; 7417 SDValue V; 7418 unsigned Idx = 0; 7419 unsigned NumDefs = 0; 7420 7421 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 7422 SDValue X = N0.getOperand(i); 7423 if (!X.isUndef()) { 7424 V = X; 7425 Idx = i; 7426 NumDefs++; 7427 } 7428 // Stop if more than one members are non-undef. 7429 if (NumDefs > 1) 7430 break; 7431 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 7432 VT.getVectorElementType(), 7433 X.getValueType().getVectorNumElements())); 7434 } 7435 7436 if (NumDefs == 0) 7437 return DAG.getUNDEF(VT); 7438 7439 if (NumDefs == 1) { 7440 assert(V.getNode() && "The single defined operand is empty!"); 7441 SmallVector<SDValue, 8> Opnds; 7442 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 7443 if (i != Idx) { 7444 Opnds.push_back(DAG.getUNDEF(VTs[i])); 7445 continue; 7446 } 7447 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 7448 AddToWorklist(NV.getNode()); 7449 Opnds.push_back(NV); 7450 } 7451 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 7452 } 7453 } 7454 7455 // Fold truncate of a bitcast of a vector to an extract of the low vector 7456 // element. 7457 // 7458 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0 7459 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 7460 SDValue VecSrc = N0.getOperand(0); 7461 EVT SrcVT = VecSrc.getValueType(); 7462 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 7463 (!LegalOperations || 7464 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 7465 SDLoc SL(N); 7466 7467 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 7468 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 7469 VecSrc, DAG.getConstant(0, SL, IdxVT)); 7470 } 7471 } 7472 7473 // Simplify the operands using demanded-bits information. 7474 if (!VT.isVector() && 7475 SimplifyDemandedBits(SDValue(N, 0))) 7476 return SDValue(N, 0); 7477 7478 return SDValue(); 7479 } 7480 7481 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 7482 SDValue Elt = N->getOperand(i); 7483 if (Elt.getOpcode() != ISD::MERGE_VALUES) 7484 return Elt.getNode(); 7485 return Elt.getOperand(Elt.getResNo()).getNode(); 7486 } 7487 7488 /// build_pair (load, load) -> load 7489 /// if load locations are consecutive. 7490 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 7491 assert(N->getOpcode() == ISD::BUILD_PAIR); 7492 7493 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 7494 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 7495 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 7496 LD1->getAddressSpace() != LD2->getAddressSpace()) 7497 return SDValue(); 7498 EVT LD1VT = LD1->getValueType(0); 7499 unsigned LD1Bytes = LD1VT.getSizeInBits() / 8; 7500 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 7501 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 7502 unsigned Align = LD1->getAlignment(); 7503 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 7504 VT.getTypeForEVT(*DAG.getContext())); 7505 7506 if (NewAlign <= Align && 7507 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 7508 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 7509 LD1->getPointerInfo(), Align); 7510 } 7511 7512 return SDValue(); 7513 } 7514 7515 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 7516 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 7517 // and Lo parts; on big-endian machines it doesn't. 7518 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 7519 } 7520 7521 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 7522 const TargetLowering &TLI) { 7523 // If this is not a bitcast to an FP type or if the target doesn't have 7524 // IEEE754-compliant FP logic, we're done. 7525 EVT VT = N->getValueType(0); 7526 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 7527 return SDValue(); 7528 7529 // TODO: Use splat values for the constant-checking below and remove this 7530 // restriction. 7531 SDValue N0 = N->getOperand(0); 7532 EVT SourceVT = N0.getValueType(); 7533 if (SourceVT.isVector()) 7534 return SDValue(); 7535 7536 unsigned FPOpcode; 7537 APInt SignMask; 7538 switch (N0.getOpcode()) { 7539 case ISD::AND: 7540 FPOpcode = ISD::FABS; 7541 SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits()); 7542 break; 7543 case ISD::XOR: 7544 FPOpcode = ISD::FNEG; 7545 SignMask = APInt::getSignBit(SourceVT.getSizeInBits()); 7546 break; 7547 // TODO: ISD::OR --> ISD::FNABS? 7548 default: 7549 return SDValue(); 7550 } 7551 7552 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 7553 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 7554 SDValue LogicOp0 = N0.getOperand(0); 7555 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7556 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 7557 LogicOp0.getOpcode() == ISD::BITCAST && 7558 LogicOp0->getOperand(0).getValueType() == VT) 7559 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0)); 7560 7561 return SDValue(); 7562 } 7563 7564 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 7565 SDValue N0 = N->getOperand(0); 7566 EVT VT = N->getValueType(0); 7567 7568 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 7569 // Only do this before legalize, since afterward the target may be depending 7570 // on the bitconvert. 7571 // First check to see if this is all constant. 7572 if (!LegalTypes && 7573 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 7574 VT.isVector()) { 7575 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 7576 7577 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 7578 assert(!DestEltVT.isVector() && 7579 "Element type of vector ValueType must not be vector!"); 7580 if (isSimple) 7581 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 7582 } 7583 7584 // If the input is a constant, let getNode fold it. 7585 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 7586 // If we can't allow illegal operations, we need to check that this is just 7587 // a fp -> int or int -> conversion and that the resulting operation will 7588 // be legal. 7589 if (!LegalOperations || 7590 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 7591 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 7592 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 7593 TLI.isOperationLegal(ISD::Constant, VT))) 7594 return DAG.getBitcast(VT, N0); 7595 } 7596 7597 // (conv (conv x, t1), t2) -> (conv x, t2) 7598 if (N0.getOpcode() == ISD::BITCAST) 7599 return DAG.getBitcast(VT, N0.getOperand(0)); 7600 7601 // fold (conv (load x)) -> (load (conv*)x) 7602 // If the resultant load doesn't need a higher alignment than the original! 7603 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7604 // Do not change the width of a volatile load. 7605 !cast<LoadSDNode>(N0)->isVolatile() && 7606 // Do not remove the cast if the types differ in endian layout. 7607 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 7608 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 7609 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 7610 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 7611 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7612 unsigned OrigAlign = LN0->getAlignment(); 7613 7614 bool Fast = false; 7615 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 7616 LN0->getAddressSpace(), OrigAlign, &Fast) && 7617 Fast) { 7618 SDValue Load = 7619 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 7620 LN0->getPointerInfo(), OrigAlign, 7621 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 7622 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7623 return Load; 7624 } 7625 } 7626 7627 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 7628 return V; 7629 7630 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7631 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7632 // 7633 // For ppc_fp128: 7634 // fold (bitcast (fneg x)) -> 7635 // flipbit = signbit 7636 // (xor (bitcast x) (build_pair flipbit, flipbit)) 7637 // 7638 // fold (bitcast (fabs x)) -> 7639 // flipbit = (and (extract_element (bitcast x), 0), signbit) 7640 // (xor (bitcast x) (build_pair flipbit, flipbit)) 7641 // This often reduces constant pool loads. 7642 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 7643 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 7644 N0.getNode()->hasOneUse() && VT.isInteger() && 7645 !VT.isVector() && !N0.getValueType().isVector()) { 7646 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 7647 AddToWorklist(NewConv.getNode()); 7648 7649 SDLoc DL(N); 7650 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 7651 assert(VT.getSizeInBits() == 128); 7652 SDValue SignBit = DAG.getConstant( 7653 APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 7654 SDValue FlipBit; 7655 if (N0.getOpcode() == ISD::FNEG) { 7656 FlipBit = SignBit; 7657 AddToWorklist(FlipBit.getNode()); 7658 } else { 7659 assert(N0.getOpcode() == ISD::FABS); 7660 SDValue Hi = 7661 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 7662 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 7663 SDLoc(NewConv))); 7664 AddToWorklist(Hi.getNode()); 7665 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 7666 AddToWorklist(FlipBit.getNode()); 7667 } 7668 SDValue FlipBits = 7669 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 7670 AddToWorklist(FlipBits.getNode()); 7671 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 7672 } 7673 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7674 if (N0.getOpcode() == ISD::FNEG) 7675 return DAG.getNode(ISD::XOR, DL, VT, 7676 NewConv, DAG.getConstant(SignBit, DL, VT)); 7677 assert(N0.getOpcode() == ISD::FABS); 7678 return DAG.getNode(ISD::AND, DL, VT, 7679 NewConv, DAG.getConstant(~SignBit, DL, VT)); 7680 } 7681 7682 // fold (bitconvert (fcopysign cst, x)) -> 7683 // (or (and (bitconvert x), sign), (and cst, (not sign))) 7684 // Note that we don't handle (copysign x, cst) because this can always be 7685 // folded to an fneg or fabs. 7686 // 7687 // For ppc_fp128: 7688 // fold (bitcast (fcopysign cst, x)) -> 7689 // flipbit = (and (extract_element 7690 // (xor (bitcast cst), (bitcast x)), 0), 7691 // signbit) 7692 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 7693 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 7694 isa<ConstantFPSDNode>(N0.getOperand(0)) && 7695 VT.isInteger() && !VT.isVector()) { 7696 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits(); 7697 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 7698 if (isTypeLegal(IntXVT)) { 7699 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 7700 AddToWorklist(X.getNode()); 7701 7702 // If X has a different width than the result/lhs, sext it or truncate it. 7703 unsigned VTWidth = VT.getSizeInBits(); 7704 if (OrigXWidth < VTWidth) { 7705 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 7706 AddToWorklist(X.getNode()); 7707 } else if (OrigXWidth > VTWidth) { 7708 // To get the sign bit in the right place, we have to shift it right 7709 // before truncating. 7710 SDLoc DL(X); 7711 X = DAG.getNode(ISD::SRL, DL, 7712 X.getValueType(), X, 7713 DAG.getConstant(OrigXWidth-VTWidth, DL, 7714 X.getValueType())); 7715 AddToWorklist(X.getNode()); 7716 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 7717 AddToWorklist(X.getNode()); 7718 } 7719 7720 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 7721 APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2); 7722 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 7723 AddToWorklist(Cst.getNode()); 7724 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 7725 AddToWorklist(X.getNode()); 7726 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 7727 AddToWorklist(XorResult.getNode()); 7728 SDValue XorResult64 = DAG.getNode( 7729 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 7730 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 7731 SDLoc(XorResult))); 7732 AddToWorklist(XorResult64.getNode()); 7733 SDValue FlipBit = 7734 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 7735 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 7736 AddToWorklist(FlipBit.getNode()); 7737 SDValue FlipBits = 7738 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 7739 AddToWorklist(FlipBits.getNode()); 7740 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 7741 } 7742 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7743 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 7744 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 7745 AddToWorklist(X.getNode()); 7746 7747 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 7748 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 7749 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 7750 AddToWorklist(Cst.getNode()); 7751 7752 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 7753 } 7754 } 7755 7756 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 7757 if (N0.getOpcode() == ISD::BUILD_PAIR) 7758 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 7759 return CombineLD; 7760 7761 // Remove double bitcasts from shuffles - this is often a legacy of 7762 // XformToShuffleWithZero being used to combine bitmaskings (of 7763 // float vectors bitcast to integer vectors) into shuffles. 7764 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 7765 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 7766 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 7767 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 7768 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 7769 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 7770 7771 // If operands are a bitcast, peek through if it casts the original VT. 7772 // If operands are a constant, just bitcast back to original VT. 7773 auto PeekThroughBitcast = [&](SDValue Op) { 7774 if (Op.getOpcode() == ISD::BITCAST && 7775 Op.getOperand(0).getValueType() == VT) 7776 return SDValue(Op.getOperand(0)); 7777 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 7778 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 7779 return DAG.getBitcast(VT, Op); 7780 return SDValue(); 7781 }; 7782 7783 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 7784 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 7785 if (!(SV0 && SV1)) 7786 return SDValue(); 7787 7788 int MaskScale = 7789 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 7790 SmallVector<int, 8> NewMask; 7791 for (int M : SVN->getMask()) 7792 for (int i = 0; i != MaskScale; ++i) 7793 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 7794 7795 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7796 if (!LegalMask) { 7797 std::swap(SV0, SV1); 7798 ShuffleVectorSDNode::commuteMask(NewMask); 7799 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7800 } 7801 7802 if (LegalMask) 7803 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 7804 } 7805 7806 return SDValue(); 7807 } 7808 7809 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 7810 EVT VT = N->getValueType(0); 7811 return CombineConsecutiveLoads(N, VT); 7812 } 7813 7814 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 7815 /// operands. DstEltVT indicates the destination element value type. 7816 SDValue DAGCombiner:: 7817 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 7818 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 7819 7820 // If this is already the right type, we're done. 7821 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 7822 7823 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 7824 unsigned DstBitSize = DstEltVT.getSizeInBits(); 7825 7826 // If this is a conversion of N elements of one type to N elements of another 7827 // type, convert each element. This handles FP<->INT cases. 7828 if (SrcBitSize == DstBitSize) { 7829 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7830 BV->getValueType(0).getVectorNumElements()); 7831 7832 // Due to the FP element handling below calling this routine recursively, 7833 // we can end up with a scalar-to-vector node here. 7834 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 7835 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 7836 DAG.getBitcast(DstEltVT, BV->getOperand(0))); 7837 7838 SmallVector<SDValue, 8> Ops; 7839 for (SDValue Op : BV->op_values()) { 7840 // If the vector element type is not legal, the BUILD_VECTOR operands 7841 // are promoted and implicitly truncated. Make that explicit here. 7842 if (Op.getValueType() != SrcEltVT) 7843 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 7844 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 7845 AddToWorklist(Ops.back().getNode()); 7846 } 7847 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 7848 } 7849 7850 // Otherwise, we're growing or shrinking the elements. To avoid having to 7851 // handle annoying details of growing/shrinking FP values, we convert them to 7852 // int first. 7853 if (SrcEltVT.isFloatingPoint()) { 7854 // Convert the input float vector to a int vector where the elements are the 7855 // same sizes. 7856 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 7857 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 7858 SrcEltVT = IntVT; 7859 } 7860 7861 // Now we know the input is an integer vector. If the output is a FP type, 7862 // convert to integer first, then to FP of the right size. 7863 if (DstEltVT.isFloatingPoint()) { 7864 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 7865 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 7866 7867 // Next, convert to FP elements of the same size. 7868 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 7869 } 7870 7871 SDLoc DL(BV); 7872 7873 // Okay, we know the src/dst types are both integers of differing types. 7874 // Handling growing first. 7875 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 7876 if (SrcBitSize < DstBitSize) { 7877 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 7878 7879 SmallVector<SDValue, 8> Ops; 7880 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 7881 i += NumInputsPerOutput) { 7882 bool isLE = DAG.getDataLayout().isLittleEndian(); 7883 APInt NewBits = APInt(DstBitSize, 0); 7884 bool EltIsUndef = true; 7885 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 7886 // Shift the previously computed bits over. 7887 NewBits <<= SrcBitSize; 7888 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 7889 if (Op.isUndef()) continue; 7890 EltIsUndef = false; 7891 7892 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 7893 zextOrTrunc(SrcBitSize).zext(DstBitSize); 7894 } 7895 7896 if (EltIsUndef) 7897 Ops.push_back(DAG.getUNDEF(DstEltVT)); 7898 else 7899 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 7900 } 7901 7902 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 7903 return DAG.getBuildVector(VT, DL, Ops); 7904 } 7905 7906 // Finally, this must be the case where we are shrinking elements: each input 7907 // turns into multiple outputs. 7908 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 7909 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7910 NumOutputsPerInput*BV->getNumOperands()); 7911 SmallVector<SDValue, 8> Ops; 7912 7913 for (const SDValue &Op : BV->op_values()) { 7914 if (Op.isUndef()) { 7915 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 7916 continue; 7917 } 7918 7919 APInt OpVal = cast<ConstantSDNode>(Op)-> 7920 getAPIntValue().zextOrTrunc(SrcBitSize); 7921 7922 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 7923 APInt ThisVal = OpVal.trunc(DstBitSize); 7924 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 7925 OpVal = OpVal.lshr(DstBitSize); 7926 } 7927 7928 // For big endian targets, swap the order of the pieces of each element. 7929 if (DAG.getDataLayout().isBigEndian()) 7930 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 7931 } 7932 7933 return DAG.getBuildVector(VT, DL, Ops); 7934 } 7935 7936 /// Try to perform FMA combining on a given FADD node. 7937 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 7938 SDValue N0 = N->getOperand(0); 7939 SDValue N1 = N->getOperand(1); 7940 EVT VT = N->getValueType(0); 7941 SDLoc SL(N); 7942 7943 const TargetOptions &Options = DAG.getTarget().Options; 7944 bool AllowFusion = 7945 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7946 7947 // Floating-point multiply-add with intermediate rounding. 7948 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7949 7950 // Floating-point multiply-add without intermediate rounding. 7951 bool HasFMA = 7952 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7953 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7954 7955 // No valid opcode, do not combine. 7956 if (!HasFMAD && !HasFMA) 7957 return SDValue(); 7958 7959 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 7960 ; 7961 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel)) 7962 return SDValue(); 7963 7964 // Always prefer FMAD to FMA for precision. 7965 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7966 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7967 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7968 7969 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 7970 // prefer to fold the multiply with fewer uses. 7971 if (Aggressive && N0.getOpcode() == ISD::FMUL && 7972 N1.getOpcode() == ISD::FMUL) { 7973 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 7974 std::swap(N0, N1); 7975 } 7976 7977 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 7978 if (N0.getOpcode() == ISD::FMUL && 7979 (Aggressive || N0->hasOneUse())) { 7980 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7981 N0.getOperand(0), N0.getOperand(1), N1); 7982 } 7983 7984 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 7985 // Note: Commutes FADD operands. 7986 if (N1.getOpcode() == ISD::FMUL && 7987 (Aggressive || N1->hasOneUse())) { 7988 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7989 N1.getOperand(0), N1.getOperand(1), N0); 7990 } 7991 7992 // Look through FP_EXTEND nodes to do more combining. 7993 if (AllowFusion && LookThroughFPExt) { 7994 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7995 if (N0.getOpcode() == ISD::FP_EXTEND) { 7996 SDValue N00 = N0.getOperand(0); 7997 if (N00.getOpcode() == ISD::FMUL) 7998 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7999 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8000 N00.getOperand(0)), 8001 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8002 N00.getOperand(1)), N1); 8003 } 8004 8005 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 8006 // Note: Commutes FADD operands. 8007 if (N1.getOpcode() == ISD::FP_EXTEND) { 8008 SDValue N10 = N1.getOperand(0); 8009 if (N10.getOpcode() == ISD::FMUL) 8010 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8011 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8012 N10.getOperand(0)), 8013 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8014 N10.getOperand(1)), N0); 8015 } 8016 } 8017 8018 // More folding opportunities when target permits. 8019 if ((AllowFusion || HasFMAD) && Aggressive) { 8020 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 8021 if (N0.getOpcode() == PreferredFusedOpcode && 8022 N0.getOperand(2).getOpcode() == ISD::FMUL) { 8023 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8024 N0.getOperand(0), N0.getOperand(1), 8025 DAG.getNode(PreferredFusedOpcode, SL, VT, 8026 N0.getOperand(2).getOperand(0), 8027 N0.getOperand(2).getOperand(1), 8028 N1)); 8029 } 8030 8031 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 8032 if (N1->getOpcode() == PreferredFusedOpcode && 8033 N1.getOperand(2).getOpcode() == ISD::FMUL) { 8034 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8035 N1.getOperand(0), N1.getOperand(1), 8036 DAG.getNode(PreferredFusedOpcode, SL, VT, 8037 N1.getOperand(2).getOperand(0), 8038 N1.getOperand(2).getOperand(1), 8039 N0)); 8040 } 8041 8042 if (AllowFusion && LookThroughFPExt) { 8043 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 8044 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 8045 auto FoldFAddFMAFPExtFMul = [&] ( 8046 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 8047 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 8048 DAG.getNode(PreferredFusedOpcode, SL, VT, 8049 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 8050 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 8051 Z)); 8052 }; 8053 if (N0.getOpcode() == PreferredFusedOpcode) { 8054 SDValue N02 = N0.getOperand(2); 8055 if (N02.getOpcode() == ISD::FP_EXTEND) { 8056 SDValue N020 = N02.getOperand(0); 8057 if (N020.getOpcode() == ISD::FMUL) 8058 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 8059 N020.getOperand(0), N020.getOperand(1), 8060 N1); 8061 } 8062 } 8063 8064 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 8065 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 8066 // FIXME: This turns two single-precision and one double-precision 8067 // operation into two double-precision operations, which might not be 8068 // interesting for all targets, especially GPUs. 8069 auto FoldFAddFPExtFMAFMul = [&] ( 8070 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 8071 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8072 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 8073 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 8074 DAG.getNode(PreferredFusedOpcode, SL, VT, 8075 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 8076 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 8077 Z)); 8078 }; 8079 if (N0.getOpcode() == ISD::FP_EXTEND) { 8080 SDValue N00 = N0.getOperand(0); 8081 if (N00.getOpcode() == PreferredFusedOpcode) { 8082 SDValue N002 = N00.getOperand(2); 8083 if (N002.getOpcode() == ISD::FMUL) 8084 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 8085 N002.getOperand(0), N002.getOperand(1), 8086 N1); 8087 } 8088 } 8089 8090 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 8091 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 8092 if (N1.getOpcode() == PreferredFusedOpcode) { 8093 SDValue N12 = N1.getOperand(2); 8094 if (N12.getOpcode() == ISD::FP_EXTEND) { 8095 SDValue N120 = N12.getOperand(0); 8096 if (N120.getOpcode() == ISD::FMUL) 8097 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 8098 N120.getOperand(0), N120.getOperand(1), 8099 N0); 8100 } 8101 } 8102 8103 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 8104 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 8105 // FIXME: This turns two single-precision and one double-precision 8106 // operation into two double-precision operations, which might not be 8107 // interesting for all targets, especially GPUs. 8108 if (N1.getOpcode() == ISD::FP_EXTEND) { 8109 SDValue N10 = N1.getOperand(0); 8110 if (N10.getOpcode() == PreferredFusedOpcode) { 8111 SDValue N102 = N10.getOperand(2); 8112 if (N102.getOpcode() == ISD::FMUL) 8113 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 8114 N102.getOperand(0), N102.getOperand(1), 8115 N0); 8116 } 8117 } 8118 } 8119 } 8120 8121 return SDValue(); 8122 } 8123 8124 /// Try to perform FMA combining on a given FSUB node. 8125 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 8126 SDValue N0 = N->getOperand(0); 8127 SDValue N1 = N->getOperand(1); 8128 EVT VT = N->getValueType(0); 8129 SDLoc SL(N); 8130 8131 const TargetOptions &Options = DAG.getTarget().Options; 8132 bool AllowFusion = 8133 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 8134 8135 // Floating-point multiply-add with intermediate rounding. 8136 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8137 8138 // Floating-point multiply-add without intermediate rounding. 8139 bool HasFMA = 8140 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 8141 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8142 8143 // No valid opcode, do not combine. 8144 if (!HasFMAD && !HasFMA) 8145 return SDValue(); 8146 8147 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 8148 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel)) 8149 return SDValue(); 8150 8151 // Always prefer FMAD to FMA for precision. 8152 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8153 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8154 bool LookThroughFPExt = TLI.isFPExtFree(VT); 8155 8156 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 8157 if (N0.getOpcode() == ISD::FMUL && 8158 (Aggressive || N0->hasOneUse())) { 8159 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8160 N0.getOperand(0), N0.getOperand(1), 8161 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8162 } 8163 8164 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 8165 // Note: Commutes FSUB operands. 8166 if (N1.getOpcode() == ISD::FMUL && 8167 (Aggressive || N1->hasOneUse())) 8168 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8169 DAG.getNode(ISD::FNEG, SL, VT, 8170 N1.getOperand(0)), 8171 N1.getOperand(1), N0); 8172 8173 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 8174 if (N0.getOpcode() == ISD::FNEG && 8175 N0.getOperand(0).getOpcode() == ISD::FMUL && 8176 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 8177 SDValue N00 = N0.getOperand(0).getOperand(0); 8178 SDValue N01 = N0.getOperand(0).getOperand(1); 8179 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8180 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 8181 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8182 } 8183 8184 // Look through FP_EXTEND nodes to do more combining. 8185 if (AllowFusion && LookThroughFPExt) { 8186 // fold (fsub (fpext (fmul x, y)), z) 8187 // -> (fma (fpext x), (fpext y), (fneg z)) 8188 if (N0.getOpcode() == ISD::FP_EXTEND) { 8189 SDValue N00 = N0.getOperand(0); 8190 if (N00.getOpcode() == ISD::FMUL) 8191 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8192 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8193 N00.getOperand(0)), 8194 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8195 N00.getOperand(1)), 8196 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8197 } 8198 8199 // fold (fsub x, (fpext (fmul y, z))) 8200 // -> (fma (fneg (fpext y)), (fpext z), x) 8201 // Note: Commutes FSUB operands. 8202 if (N1.getOpcode() == ISD::FP_EXTEND) { 8203 SDValue N10 = N1.getOperand(0); 8204 if (N10.getOpcode() == ISD::FMUL) 8205 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8206 DAG.getNode(ISD::FNEG, SL, VT, 8207 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8208 N10.getOperand(0))), 8209 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8210 N10.getOperand(1)), 8211 N0); 8212 } 8213 8214 // fold (fsub (fpext (fneg (fmul, x, y))), z) 8215 // -> (fneg (fma (fpext x), (fpext y), z)) 8216 // Note: This could be removed with appropriate canonicalization of the 8217 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 8218 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 8219 // from implementing the canonicalization in visitFSUB. 8220 if (N0.getOpcode() == ISD::FP_EXTEND) { 8221 SDValue N00 = N0.getOperand(0); 8222 if (N00.getOpcode() == ISD::FNEG) { 8223 SDValue N000 = N00.getOperand(0); 8224 if (N000.getOpcode() == ISD::FMUL) { 8225 return DAG.getNode(ISD::FNEG, SL, VT, 8226 DAG.getNode(PreferredFusedOpcode, SL, VT, 8227 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8228 N000.getOperand(0)), 8229 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8230 N000.getOperand(1)), 8231 N1)); 8232 } 8233 } 8234 } 8235 8236 // fold (fsub (fneg (fpext (fmul, x, y))), z) 8237 // -> (fneg (fma (fpext x)), (fpext y), z) 8238 // Note: This could be removed with appropriate canonicalization of the 8239 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 8240 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 8241 // from implementing the canonicalization in visitFSUB. 8242 if (N0.getOpcode() == ISD::FNEG) { 8243 SDValue N00 = N0.getOperand(0); 8244 if (N00.getOpcode() == ISD::FP_EXTEND) { 8245 SDValue N000 = N00.getOperand(0); 8246 if (N000.getOpcode() == ISD::FMUL) { 8247 return DAG.getNode(ISD::FNEG, SL, VT, 8248 DAG.getNode(PreferredFusedOpcode, SL, VT, 8249 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8250 N000.getOperand(0)), 8251 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8252 N000.getOperand(1)), 8253 N1)); 8254 } 8255 } 8256 } 8257 8258 } 8259 8260 // More folding opportunities when target permits. 8261 if ((AllowFusion || HasFMAD) && Aggressive) { 8262 // fold (fsub (fma x, y, (fmul u, v)), z) 8263 // -> (fma x, y (fma u, v, (fneg z))) 8264 if (N0.getOpcode() == PreferredFusedOpcode && 8265 N0.getOperand(2).getOpcode() == ISD::FMUL) { 8266 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8267 N0.getOperand(0), N0.getOperand(1), 8268 DAG.getNode(PreferredFusedOpcode, SL, VT, 8269 N0.getOperand(2).getOperand(0), 8270 N0.getOperand(2).getOperand(1), 8271 DAG.getNode(ISD::FNEG, SL, VT, 8272 N1))); 8273 } 8274 8275 // fold (fsub x, (fma y, z, (fmul u, v))) 8276 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 8277 if (N1.getOpcode() == PreferredFusedOpcode && 8278 N1.getOperand(2).getOpcode() == ISD::FMUL) { 8279 SDValue N20 = N1.getOperand(2).getOperand(0); 8280 SDValue N21 = N1.getOperand(2).getOperand(1); 8281 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8282 DAG.getNode(ISD::FNEG, SL, VT, 8283 N1.getOperand(0)), 8284 N1.getOperand(1), 8285 DAG.getNode(PreferredFusedOpcode, SL, VT, 8286 DAG.getNode(ISD::FNEG, SL, VT, N20), 8287 8288 N21, N0)); 8289 } 8290 8291 if (AllowFusion && LookThroughFPExt) { 8292 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 8293 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 8294 if (N0.getOpcode() == PreferredFusedOpcode) { 8295 SDValue N02 = N0.getOperand(2); 8296 if (N02.getOpcode() == ISD::FP_EXTEND) { 8297 SDValue N020 = N02.getOperand(0); 8298 if (N020.getOpcode() == ISD::FMUL) 8299 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8300 N0.getOperand(0), N0.getOperand(1), 8301 DAG.getNode(PreferredFusedOpcode, SL, VT, 8302 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8303 N020.getOperand(0)), 8304 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8305 N020.getOperand(1)), 8306 DAG.getNode(ISD::FNEG, SL, VT, 8307 N1))); 8308 } 8309 } 8310 8311 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 8312 // -> (fma (fpext x), (fpext y), 8313 // (fma (fpext u), (fpext v), (fneg z))) 8314 // FIXME: This turns two single-precision and one double-precision 8315 // operation into two double-precision operations, which might not be 8316 // interesting for all targets, especially GPUs. 8317 if (N0.getOpcode() == ISD::FP_EXTEND) { 8318 SDValue N00 = N0.getOperand(0); 8319 if (N00.getOpcode() == PreferredFusedOpcode) { 8320 SDValue N002 = N00.getOperand(2); 8321 if (N002.getOpcode() == ISD::FMUL) 8322 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8323 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8324 N00.getOperand(0)), 8325 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8326 N00.getOperand(1)), 8327 DAG.getNode(PreferredFusedOpcode, SL, VT, 8328 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8329 N002.getOperand(0)), 8330 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8331 N002.getOperand(1)), 8332 DAG.getNode(ISD::FNEG, SL, VT, 8333 N1))); 8334 } 8335 } 8336 8337 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 8338 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 8339 if (N1.getOpcode() == PreferredFusedOpcode && 8340 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 8341 SDValue N120 = N1.getOperand(2).getOperand(0); 8342 if (N120.getOpcode() == ISD::FMUL) { 8343 SDValue N1200 = N120.getOperand(0); 8344 SDValue N1201 = N120.getOperand(1); 8345 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8346 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 8347 N1.getOperand(1), 8348 DAG.getNode(PreferredFusedOpcode, SL, VT, 8349 DAG.getNode(ISD::FNEG, SL, VT, 8350 DAG.getNode(ISD::FP_EXTEND, SL, 8351 VT, N1200)), 8352 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8353 N1201), 8354 N0)); 8355 } 8356 } 8357 8358 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 8359 // -> (fma (fneg (fpext y)), (fpext z), 8360 // (fma (fneg (fpext u)), (fpext v), x)) 8361 // FIXME: This turns two single-precision and one double-precision 8362 // operation into two double-precision operations, which might not be 8363 // interesting for all targets, especially GPUs. 8364 if (N1.getOpcode() == ISD::FP_EXTEND && 8365 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 8366 SDValue N100 = N1.getOperand(0).getOperand(0); 8367 SDValue N101 = N1.getOperand(0).getOperand(1); 8368 SDValue N102 = N1.getOperand(0).getOperand(2); 8369 if (N102.getOpcode() == ISD::FMUL) { 8370 SDValue N1020 = N102.getOperand(0); 8371 SDValue N1021 = N102.getOperand(1); 8372 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8373 DAG.getNode(ISD::FNEG, SL, VT, 8374 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8375 N100)), 8376 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 8377 DAG.getNode(PreferredFusedOpcode, SL, VT, 8378 DAG.getNode(ISD::FNEG, SL, VT, 8379 DAG.getNode(ISD::FP_EXTEND, SL, 8380 VT, N1020)), 8381 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8382 N1021), 8383 N0)); 8384 } 8385 } 8386 } 8387 } 8388 8389 return SDValue(); 8390 } 8391 8392 /// Try to perform FMA combining on a given FMUL node based on the distributive 8393 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions, 8394 /// subtraction instead of addition). 8395 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) { 8396 SDValue N0 = N->getOperand(0); 8397 SDValue N1 = N->getOperand(1); 8398 EVT VT = N->getValueType(0); 8399 SDLoc SL(N); 8400 8401 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 8402 8403 const TargetOptions &Options = DAG.getTarget().Options; 8404 8405 // The transforms below are incorrect when x == 0 and y == inf, because the 8406 // intermediate multiplication produces a nan. 8407 if (!Options.NoInfsFPMath) 8408 return SDValue(); 8409 8410 // Floating-point multiply-add without intermediate rounding. 8411 bool HasFMA = 8412 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 8413 TLI.isFMAFasterThanFMulAndFAdd(VT) && 8414 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8415 8416 // Floating-point multiply-add with intermediate rounding. This can result 8417 // in a less precise result due to the changed rounding order. 8418 bool HasFMAD = Options.UnsafeFPMath && 8419 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8420 8421 // No valid opcode, do not combine. 8422 if (!HasFMAD && !HasFMA) 8423 return SDValue(); 8424 8425 // Always prefer FMAD to FMA for precision. 8426 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8427 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8428 8429 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 8430 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 8431 auto FuseFADD = [&](SDValue X, SDValue Y) { 8432 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 8433 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8434 if (XC1 && XC1->isExactlyValue(+1.0)) 8435 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8436 if (XC1 && XC1->isExactlyValue(-1.0)) 8437 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8438 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8439 } 8440 return SDValue(); 8441 }; 8442 8443 if (SDValue FMA = FuseFADD(N0, N1)) 8444 return FMA; 8445 if (SDValue FMA = FuseFADD(N1, N0)) 8446 return FMA; 8447 8448 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 8449 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 8450 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 8451 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 8452 auto FuseFSUB = [&](SDValue X, SDValue Y) { 8453 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 8454 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 8455 if (XC0 && XC0->isExactlyValue(+1.0)) 8456 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8457 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8458 Y); 8459 if (XC0 && XC0->isExactlyValue(-1.0)) 8460 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8461 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8462 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8463 8464 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8465 if (XC1 && XC1->isExactlyValue(+1.0)) 8466 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8467 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8468 if (XC1 && XC1->isExactlyValue(-1.0)) 8469 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8470 } 8471 return SDValue(); 8472 }; 8473 8474 if (SDValue FMA = FuseFSUB(N0, N1)) 8475 return FMA; 8476 if (SDValue FMA = FuseFSUB(N1, N0)) 8477 return FMA; 8478 8479 return SDValue(); 8480 } 8481 8482 SDValue DAGCombiner::visitFADD(SDNode *N) { 8483 SDValue N0 = N->getOperand(0); 8484 SDValue N1 = N->getOperand(1); 8485 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 8486 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 8487 EVT VT = N->getValueType(0); 8488 SDLoc DL(N); 8489 const TargetOptions &Options = DAG.getTarget().Options; 8490 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8491 8492 // fold vector ops 8493 if (VT.isVector()) 8494 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8495 return FoldedVOp; 8496 8497 // fold (fadd c1, c2) -> c1 + c2 8498 if (N0CFP && N1CFP) 8499 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 8500 8501 // canonicalize constant to RHS 8502 if (N0CFP && !N1CFP) 8503 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 8504 8505 // fold (fadd A, (fneg B)) -> (fsub A, B) 8506 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8507 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 8508 return DAG.getNode(ISD::FSUB, DL, VT, N0, 8509 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8510 8511 // fold (fadd (fneg A), B) -> (fsub B, A) 8512 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8513 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 8514 return DAG.getNode(ISD::FSUB, DL, VT, N1, 8515 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 8516 8517 // FIXME: Auto-upgrade the target/function-level option. 8518 if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) { 8519 // fold (fadd A, 0) -> A 8520 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 8521 if (N1C->isZero()) 8522 return N0; 8523 } 8524 8525 // If 'unsafe math' is enabled, fold lots of things. 8526 if (Options.UnsafeFPMath) { 8527 // No FP constant should be created after legalization as Instruction 8528 // Selection pass has a hard time dealing with FP constants. 8529 bool AllowNewConst = (Level < AfterLegalizeDAG); 8530 8531 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 8532 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 8533 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 8534 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 8535 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 8536 Flags), 8537 Flags); 8538 8539 // If allowed, fold (fadd (fneg x), x) -> 0.0 8540 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 8541 return DAG.getConstantFP(0.0, DL, VT); 8542 8543 // If allowed, fold (fadd x, (fneg x)) -> 0.0 8544 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 8545 return DAG.getConstantFP(0.0, DL, VT); 8546 8547 // We can fold chains of FADD's of the same value into multiplications. 8548 // This transform is not safe in general because we are reducing the number 8549 // of rounding steps. 8550 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 8551 if (N0.getOpcode() == ISD::FMUL) { 8552 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8553 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 8554 8555 // (fadd (fmul x, c), x) -> (fmul x, c+1) 8556 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 8557 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8558 DAG.getConstantFP(1.0, DL, VT), Flags); 8559 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 8560 } 8561 8562 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 8563 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 8564 N1.getOperand(0) == N1.getOperand(1) && 8565 N0.getOperand(0) == N1.getOperand(0)) { 8566 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8567 DAG.getConstantFP(2.0, DL, VT), Flags); 8568 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 8569 } 8570 } 8571 8572 if (N1.getOpcode() == ISD::FMUL) { 8573 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8574 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 8575 8576 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 8577 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 8578 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8579 DAG.getConstantFP(1.0, DL, VT), Flags); 8580 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 8581 } 8582 8583 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 8584 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 8585 N0.getOperand(0) == N0.getOperand(1) && 8586 N1.getOperand(0) == N0.getOperand(0)) { 8587 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8588 DAG.getConstantFP(2.0, DL, VT), Flags); 8589 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 8590 } 8591 } 8592 8593 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 8594 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8595 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 8596 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 8597 (N0.getOperand(0) == N1)) { 8598 return DAG.getNode(ISD::FMUL, DL, VT, 8599 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 8600 } 8601 } 8602 8603 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 8604 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8605 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 8606 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 8607 N1.getOperand(0) == N0) { 8608 return DAG.getNode(ISD::FMUL, DL, VT, 8609 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 8610 } 8611 } 8612 8613 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 8614 if (AllowNewConst && 8615 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 8616 N0.getOperand(0) == N0.getOperand(1) && 8617 N1.getOperand(0) == N1.getOperand(1) && 8618 N0.getOperand(0) == N1.getOperand(0)) { 8619 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 8620 DAG.getConstantFP(4.0, DL, VT), Flags); 8621 } 8622 } 8623 } // enable-unsafe-fp-math 8624 8625 // FADD -> FMA combines: 8626 if (SDValue Fused = visitFADDForFMACombine(N)) { 8627 AddToWorklist(Fused.getNode()); 8628 return Fused; 8629 } 8630 return SDValue(); 8631 } 8632 8633 SDValue DAGCombiner::visitFSUB(SDNode *N) { 8634 SDValue N0 = N->getOperand(0); 8635 SDValue N1 = N->getOperand(1); 8636 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8637 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8638 EVT VT = N->getValueType(0); 8639 SDLoc DL(N); 8640 const TargetOptions &Options = DAG.getTarget().Options; 8641 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8642 8643 // fold vector ops 8644 if (VT.isVector()) 8645 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8646 return FoldedVOp; 8647 8648 // fold (fsub c1, c2) -> c1-c2 8649 if (N0CFP && N1CFP) 8650 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags); 8651 8652 // fold (fsub A, (fneg B)) -> (fadd A, B) 8653 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8654 return DAG.getNode(ISD::FADD, DL, VT, N0, 8655 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8656 8657 // FIXME: Auto-upgrade the target/function-level option. 8658 if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) { 8659 // (fsub 0, B) -> -B 8660 if (N0CFP && N0CFP->isZero()) { 8661 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8662 return GetNegatedExpression(N1, DAG, LegalOperations); 8663 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8664 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags); 8665 } 8666 } 8667 8668 // If 'unsafe math' is enabled, fold lots of things. 8669 if (Options.UnsafeFPMath) { 8670 // (fsub A, 0) -> A 8671 if (N1CFP && N1CFP->isZero()) 8672 return N0; 8673 8674 // (fsub x, x) -> 0.0 8675 if (N0 == N1) 8676 return DAG.getConstantFP(0.0f, DL, VT); 8677 8678 // (fsub x, (fadd x, y)) -> (fneg y) 8679 // (fsub x, (fadd y, x)) -> (fneg y) 8680 if (N1.getOpcode() == ISD::FADD) { 8681 SDValue N10 = N1->getOperand(0); 8682 SDValue N11 = N1->getOperand(1); 8683 8684 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 8685 return GetNegatedExpression(N11, DAG, LegalOperations); 8686 8687 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 8688 return GetNegatedExpression(N10, DAG, LegalOperations); 8689 } 8690 } 8691 8692 // FSUB -> FMA combines: 8693 if (SDValue Fused = visitFSUBForFMACombine(N)) { 8694 AddToWorklist(Fused.getNode()); 8695 return Fused; 8696 } 8697 8698 return SDValue(); 8699 } 8700 8701 SDValue DAGCombiner::visitFMUL(SDNode *N) { 8702 SDValue N0 = N->getOperand(0); 8703 SDValue N1 = N->getOperand(1); 8704 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8705 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8706 EVT VT = N->getValueType(0); 8707 SDLoc DL(N); 8708 const TargetOptions &Options = DAG.getTarget().Options; 8709 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8710 8711 // fold vector ops 8712 if (VT.isVector()) { 8713 // This just handles C1 * C2 for vectors. Other vector folds are below. 8714 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8715 return FoldedVOp; 8716 } 8717 8718 // fold (fmul c1, c2) -> c1*c2 8719 if (N0CFP && N1CFP) 8720 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 8721 8722 // canonicalize constant to RHS 8723 if (isConstantFPBuildVectorOrConstantFP(N0) && 8724 !isConstantFPBuildVectorOrConstantFP(N1)) 8725 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 8726 8727 // fold (fmul A, 1.0) -> A 8728 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8729 return N0; 8730 8731 if (Options.UnsafeFPMath) { 8732 // fold (fmul A, 0) -> 0 8733 if (N1CFP && N1CFP->isZero()) 8734 return N1; 8735 8736 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 8737 if (N0.getOpcode() == ISD::FMUL) { 8738 // Fold scalars or any vector constants (not just splats). 8739 // This fold is done in general by InstCombine, but extra fmul insts 8740 // may have been generated during lowering. 8741 SDValue N00 = N0.getOperand(0); 8742 SDValue N01 = N0.getOperand(1); 8743 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 8744 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 8745 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 8746 8747 // Check 1: Make sure that the first operand of the inner multiply is NOT 8748 // a constant. Otherwise, we may induce infinite looping. 8749 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 8750 // Check 2: Make sure that the second operand of the inner multiply and 8751 // the second operand of the outer multiply are constants. 8752 if ((N1CFP && isConstOrConstSplatFP(N01)) || 8753 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 8754 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 8755 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 8756 } 8757 } 8758 } 8759 8760 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 8761 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 8762 // during an early run of DAGCombiner can prevent folding with fmuls 8763 // inserted during lowering. 8764 if (N0.getOpcode() == ISD::FADD && 8765 (N0.getOperand(0) == N0.getOperand(1)) && 8766 N0.hasOneUse()) { 8767 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 8768 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 8769 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 8770 } 8771 } 8772 8773 // fold (fmul X, 2.0) -> (fadd X, X) 8774 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 8775 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 8776 8777 // fold (fmul X, -1.0) -> (fneg X) 8778 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 8779 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8780 return DAG.getNode(ISD::FNEG, DL, VT, N0); 8781 8782 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 8783 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8784 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8785 // Both can be negated for free, check to see if at least one is cheaper 8786 // negated. 8787 if (LHSNeg == 2 || RHSNeg == 2) 8788 return DAG.getNode(ISD::FMUL, DL, VT, 8789 GetNegatedExpression(N0, DAG, LegalOperations), 8790 GetNegatedExpression(N1, DAG, LegalOperations), 8791 Flags); 8792 } 8793 } 8794 8795 // FMUL -> FMA combines: 8796 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) { 8797 AddToWorklist(Fused.getNode()); 8798 return Fused; 8799 } 8800 8801 return SDValue(); 8802 } 8803 8804 SDValue DAGCombiner::visitFMA(SDNode *N) { 8805 SDValue N0 = N->getOperand(0); 8806 SDValue N1 = N->getOperand(1); 8807 SDValue N2 = N->getOperand(2); 8808 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8809 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8810 EVT VT = N->getValueType(0); 8811 SDLoc DL(N); 8812 const TargetOptions &Options = DAG.getTarget().Options; 8813 8814 // Constant fold FMA. 8815 if (isa<ConstantFPSDNode>(N0) && 8816 isa<ConstantFPSDNode>(N1) && 8817 isa<ConstantFPSDNode>(N2)) { 8818 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2); 8819 } 8820 8821 if (Options.UnsafeFPMath) { 8822 if (N0CFP && N0CFP->isZero()) 8823 return N2; 8824 if (N1CFP && N1CFP->isZero()) 8825 return N2; 8826 } 8827 // TODO: The FMA node should have flags that propagate to these nodes. 8828 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8829 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 8830 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8831 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 8832 8833 // Canonicalize (fma c, x, y) -> (fma x, c, y) 8834 if (isConstantFPBuildVectorOrConstantFP(N0) && 8835 !isConstantFPBuildVectorOrConstantFP(N1)) 8836 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 8837 8838 // TODO: FMA nodes should have flags that propagate to the created nodes. 8839 // For now, create a Flags object for use with all unsafe math transforms. 8840 SDNodeFlags Flags; 8841 Flags.setUnsafeAlgebra(true); 8842 8843 if (Options.UnsafeFPMath) { 8844 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 8845 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 8846 isConstantFPBuildVectorOrConstantFP(N1) && 8847 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 8848 return DAG.getNode(ISD::FMUL, DL, VT, N0, 8849 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1), 8850 &Flags), &Flags); 8851 } 8852 8853 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 8854 if (N0.getOpcode() == ISD::FMUL && 8855 isConstantFPBuildVectorOrConstantFP(N1) && 8856 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 8857 return DAG.getNode(ISD::FMA, DL, VT, 8858 N0.getOperand(0), 8859 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1), 8860 &Flags), 8861 N2); 8862 } 8863 } 8864 8865 // (fma x, 1, y) -> (fadd x, y) 8866 // (fma x, -1, y) -> (fadd (fneg x), y) 8867 if (N1CFP) { 8868 if (N1CFP->isExactlyValue(1.0)) 8869 // TODO: The FMA node should have flags that propagate to this node. 8870 return DAG.getNode(ISD::FADD, DL, VT, N0, N2); 8871 8872 if (N1CFP->isExactlyValue(-1.0) && 8873 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 8874 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0); 8875 AddToWorklist(RHSNeg.getNode()); 8876 // TODO: The FMA node should have flags that propagate to this node. 8877 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg); 8878 } 8879 } 8880 8881 if (Options.UnsafeFPMath) { 8882 // (fma x, c, x) -> (fmul x, (c+1)) 8883 if (N1CFP && N0 == N2) { 8884 return DAG.getNode(ISD::FMUL, DL, VT, N0, 8885 DAG.getNode(ISD::FADD, DL, VT, N1, 8886 DAG.getConstantFP(1.0, DL, VT), &Flags), 8887 &Flags); 8888 } 8889 8890 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 8891 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 8892 return DAG.getNode(ISD::FMUL, DL, VT, N0, 8893 DAG.getNode(ISD::FADD, DL, VT, N1, 8894 DAG.getConstantFP(-1.0, DL, VT), &Flags), 8895 &Flags); 8896 } 8897 } 8898 8899 return SDValue(); 8900 } 8901 8902 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 8903 // reciprocal. 8904 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 8905 // Notice that this is not always beneficial. One reason is different targets 8906 // may have different costs for FDIV and FMUL, so sometimes the cost of two 8907 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 8908 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 8909 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 8910 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 8911 const SDNodeFlags *Flags = N->getFlags(); 8912 if (!UnsafeMath && !Flags->hasAllowReciprocal()) 8913 return SDValue(); 8914 8915 // Skip if current node is a reciprocal. 8916 SDValue N0 = N->getOperand(0); 8917 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8918 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8919 return SDValue(); 8920 8921 // Exit early if the target does not want this transform or if there can't 8922 // possibly be enough uses of the divisor to make the transform worthwhile. 8923 SDValue N1 = N->getOperand(1); 8924 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 8925 if (!MinUses || N1->use_size() < MinUses) 8926 return SDValue(); 8927 8928 // Find all FDIV users of the same divisor. 8929 // Use a set because duplicates may be present in the user list. 8930 SetVector<SDNode *> Users; 8931 for (auto *U : N1->uses()) { 8932 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 8933 // This division is eligible for optimization only if global unsafe math 8934 // is enabled or if this division allows reciprocal formation. 8935 if (UnsafeMath || U->getFlags()->hasAllowReciprocal()) 8936 Users.insert(U); 8937 } 8938 } 8939 8940 // Now that we have the actual number of divisor uses, make sure it meets 8941 // the minimum threshold specified by the target. 8942 if (Users.size() < MinUses) 8943 return SDValue(); 8944 8945 EVT VT = N->getValueType(0); 8946 SDLoc DL(N); 8947 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 8948 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 8949 8950 // Dividend / Divisor -> Dividend * Reciprocal 8951 for (auto *U : Users) { 8952 SDValue Dividend = U->getOperand(0); 8953 if (Dividend != FPOne) { 8954 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 8955 Reciprocal, Flags); 8956 CombineTo(U, NewNode); 8957 } else if (U != Reciprocal.getNode()) { 8958 // In the absence of fast-math-flags, this user node is always the 8959 // same node as Reciprocal, but with FMF they may be different nodes. 8960 CombineTo(U, Reciprocal); 8961 } 8962 } 8963 return SDValue(N, 0); // N was replaced. 8964 } 8965 8966 SDValue DAGCombiner::visitFDIV(SDNode *N) { 8967 SDValue N0 = N->getOperand(0); 8968 SDValue N1 = N->getOperand(1); 8969 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8970 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8971 EVT VT = N->getValueType(0); 8972 SDLoc DL(N); 8973 const TargetOptions &Options = DAG.getTarget().Options; 8974 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8975 8976 // fold vector ops 8977 if (VT.isVector()) 8978 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8979 return FoldedVOp; 8980 8981 // fold (fdiv c1, c2) -> c1/c2 8982 if (N0CFP && N1CFP) 8983 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 8984 8985 if (Options.UnsafeFPMath) { 8986 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 8987 if (N1CFP) { 8988 // Compute the reciprocal 1.0 / c2. 8989 const APFloat &N1APF = N1CFP->getValueAPF(); 8990 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 8991 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 8992 // Only do the transform if the reciprocal is a legal fp immediate that 8993 // isn't too nasty (eg NaN, denormal, ...). 8994 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 8995 (!LegalOperations || 8996 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 8997 // backend)... we should handle this gracefully after Legalize. 8998 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 8999 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 9000 TLI.isFPImmLegal(Recip, VT))) 9001 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9002 DAG.getConstantFP(Recip, DL, VT), Flags); 9003 } 9004 9005 // If this FDIV is part of a reciprocal square root, it may be folded 9006 // into a target-specific square root estimate instruction. 9007 if (N1.getOpcode() == ISD::FSQRT) { 9008 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) { 9009 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9010 } 9011 } else if (N1.getOpcode() == ISD::FP_EXTEND && 9012 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 9013 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 9014 Flags)) { 9015 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 9016 AddToWorklist(RV.getNode()); 9017 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9018 } 9019 } else if (N1.getOpcode() == ISD::FP_ROUND && 9020 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 9021 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 9022 Flags)) { 9023 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 9024 AddToWorklist(RV.getNode()); 9025 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9026 } 9027 } else if (N1.getOpcode() == ISD::FMUL) { 9028 // Look through an FMUL. Even though this won't remove the FDIV directly, 9029 // it's still worthwhile to get rid of the FSQRT if possible. 9030 SDValue SqrtOp; 9031 SDValue OtherOp; 9032 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 9033 SqrtOp = N1.getOperand(0); 9034 OtherOp = N1.getOperand(1); 9035 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 9036 SqrtOp = N1.getOperand(1); 9037 OtherOp = N1.getOperand(0); 9038 } 9039 if (SqrtOp.getNode()) { 9040 // We found a FSQRT, so try to make this fold: 9041 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 9042 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 9043 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 9044 AddToWorklist(RV.getNode()); 9045 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9046 } 9047 } 9048 } 9049 9050 // Fold into a reciprocal estimate and multiply instead of a real divide. 9051 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 9052 AddToWorklist(RV.getNode()); 9053 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9054 } 9055 } 9056 9057 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 9058 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 9059 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 9060 // Both can be negated for free, check to see if at least one is cheaper 9061 // negated. 9062 if (LHSNeg == 2 || RHSNeg == 2) 9063 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 9064 GetNegatedExpression(N0, DAG, LegalOperations), 9065 GetNegatedExpression(N1, DAG, LegalOperations), 9066 Flags); 9067 } 9068 } 9069 9070 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 9071 return CombineRepeatedDivisors; 9072 9073 return SDValue(); 9074 } 9075 9076 SDValue DAGCombiner::visitFREM(SDNode *N) { 9077 SDValue N0 = N->getOperand(0); 9078 SDValue N1 = N->getOperand(1); 9079 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9080 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9081 EVT VT = N->getValueType(0); 9082 9083 // fold (frem c1, c2) -> fmod(c1,c2) 9084 if (N0CFP && N1CFP) 9085 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, 9086 &cast<BinaryWithFlagsSDNode>(N)->Flags); 9087 9088 return SDValue(); 9089 } 9090 9091 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 9092 if (!DAG.getTarget().Options.UnsafeFPMath) 9093 return SDValue(); 9094 9095 SDValue N0 = N->getOperand(0); 9096 if (TLI.isFsqrtCheap(N0, DAG)) 9097 return SDValue(); 9098 9099 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 9100 // For now, create a Flags object for use with all unsafe math transforms. 9101 SDNodeFlags Flags; 9102 Flags.setUnsafeAlgebra(true); 9103 return buildSqrtEstimate(N0, &Flags); 9104 } 9105 9106 /// copysign(x, fp_extend(y)) -> copysign(x, y) 9107 /// copysign(x, fp_round(y)) -> copysign(x, y) 9108 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 9109 SDValue N1 = N->getOperand(1); 9110 if ((N1.getOpcode() == ISD::FP_EXTEND || 9111 N1.getOpcode() == ISD::FP_ROUND)) { 9112 // Do not optimize out type conversion of f128 type yet. 9113 // For some targets like x86_64, configuration is changed to keep one f128 9114 // value in one SSE register, but instruction selection cannot handle 9115 // FCOPYSIGN on SSE registers yet. 9116 EVT N1VT = N1->getValueType(0); 9117 EVT N1Op0VT = N1->getOperand(0)->getValueType(0); 9118 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 9119 } 9120 return false; 9121 } 9122 9123 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 9124 SDValue N0 = N->getOperand(0); 9125 SDValue N1 = N->getOperand(1); 9126 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9127 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9128 EVT VT = N->getValueType(0); 9129 9130 if (N0CFP && N1CFP) // Constant fold 9131 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 9132 9133 if (N1CFP) { 9134 const APFloat &V = N1CFP->getValueAPF(); 9135 // copysign(x, c1) -> fabs(x) iff ispos(c1) 9136 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 9137 if (!V.isNegative()) { 9138 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 9139 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9140 } else { 9141 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9142 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 9143 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 9144 } 9145 } 9146 9147 // copysign(fabs(x), y) -> copysign(x, y) 9148 // copysign(fneg(x), y) -> copysign(x, y) 9149 // copysign(copysign(x,z), y) -> copysign(x, y) 9150 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 9151 N0.getOpcode() == ISD::FCOPYSIGN) 9152 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1); 9153 9154 // copysign(x, abs(y)) -> abs(x) 9155 if (N1.getOpcode() == ISD::FABS) 9156 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9157 9158 // copysign(x, copysign(y,z)) -> copysign(x, z) 9159 if (N1.getOpcode() == ISD::FCOPYSIGN) 9160 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1)); 9161 9162 // copysign(x, fp_extend(y)) -> copysign(x, y) 9163 // copysign(x, fp_round(y)) -> copysign(x, y) 9164 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 9165 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0)); 9166 9167 return SDValue(); 9168 } 9169 9170 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 9171 SDValue N0 = N->getOperand(0); 9172 EVT VT = N->getValueType(0); 9173 EVT OpVT = N0.getValueType(); 9174 9175 // fold (sint_to_fp c1) -> c1fp 9176 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 9177 // ...but only if the target supports immediate floating-point values 9178 (!LegalOperations || 9179 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 9180 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 9181 9182 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 9183 // but UINT_TO_FP is legal on this target, try to convert. 9184 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 9185 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 9186 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 9187 if (DAG.SignBitIsZero(N0)) 9188 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 9189 } 9190 9191 // The next optimizations are desirable only if SELECT_CC can be lowered. 9192 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 9193 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 9194 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 9195 !VT.isVector() && 9196 (!LegalOperations || 9197 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9198 SDLoc DL(N); 9199 SDValue Ops[] = 9200 { N0.getOperand(0), N0.getOperand(1), 9201 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9202 N0.getOperand(2) }; 9203 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9204 } 9205 9206 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 9207 // (select_cc x, y, 1.0, 0.0,, cc) 9208 if (N0.getOpcode() == ISD::ZERO_EXTEND && 9209 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 9210 (!LegalOperations || 9211 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9212 SDLoc DL(N); 9213 SDValue Ops[] = 9214 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 9215 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9216 N0.getOperand(0).getOperand(2) }; 9217 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9218 } 9219 } 9220 9221 return SDValue(); 9222 } 9223 9224 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 9225 SDValue N0 = N->getOperand(0); 9226 EVT VT = N->getValueType(0); 9227 EVT OpVT = N0.getValueType(); 9228 9229 // fold (uint_to_fp c1) -> c1fp 9230 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 9231 // ...but only if the target supports immediate floating-point values 9232 (!LegalOperations || 9233 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 9234 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 9235 9236 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 9237 // but SINT_TO_FP is legal on this target, try to convert. 9238 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 9239 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 9240 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 9241 if (DAG.SignBitIsZero(N0)) 9242 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 9243 } 9244 9245 // The next optimizations are desirable only if SELECT_CC can be lowered. 9246 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 9247 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 9248 9249 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 9250 (!LegalOperations || 9251 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9252 SDLoc DL(N); 9253 SDValue Ops[] = 9254 { N0.getOperand(0), N0.getOperand(1), 9255 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9256 N0.getOperand(2) }; 9257 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9258 } 9259 } 9260 9261 return SDValue(); 9262 } 9263 9264 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 9265 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 9266 SDValue N0 = N->getOperand(0); 9267 EVT VT = N->getValueType(0); 9268 9269 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 9270 return SDValue(); 9271 9272 SDValue Src = N0.getOperand(0); 9273 EVT SrcVT = Src.getValueType(); 9274 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 9275 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 9276 9277 // We can safely assume the conversion won't overflow the output range, 9278 // because (for example) (uint8_t)18293.f is undefined behavior. 9279 9280 // Since we can assume the conversion won't overflow, our decision as to 9281 // whether the input will fit in the float should depend on the minimum 9282 // of the input range and output range. 9283 9284 // This means this is also safe for a signed input and unsigned output, since 9285 // a negative input would lead to undefined behavior. 9286 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 9287 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 9288 unsigned ActualSize = std::min(InputSize, OutputSize); 9289 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 9290 9291 // We can only fold away the float conversion if the input range can be 9292 // represented exactly in the float range. 9293 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 9294 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 9295 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 9296 : ISD::ZERO_EXTEND; 9297 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 9298 } 9299 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 9300 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 9301 return DAG.getBitcast(VT, Src); 9302 } 9303 return SDValue(); 9304 } 9305 9306 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 9307 SDValue N0 = N->getOperand(0); 9308 EVT VT = N->getValueType(0); 9309 9310 // fold (fp_to_sint c1fp) -> c1 9311 if (isConstantFPBuildVectorOrConstantFP(N0)) 9312 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 9313 9314 return FoldIntToFPToInt(N, DAG); 9315 } 9316 9317 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 9318 SDValue N0 = N->getOperand(0); 9319 EVT VT = N->getValueType(0); 9320 9321 // fold (fp_to_uint c1fp) -> c1 9322 if (isConstantFPBuildVectorOrConstantFP(N0)) 9323 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 9324 9325 return FoldIntToFPToInt(N, DAG); 9326 } 9327 9328 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 9329 SDValue N0 = N->getOperand(0); 9330 SDValue N1 = N->getOperand(1); 9331 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9332 EVT VT = N->getValueType(0); 9333 9334 // fold (fp_round c1fp) -> c1fp 9335 if (N0CFP) 9336 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 9337 9338 // fold (fp_round (fp_extend x)) -> x 9339 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 9340 return N0.getOperand(0); 9341 9342 // fold (fp_round (fp_round x)) -> (fp_round x) 9343 if (N0.getOpcode() == ISD::FP_ROUND) { 9344 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 9345 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1; 9346 9347 // Skip this folding if it results in an fp_round from f80 to f16. 9348 // 9349 // f80 to f16 always generates an expensive (and as yet, unimplemented) 9350 // libcall to __truncxfhf2 instead of selecting native f16 conversion 9351 // instructions from f32 or f64. Moreover, the first (value-preserving) 9352 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 9353 // x86. 9354 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 9355 return SDValue(); 9356 9357 // If the first fp_round isn't a value preserving truncation, it might 9358 // introduce a tie in the second fp_round, that wouldn't occur in the 9359 // single-step fp_round we want to fold to. 9360 // In other words, double rounding isn't the same as rounding. 9361 // Also, this is a value preserving truncation iff both fp_round's are. 9362 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 9363 SDLoc DL(N); 9364 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 9365 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 9366 } 9367 } 9368 9369 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 9370 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 9371 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 9372 N0.getOperand(0), N1); 9373 AddToWorklist(Tmp.getNode()); 9374 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 9375 Tmp, N0.getOperand(1)); 9376 } 9377 9378 return SDValue(); 9379 } 9380 9381 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 9382 SDValue N0 = N->getOperand(0); 9383 EVT VT = N->getValueType(0); 9384 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 9385 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9386 9387 // fold (fp_round_inreg c1fp) -> c1fp 9388 if (N0CFP && isTypeLegal(EVT)) { 9389 SDLoc DL(N); 9390 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 9391 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 9392 } 9393 9394 return SDValue(); 9395 } 9396 9397 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 9398 SDValue N0 = N->getOperand(0); 9399 EVT VT = N->getValueType(0); 9400 9401 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 9402 if (N->hasOneUse() && 9403 N->use_begin()->getOpcode() == ISD::FP_ROUND) 9404 return SDValue(); 9405 9406 // fold (fp_extend c1fp) -> c1fp 9407 if (isConstantFPBuildVectorOrConstantFP(N0)) 9408 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 9409 9410 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 9411 if (N0.getOpcode() == ISD::FP16_TO_FP && 9412 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 9413 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 9414 9415 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 9416 // value of X. 9417 if (N0.getOpcode() == ISD::FP_ROUND 9418 && N0.getConstantOperandVal(1) == 1) { 9419 SDValue In = N0.getOperand(0); 9420 if (In.getValueType() == VT) return In; 9421 if (VT.bitsLT(In.getValueType())) 9422 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 9423 In, N0.getOperand(1)); 9424 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 9425 } 9426 9427 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 9428 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 9429 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 9430 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9431 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 9432 LN0->getChain(), 9433 LN0->getBasePtr(), N0.getValueType(), 9434 LN0->getMemOperand()); 9435 CombineTo(N, ExtLoad); 9436 CombineTo(N0.getNode(), 9437 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 9438 N0.getValueType(), ExtLoad, 9439 DAG.getIntPtrConstant(1, SDLoc(N0))), 9440 ExtLoad.getValue(1)); 9441 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9442 } 9443 9444 return SDValue(); 9445 } 9446 9447 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 9448 SDValue N0 = N->getOperand(0); 9449 EVT VT = N->getValueType(0); 9450 9451 // fold (fceil c1) -> fceil(c1) 9452 if (isConstantFPBuildVectorOrConstantFP(N0)) 9453 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 9454 9455 return SDValue(); 9456 } 9457 9458 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 9459 SDValue N0 = N->getOperand(0); 9460 EVT VT = N->getValueType(0); 9461 9462 // fold (ftrunc c1) -> ftrunc(c1) 9463 if (isConstantFPBuildVectorOrConstantFP(N0)) 9464 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 9465 9466 return SDValue(); 9467 } 9468 9469 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 9470 SDValue N0 = N->getOperand(0); 9471 EVT VT = N->getValueType(0); 9472 9473 // fold (ffloor c1) -> ffloor(c1) 9474 if (isConstantFPBuildVectorOrConstantFP(N0)) 9475 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 9476 9477 return SDValue(); 9478 } 9479 9480 // FIXME: FNEG and FABS have a lot in common; refactor. 9481 SDValue DAGCombiner::visitFNEG(SDNode *N) { 9482 SDValue N0 = N->getOperand(0); 9483 EVT VT = N->getValueType(0); 9484 9485 // Constant fold FNEG. 9486 if (isConstantFPBuildVectorOrConstantFP(N0)) 9487 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 9488 9489 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 9490 &DAG.getTarget().Options)) 9491 return GetNegatedExpression(N0, DAG, LegalOperations); 9492 9493 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 9494 // constant pool values. 9495 if (!TLI.isFNegFree(VT) && 9496 N0.getOpcode() == ISD::BITCAST && 9497 N0.getNode()->hasOneUse()) { 9498 SDValue Int = N0.getOperand(0); 9499 EVT IntVT = Int.getValueType(); 9500 if (IntVT.isInteger() && !IntVT.isVector()) { 9501 APInt SignMask; 9502 if (N0.getValueType().isVector()) { 9503 // For a vector, get a mask such as 0x80... per scalar element 9504 // and splat it. 9505 SignMask = APInt::getSignBit(N0.getScalarValueSizeInBits()); 9506 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9507 } else { 9508 // For a scalar, just generate 0x80... 9509 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 9510 } 9511 SDLoc DL0(N0); 9512 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 9513 DAG.getConstant(SignMask, DL0, IntVT)); 9514 AddToWorklist(Int.getNode()); 9515 return DAG.getBitcast(VT, Int); 9516 } 9517 } 9518 9519 // (fneg (fmul c, x)) -> (fmul -c, x) 9520 if (N0.getOpcode() == ISD::FMUL && 9521 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 9522 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9523 if (CFP1) { 9524 APFloat CVal = CFP1->getValueAPF(); 9525 CVal.changeSign(); 9526 if (Level >= AfterLegalizeDAG && 9527 (TLI.isFPImmLegal(CVal, VT) || 9528 TLI.isOperationLegal(ISD::ConstantFP, VT))) 9529 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 9530 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 9531 N0.getOperand(1)), 9532 &cast<BinaryWithFlagsSDNode>(N0)->Flags); 9533 } 9534 } 9535 9536 return SDValue(); 9537 } 9538 9539 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 9540 SDValue N0 = N->getOperand(0); 9541 SDValue N1 = N->getOperand(1); 9542 EVT VT = N->getValueType(0); 9543 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9544 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9545 9546 if (N0CFP && N1CFP) { 9547 const APFloat &C0 = N0CFP->getValueAPF(); 9548 const APFloat &C1 = N1CFP->getValueAPF(); 9549 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 9550 } 9551 9552 // Canonicalize to constant on RHS. 9553 if (isConstantFPBuildVectorOrConstantFP(N0) && 9554 !isConstantFPBuildVectorOrConstantFP(N1)) 9555 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 9556 9557 return SDValue(); 9558 } 9559 9560 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 9561 SDValue N0 = N->getOperand(0); 9562 SDValue N1 = N->getOperand(1); 9563 EVT VT = N->getValueType(0); 9564 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9565 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9566 9567 if (N0CFP && N1CFP) { 9568 const APFloat &C0 = N0CFP->getValueAPF(); 9569 const APFloat &C1 = N1CFP->getValueAPF(); 9570 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 9571 } 9572 9573 // Canonicalize to constant on RHS. 9574 if (isConstantFPBuildVectorOrConstantFP(N0) && 9575 !isConstantFPBuildVectorOrConstantFP(N1)) 9576 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 9577 9578 return SDValue(); 9579 } 9580 9581 SDValue DAGCombiner::visitFABS(SDNode *N) { 9582 SDValue N0 = N->getOperand(0); 9583 EVT VT = N->getValueType(0); 9584 9585 // fold (fabs c1) -> fabs(c1) 9586 if (isConstantFPBuildVectorOrConstantFP(N0)) 9587 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9588 9589 // fold (fabs (fabs x)) -> (fabs x) 9590 if (N0.getOpcode() == ISD::FABS) 9591 return N->getOperand(0); 9592 9593 // fold (fabs (fneg x)) -> (fabs x) 9594 // fold (fabs (fcopysign x, y)) -> (fabs x) 9595 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 9596 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 9597 9598 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 9599 // constant pool values. 9600 if (!TLI.isFAbsFree(VT) && 9601 N0.getOpcode() == ISD::BITCAST && 9602 N0.getNode()->hasOneUse()) { 9603 SDValue Int = N0.getOperand(0); 9604 EVT IntVT = Int.getValueType(); 9605 if (IntVT.isInteger() && !IntVT.isVector()) { 9606 APInt SignMask; 9607 if (N0.getValueType().isVector()) { 9608 // For a vector, get a mask such as 0x7f... per scalar element 9609 // and splat it. 9610 SignMask = ~APInt::getSignBit(N0.getScalarValueSizeInBits()); 9611 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9612 } else { 9613 // For a scalar, just generate 0x7f... 9614 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 9615 } 9616 SDLoc DL(N0); 9617 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 9618 DAG.getConstant(SignMask, DL, IntVT)); 9619 AddToWorklist(Int.getNode()); 9620 return DAG.getBitcast(N->getValueType(0), Int); 9621 } 9622 } 9623 9624 return SDValue(); 9625 } 9626 9627 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 9628 SDValue Chain = N->getOperand(0); 9629 SDValue N1 = N->getOperand(1); 9630 SDValue N2 = N->getOperand(2); 9631 9632 // If N is a constant we could fold this into a fallthrough or unconditional 9633 // branch. However that doesn't happen very often in normal code, because 9634 // Instcombine/SimplifyCFG should have handled the available opportunities. 9635 // If we did this folding here, it would be necessary to update the 9636 // MachineBasicBlock CFG, which is awkward. 9637 9638 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 9639 // on the target. 9640 if (N1.getOpcode() == ISD::SETCC && 9641 TLI.isOperationLegalOrCustom(ISD::BR_CC, 9642 N1.getOperand(0).getValueType())) { 9643 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9644 Chain, N1.getOperand(2), 9645 N1.getOperand(0), N1.getOperand(1), N2); 9646 } 9647 9648 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 9649 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 9650 (N1.getOperand(0).hasOneUse() && 9651 N1.getOperand(0).getOpcode() == ISD::SRL))) { 9652 SDNode *Trunc = nullptr; 9653 if (N1.getOpcode() == ISD::TRUNCATE) { 9654 // Look pass the truncate. 9655 Trunc = N1.getNode(); 9656 N1 = N1.getOperand(0); 9657 } 9658 9659 // Match this pattern so that we can generate simpler code: 9660 // 9661 // %a = ... 9662 // %b = and i32 %a, 2 9663 // %c = srl i32 %b, 1 9664 // brcond i32 %c ... 9665 // 9666 // into 9667 // 9668 // %a = ... 9669 // %b = and i32 %a, 2 9670 // %c = setcc eq %b, 0 9671 // brcond %c ... 9672 // 9673 // This applies only when the AND constant value has one bit set and the 9674 // SRL constant is equal to the log2 of the AND constant. The back-end is 9675 // smart enough to convert the result into a TEST/JMP sequence. 9676 SDValue Op0 = N1.getOperand(0); 9677 SDValue Op1 = N1.getOperand(1); 9678 9679 if (Op0.getOpcode() == ISD::AND && 9680 Op1.getOpcode() == ISD::Constant) { 9681 SDValue AndOp1 = Op0.getOperand(1); 9682 9683 if (AndOp1.getOpcode() == ISD::Constant) { 9684 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 9685 9686 if (AndConst.isPowerOf2() && 9687 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 9688 SDLoc DL(N); 9689 SDValue SetCC = 9690 DAG.getSetCC(DL, 9691 getSetCCResultType(Op0.getValueType()), 9692 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 9693 ISD::SETNE); 9694 9695 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 9696 MVT::Other, Chain, SetCC, N2); 9697 // Don't add the new BRCond into the worklist or else SimplifySelectCC 9698 // will convert it back to (X & C1) >> C2. 9699 CombineTo(N, NewBRCond, false); 9700 // Truncate is dead. 9701 if (Trunc) 9702 deleteAndRecombine(Trunc); 9703 // Replace the uses of SRL with SETCC 9704 WorklistRemover DeadNodes(*this); 9705 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9706 deleteAndRecombine(N1.getNode()); 9707 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9708 } 9709 } 9710 } 9711 9712 if (Trunc) 9713 // Restore N1 if the above transformation doesn't match. 9714 N1 = N->getOperand(1); 9715 } 9716 9717 // Transform br(xor(x, y)) -> br(x != y) 9718 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 9719 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 9720 SDNode *TheXor = N1.getNode(); 9721 SDValue Op0 = TheXor->getOperand(0); 9722 SDValue Op1 = TheXor->getOperand(1); 9723 if (Op0.getOpcode() == Op1.getOpcode()) { 9724 // Avoid missing important xor optimizations. 9725 if (SDValue Tmp = visitXOR(TheXor)) { 9726 if (Tmp.getNode() != TheXor) { 9727 DEBUG(dbgs() << "\nReplacing.8 "; 9728 TheXor->dump(&DAG); 9729 dbgs() << "\nWith: "; 9730 Tmp.getNode()->dump(&DAG); 9731 dbgs() << '\n'); 9732 WorklistRemover DeadNodes(*this); 9733 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 9734 deleteAndRecombine(TheXor); 9735 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9736 MVT::Other, Chain, Tmp, N2); 9737 } 9738 9739 // visitXOR has changed XOR's operands or replaced the XOR completely, 9740 // bail out. 9741 return SDValue(N, 0); 9742 } 9743 } 9744 9745 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 9746 bool Equal = false; 9747 if (isOneConstant(Op0) && Op0.hasOneUse() && 9748 Op0.getOpcode() == ISD::XOR) { 9749 TheXor = Op0.getNode(); 9750 Equal = true; 9751 } 9752 9753 EVT SetCCVT = N1.getValueType(); 9754 if (LegalTypes) 9755 SetCCVT = getSetCCResultType(SetCCVT); 9756 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 9757 SetCCVT, 9758 Op0, Op1, 9759 Equal ? ISD::SETEQ : ISD::SETNE); 9760 // Replace the uses of XOR with SETCC 9761 WorklistRemover DeadNodes(*this); 9762 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9763 deleteAndRecombine(N1.getNode()); 9764 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9765 MVT::Other, Chain, SetCC, N2); 9766 } 9767 } 9768 9769 return SDValue(); 9770 } 9771 9772 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 9773 // 9774 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 9775 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 9776 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 9777 9778 // If N is a constant we could fold this into a fallthrough or unconditional 9779 // branch. However that doesn't happen very often in normal code, because 9780 // Instcombine/SimplifyCFG should have handled the available opportunities. 9781 // If we did this folding here, it would be necessary to update the 9782 // MachineBasicBlock CFG, which is awkward. 9783 9784 // Use SimplifySetCC to simplify SETCC's. 9785 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 9786 CondLHS, CondRHS, CC->get(), SDLoc(N), 9787 false); 9788 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 9789 9790 // fold to a simpler setcc 9791 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 9792 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9793 N->getOperand(0), Simp.getOperand(2), 9794 Simp.getOperand(0), Simp.getOperand(1), 9795 N->getOperand(4)); 9796 9797 return SDValue(); 9798 } 9799 9800 /// Return true if 'Use' is a load or a store that uses N as its base pointer 9801 /// and that N may be folded in the load / store addressing mode. 9802 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 9803 SelectionDAG &DAG, 9804 const TargetLowering &TLI) { 9805 EVT VT; 9806 unsigned AS; 9807 9808 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 9809 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 9810 return false; 9811 VT = LD->getMemoryVT(); 9812 AS = LD->getAddressSpace(); 9813 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 9814 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 9815 return false; 9816 VT = ST->getMemoryVT(); 9817 AS = ST->getAddressSpace(); 9818 } else 9819 return false; 9820 9821 TargetLowering::AddrMode AM; 9822 if (N->getOpcode() == ISD::ADD) { 9823 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9824 if (Offset) 9825 // [reg +/- imm] 9826 AM.BaseOffs = Offset->getSExtValue(); 9827 else 9828 // [reg +/- reg] 9829 AM.Scale = 1; 9830 } else if (N->getOpcode() == ISD::SUB) { 9831 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9832 if (Offset) 9833 // [reg +/- imm] 9834 AM.BaseOffs = -Offset->getSExtValue(); 9835 else 9836 // [reg +/- reg] 9837 AM.Scale = 1; 9838 } else 9839 return false; 9840 9841 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 9842 VT.getTypeForEVT(*DAG.getContext()), AS); 9843 } 9844 9845 /// Try turning a load/store into a pre-indexed load/store when the base 9846 /// pointer is an add or subtract and it has other uses besides the load/store. 9847 /// After the transformation, the new indexed load/store has effectively folded 9848 /// the add/subtract in and all of its other uses are redirected to the 9849 /// new load/store. 9850 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 9851 if (Level < AfterLegalizeDAG) 9852 return false; 9853 9854 bool isLoad = true; 9855 SDValue Ptr; 9856 EVT VT; 9857 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9858 if (LD->isIndexed()) 9859 return false; 9860 VT = LD->getMemoryVT(); 9861 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 9862 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 9863 return false; 9864 Ptr = LD->getBasePtr(); 9865 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9866 if (ST->isIndexed()) 9867 return false; 9868 VT = ST->getMemoryVT(); 9869 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 9870 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 9871 return false; 9872 Ptr = ST->getBasePtr(); 9873 isLoad = false; 9874 } else { 9875 return false; 9876 } 9877 9878 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 9879 // out. There is no reason to make this a preinc/predec. 9880 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 9881 Ptr.getNode()->hasOneUse()) 9882 return false; 9883 9884 // Ask the target to do addressing mode selection. 9885 SDValue BasePtr; 9886 SDValue Offset; 9887 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9888 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 9889 return false; 9890 9891 // Backends without true r+i pre-indexed forms may need to pass a 9892 // constant base with a variable offset so that constant coercion 9893 // will work with the patterns in canonical form. 9894 bool Swapped = false; 9895 if (isa<ConstantSDNode>(BasePtr)) { 9896 std::swap(BasePtr, Offset); 9897 Swapped = true; 9898 } 9899 9900 // Don't create a indexed load / store with zero offset. 9901 if (isNullConstant(Offset)) 9902 return false; 9903 9904 // Try turning it into a pre-indexed load / store except when: 9905 // 1) The new base ptr is a frame index. 9906 // 2) If N is a store and the new base ptr is either the same as or is a 9907 // predecessor of the value being stored. 9908 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 9909 // that would create a cycle. 9910 // 4) All uses are load / store ops that use it as old base ptr. 9911 9912 // Check #1. Preinc'ing a frame index would require copying the stack pointer 9913 // (plus the implicit offset) to a register to preinc anyway. 9914 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9915 return false; 9916 9917 // Check #2. 9918 if (!isLoad) { 9919 SDValue Val = cast<StoreSDNode>(N)->getValue(); 9920 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 9921 return false; 9922 } 9923 9924 // Caches for hasPredecessorHelper. 9925 SmallPtrSet<const SDNode *, 32> Visited; 9926 SmallVector<const SDNode *, 16> Worklist; 9927 Worklist.push_back(N); 9928 9929 // If the offset is a constant, there may be other adds of constants that 9930 // can be folded with this one. We should do this to avoid having to keep 9931 // a copy of the original base pointer. 9932 SmallVector<SDNode *, 16> OtherUses; 9933 if (isa<ConstantSDNode>(Offset)) 9934 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 9935 UE = BasePtr.getNode()->use_end(); 9936 UI != UE; ++UI) { 9937 SDUse &Use = UI.getUse(); 9938 // Skip the use that is Ptr and uses of other results from BasePtr's 9939 // node (important for nodes that return multiple results). 9940 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 9941 continue; 9942 9943 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 9944 continue; 9945 9946 if (Use.getUser()->getOpcode() != ISD::ADD && 9947 Use.getUser()->getOpcode() != ISD::SUB) { 9948 OtherUses.clear(); 9949 break; 9950 } 9951 9952 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 9953 if (!isa<ConstantSDNode>(Op1)) { 9954 OtherUses.clear(); 9955 break; 9956 } 9957 9958 // FIXME: In some cases, we can be smarter about this. 9959 if (Op1.getValueType() != Offset.getValueType()) { 9960 OtherUses.clear(); 9961 break; 9962 } 9963 9964 OtherUses.push_back(Use.getUser()); 9965 } 9966 9967 if (Swapped) 9968 std::swap(BasePtr, Offset); 9969 9970 // Now check for #3 and #4. 9971 bool RealUse = false; 9972 9973 for (SDNode *Use : Ptr.getNode()->uses()) { 9974 if (Use == N) 9975 continue; 9976 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 9977 return false; 9978 9979 // If Ptr may be folded in addressing mode of other use, then it's 9980 // not profitable to do this transformation. 9981 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 9982 RealUse = true; 9983 } 9984 9985 if (!RealUse) 9986 return false; 9987 9988 SDValue Result; 9989 if (isLoad) 9990 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9991 BasePtr, Offset, AM); 9992 else 9993 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9994 BasePtr, Offset, AM); 9995 ++PreIndexedNodes; 9996 ++NodesCombined; 9997 DEBUG(dbgs() << "\nReplacing.4 "; 9998 N->dump(&DAG); 9999 dbgs() << "\nWith: "; 10000 Result.getNode()->dump(&DAG); 10001 dbgs() << '\n'); 10002 WorklistRemover DeadNodes(*this); 10003 if (isLoad) { 10004 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 10005 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 10006 } else { 10007 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 10008 } 10009 10010 // Finally, since the node is now dead, remove it from the graph. 10011 deleteAndRecombine(N); 10012 10013 if (Swapped) 10014 std::swap(BasePtr, Offset); 10015 10016 // Replace other uses of BasePtr that can be updated to use Ptr 10017 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 10018 unsigned OffsetIdx = 1; 10019 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 10020 OffsetIdx = 0; 10021 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 10022 BasePtr.getNode() && "Expected BasePtr operand"); 10023 10024 // We need to replace ptr0 in the following expression: 10025 // x0 * offset0 + y0 * ptr0 = t0 10026 // knowing that 10027 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 10028 // 10029 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 10030 // indexed load/store and the expresion that needs to be re-written. 10031 // 10032 // Therefore, we have: 10033 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 10034 10035 ConstantSDNode *CN = 10036 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 10037 int X0, X1, Y0, Y1; 10038 const APInt &Offset0 = CN->getAPIntValue(); 10039 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 10040 10041 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 10042 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 10043 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 10044 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 10045 10046 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 10047 10048 APInt CNV = Offset0; 10049 if (X0 < 0) CNV = -CNV; 10050 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 10051 else CNV = CNV - Offset1; 10052 10053 SDLoc DL(OtherUses[i]); 10054 10055 // We can now generate the new expression. 10056 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 10057 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 10058 10059 SDValue NewUse = DAG.getNode(Opcode, 10060 DL, 10061 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 10062 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 10063 deleteAndRecombine(OtherUses[i]); 10064 } 10065 10066 // Replace the uses of Ptr with uses of the updated base value. 10067 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 10068 deleteAndRecombine(Ptr.getNode()); 10069 10070 return true; 10071 } 10072 10073 /// Try to combine a load/store with a add/sub of the base pointer node into a 10074 /// post-indexed load/store. The transformation folded the add/subtract into the 10075 /// new indexed load/store effectively and all of its uses are redirected to the 10076 /// new load/store. 10077 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 10078 if (Level < AfterLegalizeDAG) 10079 return false; 10080 10081 bool isLoad = true; 10082 SDValue Ptr; 10083 EVT VT; 10084 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10085 if (LD->isIndexed()) 10086 return false; 10087 VT = LD->getMemoryVT(); 10088 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 10089 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 10090 return false; 10091 Ptr = LD->getBasePtr(); 10092 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10093 if (ST->isIndexed()) 10094 return false; 10095 VT = ST->getMemoryVT(); 10096 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 10097 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 10098 return false; 10099 Ptr = ST->getBasePtr(); 10100 isLoad = false; 10101 } else { 10102 return false; 10103 } 10104 10105 if (Ptr.getNode()->hasOneUse()) 10106 return false; 10107 10108 for (SDNode *Op : Ptr.getNode()->uses()) { 10109 if (Op == N || 10110 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 10111 continue; 10112 10113 SDValue BasePtr; 10114 SDValue Offset; 10115 ISD::MemIndexedMode AM = ISD::UNINDEXED; 10116 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 10117 // Don't create a indexed load / store with zero offset. 10118 if (isNullConstant(Offset)) 10119 continue; 10120 10121 // Try turning it into a post-indexed load / store except when 10122 // 1) All uses are load / store ops that use it as base ptr (and 10123 // it may be folded as addressing mmode). 10124 // 2) Op must be independent of N, i.e. Op is neither a predecessor 10125 // nor a successor of N. Otherwise, if Op is folded that would 10126 // create a cycle. 10127 10128 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 10129 continue; 10130 10131 // Check for #1. 10132 bool TryNext = false; 10133 for (SDNode *Use : BasePtr.getNode()->uses()) { 10134 if (Use == Ptr.getNode()) 10135 continue; 10136 10137 // If all the uses are load / store addresses, then don't do the 10138 // transformation. 10139 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 10140 bool RealUse = false; 10141 for (SDNode *UseUse : Use->uses()) { 10142 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 10143 RealUse = true; 10144 } 10145 10146 if (!RealUse) { 10147 TryNext = true; 10148 break; 10149 } 10150 } 10151 } 10152 10153 if (TryNext) 10154 continue; 10155 10156 // Check for #2 10157 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 10158 SDValue Result = isLoad 10159 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 10160 BasePtr, Offset, AM) 10161 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 10162 BasePtr, Offset, AM); 10163 ++PostIndexedNodes; 10164 ++NodesCombined; 10165 DEBUG(dbgs() << "\nReplacing.5 "; 10166 N->dump(&DAG); 10167 dbgs() << "\nWith: "; 10168 Result.getNode()->dump(&DAG); 10169 dbgs() << '\n'); 10170 WorklistRemover DeadNodes(*this); 10171 if (isLoad) { 10172 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 10173 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 10174 } else { 10175 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 10176 } 10177 10178 // Finally, since the node is now dead, remove it from the graph. 10179 deleteAndRecombine(N); 10180 10181 // Replace the uses of Use with uses of the updated base value. 10182 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 10183 Result.getValue(isLoad ? 1 : 0)); 10184 deleteAndRecombine(Op); 10185 return true; 10186 } 10187 } 10188 } 10189 10190 return false; 10191 } 10192 10193 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 10194 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 10195 ISD::MemIndexedMode AM = LD->getAddressingMode(); 10196 assert(AM != ISD::UNINDEXED); 10197 SDValue BP = LD->getOperand(1); 10198 SDValue Inc = LD->getOperand(2); 10199 10200 // Some backends use TargetConstants for load offsets, but don't expect 10201 // TargetConstants in general ADD nodes. We can convert these constants into 10202 // regular Constants (if the constant is not opaque). 10203 assert((Inc.getOpcode() != ISD::TargetConstant || 10204 !cast<ConstantSDNode>(Inc)->isOpaque()) && 10205 "Cannot split out indexing using opaque target constants"); 10206 if (Inc.getOpcode() == ISD::TargetConstant) { 10207 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 10208 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 10209 ConstInc->getValueType(0)); 10210 } 10211 10212 unsigned Opc = 10213 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 10214 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 10215 } 10216 10217 SDValue DAGCombiner::visitLOAD(SDNode *N) { 10218 LoadSDNode *LD = cast<LoadSDNode>(N); 10219 SDValue Chain = LD->getChain(); 10220 SDValue Ptr = LD->getBasePtr(); 10221 10222 // If load is not volatile and there are no uses of the loaded value (and 10223 // the updated indexed value in case of indexed loads), change uses of the 10224 // chain value into uses of the chain input (i.e. delete the dead load). 10225 if (!LD->isVolatile()) { 10226 if (N->getValueType(1) == MVT::Other) { 10227 // Unindexed loads. 10228 if (!N->hasAnyUseOfValue(0)) { 10229 // It's not safe to use the two value CombineTo variant here. e.g. 10230 // v1, chain2 = load chain1, loc 10231 // v2, chain3 = load chain2, loc 10232 // v3 = add v2, c 10233 // Now we replace use of chain2 with chain1. This makes the second load 10234 // isomorphic to the one we are deleting, and thus makes this load live. 10235 DEBUG(dbgs() << "\nReplacing.6 "; 10236 N->dump(&DAG); 10237 dbgs() << "\nWith chain: "; 10238 Chain.getNode()->dump(&DAG); 10239 dbgs() << "\n"); 10240 WorklistRemover DeadNodes(*this); 10241 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10242 10243 if (N->use_empty()) 10244 deleteAndRecombine(N); 10245 10246 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10247 } 10248 } else { 10249 // Indexed loads. 10250 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 10251 10252 // If this load has an opaque TargetConstant offset, then we cannot split 10253 // the indexing into an add/sub directly (that TargetConstant may not be 10254 // valid for a different type of node, and we cannot convert an opaque 10255 // target constant into a regular constant). 10256 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 10257 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 10258 10259 if (!N->hasAnyUseOfValue(0) && 10260 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 10261 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 10262 SDValue Index; 10263 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 10264 Index = SplitIndexingFromLoad(LD); 10265 // Try to fold the base pointer arithmetic into subsequent loads and 10266 // stores. 10267 AddUsersToWorklist(N); 10268 } else 10269 Index = DAG.getUNDEF(N->getValueType(1)); 10270 DEBUG(dbgs() << "\nReplacing.7 "; 10271 N->dump(&DAG); 10272 dbgs() << "\nWith: "; 10273 Undef.getNode()->dump(&DAG); 10274 dbgs() << " and 2 other values\n"); 10275 WorklistRemover DeadNodes(*this); 10276 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 10277 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 10278 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 10279 deleteAndRecombine(N); 10280 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10281 } 10282 } 10283 } 10284 10285 // If this load is directly stored, replace the load value with the stored 10286 // value. 10287 // TODO: Handle store large -> read small portion. 10288 // TODO: Handle TRUNCSTORE/LOADEXT 10289 if (OptLevel != CodeGenOpt::None && 10290 ISD::isNormalLoad(N) && !LD->isVolatile()) { 10291 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 10292 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 10293 if (PrevST->getBasePtr() == Ptr && 10294 PrevST->getValue().getValueType() == N->getValueType(0)) 10295 return CombineTo(N, Chain.getOperand(1), Chain); 10296 } 10297 } 10298 10299 // Try to infer better alignment information than the load already has. 10300 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 10301 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 10302 if (Align > LD->getMemOperand()->getBaseAlignment()) { 10303 SDValue NewLoad = DAG.getExtLoad( 10304 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 10305 LD->getPointerInfo(), LD->getMemoryVT(), Align, 10306 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 10307 if (NewLoad.getNode() != N) 10308 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 10309 } 10310 } 10311 } 10312 10313 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 10314 : DAG.getSubtarget().useAA(); 10315 #ifndef NDEBUG 10316 if (CombinerAAOnlyFunc.getNumOccurrences() && 10317 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 10318 UseAA = false; 10319 #endif 10320 if (UseAA && LD->isUnindexed()) { 10321 // Walk up chain skipping non-aliasing memory nodes. 10322 SDValue BetterChain = FindBetterChain(N, Chain); 10323 10324 // If there is a better chain. 10325 if (Chain != BetterChain) { 10326 SDValue ReplLoad; 10327 10328 // Replace the chain to void dependency. 10329 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 10330 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 10331 BetterChain, Ptr, LD->getMemOperand()); 10332 } else { 10333 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 10334 LD->getValueType(0), 10335 BetterChain, Ptr, LD->getMemoryVT(), 10336 LD->getMemOperand()); 10337 } 10338 10339 // Create token factor to keep old chain connected. 10340 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 10341 MVT::Other, Chain, ReplLoad.getValue(1)); 10342 10343 // Make sure the new and old chains are cleaned up. 10344 AddToWorklist(Token.getNode()); 10345 10346 // Replace uses with load result and token factor. Don't add users 10347 // to work list. 10348 return CombineTo(N, ReplLoad.getValue(0), Token, false); 10349 } 10350 } 10351 10352 // Try transforming N to an indexed load. 10353 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 10354 return SDValue(N, 0); 10355 10356 // Try to slice up N to more direct loads if the slices are mapped to 10357 // different register banks or pairing can take place. 10358 if (SliceUpLoad(N)) 10359 return SDValue(N, 0); 10360 10361 return SDValue(); 10362 } 10363 10364 namespace { 10365 /// \brief Helper structure used to slice a load in smaller loads. 10366 /// Basically a slice is obtained from the following sequence: 10367 /// Origin = load Ty1, Base 10368 /// Shift = srl Ty1 Origin, CstTy Amount 10369 /// Inst = trunc Shift to Ty2 10370 /// 10371 /// Then, it will be rewriten into: 10372 /// Slice = load SliceTy, Base + SliceOffset 10373 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 10374 /// 10375 /// SliceTy is deduced from the number of bits that are actually used to 10376 /// build Inst. 10377 struct LoadedSlice { 10378 /// \brief Helper structure used to compute the cost of a slice. 10379 struct Cost { 10380 /// Are we optimizing for code size. 10381 bool ForCodeSize; 10382 /// Various cost. 10383 unsigned Loads; 10384 unsigned Truncates; 10385 unsigned CrossRegisterBanksCopies; 10386 unsigned ZExts; 10387 unsigned Shift; 10388 10389 Cost(bool ForCodeSize = false) 10390 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 10391 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 10392 10393 /// \brief Get the cost of one isolated slice. 10394 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 10395 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 10396 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 10397 EVT TruncType = LS.Inst->getValueType(0); 10398 EVT LoadedType = LS.getLoadedType(); 10399 if (TruncType != LoadedType && 10400 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 10401 ZExts = 1; 10402 } 10403 10404 /// \brief Account for slicing gain in the current cost. 10405 /// Slicing provide a few gains like removing a shift or a 10406 /// truncate. This method allows to grow the cost of the original 10407 /// load with the gain from this slice. 10408 void addSliceGain(const LoadedSlice &LS) { 10409 // Each slice saves a truncate. 10410 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 10411 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 10412 LS.Inst->getValueType(0))) 10413 ++Truncates; 10414 // If there is a shift amount, this slice gets rid of it. 10415 if (LS.Shift) 10416 ++Shift; 10417 // If this slice can merge a cross register bank copy, account for it. 10418 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 10419 ++CrossRegisterBanksCopies; 10420 } 10421 10422 Cost &operator+=(const Cost &RHS) { 10423 Loads += RHS.Loads; 10424 Truncates += RHS.Truncates; 10425 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 10426 ZExts += RHS.ZExts; 10427 Shift += RHS.Shift; 10428 return *this; 10429 } 10430 10431 bool operator==(const Cost &RHS) const { 10432 return Loads == RHS.Loads && Truncates == RHS.Truncates && 10433 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 10434 ZExts == RHS.ZExts && Shift == RHS.Shift; 10435 } 10436 10437 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 10438 10439 bool operator<(const Cost &RHS) const { 10440 // Assume cross register banks copies are as expensive as loads. 10441 // FIXME: Do we want some more target hooks? 10442 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 10443 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 10444 // Unless we are optimizing for code size, consider the 10445 // expensive operation first. 10446 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 10447 return ExpensiveOpsLHS < ExpensiveOpsRHS; 10448 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 10449 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 10450 } 10451 10452 bool operator>(const Cost &RHS) const { return RHS < *this; } 10453 10454 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 10455 10456 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 10457 }; 10458 // The last instruction that represent the slice. This should be a 10459 // truncate instruction. 10460 SDNode *Inst; 10461 // The original load instruction. 10462 LoadSDNode *Origin; 10463 // The right shift amount in bits from the original load. 10464 unsigned Shift; 10465 // The DAG from which Origin came from. 10466 // This is used to get some contextual information about legal types, etc. 10467 SelectionDAG *DAG; 10468 10469 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 10470 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 10471 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 10472 10473 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 10474 /// \return Result is \p BitWidth and has used bits set to 1 and 10475 /// not used bits set to 0. 10476 APInt getUsedBits() const { 10477 // Reproduce the trunc(lshr) sequence: 10478 // - Start from the truncated value. 10479 // - Zero extend to the desired bit width. 10480 // - Shift left. 10481 assert(Origin && "No original load to compare against."); 10482 unsigned BitWidth = Origin->getValueSizeInBits(0); 10483 assert(Inst && "This slice is not bound to an instruction"); 10484 assert(Inst->getValueSizeInBits(0) <= BitWidth && 10485 "Extracted slice is bigger than the whole type!"); 10486 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 10487 UsedBits.setAllBits(); 10488 UsedBits = UsedBits.zext(BitWidth); 10489 UsedBits <<= Shift; 10490 return UsedBits; 10491 } 10492 10493 /// \brief Get the size of the slice to be loaded in bytes. 10494 unsigned getLoadedSize() const { 10495 unsigned SliceSize = getUsedBits().countPopulation(); 10496 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 10497 return SliceSize / 8; 10498 } 10499 10500 /// \brief Get the type that will be loaded for this slice. 10501 /// Note: This may not be the final type for the slice. 10502 EVT getLoadedType() const { 10503 assert(DAG && "Missing context"); 10504 LLVMContext &Ctxt = *DAG->getContext(); 10505 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 10506 } 10507 10508 /// \brief Get the alignment of the load used for this slice. 10509 unsigned getAlignment() const { 10510 unsigned Alignment = Origin->getAlignment(); 10511 unsigned Offset = getOffsetFromBase(); 10512 if (Offset != 0) 10513 Alignment = MinAlign(Alignment, Alignment + Offset); 10514 return Alignment; 10515 } 10516 10517 /// \brief Check if this slice can be rewritten with legal operations. 10518 bool isLegal() const { 10519 // An invalid slice is not legal. 10520 if (!Origin || !Inst || !DAG) 10521 return false; 10522 10523 // Offsets are for indexed load only, we do not handle that. 10524 if (!Origin->getOffset().isUndef()) 10525 return false; 10526 10527 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10528 10529 // Check that the type is legal. 10530 EVT SliceType = getLoadedType(); 10531 if (!TLI.isTypeLegal(SliceType)) 10532 return false; 10533 10534 // Check that the load is legal for this type. 10535 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 10536 return false; 10537 10538 // Check that the offset can be computed. 10539 // 1. Check its type. 10540 EVT PtrType = Origin->getBasePtr().getValueType(); 10541 if (PtrType == MVT::Untyped || PtrType.isExtended()) 10542 return false; 10543 10544 // 2. Check that it fits in the immediate. 10545 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 10546 return false; 10547 10548 // 3. Check that the computation is legal. 10549 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 10550 return false; 10551 10552 // Check that the zext is legal if it needs one. 10553 EVT TruncateType = Inst->getValueType(0); 10554 if (TruncateType != SliceType && 10555 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 10556 return false; 10557 10558 return true; 10559 } 10560 10561 /// \brief Get the offset in bytes of this slice in the original chunk of 10562 /// bits. 10563 /// \pre DAG != nullptr. 10564 uint64_t getOffsetFromBase() const { 10565 assert(DAG && "Missing context."); 10566 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 10567 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 10568 uint64_t Offset = Shift / 8; 10569 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 10570 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 10571 "The size of the original loaded type is not a multiple of a" 10572 " byte."); 10573 // If Offset is bigger than TySizeInBytes, it means we are loading all 10574 // zeros. This should have been optimized before in the process. 10575 assert(TySizeInBytes > Offset && 10576 "Invalid shift amount for given loaded size"); 10577 if (IsBigEndian) 10578 Offset = TySizeInBytes - Offset - getLoadedSize(); 10579 return Offset; 10580 } 10581 10582 /// \brief Generate the sequence of instructions to load the slice 10583 /// represented by this object and redirect the uses of this slice to 10584 /// this new sequence of instructions. 10585 /// \pre this->Inst && this->Origin are valid Instructions and this 10586 /// object passed the legal check: LoadedSlice::isLegal returned true. 10587 /// \return The last instruction of the sequence used to load the slice. 10588 SDValue loadSlice() const { 10589 assert(Inst && Origin && "Unable to replace a non-existing slice."); 10590 const SDValue &OldBaseAddr = Origin->getBasePtr(); 10591 SDValue BaseAddr = OldBaseAddr; 10592 // Get the offset in that chunk of bytes w.r.t. the endianness. 10593 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 10594 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 10595 if (Offset) { 10596 // BaseAddr = BaseAddr + Offset. 10597 EVT ArithType = BaseAddr.getValueType(); 10598 SDLoc DL(Origin); 10599 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 10600 DAG->getConstant(Offset, DL, ArithType)); 10601 } 10602 10603 // Create the type of the loaded slice according to its size. 10604 EVT SliceType = getLoadedType(); 10605 10606 // Create the load for the slice. 10607 SDValue LastInst = 10608 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 10609 Origin->getPointerInfo().getWithOffset(Offset), 10610 getAlignment(), Origin->getMemOperand()->getFlags()); 10611 // If the final type is not the same as the loaded type, this means that 10612 // we have to pad with zero. Create a zero extend for that. 10613 EVT FinalType = Inst->getValueType(0); 10614 if (SliceType != FinalType) 10615 LastInst = 10616 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 10617 return LastInst; 10618 } 10619 10620 /// \brief Check if this slice can be merged with an expensive cross register 10621 /// bank copy. E.g., 10622 /// i = load i32 10623 /// f = bitcast i32 i to float 10624 bool canMergeExpensiveCrossRegisterBankCopy() const { 10625 if (!Inst || !Inst->hasOneUse()) 10626 return false; 10627 SDNode *Use = *Inst->use_begin(); 10628 if (Use->getOpcode() != ISD::BITCAST) 10629 return false; 10630 assert(DAG && "Missing context"); 10631 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10632 EVT ResVT = Use->getValueType(0); 10633 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 10634 const TargetRegisterClass *ArgRC = 10635 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 10636 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 10637 return false; 10638 10639 // At this point, we know that we perform a cross-register-bank copy. 10640 // Check if it is expensive. 10641 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 10642 // Assume bitcasts are cheap, unless both register classes do not 10643 // explicitly share a common sub class. 10644 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 10645 return false; 10646 10647 // Check if it will be merged with the load. 10648 // 1. Check the alignment constraint. 10649 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 10650 ResVT.getTypeForEVT(*DAG->getContext())); 10651 10652 if (RequiredAlignment > getAlignment()) 10653 return false; 10654 10655 // 2. Check that the load is a legal operation for that type. 10656 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 10657 return false; 10658 10659 // 3. Check that we do not have a zext in the way. 10660 if (Inst->getValueType(0) != getLoadedType()) 10661 return false; 10662 10663 return true; 10664 } 10665 }; 10666 } 10667 10668 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 10669 /// \p UsedBits looks like 0..0 1..1 0..0. 10670 static bool areUsedBitsDense(const APInt &UsedBits) { 10671 // If all the bits are one, this is dense! 10672 if (UsedBits.isAllOnesValue()) 10673 return true; 10674 10675 // Get rid of the unused bits on the right. 10676 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 10677 // Get rid of the unused bits on the left. 10678 if (NarrowedUsedBits.countLeadingZeros()) 10679 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 10680 // Check that the chunk of bits is completely used. 10681 return NarrowedUsedBits.isAllOnesValue(); 10682 } 10683 10684 /// \brief Check whether or not \p First and \p Second are next to each other 10685 /// in memory. This means that there is no hole between the bits loaded 10686 /// by \p First and the bits loaded by \p Second. 10687 static bool areSlicesNextToEachOther(const LoadedSlice &First, 10688 const LoadedSlice &Second) { 10689 assert(First.Origin == Second.Origin && First.Origin && 10690 "Unable to match different memory origins."); 10691 APInt UsedBits = First.getUsedBits(); 10692 assert((UsedBits & Second.getUsedBits()) == 0 && 10693 "Slices are not supposed to overlap."); 10694 UsedBits |= Second.getUsedBits(); 10695 return areUsedBitsDense(UsedBits); 10696 } 10697 10698 /// \brief Adjust the \p GlobalLSCost according to the target 10699 /// paring capabilities and the layout of the slices. 10700 /// \pre \p GlobalLSCost should account for at least as many loads as 10701 /// there is in the slices in \p LoadedSlices. 10702 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10703 LoadedSlice::Cost &GlobalLSCost) { 10704 unsigned NumberOfSlices = LoadedSlices.size(); 10705 // If there is less than 2 elements, no pairing is possible. 10706 if (NumberOfSlices < 2) 10707 return; 10708 10709 // Sort the slices so that elements that are likely to be next to each 10710 // other in memory are next to each other in the list. 10711 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 10712 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 10713 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 10714 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 10715 }); 10716 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 10717 // First (resp. Second) is the first (resp. Second) potentially candidate 10718 // to be placed in a paired load. 10719 const LoadedSlice *First = nullptr; 10720 const LoadedSlice *Second = nullptr; 10721 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 10722 // Set the beginning of the pair. 10723 First = Second) { 10724 10725 Second = &LoadedSlices[CurrSlice]; 10726 10727 // If First is NULL, it means we start a new pair. 10728 // Get to the next slice. 10729 if (!First) 10730 continue; 10731 10732 EVT LoadedType = First->getLoadedType(); 10733 10734 // If the types of the slices are different, we cannot pair them. 10735 if (LoadedType != Second->getLoadedType()) 10736 continue; 10737 10738 // Check if the target supplies paired loads for this type. 10739 unsigned RequiredAlignment = 0; 10740 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 10741 // move to the next pair, this type is hopeless. 10742 Second = nullptr; 10743 continue; 10744 } 10745 // Check if we meet the alignment requirement. 10746 if (RequiredAlignment > First->getAlignment()) 10747 continue; 10748 10749 // Check that both loads are next to each other in memory. 10750 if (!areSlicesNextToEachOther(*First, *Second)) 10751 continue; 10752 10753 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 10754 --GlobalLSCost.Loads; 10755 // Move to the next pair. 10756 Second = nullptr; 10757 } 10758 } 10759 10760 /// \brief Check the profitability of all involved LoadedSlice. 10761 /// Currently, it is considered profitable if there is exactly two 10762 /// involved slices (1) which are (2) next to each other in memory, and 10763 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 10764 /// 10765 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 10766 /// the elements themselves. 10767 /// 10768 /// FIXME: When the cost model will be mature enough, we can relax 10769 /// constraints (1) and (2). 10770 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10771 const APInt &UsedBits, bool ForCodeSize) { 10772 unsigned NumberOfSlices = LoadedSlices.size(); 10773 if (StressLoadSlicing) 10774 return NumberOfSlices > 1; 10775 10776 // Check (1). 10777 if (NumberOfSlices != 2) 10778 return false; 10779 10780 // Check (2). 10781 if (!areUsedBitsDense(UsedBits)) 10782 return false; 10783 10784 // Check (3). 10785 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 10786 // The original code has one big load. 10787 OrigCost.Loads = 1; 10788 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 10789 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 10790 // Accumulate the cost of all the slices. 10791 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 10792 GlobalSlicingCost += SliceCost; 10793 10794 // Account as cost in the original configuration the gain obtained 10795 // with the current slices. 10796 OrigCost.addSliceGain(LS); 10797 } 10798 10799 // If the target supports paired load, adjust the cost accordingly. 10800 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 10801 return OrigCost > GlobalSlicingCost; 10802 } 10803 10804 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 10805 /// operations, split it in the various pieces being extracted. 10806 /// 10807 /// This sort of thing is introduced by SROA. 10808 /// This slicing takes care not to insert overlapping loads. 10809 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 10810 bool DAGCombiner::SliceUpLoad(SDNode *N) { 10811 if (Level < AfterLegalizeDAG) 10812 return false; 10813 10814 LoadSDNode *LD = cast<LoadSDNode>(N); 10815 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 10816 !LD->getValueType(0).isInteger()) 10817 return false; 10818 10819 // Keep track of already used bits to detect overlapping values. 10820 // In that case, we will just abort the transformation. 10821 APInt UsedBits(LD->getValueSizeInBits(0), 0); 10822 10823 SmallVector<LoadedSlice, 4> LoadedSlices; 10824 10825 // Check if this load is used as several smaller chunks of bits. 10826 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 10827 // of computation for each trunc. 10828 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 10829 UI != UIEnd; ++UI) { 10830 // Skip the uses of the chain. 10831 if (UI.getUse().getResNo() != 0) 10832 continue; 10833 10834 SDNode *User = *UI; 10835 unsigned Shift = 0; 10836 10837 // Check if this is a trunc(lshr). 10838 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 10839 isa<ConstantSDNode>(User->getOperand(1))) { 10840 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 10841 User = *User->use_begin(); 10842 } 10843 10844 // At this point, User is a Truncate, iff we encountered, trunc or 10845 // trunc(lshr). 10846 if (User->getOpcode() != ISD::TRUNCATE) 10847 return false; 10848 10849 // The width of the type must be a power of 2 and greater than 8-bits. 10850 // Otherwise the load cannot be represented in LLVM IR. 10851 // Moreover, if we shifted with a non-8-bits multiple, the slice 10852 // will be across several bytes. We do not support that. 10853 unsigned Width = User->getValueSizeInBits(0); 10854 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 10855 return 0; 10856 10857 // Build the slice for this chain of computations. 10858 LoadedSlice LS(User, LD, Shift, &DAG); 10859 APInt CurrentUsedBits = LS.getUsedBits(); 10860 10861 // Check if this slice overlaps with another. 10862 if ((CurrentUsedBits & UsedBits) != 0) 10863 return false; 10864 // Update the bits used globally. 10865 UsedBits |= CurrentUsedBits; 10866 10867 // Check if the new slice would be legal. 10868 if (!LS.isLegal()) 10869 return false; 10870 10871 // Record the slice. 10872 LoadedSlices.push_back(LS); 10873 } 10874 10875 // Abort slicing if it does not seem to be profitable. 10876 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 10877 return false; 10878 10879 ++SlicedLoads; 10880 10881 // Rewrite each chain to use an independent load. 10882 // By construction, each chain can be represented by a unique load. 10883 10884 // Prepare the argument for the new token factor for all the slices. 10885 SmallVector<SDValue, 8> ArgChains; 10886 for (SmallVectorImpl<LoadedSlice>::const_iterator 10887 LSIt = LoadedSlices.begin(), 10888 LSItEnd = LoadedSlices.end(); 10889 LSIt != LSItEnd; ++LSIt) { 10890 SDValue SliceInst = LSIt->loadSlice(); 10891 CombineTo(LSIt->Inst, SliceInst, true); 10892 if (SliceInst.getOpcode() != ISD::LOAD) 10893 SliceInst = SliceInst.getOperand(0); 10894 assert(SliceInst->getOpcode() == ISD::LOAD && 10895 "It takes more than a zext to get to the loaded slice!!"); 10896 ArgChains.push_back(SliceInst.getValue(1)); 10897 } 10898 10899 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 10900 ArgChains); 10901 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10902 return true; 10903 } 10904 10905 /// Check to see if V is (and load (ptr), imm), where the load is having 10906 /// specific bytes cleared out. If so, return the byte size being masked out 10907 /// and the shift amount. 10908 static std::pair<unsigned, unsigned> 10909 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 10910 std::pair<unsigned, unsigned> Result(0, 0); 10911 10912 // Check for the structure we're looking for. 10913 if (V->getOpcode() != ISD::AND || 10914 !isa<ConstantSDNode>(V->getOperand(1)) || 10915 !ISD::isNormalLoad(V->getOperand(0).getNode())) 10916 return Result; 10917 10918 // Check the chain and pointer. 10919 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 10920 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 10921 10922 // The store should be chained directly to the load or be an operand of a 10923 // tokenfactor. 10924 if (LD == Chain.getNode()) 10925 ; // ok. 10926 else if (Chain->getOpcode() != ISD::TokenFactor) 10927 return Result; // Fail. 10928 else { 10929 bool isOk = false; 10930 for (const SDValue &ChainOp : Chain->op_values()) 10931 if (ChainOp.getNode() == LD) { 10932 isOk = true; 10933 break; 10934 } 10935 if (!isOk) return Result; 10936 } 10937 10938 // This only handles simple types. 10939 if (V.getValueType() != MVT::i16 && 10940 V.getValueType() != MVT::i32 && 10941 V.getValueType() != MVT::i64) 10942 return Result; 10943 10944 // Check the constant mask. Invert it so that the bits being masked out are 10945 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 10946 // follow the sign bit for uniformity. 10947 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 10948 unsigned NotMaskLZ = countLeadingZeros(NotMask); 10949 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 10950 unsigned NotMaskTZ = countTrailingZeros(NotMask); 10951 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 10952 if (NotMaskLZ == 64) return Result; // All zero mask. 10953 10954 // See if we have a continuous run of bits. If so, we have 0*1+0* 10955 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 10956 return Result; 10957 10958 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 10959 if (V.getValueType() != MVT::i64 && NotMaskLZ) 10960 NotMaskLZ -= 64-V.getValueSizeInBits(); 10961 10962 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 10963 switch (MaskedBytes) { 10964 case 1: 10965 case 2: 10966 case 4: break; 10967 default: return Result; // All one mask, or 5-byte mask. 10968 } 10969 10970 // Verify that the first bit starts at a multiple of mask so that the access 10971 // is aligned the same as the access width. 10972 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 10973 10974 Result.first = MaskedBytes; 10975 Result.second = NotMaskTZ/8; 10976 return Result; 10977 } 10978 10979 10980 /// Check to see if IVal is something that provides a value as specified by 10981 /// MaskInfo. If so, replace the specified store with a narrower store of 10982 /// truncated IVal. 10983 static SDNode * 10984 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 10985 SDValue IVal, StoreSDNode *St, 10986 DAGCombiner *DC) { 10987 unsigned NumBytes = MaskInfo.first; 10988 unsigned ByteShift = MaskInfo.second; 10989 SelectionDAG &DAG = DC->getDAG(); 10990 10991 // Check to see if IVal is all zeros in the part being masked in by the 'or' 10992 // that uses this. If not, this is not a replacement. 10993 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 10994 ByteShift*8, (ByteShift+NumBytes)*8); 10995 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 10996 10997 // Check that it is legal on the target to do this. It is legal if the new 10998 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 10999 // legalization. 11000 MVT VT = MVT::getIntegerVT(NumBytes*8); 11001 if (!DC->isTypeLegal(VT)) 11002 return nullptr; 11003 11004 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 11005 // shifted by ByteShift and truncated down to NumBytes. 11006 if (ByteShift) { 11007 SDLoc DL(IVal); 11008 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 11009 DAG.getConstant(ByteShift*8, DL, 11010 DC->getShiftAmountTy(IVal.getValueType()))); 11011 } 11012 11013 // Figure out the offset for the store and the alignment of the access. 11014 unsigned StOffset; 11015 unsigned NewAlign = St->getAlignment(); 11016 11017 if (DAG.getDataLayout().isLittleEndian()) 11018 StOffset = ByteShift; 11019 else 11020 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 11021 11022 SDValue Ptr = St->getBasePtr(); 11023 if (StOffset) { 11024 SDLoc DL(IVal); 11025 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 11026 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 11027 NewAlign = MinAlign(NewAlign, StOffset); 11028 } 11029 11030 // Truncate down to the new size. 11031 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 11032 11033 ++OpsNarrowed; 11034 return DAG 11035 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 11036 St->getPointerInfo().getWithOffset(StOffset), NewAlign) 11037 .getNode(); 11038 } 11039 11040 11041 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 11042 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 11043 /// narrowing the load and store if it would end up being a win for performance 11044 /// or code size. 11045 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 11046 StoreSDNode *ST = cast<StoreSDNode>(N); 11047 if (ST->isVolatile()) 11048 return SDValue(); 11049 11050 SDValue Chain = ST->getChain(); 11051 SDValue Value = ST->getValue(); 11052 SDValue Ptr = ST->getBasePtr(); 11053 EVT VT = Value.getValueType(); 11054 11055 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 11056 return SDValue(); 11057 11058 unsigned Opc = Value.getOpcode(); 11059 11060 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 11061 // is a byte mask indicating a consecutive number of bytes, check to see if 11062 // Y is known to provide just those bytes. If so, we try to replace the 11063 // load + replace + store sequence with a single (narrower) store, which makes 11064 // the load dead. 11065 if (Opc == ISD::OR) { 11066 std::pair<unsigned, unsigned> MaskedLoad; 11067 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 11068 if (MaskedLoad.first) 11069 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 11070 Value.getOperand(1), ST,this)) 11071 return SDValue(NewST, 0); 11072 11073 // Or is commutative, so try swapping X and Y. 11074 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 11075 if (MaskedLoad.first) 11076 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 11077 Value.getOperand(0), ST,this)) 11078 return SDValue(NewST, 0); 11079 } 11080 11081 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 11082 Value.getOperand(1).getOpcode() != ISD::Constant) 11083 return SDValue(); 11084 11085 SDValue N0 = Value.getOperand(0); 11086 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 11087 Chain == SDValue(N0.getNode(), 1)) { 11088 LoadSDNode *LD = cast<LoadSDNode>(N0); 11089 if (LD->getBasePtr() != Ptr || 11090 LD->getPointerInfo().getAddrSpace() != 11091 ST->getPointerInfo().getAddrSpace()) 11092 return SDValue(); 11093 11094 // Find the type to narrow it the load / op / store to. 11095 SDValue N1 = Value.getOperand(1); 11096 unsigned BitWidth = N1.getValueSizeInBits(); 11097 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 11098 if (Opc == ISD::AND) 11099 Imm ^= APInt::getAllOnesValue(BitWidth); 11100 if (Imm == 0 || Imm.isAllOnesValue()) 11101 return SDValue(); 11102 unsigned ShAmt = Imm.countTrailingZeros(); 11103 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 11104 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 11105 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 11106 // The narrowing should be profitable, the load/store operation should be 11107 // legal (or custom) and the store size should be equal to the NewVT width. 11108 while (NewBW < BitWidth && 11109 (NewVT.getStoreSizeInBits() != NewBW || 11110 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 11111 !TLI.isNarrowingProfitable(VT, NewVT))) { 11112 NewBW = NextPowerOf2(NewBW); 11113 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 11114 } 11115 if (NewBW >= BitWidth) 11116 return SDValue(); 11117 11118 // If the lsb changed does not start at the type bitwidth boundary, 11119 // start at the previous one. 11120 if (ShAmt % NewBW) 11121 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 11122 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 11123 std::min(BitWidth, ShAmt + NewBW)); 11124 if ((Imm & Mask) == Imm) { 11125 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 11126 if (Opc == ISD::AND) 11127 NewImm ^= APInt::getAllOnesValue(NewBW); 11128 uint64_t PtrOff = ShAmt / 8; 11129 // For big endian targets, we need to adjust the offset to the pointer to 11130 // load the correct bytes. 11131 if (DAG.getDataLayout().isBigEndian()) 11132 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 11133 11134 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 11135 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 11136 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 11137 return SDValue(); 11138 11139 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 11140 Ptr.getValueType(), Ptr, 11141 DAG.getConstant(PtrOff, SDLoc(LD), 11142 Ptr.getValueType())); 11143 SDValue NewLD = 11144 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 11145 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 11146 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 11147 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 11148 DAG.getConstant(NewImm, SDLoc(Value), 11149 NewVT)); 11150 SDValue NewST = 11151 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 11152 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 11153 11154 AddToWorklist(NewPtr.getNode()); 11155 AddToWorklist(NewLD.getNode()); 11156 AddToWorklist(NewVal.getNode()); 11157 WorklistRemover DeadNodes(*this); 11158 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 11159 ++OpsNarrowed; 11160 return NewST; 11161 } 11162 } 11163 11164 return SDValue(); 11165 } 11166 11167 /// For a given floating point load / store pair, if the load value isn't used 11168 /// by any other operations, then consider transforming the pair to integer 11169 /// load / store operations if the target deems the transformation profitable. 11170 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 11171 StoreSDNode *ST = cast<StoreSDNode>(N); 11172 SDValue Chain = ST->getChain(); 11173 SDValue Value = ST->getValue(); 11174 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 11175 Value.hasOneUse() && 11176 Chain == SDValue(Value.getNode(), 1)) { 11177 LoadSDNode *LD = cast<LoadSDNode>(Value); 11178 EVT VT = LD->getMemoryVT(); 11179 if (!VT.isFloatingPoint() || 11180 VT != ST->getMemoryVT() || 11181 LD->isNonTemporal() || 11182 ST->isNonTemporal() || 11183 LD->getPointerInfo().getAddrSpace() != 0 || 11184 ST->getPointerInfo().getAddrSpace() != 0) 11185 return SDValue(); 11186 11187 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 11188 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 11189 !TLI.isOperationLegal(ISD::STORE, IntVT) || 11190 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 11191 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 11192 return SDValue(); 11193 11194 unsigned LDAlign = LD->getAlignment(); 11195 unsigned STAlign = ST->getAlignment(); 11196 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 11197 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 11198 if (LDAlign < ABIAlign || STAlign < ABIAlign) 11199 return SDValue(); 11200 11201 SDValue NewLD = 11202 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 11203 LD->getPointerInfo(), LDAlign); 11204 11205 SDValue NewST = 11206 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(), 11207 ST->getPointerInfo(), STAlign); 11208 11209 AddToWorklist(NewLD.getNode()); 11210 AddToWorklist(NewST.getNode()); 11211 WorklistRemover DeadNodes(*this); 11212 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 11213 ++LdStFP2Int; 11214 return NewST; 11215 } 11216 11217 return SDValue(); 11218 } 11219 11220 namespace { 11221 /// Helper struct to parse and store a memory address as base + index + offset. 11222 /// We ignore sign extensions when it is safe to do so. 11223 /// The following two expressions are not equivalent. To differentiate we need 11224 /// to store whether there was a sign extension involved in the index 11225 /// computation. 11226 /// (load (i64 add (i64 copyfromreg %c) 11227 /// (i64 signextend (add (i8 load %index) 11228 /// (i8 1)))) 11229 /// vs 11230 /// 11231 /// (load (i64 add (i64 copyfromreg %c) 11232 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 11233 /// (i32 1))))) 11234 struct BaseIndexOffset { 11235 SDValue Base; 11236 SDValue Index; 11237 int64_t Offset; 11238 bool IsIndexSignExt; 11239 11240 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 11241 11242 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 11243 bool IsIndexSignExt) : 11244 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 11245 11246 bool equalBaseIndex(const BaseIndexOffset &Other) { 11247 return Other.Base == Base && Other.Index == Index && 11248 Other.IsIndexSignExt == IsIndexSignExt; 11249 } 11250 11251 /// Parses tree in Ptr for base, index, offset addresses. 11252 static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) { 11253 bool IsIndexSignExt = false; 11254 11255 // Split up a folded GlobalAddress+Offset into its component parts. 11256 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr)) 11257 if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) { 11258 return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(), 11259 SDLoc(GA), 11260 GA->getValueType(0), 11261 /*Offset=*/0, 11262 /*isTargetGA=*/false, 11263 GA->getTargetFlags()), 11264 SDValue(), 11265 GA->getOffset(), 11266 IsIndexSignExt); 11267 } 11268 11269 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 11270 // instruction, then it could be just the BASE or everything else we don't 11271 // know how to handle. Just use Ptr as BASE and give up. 11272 if (Ptr->getOpcode() != ISD::ADD) 11273 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11274 11275 // We know that we have at least an ADD instruction. Try to pattern match 11276 // the simple case of BASE + OFFSET. 11277 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 11278 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 11279 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 11280 IsIndexSignExt); 11281 } 11282 11283 // Inside a loop the current BASE pointer is calculated using an ADD and a 11284 // MUL instruction. In this case Ptr is the actual BASE pointer. 11285 // (i64 add (i64 %array_ptr) 11286 // (i64 mul (i64 %induction_var) 11287 // (i64 %element_size))) 11288 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 11289 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11290 11291 // Look at Base + Index + Offset cases. 11292 SDValue Base = Ptr->getOperand(0); 11293 SDValue IndexOffset = Ptr->getOperand(1); 11294 11295 // Skip signextends. 11296 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 11297 IndexOffset = IndexOffset->getOperand(0); 11298 IsIndexSignExt = true; 11299 } 11300 11301 // Either the case of Base + Index (no offset) or something else. 11302 if (IndexOffset->getOpcode() != ISD::ADD) 11303 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 11304 11305 // Now we have the case of Base + Index + offset. 11306 SDValue Index = IndexOffset->getOperand(0); 11307 SDValue Offset = IndexOffset->getOperand(1); 11308 11309 if (!isa<ConstantSDNode>(Offset)) 11310 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11311 11312 // Ignore signextends. 11313 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 11314 Index = Index->getOperand(0); 11315 IsIndexSignExt = true; 11316 } else IsIndexSignExt = false; 11317 11318 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 11319 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 11320 } 11321 }; 11322 } // namespace 11323 11324 // This is a helper function for visitMUL to check the profitability 11325 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 11326 // MulNode is the original multiply, AddNode is (add x, c1), 11327 // and ConstNode is c2. 11328 // 11329 // If the (add x, c1) has multiple uses, we could increase 11330 // the number of adds if we make this transformation. 11331 // It would only be worth doing this if we can remove a 11332 // multiply in the process. Check for that here. 11333 // To illustrate: 11334 // (A + c1) * c3 11335 // (A + c2) * c3 11336 // We're checking for cases where we have common "c3 * A" expressions. 11337 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 11338 SDValue &AddNode, 11339 SDValue &ConstNode) { 11340 APInt Val; 11341 11342 // If the add only has one use, this would be OK to do. 11343 if (AddNode.getNode()->hasOneUse()) 11344 return true; 11345 11346 // Walk all the users of the constant with which we're multiplying. 11347 for (SDNode *Use : ConstNode->uses()) { 11348 11349 if (Use == MulNode) // This use is the one we're on right now. Skip it. 11350 continue; 11351 11352 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 11353 SDNode *OtherOp; 11354 SDNode *MulVar = AddNode.getOperand(0).getNode(); 11355 11356 // OtherOp is what we're multiplying against the constant. 11357 if (Use->getOperand(0) == ConstNode) 11358 OtherOp = Use->getOperand(1).getNode(); 11359 else 11360 OtherOp = Use->getOperand(0).getNode(); 11361 11362 // Check to see if multiply is with the same operand of our "add". 11363 // 11364 // ConstNode = CONST 11365 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 11366 // ... 11367 // AddNode = (A + c1) <-- MulVar is A. 11368 // = AddNode * ConstNode <-- current visiting instruction. 11369 // 11370 // If we make this transformation, we will have a common 11371 // multiply (ConstNode * A) that we can save. 11372 if (OtherOp == MulVar) 11373 return true; 11374 11375 // Now check to see if a future expansion will give us a common 11376 // multiply. 11377 // 11378 // ConstNode = CONST 11379 // AddNode = (A + c1) 11380 // ... = AddNode * ConstNode <-- current visiting instruction. 11381 // ... 11382 // OtherOp = (A + c2) 11383 // Use = OtherOp * ConstNode <-- visiting Use. 11384 // 11385 // If we make this transformation, we will have a common 11386 // multiply (CONST * A) after we also do the same transformation 11387 // to the "t2" instruction. 11388 if (OtherOp->getOpcode() == ISD::ADD && 11389 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 11390 OtherOp->getOperand(0).getNode() == MulVar) 11391 return true; 11392 } 11393 } 11394 11395 // Didn't find a case where this would be profitable. 11396 return false; 11397 } 11398 11399 SDValue DAGCombiner::getMergedConstantVectorStore( 11400 SelectionDAG &DAG, const SDLoc &SL, ArrayRef<MemOpLink> Stores, 11401 SmallVectorImpl<SDValue> &Chains, EVT Ty) const { 11402 SmallVector<SDValue, 8> BuildVector; 11403 11404 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) { 11405 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode); 11406 Chains.push_back(St->getChain()); 11407 BuildVector.push_back(St->getValue()); 11408 } 11409 11410 return DAG.getBuildVector(Ty, SL, BuildVector); 11411 } 11412 11413 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 11414 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 11415 unsigned NumStores, bool IsConstantSrc, bool UseVector) { 11416 // Make sure we have something to merge. 11417 if (NumStores < 2) 11418 return false; 11419 11420 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11421 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11422 unsigned LatestNodeUsed = 0; 11423 11424 for (unsigned i=0; i < NumStores; ++i) { 11425 // Find a chain for the new wide-store operand. Notice that some 11426 // of the store nodes that we found may not be selected for inclusion 11427 // in the wide store. The chain we use needs to be the chain of the 11428 // latest store node which is *used* and replaced by the wide store. 11429 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11430 LatestNodeUsed = i; 11431 } 11432 11433 SmallVector<SDValue, 8> Chains; 11434 11435 // The latest Node in the DAG. 11436 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11437 SDLoc DL(StoreNodes[0].MemNode); 11438 11439 SDValue StoredVal; 11440 if (UseVector) { 11441 bool IsVec = MemVT.isVector(); 11442 unsigned Elts = NumStores; 11443 if (IsVec) { 11444 // When merging vector stores, get the total number of elements. 11445 Elts *= MemVT.getVectorNumElements(); 11446 } 11447 // Get the type for the merged vector store. 11448 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11449 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 11450 11451 if (IsConstantSrc) { 11452 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty); 11453 } else { 11454 SmallVector<SDValue, 8> Ops; 11455 for (unsigned i = 0; i < NumStores; ++i) { 11456 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11457 SDValue Val = St->getValue(); 11458 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 11459 if (Val.getValueType() != MemVT) 11460 return false; 11461 Ops.push_back(Val); 11462 Chains.push_back(St->getChain()); 11463 } 11464 11465 // Build the extracted vector elements back into a vector. 11466 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 11467 DL, Ty, Ops); } 11468 } else { 11469 // We should always use a vector store when merging extracted vector 11470 // elements, so this path implies a store of constants. 11471 assert(IsConstantSrc && "Merged vector elements should use vector store"); 11472 11473 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 11474 APInt StoreInt(SizeInBits, 0); 11475 11476 // Construct a single integer constant which is made of the smaller 11477 // constant inputs. 11478 bool IsLE = DAG.getDataLayout().isLittleEndian(); 11479 for (unsigned i = 0; i < NumStores; ++i) { 11480 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 11481 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 11482 Chains.push_back(St->getChain()); 11483 11484 SDValue Val = St->getValue(); 11485 StoreInt <<= ElementSizeBytes * 8; 11486 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 11487 StoreInt |= C->getAPIntValue().zext(SizeInBits); 11488 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 11489 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits); 11490 } else { 11491 llvm_unreachable("Invalid constant element type"); 11492 } 11493 } 11494 11495 // Create the new Load and Store operations. 11496 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 11497 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 11498 } 11499 11500 assert(!Chains.empty()); 11501 11502 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11503 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal, 11504 FirstInChain->getBasePtr(), 11505 FirstInChain->getPointerInfo(), 11506 FirstInChain->getAlignment()); 11507 11508 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11509 : DAG.getSubtarget().useAA(); 11510 if (UseAA) { 11511 // Replace all merged stores with the new store. 11512 for (unsigned i = 0; i < NumStores; ++i) 11513 CombineTo(StoreNodes[i].MemNode, NewStore); 11514 } else { 11515 // Replace the last store with the new store. 11516 CombineTo(LatestOp, NewStore); 11517 // Erase all other stores. 11518 for (unsigned i = 0; i < NumStores; ++i) { 11519 if (StoreNodes[i].MemNode == LatestOp) 11520 continue; 11521 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11522 // ReplaceAllUsesWith will replace all uses that existed when it was 11523 // called, but graph optimizations may cause new ones to appear. For 11524 // example, the case in pr14333 looks like 11525 // 11526 // St's chain -> St -> another store -> X 11527 // 11528 // And the only difference from St to the other store is the chain. 11529 // When we change it's chain to be St's chain they become identical, 11530 // get CSEed and the net result is that X is now a use of St. 11531 // Since we know that St is redundant, just iterate. 11532 while (!St->use_empty()) 11533 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 11534 deleteAndRecombine(St); 11535 } 11536 } 11537 11538 StoreNodes.erase(StoreNodes.begin() + NumStores, StoreNodes.end()); 11539 return true; 11540 } 11541 11542 void DAGCombiner::getStoreMergeAndAliasCandidates( 11543 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 11544 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) { 11545 // This holds the base pointer, index, and the offset in bytes from the base 11546 // pointer. 11547 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 11548 11549 // We must have a base and an offset. 11550 if (!BasePtr.Base.getNode()) 11551 return; 11552 11553 // Do not handle stores to undef base pointers. 11554 if (BasePtr.Base.isUndef()) 11555 return; 11556 11557 // Walk up the chain and look for nodes with offsets from the same 11558 // base pointer. Stop when reaching an instruction with a different kind 11559 // or instruction which has a different base pointer. 11560 EVT MemVT = St->getMemoryVT(); 11561 unsigned Seq = 0; 11562 StoreSDNode *Index = St; 11563 11564 11565 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11566 : DAG.getSubtarget().useAA(); 11567 11568 if (UseAA) { 11569 // Look at other users of the same chain. Stores on the same chain do not 11570 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized 11571 // to be on the same chain, so don't bother looking at adjacent chains. 11572 11573 SDValue Chain = St->getChain(); 11574 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) { 11575 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 11576 if (I.getOperandNo() != 0) 11577 continue; 11578 11579 if (OtherST->isVolatile() || OtherST->isIndexed()) 11580 continue; 11581 11582 if (OtherST->getMemoryVT() != MemVT) 11583 continue; 11584 11585 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG); 11586 11587 if (Ptr.equalBaseIndex(BasePtr)) 11588 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++)); 11589 } 11590 } 11591 11592 return; 11593 } 11594 11595 while (Index) { 11596 // If the chain has more than one use, then we can't reorder the mem ops. 11597 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 11598 break; 11599 11600 // Find the base pointer and offset for this memory node. 11601 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 11602 11603 // Check that the base pointer is the same as the original one. 11604 if (!Ptr.equalBaseIndex(BasePtr)) 11605 break; 11606 11607 // The memory operands must not be volatile. 11608 if (Index->isVolatile() || Index->isIndexed()) 11609 break; 11610 11611 // No truncation. 11612 if (Index->isTruncatingStore()) 11613 break; 11614 11615 // The stored memory type must be the same. 11616 if (Index->getMemoryVT() != MemVT) 11617 break; 11618 11619 // We do not allow under-aligned stores in order to prevent 11620 // overriding stores. NOTE: this is a bad hack. Alignment SHOULD 11621 // be irrelevant here; what MATTERS is that we not move memory 11622 // operations that potentially overlap past each-other. 11623 if (Index->getAlignment() < MemVT.getStoreSize()) 11624 break; 11625 11626 // We found a potential memory operand to merge. 11627 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 11628 11629 // Find the next memory operand in the chain. If the next operand in the 11630 // chain is a store then move up and continue the scan with the next 11631 // memory operand. If the next operand is a load save it and use alias 11632 // information to check if it interferes with anything. 11633 SDNode *NextInChain = Index->getChain().getNode(); 11634 while (1) { 11635 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 11636 // We found a store node. Use it for the next iteration. 11637 Index = STn; 11638 break; 11639 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 11640 if (Ldn->isVolatile()) { 11641 Index = nullptr; 11642 break; 11643 } 11644 11645 // Save the load node for later. Continue the scan. 11646 AliasLoadNodes.push_back(Ldn); 11647 NextInChain = Ldn->getChain().getNode(); 11648 continue; 11649 } else { 11650 Index = nullptr; 11651 break; 11652 } 11653 } 11654 } 11655 } 11656 11657 // We need to check that merging these stores does not cause a loop 11658 // in the DAG. Any store candidate may depend on another candidate 11659 // indirectly through its operand (we already consider dependencies 11660 // through the chain). Check in parallel by searching up from 11661 // non-chain operands of candidates. 11662 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 11663 SmallVectorImpl<MemOpLink> &StoreNodes) { 11664 SmallPtrSet<const SDNode *, 16> Visited; 11665 SmallVector<const SDNode *, 8> Worklist; 11666 // search ops of store candidates 11667 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 11668 SDNode *n = StoreNodes[i].MemNode; 11669 // Potential loops may happen only through non-chain operands 11670 for (unsigned j = 1; j < n->getNumOperands(); ++j) 11671 Worklist.push_back(n->getOperand(j).getNode()); 11672 } 11673 // search through DAG. We can stop early if we find a storenode 11674 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 11675 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist)) 11676 return false; 11677 } 11678 return true; 11679 } 11680 11681 bool DAGCombiner::MergeConsecutiveStores( 11682 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes) { 11683 if (OptLevel == CodeGenOpt::None) 11684 return false; 11685 11686 EVT MemVT = St->getMemoryVT(); 11687 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11688 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 11689 Attribute::NoImplicitFloat); 11690 11691 // This function cannot currently deal with non-byte-sized memory sizes. 11692 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 11693 return false; 11694 11695 if (!MemVT.isSimple()) 11696 return false; 11697 11698 // Perform an early exit check. Do not bother looking at stored values that 11699 // are not constants, loads, or extracted vector elements. 11700 SDValue StoredVal = St->getValue(); 11701 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 11702 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 11703 isa<ConstantFPSDNode>(StoredVal); 11704 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 11705 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 11706 11707 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 11708 return false; 11709 11710 // Don't merge vectors into wider vectors if the source data comes from loads. 11711 // TODO: This restriction can be lifted by using logic similar to the 11712 // ExtractVecSrc case. 11713 if (MemVT.isVector() && IsLoadSrc) 11714 return false; 11715 11716 // Only look at ends of store sequences. 11717 SDValue Chain = SDValue(St, 0); 11718 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 11719 return false; 11720 11721 // Save the LoadSDNodes that we find in the chain. 11722 // We need to make sure that these nodes do not interfere with 11723 // any of the store nodes. 11724 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 11725 11726 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes); 11727 11728 // Check if there is anything to merge. 11729 if (StoreNodes.size() < 2) 11730 return false; 11731 11732 // only do dependence check in AA case 11733 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11734 : DAG.getSubtarget().useAA(); 11735 if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes)) 11736 return false; 11737 11738 // Sort the memory operands according to their distance from the 11739 // base pointer. As a secondary criteria: make sure stores coming 11740 // later in the code come first in the list. This is important for 11741 // the non-UseAA case, because we're merging stores into the FINAL 11742 // store along a chain which potentially contains aliasing stores. 11743 // Thus, if there are multiple stores to the same address, the last 11744 // one can be considered for merging but not the others. 11745 std::sort(StoreNodes.begin(), StoreNodes.end(), 11746 [](MemOpLink LHS, MemOpLink RHS) { 11747 return LHS.OffsetFromBase < RHS.OffsetFromBase || 11748 (LHS.OffsetFromBase == RHS.OffsetFromBase && 11749 LHS.SequenceNum < RHS.SequenceNum); 11750 }); 11751 11752 // Scan the memory operations on the chain and find the first non-consecutive 11753 // store memory address. 11754 unsigned LastConsecutiveStore = 0; 11755 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 11756 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 11757 11758 // Check that the addresses are consecutive starting from the second 11759 // element in the list of stores. 11760 if (i > 0) { 11761 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 11762 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11763 break; 11764 } 11765 11766 // Check if this store interferes with any of the loads that we found. 11767 // If we find a load that alias with this store. Stop the sequence. 11768 if (any_of(AliasLoadNodes, [&](LSBaseSDNode *Ldn) { 11769 return isAlias(Ldn, StoreNodes[i].MemNode); 11770 })) 11771 break; 11772 11773 // Mark this node as useful. 11774 LastConsecutiveStore = i; 11775 } 11776 11777 // The node with the lowest store address. 11778 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11779 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 11780 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 11781 LLVMContext &Context = *DAG.getContext(); 11782 const DataLayout &DL = DAG.getDataLayout(); 11783 11784 // Store the constants into memory as one consecutive store. 11785 if (IsConstantSrc) { 11786 unsigned LastLegalType = 0; 11787 unsigned LastLegalVectorType = 0; 11788 bool NonZero = false; 11789 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11790 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11791 SDValue StoredVal = St->getValue(); 11792 11793 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 11794 NonZero |= !C->isNullValue(); 11795 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 11796 NonZero |= !C->getConstantFPValue()->isNullValue(); 11797 } else { 11798 // Non-constant. 11799 break; 11800 } 11801 11802 // Find a legal type for the constant store. 11803 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11804 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11805 bool IsFast; 11806 if (TLI.isTypeLegal(StoreTy) && 11807 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11808 FirstStoreAlign, &IsFast) && IsFast) { 11809 LastLegalType = i+1; 11810 // Or check whether a truncstore is legal. 11811 } else if (TLI.getTypeAction(Context, StoreTy) == 11812 TargetLowering::TypePromoteInteger) { 11813 EVT LegalizedStoredValueTy = 11814 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 11815 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11816 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11817 FirstStoreAS, FirstStoreAlign, &IsFast) && 11818 IsFast) { 11819 LastLegalType = i + 1; 11820 } 11821 } 11822 11823 // We only use vectors if the constant is known to be zero or the target 11824 // allows it and the function is not marked with the noimplicitfloat 11825 // attribute. 11826 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1, 11827 FirstStoreAS)) && 11828 !NoVectors) { 11829 // Find a legal type for the vector store. 11830 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1); 11831 if (TLI.isTypeLegal(Ty) && 11832 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11833 FirstStoreAlign, &IsFast) && IsFast) 11834 LastLegalVectorType = i + 1; 11835 } 11836 } 11837 11838 // Check if we found a legal integer type to store. 11839 if (LastLegalType == 0 && LastLegalVectorType == 0) 11840 return false; 11841 11842 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 11843 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 11844 11845 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 11846 true, UseVector); 11847 } 11848 11849 // When extracting multiple vector elements, try to store them 11850 // in one vector store rather than a sequence of scalar stores. 11851 if (IsExtractVecSrc) { 11852 unsigned NumStoresToMerge = 0; 11853 bool IsVec = MemVT.isVector(); 11854 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 11855 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11856 unsigned StoreValOpcode = St->getValue().getOpcode(); 11857 // This restriction could be loosened. 11858 // Bail out if any stored values are not elements extracted from a vector. 11859 // It should be possible to handle mixed sources, but load sources need 11860 // more careful handling (see the block of code below that handles 11861 // consecutive loads). 11862 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT && 11863 StoreValOpcode != ISD::EXTRACT_SUBVECTOR) 11864 return false; 11865 11866 // Find a legal type for the vector store. 11867 unsigned Elts = i + 1; 11868 if (IsVec) { 11869 // When merging vector stores, get the total number of elements. 11870 Elts *= MemVT.getVectorNumElements(); 11871 } 11872 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11873 bool IsFast; 11874 if (TLI.isTypeLegal(Ty) && 11875 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11876 FirstStoreAlign, &IsFast) && IsFast) 11877 NumStoresToMerge = i + 1; 11878 } 11879 11880 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge, 11881 false, true); 11882 } 11883 11884 // Below we handle the case of multiple consecutive stores that 11885 // come from multiple consecutive loads. We merge them into a single 11886 // wide load and a single wide store. 11887 11888 // Look for load nodes which are used by the stored values. 11889 SmallVector<MemOpLink, 8> LoadNodes; 11890 11891 // Find acceptable loads. Loads need to have the same chain (token factor), 11892 // must not be zext, volatile, indexed, and they must be consecutive. 11893 BaseIndexOffset LdBasePtr; 11894 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11895 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11896 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 11897 if (!Ld) break; 11898 11899 // Loads must only have one use. 11900 if (!Ld->hasNUsesOfValue(1, 0)) 11901 break; 11902 11903 // The memory operands must not be volatile. 11904 if (Ld->isVolatile() || Ld->isIndexed()) 11905 break; 11906 11907 // We do not accept ext loads. 11908 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 11909 break; 11910 11911 // The stored memory type must be the same. 11912 if (Ld->getMemoryVT() != MemVT) 11913 break; 11914 11915 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 11916 // If this is not the first ptr that we check. 11917 if (LdBasePtr.Base.getNode()) { 11918 // The base ptr must be the same. 11919 if (!LdPtr.equalBaseIndex(LdBasePtr)) 11920 break; 11921 } else { 11922 // Check that all other base pointers are the same as this one. 11923 LdBasePtr = LdPtr; 11924 } 11925 11926 // We found a potential memory operand to merge. 11927 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 11928 } 11929 11930 if (LoadNodes.size() < 2) 11931 return false; 11932 11933 // If we have load/store pair instructions and we only have two values, 11934 // don't bother. 11935 unsigned RequiredAlignment; 11936 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 11937 St->getAlignment() >= RequiredAlignment) 11938 return false; 11939 11940 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 11941 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 11942 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 11943 11944 // Scan the memory operations on the chain and find the first non-consecutive 11945 // load memory address. These variables hold the index in the store node 11946 // array. 11947 unsigned LastConsecutiveLoad = 0; 11948 // This variable refers to the size and not index in the array. 11949 unsigned LastLegalVectorType = 0; 11950 unsigned LastLegalIntegerType = 0; 11951 StartAddress = LoadNodes[0].OffsetFromBase; 11952 SDValue FirstChain = FirstLoad->getChain(); 11953 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 11954 // All loads must share the same chain. 11955 if (LoadNodes[i].MemNode->getChain() != FirstChain) 11956 break; 11957 11958 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 11959 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11960 break; 11961 LastConsecutiveLoad = i; 11962 // Find a legal type for the vector store. 11963 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1); 11964 bool IsFastSt, IsFastLd; 11965 if (TLI.isTypeLegal(StoreTy) && 11966 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11967 FirstStoreAlign, &IsFastSt) && IsFastSt && 11968 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11969 FirstLoadAlign, &IsFastLd) && IsFastLd) { 11970 LastLegalVectorType = i + 1; 11971 } 11972 11973 // Find a legal type for the integer store. 11974 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11975 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11976 if (TLI.isTypeLegal(StoreTy) && 11977 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11978 FirstStoreAlign, &IsFastSt) && IsFastSt && 11979 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11980 FirstLoadAlign, &IsFastLd) && IsFastLd) 11981 LastLegalIntegerType = i + 1; 11982 // Or check whether a truncstore and extload is legal. 11983 else if (TLI.getTypeAction(Context, StoreTy) == 11984 TargetLowering::TypePromoteInteger) { 11985 EVT LegalizedStoredValueTy = 11986 TLI.getTypeToTransformTo(Context, StoreTy); 11987 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11988 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11989 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11990 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 11991 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11992 FirstStoreAS, FirstStoreAlign, &IsFastSt) && 11993 IsFastSt && 11994 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11995 FirstLoadAS, FirstLoadAlign, &IsFastLd) && 11996 IsFastLd) 11997 LastLegalIntegerType = i+1; 11998 } 11999 } 12000 12001 // Only use vector types if the vector type is larger than the integer type. 12002 // If they are the same, use integers. 12003 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 12004 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 12005 12006 // We add +1 here because the LastXXX variables refer to location while 12007 // the NumElem refers to array/index size. 12008 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 12009 NumElem = std::min(LastLegalType, NumElem); 12010 12011 if (NumElem < 2) 12012 return false; 12013 12014 // Collect the chains from all merged stores. 12015 SmallVector<SDValue, 8> MergeStoreChains; 12016 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain()); 12017 12018 // The latest Node in the DAG. 12019 unsigned LatestNodeUsed = 0; 12020 for (unsigned i=1; i<NumElem; ++i) { 12021 // Find a chain for the new wide-store operand. Notice that some 12022 // of the store nodes that we found may not be selected for inclusion 12023 // in the wide store. The chain we use needs to be the chain of the 12024 // latest store node which is *used* and replaced by the wide store. 12025 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 12026 LatestNodeUsed = i; 12027 12028 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain()); 12029 } 12030 12031 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 12032 12033 // Find if it is better to use vectors or integers to load and store 12034 // to memory. 12035 EVT JointMemOpVT; 12036 if (UseVectorTy) { 12037 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 12038 } else { 12039 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 12040 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 12041 } 12042 12043 SDLoc LoadDL(LoadNodes[0].MemNode); 12044 SDLoc StoreDL(StoreNodes[0].MemNode); 12045 12046 // The merged loads are required to have the same incoming chain, so 12047 // using the first's chain is acceptable. 12048 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(), 12049 FirstLoad->getBasePtr(), 12050 FirstLoad->getPointerInfo(), FirstLoadAlign); 12051 12052 SDValue NewStoreChain = 12053 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains); 12054 12055 SDValue NewStore = 12056 DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 12057 FirstInChain->getPointerInfo(), FirstStoreAlign); 12058 12059 // Transfer chain users from old loads to the new load. 12060 for (unsigned i = 0; i < NumElem; ++i) { 12061 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 12062 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 12063 SDValue(NewLoad.getNode(), 1)); 12064 } 12065 12066 if (UseAA) { 12067 // Replace the all stores with the new store. 12068 for (unsigned i = 0; i < NumElem; ++i) 12069 CombineTo(StoreNodes[i].MemNode, NewStore); 12070 } else { 12071 // Replace the last store with the new store. 12072 CombineTo(LatestOp, NewStore); 12073 // Erase all other stores. 12074 for (unsigned i = 0; i < NumElem; ++i) { 12075 // Remove all Store nodes. 12076 if (StoreNodes[i].MemNode == LatestOp) 12077 continue; 12078 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12079 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 12080 deleteAndRecombine(St); 12081 } 12082 } 12083 12084 StoreNodes.erase(StoreNodes.begin() + NumElem, StoreNodes.end()); 12085 return true; 12086 } 12087 12088 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 12089 SDLoc SL(ST); 12090 SDValue ReplStore; 12091 12092 // Replace the chain to avoid dependency. 12093 if (ST->isTruncatingStore()) { 12094 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 12095 ST->getBasePtr(), ST->getMemoryVT(), 12096 ST->getMemOperand()); 12097 } else { 12098 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 12099 ST->getMemOperand()); 12100 } 12101 12102 // Create token to keep both nodes around. 12103 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 12104 MVT::Other, ST->getChain(), ReplStore); 12105 12106 // Make sure the new and old chains are cleaned up. 12107 AddToWorklist(Token.getNode()); 12108 12109 // Don't add users to work list. 12110 return CombineTo(ST, Token, false); 12111 } 12112 12113 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 12114 SDValue Value = ST->getValue(); 12115 if (Value.getOpcode() == ISD::TargetConstantFP) 12116 return SDValue(); 12117 12118 SDLoc DL(ST); 12119 12120 SDValue Chain = ST->getChain(); 12121 SDValue Ptr = ST->getBasePtr(); 12122 12123 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 12124 12125 // NOTE: If the original store is volatile, this transform must not increase 12126 // the number of stores. For example, on x86-32 an f64 can be stored in one 12127 // processor operation but an i64 (which is not legal) requires two. So the 12128 // transform should not be done in this case. 12129 12130 SDValue Tmp; 12131 switch (CFP->getSimpleValueType(0).SimpleTy) { 12132 default: 12133 llvm_unreachable("Unknown FP type"); 12134 case MVT::f16: // We don't do this for these yet. 12135 case MVT::f80: 12136 case MVT::f128: 12137 case MVT::ppcf128: 12138 return SDValue(); 12139 case MVT::f32: 12140 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 12141 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 12142 ; 12143 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 12144 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 12145 MVT::i32); 12146 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 12147 } 12148 12149 return SDValue(); 12150 case MVT::f64: 12151 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 12152 !ST->isVolatile()) || 12153 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 12154 ; 12155 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 12156 getZExtValue(), SDLoc(CFP), MVT::i64); 12157 return DAG.getStore(Chain, DL, Tmp, 12158 Ptr, ST->getMemOperand()); 12159 } 12160 12161 if (!ST->isVolatile() && 12162 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 12163 // Many FP stores are not made apparent until after legalize, e.g. for 12164 // argument passing. Since this is so common, custom legalize the 12165 // 64-bit integer store into two 32-bit stores. 12166 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 12167 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 12168 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 12169 if (DAG.getDataLayout().isBigEndian()) 12170 std::swap(Lo, Hi); 12171 12172 unsigned Alignment = ST->getAlignment(); 12173 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 12174 AAMDNodes AAInfo = ST->getAAInfo(); 12175 12176 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 12177 ST->getAlignment(), MMOFlags, AAInfo); 12178 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 12179 DAG.getConstant(4, DL, Ptr.getValueType())); 12180 Alignment = MinAlign(Alignment, 4U); 12181 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 12182 ST->getPointerInfo().getWithOffset(4), 12183 Alignment, MMOFlags, AAInfo); 12184 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 12185 St0, St1); 12186 } 12187 12188 return SDValue(); 12189 } 12190 } 12191 12192 SDValue DAGCombiner::visitSTORE(SDNode *N) { 12193 StoreSDNode *ST = cast<StoreSDNode>(N); 12194 SDValue Chain = ST->getChain(); 12195 SDValue Value = ST->getValue(); 12196 SDValue Ptr = ST->getBasePtr(); 12197 12198 // If this is a store of a bit convert, store the input value if the 12199 // resultant store does not need a higher alignment than the original. 12200 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 12201 ST->isUnindexed()) { 12202 EVT SVT = Value.getOperand(0).getValueType(); 12203 if (((!LegalOperations && !ST->isVolatile()) || 12204 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) && 12205 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 12206 unsigned OrigAlign = ST->getAlignment(); 12207 bool Fast = false; 12208 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 12209 ST->getAddressSpace(), OrigAlign, &Fast) && 12210 Fast) { 12211 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 12212 ST->getPointerInfo(), OrigAlign, 12213 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 12214 } 12215 } 12216 } 12217 12218 // Turn 'store undef, Ptr' -> nothing. 12219 if (Value.isUndef() && ST->isUnindexed()) 12220 return Chain; 12221 12222 // Try to infer better alignment information than the store already has. 12223 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 12224 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 12225 if (Align > ST->getAlignment()) { 12226 SDValue NewStore = 12227 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 12228 ST->getMemoryVT(), Align, 12229 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 12230 if (NewStore.getNode() != N) 12231 return CombineTo(ST, NewStore, true); 12232 } 12233 } 12234 } 12235 12236 // Try transforming a pair floating point load / store ops to integer 12237 // load / store ops. 12238 if (SDValue NewST = TransformFPLoadStorePair(N)) 12239 return NewST; 12240 12241 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 12242 : DAG.getSubtarget().useAA(); 12243 #ifndef NDEBUG 12244 if (CombinerAAOnlyFunc.getNumOccurrences() && 12245 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 12246 UseAA = false; 12247 #endif 12248 if (UseAA && ST->isUnindexed()) { 12249 // FIXME: We should do this even without AA enabled. AA will just allow 12250 // FindBetterChain to work in more situations. The problem with this is that 12251 // any combine that expects memory operations to be on consecutive chains 12252 // first needs to be updated to look for users of the same chain. 12253 12254 // Walk up chain skipping non-aliasing memory nodes, on this store and any 12255 // adjacent stores. 12256 if (findBetterNeighborChains(ST)) { 12257 // replaceStoreChain uses CombineTo, which handled all of the worklist 12258 // manipulation. Return the original node to not do anything else. 12259 return SDValue(ST, 0); 12260 } 12261 Chain = ST->getChain(); 12262 } 12263 12264 // Try transforming N to an indexed store. 12265 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 12266 return SDValue(N, 0); 12267 12268 // FIXME: is there such a thing as a truncating indexed store? 12269 if (ST->isTruncatingStore() && ST->isUnindexed() && 12270 Value.getValueType().isInteger()) { 12271 // See if we can simplify the input to this truncstore with knowledge that 12272 // only the low bits are being used. For example: 12273 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 12274 SDValue Shorter = GetDemandedBits( 12275 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 12276 ST->getMemoryVT().getScalarSizeInBits())); 12277 AddToWorklist(Value.getNode()); 12278 if (Shorter.getNode()) 12279 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 12280 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12281 12282 // Otherwise, see if we can simplify the operation with 12283 // SimplifyDemandedBits, which only works if the value has a single use. 12284 if (SimplifyDemandedBits( 12285 Value, 12286 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 12287 ST->getMemoryVT().getScalarSizeInBits()))) 12288 return SDValue(N, 0); 12289 } 12290 12291 // If this is a load followed by a store to the same location, then the store 12292 // is dead/noop. 12293 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 12294 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 12295 ST->isUnindexed() && !ST->isVolatile() && 12296 // There can't be any side effects between the load and store, such as 12297 // a call or store. 12298 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 12299 // The store is dead, remove it. 12300 return Chain; 12301 } 12302 } 12303 12304 // If this is a store followed by a store with the same value to the same 12305 // location, then the store is dead/noop. 12306 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 12307 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 12308 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 12309 ST1->isUnindexed() && !ST1->isVolatile()) { 12310 // The store is dead, remove it. 12311 return Chain; 12312 } 12313 } 12314 12315 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 12316 // truncating store. We can do this even if this is already a truncstore. 12317 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 12318 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 12319 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 12320 ST->getMemoryVT())) { 12321 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 12322 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12323 } 12324 12325 // Only perform this optimization before the types are legal, because we 12326 // don't want to perform this optimization on every DAGCombine invocation. 12327 if (!LegalTypes) { 12328 for (;;) { 12329 // There can be multiple store sequences on the same chain. 12330 // Keep trying to merge store sequences until we are unable to do so 12331 // or until we merge the last store on the chain. 12332 SmallVector<MemOpLink, 8> StoreNodes; 12333 bool Changed = MergeConsecutiveStores(ST, StoreNodes); 12334 if (!Changed) break; 12335 12336 if (any_of(StoreNodes, 12337 [ST](const MemOpLink &Link) { return Link.MemNode == ST; })) { 12338 // ST has been merged and no longer exists. 12339 return SDValue(N, 0); 12340 } 12341 } 12342 } 12343 12344 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 12345 // 12346 // Make sure to do this only after attempting to merge stores in order to 12347 // avoid changing the types of some subset of stores due to visit order, 12348 // preventing their merging. 12349 if (isa<ConstantFPSDNode>(Value)) { 12350 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 12351 return NewSt; 12352 } 12353 12354 if (SDValue NewSt = splitMergedValStore(ST)) 12355 return NewSt; 12356 12357 return ReduceLoadOpStoreWidth(N); 12358 } 12359 12360 /// For the instruction sequence of store below, F and I values 12361 /// are bundled together as an i64 value before being stored into memory. 12362 /// Sometimes it is more efficent to generate separate stores for F and I, 12363 /// which can remove the bitwise instructions or sink them to colder places. 12364 /// 12365 /// (store (or (zext (bitcast F to i32) to i64), 12366 /// (shl (zext I to i64), 32)), addr) --> 12367 /// (store F, addr) and (store I, addr+4) 12368 /// 12369 /// Similarly, splitting for other merged store can also be beneficial, like: 12370 /// For pair of {i32, i32}, i64 store --> two i32 stores. 12371 /// For pair of {i32, i16}, i64 store --> two i32 stores. 12372 /// For pair of {i16, i16}, i32 store --> two i16 stores. 12373 /// For pair of {i16, i8}, i32 store --> two i16 stores. 12374 /// For pair of {i8, i8}, i16 store --> two i8 stores. 12375 /// 12376 /// We allow each target to determine specifically which kind of splitting is 12377 /// supported. 12378 /// 12379 /// The store patterns are commonly seen from the simple code snippet below 12380 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 12381 /// void goo(const std::pair<int, float> &); 12382 /// hoo() { 12383 /// ... 12384 /// goo(std::make_pair(tmp, ftmp)); 12385 /// ... 12386 /// } 12387 /// 12388 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) { 12389 if (OptLevel == CodeGenOpt::None) 12390 return SDValue(); 12391 12392 SDValue Val = ST->getValue(); 12393 SDLoc DL(ST); 12394 12395 // Match OR operand. 12396 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR) 12397 return SDValue(); 12398 12399 // Match SHL operand and get Lower and Higher parts of Val. 12400 SDValue Op1 = Val.getOperand(0); 12401 SDValue Op2 = Val.getOperand(1); 12402 SDValue Lo, Hi; 12403 if (Op1.getOpcode() != ISD::SHL) { 12404 std::swap(Op1, Op2); 12405 if (Op1.getOpcode() != ISD::SHL) 12406 return SDValue(); 12407 } 12408 Lo = Op2; 12409 Hi = Op1.getOperand(0); 12410 if (!Op1.hasOneUse()) 12411 return SDValue(); 12412 12413 // Match shift amount to HalfValBitSize. 12414 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2; 12415 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1)); 12416 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize) 12417 return SDValue(); 12418 12419 // Lo and Hi are zero-extended from int with size less equal than 32 12420 // to i64. 12421 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() || 12422 !Lo.getOperand(0).getValueType().isScalarInteger() || 12423 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize || 12424 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() || 12425 !Hi.getOperand(0).getValueType().isScalarInteger() || 12426 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize) 12427 return SDValue(); 12428 12429 if (!TLI.isMultiStoresCheaperThanBitsMerge(Lo.getOperand(0), 12430 Hi.getOperand(0))) 12431 return SDValue(); 12432 12433 // Start to split store. 12434 unsigned Alignment = ST->getAlignment(); 12435 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 12436 AAMDNodes AAInfo = ST->getAAInfo(); 12437 12438 // Change the sizes of Lo and Hi's value types to HalfValBitSize. 12439 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize); 12440 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0)); 12441 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0)); 12442 12443 SDValue Chain = ST->getChain(); 12444 SDValue Ptr = ST->getBasePtr(); 12445 // Lower value store. 12446 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 12447 ST->getAlignment(), MMOFlags, AAInfo); 12448 Ptr = 12449 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 12450 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType())); 12451 // Higher value store. 12452 SDValue St1 = 12453 DAG.getStore(St0, DL, Hi, Ptr, 12454 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8), 12455 Alignment / 2, MMOFlags, AAInfo); 12456 return St1; 12457 } 12458 12459 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 12460 SDValue InVec = N->getOperand(0); 12461 SDValue InVal = N->getOperand(1); 12462 SDValue EltNo = N->getOperand(2); 12463 SDLoc DL(N); 12464 12465 // If the inserted element is an UNDEF, just use the input vector. 12466 if (InVal.isUndef()) 12467 return InVec; 12468 12469 EVT VT = InVec.getValueType(); 12470 12471 // If we can't generate a legal BUILD_VECTOR, exit 12472 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 12473 return SDValue(); 12474 12475 // Check that we know which element is being inserted 12476 if (!isa<ConstantSDNode>(EltNo)) 12477 return SDValue(); 12478 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12479 12480 // Canonicalize insert_vector_elt dag nodes. 12481 // Example: 12482 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 12483 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 12484 // 12485 // Do this only if the child insert_vector node has one use; also 12486 // do this only if indices are both constants and Idx1 < Idx0. 12487 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 12488 && isa<ConstantSDNode>(InVec.getOperand(2))) { 12489 unsigned OtherElt = 12490 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 12491 if (Elt < OtherElt) { 12492 // Swap nodes. 12493 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, 12494 InVec.getOperand(0), InVal, EltNo); 12495 AddToWorklist(NewOp.getNode()); 12496 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 12497 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 12498 } 12499 } 12500 12501 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 12502 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 12503 // vector elements. 12504 SmallVector<SDValue, 8> Ops; 12505 // Do not combine these two vectors if the output vector will not replace 12506 // the input vector. 12507 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 12508 Ops.append(InVec.getNode()->op_begin(), 12509 InVec.getNode()->op_end()); 12510 } else if (InVec.isUndef()) { 12511 unsigned NElts = VT.getVectorNumElements(); 12512 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 12513 } else { 12514 return SDValue(); 12515 } 12516 12517 // Insert the element 12518 if (Elt < Ops.size()) { 12519 // All the operands of BUILD_VECTOR must have the same type; 12520 // we enforce that here. 12521 EVT OpVT = Ops[0].getValueType(); 12522 if (InVal.getValueType() != OpVT) 12523 InVal = OpVT.bitsGT(InVal.getValueType()) ? 12524 DAG.getNode(ISD::ANY_EXTEND, DL, OpVT, InVal) : 12525 DAG.getNode(ISD::TRUNCATE, DL, OpVT, InVal); 12526 Ops[Elt] = InVal; 12527 } 12528 12529 // Return the new vector 12530 return DAG.getBuildVector(VT, DL, Ops); 12531 } 12532 12533 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 12534 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 12535 assert(!OriginalLoad->isVolatile()); 12536 12537 EVT ResultVT = EVE->getValueType(0); 12538 EVT VecEltVT = InVecVT.getVectorElementType(); 12539 unsigned Align = OriginalLoad->getAlignment(); 12540 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 12541 VecEltVT.getTypeForEVT(*DAG.getContext())); 12542 12543 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 12544 return SDValue(); 12545 12546 Align = NewAlign; 12547 12548 SDValue NewPtr = OriginalLoad->getBasePtr(); 12549 SDValue Offset; 12550 EVT PtrType = NewPtr.getValueType(); 12551 MachinePointerInfo MPI; 12552 SDLoc DL(EVE); 12553 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 12554 int Elt = ConstEltNo->getZExtValue(); 12555 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 12556 Offset = DAG.getConstant(PtrOff, DL, PtrType); 12557 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 12558 } else { 12559 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 12560 Offset = DAG.getNode( 12561 ISD::MUL, DL, PtrType, Offset, 12562 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 12563 MPI = OriginalLoad->getPointerInfo(); 12564 } 12565 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 12566 12567 // The replacement we need to do here is a little tricky: we need to 12568 // replace an extractelement of a load with a load. 12569 // Use ReplaceAllUsesOfValuesWith to do the replacement. 12570 // Note that this replacement assumes that the extractvalue is the only 12571 // use of the load; that's okay because we don't want to perform this 12572 // transformation in other cases anyway. 12573 SDValue Load; 12574 SDValue Chain; 12575 if (ResultVT.bitsGT(VecEltVT)) { 12576 // If the result type of vextract is wider than the load, then issue an 12577 // extending load instead. 12578 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 12579 VecEltVT) 12580 ? ISD::ZEXTLOAD 12581 : ISD::EXTLOAD; 12582 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 12583 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 12584 Align, OriginalLoad->getMemOperand()->getFlags(), 12585 OriginalLoad->getAAInfo()); 12586 Chain = Load.getValue(1); 12587 } else { 12588 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, 12589 MPI, Align, OriginalLoad->getMemOperand()->getFlags(), 12590 OriginalLoad->getAAInfo()); 12591 Chain = Load.getValue(1); 12592 if (ResultVT.bitsLT(VecEltVT)) 12593 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 12594 else 12595 Load = DAG.getBitcast(ResultVT, Load); 12596 } 12597 WorklistRemover DeadNodes(*this); 12598 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 12599 SDValue To[] = { Load, Chain }; 12600 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 12601 // Since we're explicitly calling ReplaceAllUses, add the new node to the 12602 // worklist explicitly as well. 12603 AddToWorklist(Load.getNode()); 12604 AddUsersToWorklist(Load.getNode()); // Add users too 12605 // Make sure to revisit this node to clean it up; it will usually be dead. 12606 AddToWorklist(EVE); 12607 ++OpsNarrowed; 12608 return SDValue(EVE, 0); 12609 } 12610 12611 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 12612 // (vextract (scalar_to_vector val, 0) -> val 12613 SDValue InVec = N->getOperand(0); 12614 EVT VT = InVec.getValueType(); 12615 EVT NVT = N->getValueType(0); 12616 12617 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 12618 // Check if the result type doesn't match the inserted element type. A 12619 // SCALAR_TO_VECTOR may truncate the inserted element and the 12620 // EXTRACT_VECTOR_ELT may widen the extracted vector. 12621 SDValue InOp = InVec.getOperand(0); 12622 if (InOp.getValueType() != NVT) { 12623 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12624 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 12625 } 12626 return InOp; 12627 } 12628 12629 SDValue EltNo = N->getOperand(1); 12630 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 12631 12632 // extract_vector_elt (build_vector x, y), 1 -> y 12633 if (ConstEltNo && 12634 InVec.getOpcode() == ISD::BUILD_VECTOR && 12635 TLI.isTypeLegal(VT) && 12636 (InVec.hasOneUse() || 12637 TLI.aggressivelyPreferBuildVectorSources(VT))) { 12638 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 12639 EVT InEltVT = Elt.getValueType(); 12640 12641 // Sometimes build_vector's scalar input types do not match result type. 12642 if (NVT == InEltVT) 12643 return Elt; 12644 12645 // TODO: It may be useful to truncate if free if the build_vector implicitly 12646 // converts. 12647 } 12648 12649 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x) 12650 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 12651 ConstEltNo->isNullValue() && VT.isInteger()) { 12652 SDValue BCSrc = InVec.getOperand(0); 12653 if (BCSrc.getValueType().isScalarInteger()) 12654 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 12655 } 12656 12657 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 12658 // 12659 // This only really matters if the index is non-constant since other combines 12660 // on the constant elements already work. 12661 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && 12662 EltNo == InVec.getOperand(2)) { 12663 SDValue Elt = InVec.getOperand(1); 12664 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt; 12665 } 12666 12667 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 12668 // We only perform this optimization before the op legalization phase because 12669 // we may introduce new vector instructions which are not backed by TD 12670 // patterns. For example on AVX, extracting elements from a wide vector 12671 // without using extract_subvector. However, if we can find an underlying 12672 // scalar value, then we can always use that. 12673 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 12674 int NumElem = VT.getVectorNumElements(); 12675 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 12676 // Find the new index to extract from. 12677 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 12678 12679 // Extracting an undef index is undef. 12680 if (OrigElt == -1) 12681 return DAG.getUNDEF(NVT); 12682 12683 // Select the right vector half to extract from. 12684 SDValue SVInVec; 12685 if (OrigElt < NumElem) { 12686 SVInVec = InVec->getOperand(0); 12687 } else { 12688 SVInVec = InVec->getOperand(1); 12689 OrigElt -= NumElem; 12690 } 12691 12692 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 12693 SDValue InOp = SVInVec.getOperand(OrigElt); 12694 if (InOp.getValueType() != NVT) { 12695 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12696 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 12697 } 12698 12699 return InOp; 12700 } 12701 12702 // FIXME: We should handle recursing on other vector shuffles and 12703 // scalar_to_vector here as well. 12704 12705 if (!LegalOperations) { 12706 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 12707 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 12708 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 12709 } 12710 } 12711 12712 bool BCNumEltsChanged = false; 12713 EVT ExtVT = VT.getVectorElementType(); 12714 EVT LVT = ExtVT; 12715 12716 // If the result of load has to be truncated, then it's not necessarily 12717 // profitable. 12718 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 12719 return SDValue(); 12720 12721 if (InVec.getOpcode() == ISD::BITCAST) { 12722 // Don't duplicate a load with other uses. 12723 if (!InVec.hasOneUse()) 12724 return SDValue(); 12725 12726 EVT BCVT = InVec.getOperand(0).getValueType(); 12727 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 12728 return SDValue(); 12729 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 12730 BCNumEltsChanged = true; 12731 InVec = InVec.getOperand(0); 12732 ExtVT = BCVT.getVectorElementType(); 12733 } 12734 12735 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 12736 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 12737 ISD::isNormalLoad(InVec.getNode()) && 12738 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 12739 SDValue Index = N->getOperand(1); 12740 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) { 12741 if (!OrigLoad->isVolatile()) { 12742 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 12743 OrigLoad); 12744 } 12745 } 12746 } 12747 12748 // Perform only after legalization to ensure build_vector / vector_shuffle 12749 // optimizations have already been done. 12750 if (!LegalOperations) return SDValue(); 12751 12752 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 12753 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 12754 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 12755 12756 if (ConstEltNo) { 12757 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12758 12759 LoadSDNode *LN0 = nullptr; 12760 const ShuffleVectorSDNode *SVN = nullptr; 12761 if (ISD::isNormalLoad(InVec.getNode())) { 12762 LN0 = cast<LoadSDNode>(InVec); 12763 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 12764 InVec.getOperand(0).getValueType() == ExtVT && 12765 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 12766 // Don't duplicate a load with other uses. 12767 if (!InVec.hasOneUse()) 12768 return SDValue(); 12769 12770 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 12771 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 12772 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 12773 // => 12774 // (load $addr+1*size) 12775 12776 // Don't duplicate a load with other uses. 12777 if (!InVec.hasOneUse()) 12778 return SDValue(); 12779 12780 // If the bit convert changed the number of elements, it is unsafe 12781 // to examine the mask. 12782 if (BCNumEltsChanged) 12783 return SDValue(); 12784 12785 // Select the input vector, guarding against out of range extract vector. 12786 unsigned NumElems = VT.getVectorNumElements(); 12787 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 12788 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 12789 12790 if (InVec.getOpcode() == ISD::BITCAST) { 12791 // Don't duplicate a load with other uses. 12792 if (!InVec.hasOneUse()) 12793 return SDValue(); 12794 12795 InVec = InVec.getOperand(0); 12796 } 12797 if (ISD::isNormalLoad(InVec.getNode())) { 12798 LN0 = cast<LoadSDNode>(InVec); 12799 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 12800 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 12801 } 12802 } 12803 12804 // Make sure we found a non-volatile load and the extractelement is 12805 // the only use. 12806 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 12807 return SDValue(); 12808 12809 // If Idx was -1 above, Elt is going to be -1, so just return undef. 12810 if (Elt == -1) 12811 return DAG.getUNDEF(LVT); 12812 12813 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 12814 } 12815 12816 return SDValue(); 12817 } 12818 12819 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 12820 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 12821 // We perform this optimization post type-legalization because 12822 // the type-legalizer often scalarizes integer-promoted vectors. 12823 // Performing this optimization before may create bit-casts which 12824 // will be type-legalized to complex code sequences. 12825 // We perform this optimization only before the operation legalizer because we 12826 // may introduce illegal operations. 12827 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 12828 return SDValue(); 12829 12830 unsigned NumInScalars = N->getNumOperands(); 12831 SDLoc DL(N); 12832 EVT VT = N->getValueType(0); 12833 12834 // Check to see if this is a BUILD_VECTOR of a bunch of values 12835 // which come from any_extend or zero_extend nodes. If so, we can create 12836 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 12837 // optimizations. We do not handle sign-extend because we can't fill the sign 12838 // using shuffles. 12839 EVT SourceType = MVT::Other; 12840 bool AllAnyExt = true; 12841 12842 for (unsigned i = 0; i != NumInScalars; ++i) { 12843 SDValue In = N->getOperand(i); 12844 // Ignore undef inputs. 12845 if (In.isUndef()) continue; 12846 12847 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 12848 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 12849 12850 // Abort if the element is not an extension. 12851 if (!ZeroExt && !AnyExt) { 12852 SourceType = MVT::Other; 12853 break; 12854 } 12855 12856 // The input is a ZeroExt or AnyExt. Check the original type. 12857 EVT InTy = In.getOperand(0).getValueType(); 12858 12859 // Check that all of the widened source types are the same. 12860 if (SourceType == MVT::Other) 12861 // First time. 12862 SourceType = InTy; 12863 else if (InTy != SourceType) { 12864 // Multiple income types. Abort. 12865 SourceType = MVT::Other; 12866 break; 12867 } 12868 12869 // Check if all of the extends are ANY_EXTENDs. 12870 AllAnyExt &= AnyExt; 12871 } 12872 12873 // In order to have valid types, all of the inputs must be extended from the 12874 // same source type and all of the inputs must be any or zero extend. 12875 // Scalar sizes must be a power of two. 12876 EVT OutScalarTy = VT.getScalarType(); 12877 bool ValidTypes = SourceType != MVT::Other && 12878 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 12879 isPowerOf2_32(SourceType.getSizeInBits()); 12880 12881 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 12882 // turn into a single shuffle instruction. 12883 if (!ValidTypes) 12884 return SDValue(); 12885 12886 bool isLE = DAG.getDataLayout().isLittleEndian(); 12887 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 12888 assert(ElemRatio > 1 && "Invalid element size ratio"); 12889 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 12890 DAG.getConstant(0, DL, SourceType); 12891 12892 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 12893 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 12894 12895 // Populate the new build_vector 12896 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12897 SDValue Cast = N->getOperand(i); 12898 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 12899 Cast.getOpcode() == ISD::ZERO_EXTEND || 12900 Cast.isUndef()) && "Invalid cast opcode"); 12901 SDValue In; 12902 if (Cast.isUndef()) 12903 In = DAG.getUNDEF(SourceType); 12904 else 12905 In = Cast->getOperand(0); 12906 unsigned Index = isLE ? (i * ElemRatio) : 12907 (i * ElemRatio + (ElemRatio - 1)); 12908 12909 assert(Index < Ops.size() && "Invalid index"); 12910 Ops[Index] = In; 12911 } 12912 12913 // The type of the new BUILD_VECTOR node. 12914 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 12915 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 12916 "Invalid vector size"); 12917 // Check if the new vector type is legal. 12918 if (!isTypeLegal(VecVT)) return SDValue(); 12919 12920 // Make the new BUILD_VECTOR. 12921 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops); 12922 12923 // The new BUILD_VECTOR node has the potential to be further optimized. 12924 AddToWorklist(BV.getNode()); 12925 // Bitcast to the desired type. 12926 return DAG.getBitcast(VT, BV); 12927 } 12928 12929 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 12930 EVT VT = N->getValueType(0); 12931 12932 unsigned NumInScalars = N->getNumOperands(); 12933 SDLoc DL(N); 12934 12935 EVT SrcVT = MVT::Other; 12936 unsigned Opcode = ISD::DELETED_NODE; 12937 unsigned NumDefs = 0; 12938 12939 for (unsigned i = 0; i != NumInScalars; ++i) { 12940 SDValue In = N->getOperand(i); 12941 unsigned Opc = In.getOpcode(); 12942 12943 if (Opc == ISD::UNDEF) 12944 continue; 12945 12946 // If all scalar values are floats and converted from integers. 12947 if (Opcode == ISD::DELETED_NODE && 12948 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 12949 Opcode = Opc; 12950 } 12951 12952 if (Opc != Opcode) 12953 return SDValue(); 12954 12955 EVT InVT = In.getOperand(0).getValueType(); 12956 12957 // If all scalar values are typed differently, bail out. It's chosen to 12958 // simplify BUILD_VECTOR of integer types. 12959 if (SrcVT == MVT::Other) 12960 SrcVT = InVT; 12961 if (SrcVT != InVT) 12962 return SDValue(); 12963 NumDefs++; 12964 } 12965 12966 // If the vector has just one element defined, it's not worth to fold it into 12967 // a vectorized one. 12968 if (NumDefs < 2) 12969 return SDValue(); 12970 12971 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 12972 && "Should only handle conversion from integer to float."); 12973 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 12974 12975 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 12976 12977 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 12978 return SDValue(); 12979 12980 // Just because the floating-point vector type is legal does not necessarily 12981 // mean that the corresponding integer vector type is. 12982 if (!isTypeLegal(NVT)) 12983 return SDValue(); 12984 12985 SmallVector<SDValue, 8> Opnds; 12986 for (unsigned i = 0; i != NumInScalars; ++i) { 12987 SDValue In = N->getOperand(i); 12988 12989 if (In.isUndef()) 12990 Opnds.push_back(DAG.getUNDEF(SrcVT)); 12991 else 12992 Opnds.push_back(In.getOperand(0)); 12993 } 12994 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds); 12995 AddToWorklist(BV.getNode()); 12996 12997 return DAG.getNode(Opcode, DL, VT, BV); 12998 } 12999 13000 SDValue DAGCombiner::createBuildVecShuffle(SDLoc DL, SDNode *N, 13001 ArrayRef<int> VectorMask, 13002 SDValue VecIn1, SDValue VecIn2, 13003 unsigned LeftIdx) { 13004 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 13005 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy); 13006 13007 EVT VT = N->getValueType(0); 13008 EVT InVT1 = VecIn1.getValueType(); 13009 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1; 13010 13011 unsigned Vec2Offset = InVT1.getVectorNumElements(); 13012 unsigned NumElems = VT.getVectorNumElements(); 13013 unsigned ShuffleNumElems = NumElems; 13014 13015 // We can't generate a shuffle node with mismatched input and output types. 13016 // Try to make the types match the type of the output. 13017 if (InVT1 != VT || InVT2 != VT) { 13018 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) { 13019 // If the output vector length is a multiple of both input lengths, 13020 // we can concatenate them and pad the rest with undefs. 13021 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits(); 13022 assert(NumConcats >= 2 && "Concat needs at least two inputs!"); 13023 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1)); 13024 ConcatOps[0] = VecIn1; 13025 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1); 13026 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 13027 VecIn2 = SDValue(); 13028 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) { 13029 if (!TLI.isExtractSubvectorCheap(VT, NumElems)) 13030 return SDValue(); 13031 13032 if (!VecIn2.getNode()) { 13033 // If we only have one input vector, and it's twice the size of the 13034 // output, split it in two. 13035 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, 13036 DAG.getConstant(NumElems, DL, IdxTy)); 13037 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx); 13038 // Since we now have shorter input vectors, adjust the offset of the 13039 // second vector's start. 13040 Vec2Offset = NumElems; 13041 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) { 13042 // VecIn1 is wider than the output, and we have another, possibly 13043 // smaller input. Pad the smaller input with undefs, shuffle at the 13044 // input vector width, and extract the output. 13045 // The shuffle type is different than VT, so check legality again. 13046 if (LegalOperations && 13047 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1)) 13048 return SDValue(); 13049 13050 if (InVT1 != InVT2) 13051 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1, 13052 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx); 13053 ShuffleNumElems = NumElems * 2; 13054 } else { 13055 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider 13056 // than VecIn1. We can't handle this for now - this case will disappear 13057 // when we start sorting the vectors by type. 13058 return SDValue(); 13059 } 13060 } else { 13061 // TODO: Support cases where the length mismatch isn't exactly by a 13062 // factor of 2. 13063 // TODO: Move this check upwards, so that if we have bad type 13064 // mismatches, we don't create any DAG nodes. 13065 return SDValue(); 13066 } 13067 } 13068 13069 // Initialize mask to undef. 13070 SmallVector<int, 8> Mask(ShuffleNumElems, -1); 13071 13072 // Only need to run up to the number of elements actually used, not the 13073 // total number of elements in the shuffle - if we are shuffling a wider 13074 // vector, the high lanes should be set to undef. 13075 for (unsigned i = 0; i != NumElems; ++i) { 13076 if (VectorMask[i] <= 0) 13077 continue; 13078 13079 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1); 13080 if (VectorMask[i] == (int)LeftIdx) { 13081 Mask[i] = ExtIndex; 13082 } else if (VectorMask[i] == (int)LeftIdx + 1) { 13083 Mask[i] = Vec2Offset + ExtIndex; 13084 } 13085 } 13086 13087 // The type the input vectors may have changed above. 13088 InVT1 = VecIn1.getValueType(); 13089 13090 // If we already have a VecIn2, it should have the same type as VecIn1. 13091 // If we don't, get an undef/zero vector of the appropriate type. 13092 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1); 13093 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type."); 13094 13095 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask); 13096 if (ShuffleNumElems > NumElems) 13097 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx); 13098 13099 return Shuffle; 13100 } 13101 13102 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 13103 // operations. If the types of the vectors we're extracting from allow it, 13104 // turn this into a vector_shuffle node. 13105 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) { 13106 SDLoc DL(N); 13107 EVT VT = N->getValueType(0); 13108 13109 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 13110 if (!isTypeLegal(VT)) 13111 return SDValue(); 13112 13113 // May only combine to shuffle after legalize if shuffle is legal. 13114 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 13115 return SDValue(); 13116 13117 bool UsesZeroVector = false; 13118 unsigned NumElems = N->getNumOperands(); 13119 13120 // Record, for each element of the newly built vector, which input vector 13121 // that element comes from. -1 stands for undef, 0 for the zero vector, 13122 // and positive values for the input vectors. 13123 // VectorMask maps each element to its vector number, and VecIn maps vector 13124 // numbers to their initial SDValues. 13125 13126 SmallVector<int, 8> VectorMask(NumElems, -1); 13127 SmallVector<SDValue, 8> VecIn; 13128 VecIn.push_back(SDValue()); 13129 13130 for (unsigned i = 0; i != NumElems; ++i) { 13131 SDValue Op = N->getOperand(i); 13132 13133 if (Op.isUndef()) 13134 continue; 13135 13136 // See if we can use a blend with a zero vector. 13137 // TODO: Should we generalize this to a blend with an arbitrary constant 13138 // vector? 13139 if (isNullConstant(Op) || isNullFPConstant(Op)) { 13140 UsesZeroVector = true; 13141 VectorMask[i] = 0; 13142 continue; 13143 } 13144 13145 // Not an undef or zero. If the input is something other than an 13146 // EXTRACT_VECTOR_ELT with a constant index, bail out. 13147 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13148 !isa<ConstantSDNode>(Op.getOperand(1))) 13149 return SDValue(); 13150 13151 SDValue ExtractedFromVec = Op.getOperand(0); 13152 13153 // All inputs must have the same element type as the output. 13154 if (VT.getVectorElementType() != 13155 ExtractedFromVec.getValueType().getVectorElementType()) 13156 return SDValue(); 13157 13158 // Have we seen this input vector before? 13159 // The vectors are expected to be tiny (usually 1 or 2 elements), so using 13160 // a map back from SDValues to numbers isn't worth it. 13161 unsigned Idx = std::distance( 13162 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec)); 13163 if (Idx == VecIn.size()) 13164 VecIn.push_back(ExtractedFromVec); 13165 13166 VectorMask[i] = Idx; 13167 } 13168 13169 // If we didn't find at least one input vector, bail out. 13170 if (VecIn.size() < 2) 13171 return SDValue(); 13172 13173 // TODO: We want to sort the vectors by descending length, so that adjacent 13174 // pairs have similar length, and the longer vector is always first in the 13175 // pair. 13176 13177 // TODO: Should this fire if some of the input vectors has illegal type (like 13178 // it does now), or should we let legalization run its course first? 13179 13180 // Shuffle phase: 13181 // Take pairs of vectors, and shuffle them so that the result has elements 13182 // from these vectors in the correct places. 13183 // For example, given: 13184 // t10: i32 = extract_vector_elt t1, Constant:i64<0> 13185 // t11: i32 = extract_vector_elt t2, Constant:i64<0> 13186 // t12: i32 = extract_vector_elt t3, Constant:i64<0> 13187 // t13: i32 = extract_vector_elt t1, Constant:i64<1> 13188 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13 13189 // We will generate: 13190 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2 13191 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef 13192 SmallVector<SDValue, 4> Shuffles; 13193 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) { 13194 unsigned LeftIdx = 2 * In + 1; 13195 SDValue VecLeft = VecIn[LeftIdx]; 13196 SDValue VecRight = 13197 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue(); 13198 13199 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft, 13200 VecRight, LeftIdx)) 13201 Shuffles.push_back(Shuffle); 13202 else 13203 return SDValue(); 13204 } 13205 13206 // If we need the zero vector as an "ingredient" in the blend tree, add it 13207 // to the list of shuffles. 13208 if (UsesZeroVector) 13209 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT) 13210 : DAG.getConstantFP(0.0, DL, VT)); 13211 13212 // If we only have one shuffle, we're done. 13213 if (Shuffles.size() == 1) 13214 return Shuffles[0]; 13215 13216 // Update the vector mask to point to the post-shuffle vectors. 13217 for (int &Vec : VectorMask) 13218 if (Vec == 0) 13219 Vec = Shuffles.size() - 1; 13220 else 13221 Vec = (Vec - 1) / 2; 13222 13223 // More than one shuffle. Generate a binary tree of blends, e.g. if from 13224 // the previous step we got the set of shuffles t10, t11, t12, t13, we will 13225 // generate: 13226 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2 13227 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4 13228 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6 13229 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8 13230 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11 13231 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13 13232 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21 13233 13234 // Make sure the initial size of the shuffle list is even. 13235 if (Shuffles.size() % 2) 13236 Shuffles.push_back(DAG.getUNDEF(VT)); 13237 13238 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) { 13239 if (CurSize % 2) { 13240 Shuffles[CurSize] = DAG.getUNDEF(VT); 13241 CurSize++; 13242 } 13243 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) { 13244 int Left = 2 * In; 13245 int Right = 2 * In + 1; 13246 SmallVector<int, 8> Mask(NumElems, -1); 13247 for (unsigned i = 0; i != NumElems; ++i) { 13248 if (VectorMask[i] == Left) { 13249 Mask[i] = i; 13250 VectorMask[i] = In; 13251 } else if (VectorMask[i] == Right) { 13252 Mask[i] = i + NumElems; 13253 VectorMask[i] = In; 13254 } 13255 } 13256 13257 Shuffles[In] = 13258 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask); 13259 } 13260 } 13261 13262 return Shuffles[0]; 13263 } 13264 13265 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 13266 EVT VT = N->getValueType(0); 13267 13268 // A vector built entirely of undefs is undef. 13269 if (ISD::allOperandsUndef(N)) 13270 return DAG.getUNDEF(VT); 13271 13272 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 13273 return V; 13274 13275 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 13276 return V; 13277 13278 if (SDValue V = reduceBuildVecToShuffle(N)) 13279 return V; 13280 13281 return SDValue(); 13282 } 13283 13284 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 13285 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13286 EVT OpVT = N->getOperand(0).getValueType(); 13287 13288 // If the operands are legal vectors, leave them alone. 13289 if (TLI.isTypeLegal(OpVT)) 13290 return SDValue(); 13291 13292 SDLoc DL(N); 13293 EVT VT = N->getValueType(0); 13294 SmallVector<SDValue, 8> Ops; 13295 13296 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 13297 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 13298 13299 // Keep track of what we encounter. 13300 bool AnyInteger = false; 13301 bool AnyFP = false; 13302 for (const SDValue &Op : N->ops()) { 13303 if (ISD::BITCAST == Op.getOpcode() && 13304 !Op.getOperand(0).getValueType().isVector()) 13305 Ops.push_back(Op.getOperand(0)); 13306 else if (ISD::UNDEF == Op.getOpcode()) 13307 Ops.push_back(ScalarUndef); 13308 else 13309 return SDValue(); 13310 13311 // Note whether we encounter an integer or floating point scalar. 13312 // If it's neither, bail out, it could be something weird like x86mmx. 13313 EVT LastOpVT = Ops.back().getValueType(); 13314 if (LastOpVT.isFloatingPoint()) 13315 AnyFP = true; 13316 else if (LastOpVT.isInteger()) 13317 AnyInteger = true; 13318 else 13319 return SDValue(); 13320 } 13321 13322 // If any of the operands is a floating point scalar bitcast to a vector, 13323 // use floating point types throughout, and bitcast everything. 13324 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 13325 if (AnyFP) { 13326 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 13327 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 13328 if (AnyInteger) { 13329 for (SDValue &Op : Ops) { 13330 if (Op.getValueType() == SVT) 13331 continue; 13332 if (Op.isUndef()) 13333 Op = ScalarUndef; 13334 else 13335 Op = DAG.getBitcast(SVT, Op); 13336 } 13337 } 13338 } 13339 13340 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 13341 VT.getSizeInBits() / SVT.getSizeInBits()); 13342 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 13343 } 13344 13345 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 13346 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 13347 // most two distinct vectors the same size as the result, attempt to turn this 13348 // into a legal shuffle. 13349 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 13350 EVT VT = N->getValueType(0); 13351 EVT OpVT = N->getOperand(0).getValueType(); 13352 int NumElts = VT.getVectorNumElements(); 13353 int NumOpElts = OpVT.getVectorNumElements(); 13354 13355 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 13356 SmallVector<int, 8> Mask; 13357 13358 for (SDValue Op : N->ops()) { 13359 // Peek through any bitcast. 13360 while (Op.getOpcode() == ISD::BITCAST) 13361 Op = Op.getOperand(0); 13362 13363 // UNDEF nodes convert to UNDEF shuffle mask values. 13364 if (Op.isUndef()) { 13365 Mask.append((unsigned)NumOpElts, -1); 13366 continue; 13367 } 13368 13369 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13370 return SDValue(); 13371 13372 // What vector are we extracting the subvector from and at what index? 13373 SDValue ExtVec = Op.getOperand(0); 13374 13375 // We want the EVT of the original extraction to correctly scale the 13376 // extraction index. 13377 EVT ExtVT = ExtVec.getValueType(); 13378 13379 // Peek through any bitcast. 13380 while (ExtVec.getOpcode() == ISD::BITCAST) 13381 ExtVec = ExtVec.getOperand(0); 13382 13383 // UNDEF nodes convert to UNDEF shuffle mask values. 13384 if (ExtVec.isUndef()) { 13385 Mask.append((unsigned)NumOpElts, -1); 13386 continue; 13387 } 13388 13389 if (!isa<ConstantSDNode>(Op.getOperand(1))) 13390 return SDValue(); 13391 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 13392 13393 // Ensure that we are extracting a subvector from a vector the same 13394 // size as the result. 13395 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 13396 return SDValue(); 13397 13398 // Scale the subvector index to account for any bitcast. 13399 int NumExtElts = ExtVT.getVectorNumElements(); 13400 if (0 == (NumExtElts % NumElts)) 13401 ExtIdx /= (NumExtElts / NumElts); 13402 else if (0 == (NumElts % NumExtElts)) 13403 ExtIdx *= (NumElts / NumExtElts); 13404 else 13405 return SDValue(); 13406 13407 // At most we can reference 2 inputs in the final shuffle. 13408 if (SV0.isUndef() || SV0 == ExtVec) { 13409 SV0 = ExtVec; 13410 for (int i = 0; i != NumOpElts; ++i) 13411 Mask.push_back(i + ExtIdx); 13412 } else if (SV1.isUndef() || SV1 == ExtVec) { 13413 SV1 = ExtVec; 13414 for (int i = 0; i != NumOpElts; ++i) 13415 Mask.push_back(i + ExtIdx + NumElts); 13416 } else { 13417 return SDValue(); 13418 } 13419 } 13420 13421 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 13422 return SDValue(); 13423 13424 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 13425 DAG.getBitcast(VT, SV1), Mask); 13426 } 13427 13428 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 13429 // If we only have one input vector, we don't need to do any concatenation. 13430 if (N->getNumOperands() == 1) 13431 return N->getOperand(0); 13432 13433 // Check if all of the operands are undefs. 13434 EVT VT = N->getValueType(0); 13435 if (ISD::allOperandsUndef(N)) 13436 return DAG.getUNDEF(VT); 13437 13438 // Optimize concat_vectors where all but the first of the vectors are undef. 13439 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 13440 return Op.isUndef(); 13441 })) { 13442 SDValue In = N->getOperand(0); 13443 assert(In.getValueType().isVector() && "Must concat vectors"); 13444 13445 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 13446 if (In->getOpcode() == ISD::BITCAST && 13447 !In->getOperand(0)->getValueType(0).isVector()) { 13448 SDValue Scalar = In->getOperand(0); 13449 13450 // If the bitcast type isn't legal, it might be a trunc of a legal type; 13451 // look through the trunc so we can still do the transform: 13452 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 13453 if (Scalar->getOpcode() == ISD::TRUNCATE && 13454 !TLI.isTypeLegal(Scalar.getValueType()) && 13455 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 13456 Scalar = Scalar->getOperand(0); 13457 13458 EVT SclTy = Scalar->getValueType(0); 13459 13460 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 13461 return SDValue(); 13462 13463 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 13464 VT.getSizeInBits() / SclTy.getSizeInBits()); 13465 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 13466 return SDValue(); 13467 13468 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar); 13469 return DAG.getBitcast(VT, Res); 13470 } 13471 } 13472 13473 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 13474 // We have already tested above for an UNDEF only concatenation. 13475 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 13476 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 13477 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 13478 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 13479 }; 13480 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 13481 SmallVector<SDValue, 8> Opnds; 13482 EVT SVT = VT.getScalarType(); 13483 13484 EVT MinVT = SVT; 13485 if (!SVT.isFloatingPoint()) { 13486 // If BUILD_VECTOR are from built from integer, they may have different 13487 // operand types. Get the smallest type and truncate all operands to it. 13488 bool FoundMinVT = false; 13489 for (const SDValue &Op : N->ops()) 13490 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 13491 EVT OpSVT = Op.getOperand(0)->getValueType(0); 13492 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 13493 FoundMinVT = true; 13494 } 13495 assert(FoundMinVT && "Concat vector type mismatch"); 13496 } 13497 13498 for (const SDValue &Op : N->ops()) { 13499 EVT OpVT = Op.getValueType(); 13500 unsigned NumElts = OpVT.getVectorNumElements(); 13501 13502 if (ISD::UNDEF == Op.getOpcode()) 13503 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 13504 13505 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 13506 if (SVT.isFloatingPoint()) { 13507 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 13508 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 13509 } else { 13510 for (unsigned i = 0; i != NumElts; ++i) 13511 Opnds.push_back( 13512 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 13513 } 13514 } 13515 } 13516 13517 assert(VT.getVectorNumElements() == Opnds.size() && 13518 "Concat vector type mismatch"); 13519 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 13520 } 13521 13522 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 13523 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 13524 return V; 13525 13526 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 13527 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 13528 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 13529 return V; 13530 13531 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 13532 // nodes often generate nop CONCAT_VECTOR nodes. 13533 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 13534 // place the incoming vectors at the exact same location. 13535 SDValue SingleSource = SDValue(); 13536 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 13537 13538 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13539 SDValue Op = N->getOperand(i); 13540 13541 if (Op.isUndef()) 13542 continue; 13543 13544 // Check if this is the identity extract: 13545 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13546 return SDValue(); 13547 13548 // Find the single incoming vector for the extract_subvector. 13549 if (SingleSource.getNode()) { 13550 if (Op.getOperand(0) != SingleSource) 13551 return SDValue(); 13552 } else { 13553 SingleSource = Op.getOperand(0); 13554 13555 // Check the source type is the same as the type of the result. 13556 // If not, this concat may extend the vector, so we can not 13557 // optimize it away. 13558 if (SingleSource.getValueType() != N->getValueType(0)) 13559 return SDValue(); 13560 } 13561 13562 unsigned IdentityIndex = i * PartNumElem; 13563 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 13564 // The extract index must be constant. 13565 if (!CS) 13566 return SDValue(); 13567 13568 // Check that we are reading from the identity index. 13569 if (CS->getZExtValue() != IdentityIndex) 13570 return SDValue(); 13571 } 13572 13573 if (SingleSource.getNode()) 13574 return SingleSource; 13575 13576 return SDValue(); 13577 } 13578 13579 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 13580 EVT NVT = N->getValueType(0); 13581 SDValue V = N->getOperand(0); 13582 13583 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 13584 // Combine: 13585 // (extract_subvec (concat V1, V2, ...), i) 13586 // Into: 13587 // Vi if possible 13588 // Only operand 0 is checked as 'concat' assumes all inputs of the same 13589 // type. 13590 if (V->getOperand(0).getValueType() != NVT) 13591 return SDValue(); 13592 unsigned Idx = N->getConstantOperandVal(1); 13593 unsigned NumElems = NVT.getVectorNumElements(); 13594 assert((Idx % NumElems) == 0 && 13595 "IDX in concat is not a multiple of the result vector length."); 13596 return V->getOperand(Idx / NumElems); 13597 } 13598 13599 // Skip bitcasting 13600 if (V->getOpcode() == ISD::BITCAST) 13601 V = V.getOperand(0); 13602 13603 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 13604 // Handle only simple case where vector being inserted and vector 13605 // being extracted are of same type, and are half size of larger vectors. 13606 EVT BigVT = V->getOperand(0).getValueType(); 13607 EVT SmallVT = V->getOperand(1).getValueType(); 13608 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 13609 return SDValue(); 13610 13611 // Only handle cases where both indexes are constants with the same type. 13612 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 13613 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13614 13615 if (InsIdx && ExtIdx && 13616 InsIdx->getValueType(0).getSizeInBits() <= 64 && 13617 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 13618 // Combine: 13619 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 13620 // Into: 13621 // indices are equal or bit offsets are equal => V1 13622 // otherwise => (extract_subvec V1, ExtIdx) 13623 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() == 13624 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits()) 13625 return DAG.getBitcast(NVT, V->getOperand(1)); 13626 return DAG.getNode( 13627 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, 13628 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)), 13629 N->getOperand(1)); 13630 } 13631 } 13632 13633 return SDValue(); 13634 } 13635 13636 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 13637 SDValue V, SelectionDAG &DAG) { 13638 SDLoc DL(V); 13639 EVT VT = V.getValueType(); 13640 13641 switch (V.getOpcode()) { 13642 default: 13643 return V; 13644 13645 case ISD::CONCAT_VECTORS: { 13646 EVT OpVT = V->getOperand(0).getValueType(); 13647 int OpSize = OpVT.getVectorNumElements(); 13648 SmallBitVector OpUsedElements(OpSize, false); 13649 bool FoundSimplification = false; 13650 SmallVector<SDValue, 4> NewOps; 13651 NewOps.reserve(V->getNumOperands()); 13652 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 13653 SDValue Op = V->getOperand(i); 13654 bool OpUsed = false; 13655 for (int j = 0; j < OpSize; ++j) 13656 if (UsedElements[i * OpSize + j]) { 13657 OpUsedElements[j] = true; 13658 OpUsed = true; 13659 } 13660 NewOps.push_back( 13661 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 13662 : DAG.getUNDEF(OpVT)); 13663 FoundSimplification |= Op == NewOps.back(); 13664 OpUsedElements.reset(); 13665 } 13666 if (FoundSimplification) 13667 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 13668 return V; 13669 } 13670 13671 case ISD::INSERT_SUBVECTOR: { 13672 SDValue BaseV = V->getOperand(0); 13673 SDValue SubV = V->getOperand(1); 13674 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13675 if (!IdxN) 13676 return V; 13677 13678 int SubSize = SubV.getValueType().getVectorNumElements(); 13679 int Idx = IdxN->getZExtValue(); 13680 bool SubVectorUsed = false; 13681 SmallBitVector SubUsedElements(SubSize, false); 13682 for (int i = 0; i < SubSize; ++i) 13683 if (UsedElements[i + Idx]) { 13684 SubVectorUsed = true; 13685 SubUsedElements[i] = true; 13686 UsedElements[i + Idx] = false; 13687 } 13688 13689 // Now recurse on both the base and sub vectors. 13690 SDValue SimplifiedSubV = 13691 SubVectorUsed 13692 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 13693 : DAG.getUNDEF(SubV.getValueType()); 13694 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 13695 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 13696 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 13697 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 13698 return V; 13699 } 13700 } 13701 } 13702 13703 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 13704 SDValue N1, SelectionDAG &DAG) { 13705 EVT VT = SVN->getValueType(0); 13706 int NumElts = VT.getVectorNumElements(); 13707 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 13708 for (int M : SVN->getMask()) 13709 if (M >= 0 && M < NumElts) 13710 N0UsedElements[M] = true; 13711 else if (M >= NumElts) 13712 N1UsedElements[M - NumElts] = true; 13713 13714 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 13715 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 13716 if (S0 == N0 && S1 == N1) 13717 return SDValue(); 13718 13719 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 13720 } 13721 13722 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 13723 // or turn a shuffle of a single concat into simpler shuffle then concat. 13724 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 13725 EVT VT = N->getValueType(0); 13726 unsigned NumElts = VT.getVectorNumElements(); 13727 13728 SDValue N0 = N->getOperand(0); 13729 SDValue N1 = N->getOperand(1); 13730 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13731 13732 SmallVector<SDValue, 4> Ops; 13733 EVT ConcatVT = N0.getOperand(0).getValueType(); 13734 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 13735 unsigned NumConcats = NumElts / NumElemsPerConcat; 13736 13737 // Special case: shuffle(concat(A,B)) can be more efficiently represented 13738 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 13739 // half vector elements. 13740 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 13741 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 13742 SVN->getMask().end(), [](int i) { return i == -1; })) { 13743 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 13744 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 13745 N1 = DAG.getUNDEF(ConcatVT); 13746 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 13747 } 13748 13749 // Look at every vector that's inserted. We're looking for exact 13750 // subvector-sized copies from a concatenated vector 13751 for (unsigned I = 0; I != NumConcats; ++I) { 13752 // Make sure we're dealing with a copy. 13753 unsigned Begin = I * NumElemsPerConcat; 13754 bool AllUndef = true, NoUndef = true; 13755 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 13756 if (SVN->getMaskElt(J) >= 0) 13757 AllUndef = false; 13758 else 13759 NoUndef = false; 13760 } 13761 13762 if (NoUndef) { 13763 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 13764 return SDValue(); 13765 13766 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 13767 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 13768 return SDValue(); 13769 13770 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 13771 if (FirstElt < N0.getNumOperands()) 13772 Ops.push_back(N0.getOperand(FirstElt)); 13773 else 13774 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 13775 13776 } else if (AllUndef) { 13777 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 13778 } else { // Mixed with general masks and undefs, can't do optimization. 13779 return SDValue(); 13780 } 13781 } 13782 13783 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 13784 } 13785 13786 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 13787 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 13788 // This combine is done in the following cases: 13789 // 1. Both N0,N1 are BUILD_VECTOR's composed of constants or undefs. 13790 // 2. Only one of N0,N1 is a BUILD_VECTOR composed of constants or undefs - 13791 // Combine iff that node is ALL_ZEROS. We prefer not to combine a 13792 // BUILD_VECTOR of all constants to allow efficient materialization of 13793 // constant vectors, but the ALL_ZEROS is an exception because 13794 // zero-extension matching seems to rely on having BUILD_VECTOR nodes with 13795 // zero padding between elements. FIXME: Eliminate this exception for 13796 // ALL_ZEROS constant vectors. 13797 // 3. Neither N0,N1 are composed of only constants. 13798 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN, 13799 SelectionDAG &DAG, 13800 const TargetLowering &TLI) { 13801 EVT VT = SVN->getValueType(0); 13802 unsigned NumElts = VT.getVectorNumElements(); 13803 SDValue N0 = SVN->getOperand(0); 13804 SDValue N1 = SVN->getOperand(1); 13805 13806 if (!N0->hasOneUse() || !N1->hasOneUse()) 13807 return SDValue(); 13808 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as 13809 // discussed above. 13810 if (!N1.isUndef()) { 13811 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode()); 13812 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode()); 13813 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode())) 13814 return SDValue(); 13815 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode())) 13816 return SDValue(); 13817 } 13818 13819 SmallVector<SDValue, 8> Ops; 13820 for (int M : SVN->getMask()) { 13821 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 13822 if (M >= 0) { 13823 int Idx = M < (int)NumElts ? M : M - NumElts; 13824 SDValue &S = (M < (int)NumElts ? N0 : N1); 13825 if (S.getOpcode() == ISD::BUILD_VECTOR) { 13826 Op = S.getOperand(Idx); 13827 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) { 13828 if (Idx == 0) 13829 Op = S.getOperand(0); 13830 } else { 13831 // Operand can't be combined - bail out. 13832 return SDValue(); 13833 } 13834 } 13835 Ops.push_back(Op); 13836 } 13837 // BUILD_VECTOR requires all inputs to be of the same type, find the 13838 // maximum type and extend them all. 13839 EVT SVT = VT.getScalarType(); 13840 if (SVT.isInteger()) 13841 for (SDValue &Op : Ops) 13842 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 13843 if (SVT != VT.getScalarType()) 13844 for (SDValue &Op : Ops) 13845 Op = TLI.isZExtFree(Op.getValueType(), SVT) 13846 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT) 13847 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT); 13848 return DAG.getBuildVector(VT, SDLoc(SVN), Ops); 13849 } 13850 13851 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 13852 EVT VT = N->getValueType(0); 13853 unsigned NumElts = VT.getVectorNumElements(); 13854 13855 SDValue N0 = N->getOperand(0); 13856 SDValue N1 = N->getOperand(1); 13857 13858 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 13859 13860 // Canonicalize shuffle undef, undef -> undef 13861 if (N0.isUndef() && N1.isUndef()) 13862 return DAG.getUNDEF(VT); 13863 13864 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13865 13866 // Canonicalize shuffle v, v -> v, undef 13867 if (N0 == N1) { 13868 SmallVector<int, 8> NewMask; 13869 for (unsigned i = 0; i != NumElts; ++i) { 13870 int Idx = SVN->getMaskElt(i); 13871 if (Idx >= (int)NumElts) Idx -= NumElts; 13872 NewMask.push_back(Idx); 13873 } 13874 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 13875 } 13876 13877 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 13878 if (N0.isUndef()) 13879 return DAG.getCommutedVectorShuffle(*SVN); 13880 13881 // Remove references to rhs if it is undef 13882 if (N1.isUndef()) { 13883 bool Changed = false; 13884 SmallVector<int, 8> NewMask; 13885 for (unsigned i = 0; i != NumElts; ++i) { 13886 int Idx = SVN->getMaskElt(i); 13887 if (Idx >= (int)NumElts) { 13888 Idx = -1; 13889 Changed = true; 13890 } 13891 NewMask.push_back(Idx); 13892 } 13893 if (Changed) 13894 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 13895 } 13896 13897 // If it is a splat, check if the argument vector is another splat or a 13898 // build_vector. 13899 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 13900 SDNode *V = N0.getNode(); 13901 13902 // If this is a bit convert that changes the element type of the vector but 13903 // not the number of vector elements, look through it. Be careful not to 13904 // look though conversions that change things like v4f32 to v2f64. 13905 if (V->getOpcode() == ISD::BITCAST) { 13906 SDValue ConvInput = V->getOperand(0); 13907 if (ConvInput.getValueType().isVector() && 13908 ConvInput.getValueType().getVectorNumElements() == NumElts) 13909 V = ConvInput.getNode(); 13910 } 13911 13912 if (V->getOpcode() == ISD::BUILD_VECTOR) { 13913 assert(V->getNumOperands() == NumElts && 13914 "BUILD_VECTOR has wrong number of operands"); 13915 SDValue Base; 13916 bool AllSame = true; 13917 for (unsigned i = 0; i != NumElts; ++i) { 13918 if (!V->getOperand(i).isUndef()) { 13919 Base = V->getOperand(i); 13920 break; 13921 } 13922 } 13923 // Splat of <u, u, u, u>, return <u, u, u, u> 13924 if (!Base.getNode()) 13925 return N0; 13926 for (unsigned i = 0; i != NumElts; ++i) { 13927 if (V->getOperand(i) != Base) { 13928 AllSame = false; 13929 break; 13930 } 13931 } 13932 // Splat of <x, x, x, x>, return <x, x, x, x> 13933 if (AllSame) 13934 return N0; 13935 13936 // Canonicalize any other splat as a build_vector. 13937 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 13938 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 13939 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 13940 13941 // We may have jumped through bitcasts, so the type of the 13942 // BUILD_VECTOR may not match the type of the shuffle. 13943 if (V->getValueType(0) != VT) 13944 NewBV = DAG.getBitcast(VT, NewBV); 13945 return NewBV; 13946 } 13947 } 13948 13949 // There are various patterns used to build up a vector from smaller vectors, 13950 // subvectors, or elements. Scan chains of these and replace unused insertions 13951 // or components with undef. 13952 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 13953 return S; 13954 13955 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13956 Level < AfterLegalizeVectorOps && 13957 (N1.isUndef() || 13958 (N1.getOpcode() == ISD::CONCAT_VECTORS && 13959 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 13960 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 13961 return V; 13962 } 13963 13964 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 13965 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 13966 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 13967 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI)) 13968 return Res; 13969 13970 // If this shuffle only has a single input that is a bitcasted shuffle, 13971 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 13972 // back to their original types. 13973 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 13974 N1.isUndef() && Level < AfterLegalizeVectorOps && 13975 TLI.isTypeLegal(VT)) { 13976 13977 // Peek through the bitcast only if there is one user. 13978 SDValue BC0 = N0; 13979 while (BC0.getOpcode() == ISD::BITCAST) { 13980 if (!BC0.hasOneUse()) 13981 break; 13982 BC0 = BC0.getOperand(0); 13983 } 13984 13985 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 13986 if (Scale == 1) 13987 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 13988 13989 SmallVector<int, 8> NewMask; 13990 for (int M : Mask) 13991 for (int s = 0; s != Scale; ++s) 13992 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 13993 return NewMask; 13994 }; 13995 13996 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 13997 EVT SVT = VT.getScalarType(); 13998 EVT InnerVT = BC0->getValueType(0); 13999 EVT InnerSVT = InnerVT.getScalarType(); 14000 14001 // Determine which shuffle works with the smaller scalar type. 14002 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 14003 EVT ScaleSVT = ScaleVT.getScalarType(); 14004 14005 if (TLI.isTypeLegal(ScaleVT) && 14006 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 14007 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 14008 14009 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 14010 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 14011 14012 // Scale the shuffle masks to the smaller scalar type. 14013 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 14014 SmallVector<int, 8> InnerMask = 14015 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 14016 SmallVector<int, 8> OuterMask = 14017 ScaleShuffleMask(SVN->getMask(), OuterScale); 14018 14019 // Merge the shuffle masks. 14020 SmallVector<int, 8> NewMask; 14021 for (int M : OuterMask) 14022 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 14023 14024 // Test for shuffle mask legality over both commutations. 14025 SDValue SV0 = BC0->getOperand(0); 14026 SDValue SV1 = BC0->getOperand(1); 14027 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 14028 if (!LegalMask) { 14029 std::swap(SV0, SV1); 14030 ShuffleVectorSDNode::commuteMask(NewMask); 14031 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 14032 } 14033 14034 if (LegalMask) { 14035 SV0 = DAG.getBitcast(ScaleVT, SV0); 14036 SV1 = DAG.getBitcast(ScaleVT, SV1); 14037 return DAG.getBitcast( 14038 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 14039 } 14040 } 14041 } 14042 } 14043 14044 // Canonicalize shuffles according to rules: 14045 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 14046 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 14047 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 14048 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 14049 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 14050 TLI.isTypeLegal(VT)) { 14051 // The incoming shuffle must be of the same type as the result of the 14052 // current shuffle. 14053 assert(N1->getOperand(0).getValueType() == VT && 14054 "Shuffle types don't match"); 14055 14056 SDValue SV0 = N1->getOperand(0); 14057 SDValue SV1 = N1->getOperand(1); 14058 bool HasSameOp0 = N0 == SV0; 14059 bool IsSV1Undef = SV1.isUndef(); 14060 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 14061 // Commute the operands of this shuffle so that next rule 14062 // will trigger. 14063 return DAG.getCommutedVectorShuffle(*SVN); 14064 } 14065 14066 // Try to fold according to rules: 14067 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 14068 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 14069 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 14070 // Don't try to fold shuffles with illegal type. 14071 // Only fold if this shuffle is the only user of the other shuffle. 14072 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 14073 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 14074 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 14075 14076 // The incoming shuffle must be of the same type as the result of the 14077 // current shuffle. 14078 assert(OtherSV->getOperand(0).getValueType() == VT && 14079 "Shuffle types don't match"); 14080 14081 SDValue SV0, SV1; 14082 SmallVector<int, 4> Mask; 14083 // Compute the combined shuffle mask for a shuffle with SV0 as the first 14084 // operand, and SV1 as the second operand. 14085 for (unsigned i = 0; i != NumElts; ++i) { 14086 int Idx = SVN->getMaskElt(i); 14087 if (Idx < 0) { 14088 // Propagate Undef. 14089 Mask.push_back(Idx); 14090 continue; 14091 } 14092 14093 SDValue CurrentVec; 14094 if (Idx < (int)NumElts) { 14095 // This shuffle index refers to the inner shuffle N0. Lookup the inner 14096 // shuffle mask to identify which vector is actually referenced. 14097 Idx = OtherSV->getMaskElt(Idx); 14098 if (Idx < 0) { 14099 // Propagate Undef. 14100 Mask.push_back(Idx); 14101 continue; 14102 } 14103 14104 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 14105 : OtherSV->getOperand(1); 14106 } else { 14107 // This shuffle index references an element within N1. 14108 CurrentVec = N1; 14109 } 14110 14111 // Simple case where 'CurrentVec' is UNDEF. 14112 if (CurrentVec.isUndef()) { 14113 Mask.push_back(-1); 14114 continue; 14115 } 14116 14117 // Canonicalize the shuffle index. We don't know yet if CurrentVec 14118 // will be the first or second operand of the combined shuffle. 14119 Idx = Idx % NumElts; 14120 if (!SV0.getNode() || SV0 == CurrentVec) { 14121 // Ok. CurrentVec is the left hand side. 14122 // Update the mask accordingly. 14123 SV0 = CurrentVec; 14124 Mask.push_back(Idx); 14125 continue; 14126 } 14127 14128 // Bail out if we cannot convert the shuffle pair into a single shuffle. 14129 if (SV1.getNode() && SV1 != CurrentVec) 14130 return SDValue(); 14131 14132 // Ok. CurrentVec is the right hand side. 14133 // Update the mask accordingly. 14134 SV1 = CurrentVec; 14135 Mask.push_back(Idx + NumElts); 14136 } 14137 14138 // Check if all indices in Mask are Undef. In case, propagate Undef. 14139 bool isUndefMask = true; 14140 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 14141 isUndefMask &= Mask[i] < 0; 14142 14143 if (isUndefMask) 14144 return DAG.getUNDEF(VT); 14145 14146 if (!SV0.getNode()) 14147 SV0 = DAG.getUNDEF(VT); 14148 if (!SV1.getNode()) 14149 SV1 = DAG.getUNDEF(VT); 14150 14151 // Avoid introducing shuffles with illegal mask. 14152 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 14153 ShuffleVectorSDNode::commuteMask(Mask); 14154 14155 if (!TLI.isShuffleMaskLegal(Mask, VT)) 14156 return SDValue(); 14157 14158 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 14159 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 14160 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 14161 std::swap(SV0, SV1); 14162 } 14163 14164 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 14165 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 14166 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 14167 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask); 14168 } 14169 14170 return SDValue(); 14171 } 14172 14173 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 14174 SDValue InVal = N->getOperand(0); 14175 EVT VT = N->getValueType(0); 14176 14177 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 14178 // with a VECTOR_SHUFFLE. 14179 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14180 SDValue InVec = InVal->getOperand(0); 14181 SDValue EltNo = InVal->getOperand(1); 14182 14183 // FIXME: We could support implicit truncation if the shuffle can be 14184 // scaled to a smaller vector scalar type. 14185 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 14186 if (C0 && VT == InVec.getValueType() && 14187 VT.getScalarType() == InVal.getValueType()) { 14188 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 14189 int Elt = C0->getZExtValue(); 14190 NewMask[0] = Elt; 14191 14192 if (TLI.isShuffleMaskLegal(NewMask, VT)) 14193 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 14194 NewMask); 14195 } 14196 } 14197 14198 return SDValue(); 14199 } 14200 14201 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 14202 EVT VT = N->getValueType(0); 14203 SDValue N0 = N->getOperand(0); 14204 SDValue N1 = N->getOperand(1); 14205 SDValue N2 = N->getOperand(2); 14206 14207 // Combine INSERT_SUBVECTORs where we are inserting to the same index. 14208 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) 14209 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) 14210 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && 14211 N0.getOperand(1).getValueType() == N1.getValueType() && 14212 N0.getOperand(2) == N2) 14213 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), 14214 N1, N2); 14215 14216 if (N0.getValueType() != N1.getValueType()) 14217 return SDValue(); 14218 14219 // If the input vector is a concatenation, and the insert replaces 14220 // one of the halves, we can optimize into a single concat_vectors. 14221 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0->getNumOperands() == 2 && 14222 N2.getOpcode() == ISD::Constant) { 14223 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 14224 14225 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 14226 // (concat_vectors Z, Y) 14227 if (InsIdx == 0) 14228 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N1, 14229 N0.getOperand(1)); 14230 14231 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 14232 // (concat_vectors X, Z) 14233 if (InsIdx == VT.getVectorNumElements() / 2) 14234 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0.getOperand(0), 14235 N1); 14236 } 14237 14238 return SDValue(); 14239 } 14240 14241 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 14242 SDValue N0 = N->getOperand(0); 14243 14244 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 14245 if (N0->getOpcode() == ISD::FP16_TO_FP) 14246 return N0->getOperand(0); 14247 14248 return SDValue(); 14249 } 14250 14251 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 14252 SDValue N0 = N->getOperand(0); 14253 14254 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 14255 if (N0->getOpcode() == ISD::AND) { 14256 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 14257 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 14258 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 14259 N0.getOperand(0)); 14260 } 14261 } 14262 14263 return SDValue(); 14264 } 14265 14266 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 14267 /// with the destination vector and a zero vector. 14268 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 14269 /// vector_shuffle V, Zero, <0, 4, 2, 4> 14270 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 14271 EVT VT = N->getValueType(0); 14272 SDValue LHS = N->getOperand(0); 14273 SDValue RHS = N->getOperand(1); 14274 SDLoc DL(N); 14275 14276 // Make sure we're not running after operation legalization where it 14277 // may have custom lowered the vector shuffles. 14278 if (LegalOperations) 14279 return SDValue(); 14280 14281 if (N->getOpcode() != ISD::AND) 14282 return SDValue(); 14283 14284 if (RHS.getOpcode() == ISD::BITCAST) 14285 RHS = RHS.getOperand(0); 14286 14287 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 14288 return SDValue(); 14289 14290 EVT RVT = RHS.getValueType(); 14291 unsigned NumElts = RHS.getNumOperands(); 14292 14293 // Attempt to create a valid clear mask, splitting the mask into 14294 // sub elements and checking to see if each is 14295 // all zeros or all ones - suitable for shuffle masking. 14296 auto BuildClearMask = [&](int Split) { 14297 int NumSubElts = NumElts * Split; 14298 int NumSubBits = RVT.getScalarSizeInBits() / Split; 14299 14300 SmallVector<int, 8> Indices; 14301 for (int i = 0; i != NumSubElts; ++i) { 14302 int EltIdx = i / Split; 14303 int SubIdx = i % Split; 14304 SDValue Elt = RHS.getOperand(EltIdx); 14305 if (Elt.isUndef()) { 14306 Indices.push_back(-1); 14307 continue; 14308 } 14309 14310 APInt Bits; 14311 if (isa<ConstantSDNode>(Elt)) 14312 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 14313 else if (isa<ConstantFPSDNode>(Elt)) 14314 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 14315 else 14316 return SDValue(); 14317 14318 // Extract the sub element from the constant bit mask. 14319 if (DAG.getDataLayout().isBigEndian()) { 14320 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits); 14321 } else { 14322 Bits = Bits.lshr(SubIdx * NumSubBits); 14323 } 14324 14325 if (Split > 1) 14326 Bits = Bits.trunc(NumSubBits); 14327 14328 if (Bits.isAllOnesValue()) 14329 Indices.push_back(i); 14330 else if (Bits == 0) 14331 Indices.push_back(i + NumSubElts); 14332 else 14333 return SDValue(); 14334 } 14335 14336 // Let's see if the target supports this vector_shuffle. 14337 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 14338 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 14339 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 14340 return SDValue(); 14341 14342 SDValue Zero = DAG.getConstant(0, DL, ClearVT); 14343 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL, 14344 DAG.getBitcast(ClearVT, LHS), 14345 Zero, Indices)); 14346 }; 14347 14348 // Determine maximum split level (byte level masking). 14349 int MaxSplit = 1; 14350 if (RVT.getScalarSizeInBits() % 8 == 0) 14351 MaxSplit = RVT.getScalarSizeInBits() / 8; 14352 14353 for (int Split = 1; Split <= MaxSplit; ++Split) 14354 if (RVT.getScalarSizeInBits() % Split == 0) 14355 if (SDValue S = BuildClearMask(Split)) 14356 return S; 14357 14358 return SDValue(); 14359 } 14360 14361 /// Visit a binary vector operation, like ADD. 14362 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 14363 assert(N->getValueType(0).isVector() && 14364 "SimplifyVBinOp only works on vectors!"); 14365 14366 SDValue LHS = N->getOperand(0); 14367 SDValue RHS = N->getOperand(1); 14368 SDValue Ops[] = {LHS, RHS}; 14369 14370 // See if we can constant fold the vector operation. 14371 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 14372 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 14373 return Fold; 14374 14375 // Try to convert a constant mask AND into a shuffle clear mask. 14376 if (SDValue Shuffle = XformToShuffleWithZero(N)) 14377 return Shuffle; 14378 14379 // Type legalization might introduce new shuffles in the DAG. 14380 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 14381 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 14382 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 14383 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 14384 LHS.getOperand(1).isUndef() && 14385 RHS.getOperand(1).isUndef()) { 14386 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 14387 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 14388 14389 if (SVN0->getMask().equals(SVN1->getMask())) { 14390 EVT VT = N->getValueType(0); 14391 SDValue UndefVector = LHS.getOperand(1); 14392 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 14393 LHS.getOperand(0), RHS.getOperand(0), 14394 N->getFlags()); 14395 AddUsersToWorklist(N); 14396 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 14397 SVN0->getMask()); 14398 } 14399 } 14400 14401 return SDValue(); 14402 } 14403 14404 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 14405 SDValue N2) { 14406 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 14407 14408 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 14409 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 14410 14411 // If we got a simplified select_cc node back from SimplifySelectCC, then 14412 // break it down into a new SETCC node, and a new SELECT node, and then return 14413 // the SELECT node, since we were called with a SELECT node. 14414 if (SCC.getNode()) { 14415 // Check to see if we got a select_cc back (to turn into setcc/select). 14416 // Otherwise, just return whatever node we got back, like fabs. 14417 if (SCC.getOpcode() == ISD::SELECT_CC) { 14418 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 14419 N0.getValueType(), 14420 SCC.getOperand(0), SCC.getOperand(1), 14421 SCC.getOperand(4)); 14422 AddToWorklist(SETCC.getNode()); 14423 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 14424 SCC.getOperand(2), SCC.getOperand(3)); 14425 } 14426 14427 return SCC; 14428 } 14429 return SDValue(); 14430 } 14431 14432 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 14433 /// being selected between, see if we can simplify the select. Callers of this 14434 /// should assume that TheSelect is deleted if this returns true. As such, they 14435 /// should return the appropriate thing (e.g. the node) back to the top-level of 14436 /// the DAG combiner loop to avoid it being looked at. 14437 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 14438 SDValue RHS) { 14439 14440 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 14441 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 14442 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 14443 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 14444 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 14445 SDValue Sqrt = RHS; 14446 ISD::CondCode CC; 14447 SDValue CmpLHS; 14448 const ConstantFPSDNode *Zero = nullptr; 14449 14450 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 14451 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 14452 CmpLHS = TheSelect->getOperand(0); 14453 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 14454 } else { 14455 // SELECT or VSELECT 14456 SDValue Cmp = TheSelect->getOperand(0); 14457 if (Cmp.getOpcode() == ISD::SETCC) { 14458 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 14459 CmpLHS = Cmp.getOperand(0); 14460 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 14461 } 14462 } 14463 if (Zero && Zero->isZero() && 14464 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 14465 CC == ISD::SETULT || CC == ISD::SETLT)) { 14466 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 14467 CombineTo(TheSelect, Sqrt); 14468 return true; 14469 } 14470 } 14471 } 14472 // Cannot simplify select with vector condition 14473 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 14474 14475 // If this is a select from two identical things, try to pull the operation 14476 // through the select. 14477 if (LHS.getOpcode() != RHS.getOpcode() || 14478 !LHS.hasOneUse() || !RHS.hasOneUse()) 14479 return false; 14480 14481 // If this is a load and the token chain is identical, replace the select 14482 // of two loads with a load through a select of the address to load from. 14483 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 14484 // constants have been dropped into the constant pool. 14485 if (LHS.getOpcode() == ISD::LOAD) { 14486 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 14487 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 14488 14489 // Token chains must be identical. 14490 if (LHS.getOperand(0) != RHS.getOperand(0) || 14491 // Do not let this transformation reduce the number of volatile loads. 14492 LLD->isVolatile() || RLD->isVolatile() || 14493 // FIXME: If either is a pre/post inc/dec load, 14494 // we'd need to split out the address adjustment. 14495 LLD->isIndexed() || RLD->isIndexed() || 14496 // If this is an EXTLOAD, the VT's must match. 14497 LLD->getMemoryVT() != RLD->getMemoryVT() || 14498 // If this is an EXTLOAD, the kind of extension must match. 14499 (LLD->getExtensionType() != RLD->getExtensionType() && 14500 // The only exception is if one of the extensions is anyext. 14501 LLD->getExtensionType() != ISD::EXTLOAD && 14502 RLD->getExtensionType() != ISD::EXTLOAD) || 14503 // FIXME: this discards src value information. This is 14504 // over-conservative. It would be beneficial to be able to remember 14505 // both potential memory locations. Since we are discarding 14506 // src value info, don't do the transformation if the memory 14507 // locations are not in the default address space. 14508 LLD->getPointerInfo().getAddrSpace() != 0 || 14509 RLD->getPointerInfo().getAddrSpace() != 0 || 14510 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 14511 LLD->getBasePtr().getValueType())) 14512 return false; 14513 14514 // Check that the select condition doesn't reach either load. If so, 14515 // folding this will induce a cycle into the DAG. If not, this is safe to 14516 // xform, so create a select of the addresses. 14517 SDValue Addr; 14518 if (TheSelect->getOpcode() == ISD::SELECT) { 14519 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 14520 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 14521 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 14522 return false; 14523 // The loads must not depend on one another. 14524 if (LLD->isPredecessorOf(RLD) || 14525 RLD->isPredecessorOf(LLD)) 14526 return false; 14527 Addr = DAG.getSelect(SDLoc(TheSelect), 14528 LLD->getBasePtr().getValueType(), 14529 TheSelect->getOperand(0), LLD->getBasePtr(), 14530 RLD->getBasePtr()); 14531 } else { // Otherwise SELECT_CC 14532 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 14533 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 14534 14535 if ((LLD->hasAnyUseOfValue(1) && 14536 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 14537 (RLD->hasAnyUseOfValue(1) && 14538 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 14539 return false; 14540 14541 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 14542 LLD->getBasePtr().getValueType(), 14543 TheSelect->getOperand(0), 14544 TheSelect->getOperand(1), 14545 LLD->getBasePtr(), RLD->getBasePtr(), 14546 TheSelect->getOperand(4)); 14547 } 14548 14549 SDValue Load; 14550 // It is safe to replace the two loads if they have different alignments, 14551 // but the new load must be the minimum (most restrictive) alignment of the 14552 // inputs. 14553 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 14554 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 14555 if (!RLD->isInvariant()) 14556 MMOFlags &= ~MachineMemOperand::MOInvariant; 14557 if (!RLD->isDereferenceable()) 14558 MMOFlags &= ~MachineMemOperand::MODereferenceable; 14559 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 14560 // FIXME: Discards pointer and AA info. 14561 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 14562 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 14563 MMOFlags); 14564 } else { 14565 // FIXME: Discards pointer and AA info. 14566 Load = DAG.getExtLoad( 14567 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 14568 : LLD->getExtensionType(), 14569 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 14570 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 14571 } 14572 14573 // Users of the select now use the result of the load. 14574 CombineTo(TheSelect, Load); 14575 14576 // Users of the old loads now use the new load's chain. We know the 14577 // old-load value is dead now. 14578 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 14579 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 14580 return true; 14581 } 14582 14583 return false; 14584 } 14585 14586 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and 14587 /// bitwise 'and'. 14588 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, 14589 SDValue N1, SDValue N2, SDValue N3, 14590 ISD::CondCode CC) { 14591 // Check to see if we can perform the "gzip trick", transforming 14592 // (select_cc setlt X, 0, A, 0) -> (and (sra X, size(X)-1), A) 14593 EVT XType = N0.getValueType(); 14594 EVT AType = N2.getValueType(); 14595 if (!isNullConstant(N3) || CC != ISD::SETLT || !XType.bitsGE(AType)) 14596 return SDValue(); 14597 14598 // (a < 0) ? b : 0 14599 // (a < 1) ? a : 0 14600 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2))) 14601 return SDValue(); 14602 14603 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit 14604 // constant. 14605 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 14606 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 14607 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 14608 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1; 14609 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); 14610 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt); 14611 AddToWorklist(Shift.getNode()); 14612 14613 if (XType.bitsGT(AType)) { 14614 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14615 AddToWorklist(Shift.getNode()); 14616 } 14617 14618 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14619 } 14620 14621 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy); 14622 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt); 14623 AddToWorklist(Shift.getNode()); 14624 14625 if (XType.bitsGT(AType)) { 14626 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14627 AddToWorklist(Shift.getNode()); 14628 } 14629 14630 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14631 } 14632 14633 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 14634 /// where 'cond' is the comparison specified by CC. 14635 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 14636 SDValue N2, SDValue N3, ISD::CondCode CC, 14637 bool NotExtCompare) { 14638 // (x ? y : y) -> y. 14639 if (N2 == N3) return N2; 14640 14641 EVT VT = N2.getValueType(); 14642 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 14643 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 14644 14645 // Determine if the condition we're dealing with is constant 14646 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 14647 N0, N1, CC, DL, false); 14648 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 14649 14650 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 14651 // fold select_cc true, x, y -> x 14652 // fold select_cc false, x, y -> y 14653 return !SCCC->isNullValue() ? N2 : N3; 14654 } 14655 14656 // Check to see if we can simplify the select into an fabs node 14657 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 14658 // Allow either -0.0 or 0.0 14659 if (CFP->isZero()) { 14660 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 14661 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 14662 N0 == N2 && N3.getOpcode() == ISD::FNEG && 14663 N2 == N3.getOperand(0)) 14664 return DAG.getNode(ISD::FABS, DL, VT, N0); 14665 14666 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 14667 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 14668 N0 == N3 && N2.getOpcode() == ISD::FNEG && 14669 N2.getOperand(0) == N3) 14670 return DAG.getNode(ISD::FABS, DL, VT, N3); 14671 } 14672 } 14673 14674 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 14675 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 14676 // in it. This is a win when the constant is not otherwise available because 14677 // it replaces two constant pool loads with one. We only do this if the FP 14678 // type is known to be legal, because if it isn't, then we are before legalize 14679 // types an we want the other legalization to happen first (e.g. to avoid 14680 // messing with soft float) and if the ConstantFP is not legal, because if 14681 // it is legal, we may not need to store the FP constant in a constant pool. 14682 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 14683 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 14684 if (TLI.isTypeLegal(N2.getValueType()) && 14685 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 14686 TargetLowering::Legal && 14687 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 14688 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 14689 // If both constants have multiple uses, then we won't need to do an 14690 // extra load, they are likely around in registers for other users. 14691 (TV->hasOneUse() || FV->hasOneUse())) { 14692 Constant *Elts[] = { 14693 const_cast<ConstantFP*>(FV->getConstantFPValue()), 14694 const_cast<ConstantFP*>(TV->getConstantFPValue()) 14695 }; 14696 Type *FPTy = Elts[0]->getType(); 14697 const DataLayout &TD = DAG.getDataLayout(); 14698 14699 // Create a ConstantArray of the two constants. 14700 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 14701 SDValue CPIdx = 14702 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 14703 TD.getPrefTypeAlignment(FPTy)); 14704 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 14705 14706 // Get the offsets to the 0 and 1 element of the array so that we can 14707 // select between them. 14708 SDValue Zero = DAG.getIntPtrConstant(0, DL); 14709 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 14710 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 14711 14712 SDValue Cond = DAG.getSetCC(DL, 14713 getSetCCResultType(N0.getValueType()), 14714 N0, N1, CC); 14715 AddToWorklist(Cond.getNode()); 14716 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 14717 Cond, One, Zero); 14718 AddToWorklist(CstOffset.getNode()); 14719 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 14720 CstOffset); 14721 AddToWorklist(CPIdx.getNode()); 14722 return DAG.getLoad( 14723 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 14724 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 14725 Alignment); 14726 } 14727 } 14728 14729 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC)) 14730 return V; 14731 14732 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 14733 // where y is has a single bit set. 14734 // A plaintext description would be, we can turn the SELECT_CC into an AND 14735 // when the condition can be materialized as an all-ones register. Any 14736 // single bit-test can be materialized as an all-ones register with 14737 // shift-left and shift-right-arith. 14738 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 14739 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 14740 SDValue AndLHS = N0->getOperand(0); 14741 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 14742 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 14743 // Shift the tested bit over the sign bit. 14744 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 14745 SDValue ShlAmt = 14746 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 14747 getShiftAmountTy(AndLHS.getValueType())); 14748 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 14749 14750 // Now arithmetic right shift it all the way over, so the result is either 14751 // all-ones, or zero. 14752 SDValue ShrAmt = 14753 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 14754 getShiftAmountTy(Shl.getValueType())); 14755 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 14756 14757 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 14758 } 14759 } 14760 14761 // fold select C, 16, 0 -> shl C, 4 14762 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 14763 TLI.getBooleanContents(N0.getValueType()) == 14764 TargetLowering::ZeroOrOneBooleanContent) { 14765 14766 // If the caller doesn't want us to simplify this into a zext of a compare, 14767 // don't do it. 14768 if (NotExtCompare && N2C->isOne()) 14769 return SDValue(); 14770 14771 // Get a SetCC of the condition 14772 // NOTE: Don't create a SETCC if it's not legal on this target. 14773 if (!LegalOperations || 14774 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 14775 SDValue Temp, SCC; 14776 // cast from setcc result type to select result type 14777 if (LegalTypes) { 14778 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 14779 N0, N1, CC); 14780 if (N2.getValueType().bitsLT(SCC.getValueType())) 14781 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 14782 N2.getValueType()); 14783 else 14784 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14785 N2.getValueType(), SCC); 14786 } else { 14787 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 14788 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14789 N2.getValueType(), SCC); 14790 } 14791 14792 AddToWorklist(SCC.getNode()); 14793 AddToWorklist(Temp.getNode()); 14794 14795 if (N2C->isOne()) 14796 return Temp; 14797 14798 // shl setcc result by log2 n2c 14799 return DAG.getNode( 14800 ISD::SHL, DL, N2.getValueType(), Temp, 14801 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 14802 getShiftAmountTy(Temp.getValueType()))); 14803 } 14804 } 14805 14806 // Check to see if this is an integer abs. 14807 // select_cc setg[te] X, 0, X, -X -> 14808 // select_cc setgt X, -1, X, -X -> 14809 // select_cc setl[te] X, 0, -X, X -> 14810 // select_cc setlt X, 1, -X, X -> 14811 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 14812 if (N1C) { 14813 ConstantSDNode *SubC = nullptr; 14814 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 14815 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 14816 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 14817 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 14818 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 14819 (N1C->isOne() && CC == ISD::SETLT)) && 14820 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 14821 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 14822 14823 EVT XType = N0.getValueType(); 14824 if (SubC && SubC->isNullValue() && XType.isInteger()) { 14825 SDLoc DL(N0); 14826 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 14827 N0, 14828 DAG.getConstant(XType.getSizeInBits() - 1, DL, 14829 getShiftAmountTy(N0.getValueType()))); 14830 SDValue Add = DAG.getNode(ISD::ADD, DL, 14831 XType, N0, Shift); 14832 AddToWorklist(Shift.getNode()); 14833 AddToWorklist(Add.getNode()); 14834 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 14835 } 14836 } 14837 14838 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 14839 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 14840 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 14841 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 14842 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 14843 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 14844 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 14845 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 14846 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 14847 SDValue ValueOnZero = N2; 14848 SDValue Count = N3; 14849 // If the condition is NE instead of E, swap the operands. 14850 if (CC == ISD::SETNE) 14851 std::swap(ValueOnZero, Count); 14852 // Check if the value on zero is a constant equal to the bits in the type. 14853 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 14854 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 14855 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 14856 // legal, combine to just cttz. 14857 if ((Count.getOpcode() == ISD::CTTZ || 14858 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 14859 N0 == Count.getOperand(0) && 14860 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 14861 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 14862 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 14863 // legal, combine to just ctlz. 14864 if ((Count.getOpcode() == ISD::CTLZ || 14865 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 14866 N0 == Count.getOperand(0) && 14867 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 14868 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 14869 } 14870 } 14871 } 14872 14873 return SDValue(); 14874 } 14875 14876 /// This is a stub for TargetLowering::SimplifySetCC. 14877 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 14878 ISD::CondCode Cond, const SDLoc &DL, 14879 bool foldBooleans) { 14880 TargetLowering::DAGCombinerInfo 14881 DagCombineInfo(DAG, Level, false, this); 14882 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 14883 } 14884 14885 /// Given an ISD::SDIV node expressing a divide by constant, return 14886 /// a DAG expression to select that will generate the same value by multiplying 14887 /// by a magic number. 14888 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14889 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 14890 // when optimising for minimum size, we don't want to expand a div to a mul 14891 // and a shift. 14892 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 14893 return SDValue(); 14894 14895 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14896 if (!C) 14897 return SDValue(); 14898 14899 // Avoid division by zero. 14900 if (C->isNullValue()) 14901 return SDValue(); 14902 14903 std::vector<SDNode*> Built; 14904 SDValue S = 14905 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14906 14907 for (SDNode *N : Built) 14908 AddToWorklist(N); 14909 return S; 14910 } 14911 14912 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 14913 /// DAG expression that will generate the same value by right shifting. 14914 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 14915 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14916 if (!C) 14917 return SDValue(); 14918 14919 // Avoid division by zero. 14920 if (C->isNullValue()) 14921 return SDValue(); 14922 14923 std::vector<SDNode *> Built; 14924 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 14925 14926 for (SDNode *N : Built) 14927 AddToWorklist(N); 14928 return S; 14929 } 14930 14931 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 14932 /// expression that will generate the same value by multiplying by a magic 14933 /// number. 14934 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14935 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 14936 // when optimising for minimum size, we don't want to expand a div to a mul 14937 // and a shift. 14938 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 14939 return SDValue(); 14940 14941 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14942 if (!C) 14943 return SDValue(); 14944 14945 // Avoid division by zero. 14946 if (C->isNullValue()) 14947 return SDValue(); 14948 14949 std::vector<SDNode*> Built; 14950 SDValue S = 14951 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14952 14953 for (SDNode *N : Built) 14954 AddToWorklist(N); 14955 return S; 14956 } 14957 14958 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14959 /// For the reciprocal, we need to find the zero of the function: 14960 /// F(X) = A X - 1 [which has a zero at X = 1/A] 14961 /// => 14962 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 14963 /// does not require additional intermediate precision] 14964 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) { 14965 if (Level >= AfterLegalizeDAG) 14966 return SDValue(); 14967 14968 // TODO: Handle half and/or extended types? 14969 EVT VT = Op.getValueType(); 14970 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 14971 return SDValue(); 14972 14973 // If estimates are explicitly disabled for this function, we're done. 14974 MachineFunction &MF = DAG.getMachineFunction(); 14975 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF); 14976 if (Enabled == TLI.ReciprocalEstimate::Disabled) 14977 return SDValue(); 14978 14979 // Estimates may be explicitly enabled for this type with a custom number of 14980 // refinement steps. 14981 int Iterations = TLI.getDivRefinementSteps(VT, MF); 14982 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) { 14983 AddToWorklist(Est.getNode()); 14984 14985 if (Iterations) { 14986 EVT VT = Op.getValueType(); 14987 SDLoc DL(Op); 14988 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 14989 14990 // Newton iterations: Est = Est + Est (1 - Arg * Est) 14991 for (int i = 0; i < Iterations; ++i) { 14992 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 14993 AddToWorklist(NewEst.getNode()); 14994 14995 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 14996 AddToWorklist(NewEst.getNode()); 14997 14998 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14999 AddToWorklist(NewEst.getNode()); 15000 15001 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 15002 AddToWorklist(Est.getNode()); 15003 } 15004 } 15005 return Est; 15006 } 15007 15008 return SDValue(); 15009 } 15010 15011 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 15012 /// For the reciprocal sqrt, we need to find the zero of the function: 15013 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 15014 /// => 15015 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 15016 /// As a result, we precompute A/2 prior to the iteration loop. 15017 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 15018 unsigned Iterations, 15019 SDNodeFlags *Flags, bool Reciprocal) { 15020 EVT VT = Arg.getValueType(); 15021 SDLoc DL(Arg); 15022 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 15023 15024 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 15025 // this entire sequence requires only one FP constant. 15026 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 15027 AddToWorklist(HalfArg.getNode()); 15028 15029 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 15030 AddToWorklist(HalfArg.getNode()); 15031 15032 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 15033 for (unsigned i = 0; i < Iterations; ++i) { 15034 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 15035 AddToWorklist(NewEst.getNode()); 15036 15037 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 15038 AddToWorklist(NewEst.getNode()); 15039 15040 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 15041 AddToWorklist(NewEst.getNode()); 15042 15043 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 15044 AddToWorklist(Est.getNode()); 15045 } 15046 15047 // If non-reciprocal square root is requested, multiply the result by Arg. 15048 if (!Reciprocal) { 15049 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 15050 AddToWorklist(Est.getNode()); 15051 } 15052 15053 return Est; 15054 } 15055 15056 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 15057 /// For the reciprocal sqrt, we need to find the zero of the function: 15058 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 15059 /// => 15060 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 15061 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 15062 unsigned Iterations, 15063 SDNodeFlags *Flags, bool Reciprocal) { 15064 EVT VT = Arg.getValueType(); 15065 SDLoc DL(Arg); 15066 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 15067 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 15068 15069 // This routine must enter the loop below to work correctly 15070 // when (Reciprocal == false). 15071 assert(Iterations > 0); 15072 15073 // Newton iterations for reciprocal square root: 15074 // E = (E * -0.5) * ((A * E) * E + -3.0) 15075 for (unsigned i = 0; i < Iterations; ++i) { 15076 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 15077 AddToWorklist(AE.getNode()); 15078 15079 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 15080 AddToWorklist(AEE.getNode()); 15081 15082 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 15083 AddToWorklist(RHS.getNode()); 15084 15085 // When calculating a square root at the last iteration build: 15086 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 15087 // (notice a common subexpression) 15088 SDValue LHS; 15089 if (Reciprocal || (i + 1) < Iterations) { 15090 // RSQRT: LHS = (E * -0.5) 15091 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 15092 } else { 15093 // SQRT: LHS = (A * E) * -0.5 15094 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 15095 } 15096 AddToWorklist(LHS.getNode()); 15097 15098 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 15099 AddToWorklist(Est.getNode()); 15100 } 15101 15102 return Est; 15103 } 15104 15105 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 15106 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 15107 /// Op can be zero. 15108 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, 15109 bool Reciprocal) { 15110 if (Level >= AfterLegalizeDAG) 15111 return SDValue(); 15112 15113 // TODO: Handle half and/or extended types? 15114 EVT VT = Op.getValueType(); 15115 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 15116 return SDValue(); 15117 15118 // If estimates are explicitly disabled for this function, we're done. 15119 MachineFunction &MF = DAG.getMachineFunction(); 15120 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF); 15121 if (Enabled == TLI.ReciprocalEstimate::Disabled) 15122 return SDValue(); 15123 15124 // Estimates may be explicitly enabled for this type with a custom number of 15125 // refinement steps. 15126 int Iterations = TLI.getSqrtRefinementSteps(VT, MF); 15127 15128 bool UseOneConstNR = false; 15129 if (SDValue Est = 15130 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR, 15131 Reciprocal)) { 15132 AddToWorklist(Est.getNode()); 15133 15134 if (Iterations) { 15135 Est = UseOneConstNR 15136 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 15137 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 15138 15139 if (!Reciprocal) { 15140 // Unfortunately, Est is now NaN if the input was exactly 0.0. 15141 // Select out this case and force the answer to 0.0. 15142 EVT VT = Op.getValueType(); 15143 SDLoc DL(Op); 15144 15145 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 15146 EVT CCVT = getSetCCResultType(VT); 15147 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 15148 AddToWorklist(ZeroCmp.getNode()); 15149 15150 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 15151 ZeroCmp, FPZero, Est); 15152 AddToWorklist(Est.getNode()); 15153 } 15154 } 15155 return Est; 15156 } 15157 15158 return SDValue(); 15159 } 15160 15161 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 15162 return buildSqrtEstimateImpl(Op, Flags, true); 15163 } 15164 15165 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 15166 return buildSqrtEstimateImpl(Op, Flags, false); 15167 } 15168 15169 /// Return true if base is a frame index, which is known not to alias with 15170 /// anything but itself. Provides base object and offset as results. 15171 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 15172 const GlobalValue *&GV, const void *&CV) { 15173 // Assume it is a primitive operation. 15174 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 15175 15176 // If it's an adding a simple constant then integrate the offset. 15177 if (Base.getOpcode() == ISD::ADD) { 15178 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 15179 Base = Base.getOperand(0); 15180 Offset += C->getZExtValue(); 15181 } 15182 } 15183 15184 // Return the underlying GlobalValue, and update the Offset. Return false 15185 // for GlobalAddressSDNode since the same GlobalAddress may be represented 15186 // by multiple nodes with different offsets. 15187 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 15188 GV = G->getGlobal(); 15189 Offset += G->getOffset(); 15190 return false; 15191 } 15192 15193 // Return the underlying Constant value, and update the Offset. Return false 15194 // for ConstantSDNodes since the same constant pool entry may be represented 15195 // by multiple nodes with different offsets. 15196 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 15197 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 15198 : (const void *)C->getConstVal(); 15199 Offset += C->getOffset(); 15200 return false; 15201 } 15202 // If it's any of the following then it can't alias with anything but itself. 15203 return isa<FrameIndexSDNode>(Base); 15204 } 15205 15206 /// Return true if there is any possibility that the two addresses overlap. 15207 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 15208 // If they are the same then they must be aliases. 15209 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 15210 15211 // If they are both volatile then they cannot be reordered. 15212 if (Op0->isVolatile() && Op1->isVolatile()) return true; 15213 15214 // If one operation reads from invariant memory, and the other may store, they 15215 // cannot alias. These should really be checking the equivalent of mayWrite, 15216 // but it only matters for memory nodes other than load /store. 15217 if (Op0->isInvariant() && Op1->writeMem()) 15218 return false; 15219 15220 if (Op1->isInvariant() && Op0->writeMem()) 15221 return false; 15222 15223 // Gather base node and offset information. 15224 SDValue Base1, Base2; 15225 int64_t Offset1, Offset2; 15226 const GlobalValue *GV1, *GV2; 15227 const void *CV1, *CV2; 15228 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 15229 Base1, Offset1, GV1, CV1); 15230 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 15231 Base2, Offset2, GV2, CV2); 15232 15233 // If they have a same base address then check to see if they overlap. 15234 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 15235 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 15236 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 15237 15238 // It is possible for different frame indices to alias each other, mostly 15239 // when tail call optimization reuses return address slots for arguments. 15240 // To catch this case, look up the actual index of frame indices to compute 15241 // the real alias relationship. 15242 if (isFrameIndex1 && isFrameIndex2) { 15243 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 15244 Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 15245 Offset2 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 15246 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 15247 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 15248 } 15249 15250 // Otherwise, if we know what the bases are, and they aren't identical, then 15251 // we know they cannot alias. 15252 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 15253 return false; 15254 15255 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 15256 // compared to the size and offset of the access, we may be able to prove they 15257 // do not alias. This check is conservative for now to catch cases created by 15258 // splitting vector types. 15259 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 15260 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 15261 (Op0->getMemoryVT().getSizeInBits() >> 3 == 15262 Op1->getMemoryVT().getSizeInBits() >> 3) && 15263 (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) { 15264 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 15265 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 15266 15267 // There is no overlap between these relatively aligned accesses of similar 15268 // size, return no alias. 15269 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 15270 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 15271 return false; 15272 } 15273 15274 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 15275 ? CombinerGlobalAA 15276 : DAG.getSubtarget().useAA(); 15277 #ifndef NDEBUG 15278 if (CombinerAAOnlyFunc.getNumOccurrences() && 15279 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 15280 UseAA = false; 15281 #endif 15282 if (UseAA && 15283 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 15284 // Use alias analysis information. 15285 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 15286 Op1->getSrcValueOffset()); 15287 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 15288 Op0->getSrcValueOffset() - MinOffset; 15289 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 15290 Op1->getSrcValueOffset() - MinOffset; 15291 AliasResult AAResult = 15292 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1, 15293 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 15294 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2, 15295 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 15296 if (AAResult == NoAlias) 15297 return false; 15298 } 15299 15300 // Otherwise we have to assume they alias. 15301 return true; 15302 } 15303 15304 /// Walk up chain skipping non-aliasing memory nodes, 15305 /// looking for aliasing nodes and adding them to the Aliases vector. 15306 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 15307 SmallVectorImpl<SDValue> &Aliases) { 15308 SmallVector<SDValue, 8> Chains; // List of chains to visit. 15309 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 15310 15311 // Get alias information for node. 15312 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 15313 15314 // Starting off. 15315 Chains.push_back(OriginalChain); 15316 unsigned Depth = 0; 15317 15318 // Look at each chain and determine if it is an alias. If so, add it to the 15319 // aliases list. If not, then continue up the chain looking for the next 15320 // candidate. 15321 while (!Chains.empty()) { 15322 SDValue Chain = Chains.pop_back_val(); 15323 15324 // For TokenFactor nodes, look at each operand and only continue up the 15325 // chain until we reach the depth limit. 15326 // 15327 // FIXME: The depth check could be made to return the last non-aliasing 15328 // chain we found before we hit a tokenfactor rather than the original 15329 // chain. 15330 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 15331 Aliases.clear(); 15332 Aliases.push_back(OriginalChain); 15333 return; 15334 } 15335 15336 // Don't bother if we've been before. 15337 if (!Visited.insert(Chain.getNode()).second) 15338 continue; 15339 15340 switch (Chain.getOpcode()) { 15341 case ISD::EntryToken: 15342 // Entry token is ideal chain operand, but handled in FindBetterChain. 15343 break; 15344 15345 case ISD::LOAD: 15346 case ISD::STORE: { 15347 // Get alias information for Chain. 15348 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 15349 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 15350 15351 // If chain is alias then stop here. 15352 if (!(IsLoad && IsOpLoad) && 15353 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 15354 Aliases.push_back(Chain); 15355 } else { 15356 // Look further up the chain. 15357 Chains.push_back(Chain.getOperand(0)); 15358 ++Depth; 15359 } 15360 break; 15361 } 15362 15363 case ISD::TokenFactor: 15364 // We have to check each of the operands of the token factor for "small" 15365 // token factors, so we queue them up. Adding the operands to the queue 15366 // (stack) in reverse order maintains the original order and increases the 15367 // likelihood that getNode will find a matching token factor (CSE.) 15368 if (Chain.getNumOperands() > 16) { 15369 Aliases.push_back(Chain); 15370 break; 15371 } 15372 for (unsigned n = Chain.getNumOperands(); n;) 15373 Chains.push_back(Chain.getOperand(--n)); 15374 ++Depth; 15375 break; 15376 15377 default: 15378 // For all other instructions we will just have to take what we can get. 15379 Aliases.push_back(Chain); 15380 break; 15381 } 15382 } 15383 } 15384 15385 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 15386 /// (aliasing node.) 15387 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 15388 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 15389 15390 // Accumulate all the aliases to this node. 15391 GatherAllAliases(N, OldChain, Aliases); 15392 15393 // If no operands then chain to entry token. 15394 if (Aliases.size() == 0) 15395 return DAG.getEntryNode(); 15396 15397 // If a single operand then chain to it. We don't need to revisit it. 15398 if (Aliases.size() == 1) 15399 return Aliases[0]; 15400 15401 // Construct a custom tailored token factor. 15402 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 15403 } 15404 15405 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 15406 // This holds the base pointer, index, and the offset in bytes from the base 15407 // pointer. 15408 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 15409 15410 // We must have a base and an offset. 15411 if (!BasePtr.Base.getNode()) 15412 return false; 15413 15414 // Do not handle stores to undef base pointers. 15415 if (BasePtr.Base.isUndef()) 15416 return false; 15417 15418 SmallVector<StoreSDNode *, 8> ChainedStores; 15419 ChainedStores.push_back(St); 15420 15421 // Walk up the chain and look for nodes with offsets from the same 15422 // base pointer. Stop when reaching an instruction with a different kind 15423 // or instruction which has a different base pointer. 15424 StoreSDNode *Index = St; 15425 while (Index) { 15426 // If the chain has more than one use, then we can't reorder the mem ops. 15427 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 15428 break; 15429 15430 if (Index->isVolatile() || Index->isIndexed()) 15431 break; 15432 15433 // Find the base pointer and offset for this memory node. 15434 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 15435 15436 // Check that the base pointer is the same as the original one. 15437 if (!Ptr.equalBaseIndex(BasePtr)) 15438 break; 15439 15440 // Find the next memory operand in the chain. If the next operand in the 15441 // chain is a store then move up and continue the scan with the next 15442 // memory operand. If the next operand is a load save it and use alias 15443 // information to check if it interferes with anything. 15444 SDNode *NextInChain = Index->getChain().getNode(); 15445 while (true) { 15446 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 15447 // We found a store node. Use it for the next iteration. 15448 if (STn->isVolatile() || STn->isIndexed()) { 15449 Index = nullptr; 15450 break; 15451 } 15452 ChainedStores.push_back(STn); 15453 Index = STn; 15454 break; 15455 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 15456 NextInChain = Ldn->getChain().getNode(); 15457 continue; 15458 } else { 15459 Index = nullptr; 15460 break; 15461 } 15462 } 15463 } 15464 15465 bool MadeChangeToSt = false; 15466 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 15467 15468 for (StoreSDNode *ChainedStore : ChainedStores) { 15469 SDValue Chain = ChainedStore->getChain(); 15470 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 15471 15472 if (Chain != BetterChain) { 15473 if (ChainedStore == St) 15474 MadeChangeToSt = true; 15475 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 15476 } 15477 } 15478 15479 // Do all replacements after finding the replacements to make to avoid making 15480 // the chains more complicated by introducing new TokenFactors. 15481 for (auto Replacement : BetterChains) 15482 replaceStoreChain(Replacement.first, Replacement.second); 15483 15484 return MadeChangeToSt; 15485 } 15486 15487 /// This is the entry point for the file. 15488 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 15489 CodeGenOpt::Level OptLevel) { 15490 /// This is the main entry point to this class. 15491 DAGCombiner(*this, AA, OptLevel).Run(Level); 15492 } 15493